@mlightcad/cad-llm-plugin 1.8.0-preview.4 → 1.8.0-preview.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +71 -71
- package/dist/cad-llm-plugin-cad-llm-plugin-CUD12ss2.js +21572 -0
- package/dist/cad-llm-plugin-cad-llm-plugin-nXv_Lph-.js +514 -0
- package/dist/cad-llm-plugin-cad-llm-plugin-register-BMfUTRMq.js +7 -0
- package/dist/cad-llm-plugin-cad-llm-plugin-register-W9G8zpBG.js +759 -0
- package/dist/cad-llm-plugin-register.js +10 -611
- package/dist/cad-llm-plugin-register.umd.cjs +1 -1
- package/dist/cad-llm-plugin.js +62 -21479
- package/dist/cad-llm-plugin.umd.cjs +1 -514
- package/lib/AcApLlmOcrProviders.d.ts +17 -0
- package/lib/AcApLlmOcrProviders.d.ts.map +1 -0
- package/lib/AcApLlmOcrProviders.js +214 -0
- package/lib/AcApLlmOcrProviders.js.map +1 -0
- package/lib/AcApLlmPlugin.js +2 -2
- package/lib/AcApLlmPlugin.js.map +1 -1
- package/lib/AcApLlmTextRecognizer.d.ts +12 -5
- package/lib/AcApLlmTextRecognizer.d.ts.map +1 -1
- package/lib/AcApLlmTextRecognizer.js +20 -11
- package/lib/AcApLlmTextRecognizer.js.map +1 -1
- package/lib/command/AcApLlmSettingsCmd.js +1 -1
- package/lib/command/AcApLlmSettingsCmd.js.map +1 -1
- package/lib/constants.d.ts +19 -1
- package/lib/constants.d.ts.map +1 -1
- package/lib/constants.js +36 -1
- package/lib/constants.js.map +1 -1
- package/lib/i18n/ar.d.ts +4 -0
- package/lib/i18n/ar.d.ts.map +1 -1
- package/lib/i18n/ar.js +4 -0
- package/lib/i18n/ar.js.map +1 -1
- package/lib/i18n/chrome.d.ts +10 -0
- package/lib/i18n/chrome.d.ts.map +1 -0
- package/lib/i18n/chrome.js +39 -0
- package/lib/i18n/chrome.js.map +1 -0
- package/lib/i18n/cs.d.ts +4 -0
- package/lib/i18n/cs.d.ts.map +1 -1
- package/lib/i18n/cs.js +4 -0
- package/lib/i18n/cs.js.map +1 -1
- package/lib/i18n/en.d.ts +5 -0
- package/lib/i18n/en.d.ts.map +1 -1
- package/lib/i18n/en.js +5 -0
- package/lib/i18n/en.js.map +1 -1
- package/lib/i18n/index.d.ts +582 -1
- package/lib/i18n/index.d.ts.map +1 -1
- package/lib/i18n/index.js +55 -24
- package/lib/i18n/index.js.map +1 -1
- package/lib/i18n/ja.d.ts +4 -0
- package/lib/i18n/ja.d.ts.map +1 -1
- package/lib/i18n/ja.js +4 -0
- package/lib/i18n/ja.js.map +1 -1
- package/lib/i18n/ko.d.ts +4 -0
- package/lib/i18n/ko.d.ts.map +1 -1
- package/lib/i18n/ko.js +4 -0
- package/lib/i18n/ko.js.map +1 -1
- package/lib/i18n/tr.d.ts +4 -0
- package/lib/i18n/tr.d.ts.map +1 -1
- package/lib/i18n/tr.js +4 -0
- package/lib/i18n/tr.js.map +1 -1
- package/lib/i18n/zh.d.ts +4 -0
- package/lib/i18n/zh.d.ts.map +1 -1
- package/lib/i18n/zh.js +4 -0
- package/lib/i18n/zh.js.map +1 -1
- package/lib/index.d.ts +16 -15
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +16 -15
- package/lib/index.js.map +1 -1
- package/lib/model/AcApLlmModelFactory.d.ts +1 -1
- package/lib/model/AcApLlmModelFactory.d.ts.map +1 -1
- package/lib/model/AcApLlmModelFactory.js +3 -3
- package/lib/model/AcApLlmModelFactory.js.map +1 -1
- package/lib/model/AcApLlmModelListing.d.ts +1 -1
- package/lib/model/AcApLlmModelListing.d.ts.map +1 -1
- package/lib/model/AcApLlmModelListing.js +2 -2
- package/lib/model/AcApLlmModelListing.js.map +1 -1
- package/lib/register.d.ts +5 -4
- package/lib/register.d.ts.map +1 -1
- package/lib/register.js +57 -7
- package/lib/register.js.map +1 -1
- package/lib/storage/AcApLlmConfigStore.d.ts +18 -1
- package/lib/storage/AcApLlmConfigStore.d.ts.map +1 -1
- package/lib/storage/AcApLlmConfigStore.js +60 -16
- package/lib/storage/AcApLlmConfigStore.js.map +1 -1
- package/lib/storage/AcApLlmModelCatalog.d.ts +5 -0
- package/lib/storage/AcApLlmModelCatalog.d.ts.map +1 -1
- package/lib/storage/AcApLlmModelCatalog.js.map +1 -1
- package/lib/storage/settingsEquality.d.ts +1 -1
- package/lib/storage/settingsEquality.d.ts.map +1 -1
- package/lib/storage/settingsEquality.js +3 -2
- package/lib/storage/settingsEquality.js.map +1 -1
- package/lib/ui/AcApLlmModelChoices.d.ts +1 -1
- package/lib/ui/AcApLlmModelChoices.d.ts.map +1 -1
- package/lib/ui/AcApLlmModelChoices.js +3 -3
- package/lib/ui/AcApLlmModelChoices.js.map +1 -1
- package/lib/ui/AcApLlmProviderLabels.d.ts +2 -2
- package/lib/ui/AcApLlmProviderLabels.d.ts.map +1 -1
- package/lib/ui/AcApLlmProviderLabels.js +2 -2
- package/lib/ui/AcApLlmProviderLabels.js.map +1 -1
- package/lib/ui/AcUiLlmSettingsDialog.d.ts.map +1 -1
- package/lib/ui/AcUiLlmSettingsDialog.js +14 -9
- package/lib/ui/AcUiLlmSettingsDialog.js.map +1 -1
- package/lib/ui/icons.d.ts +3 -0
- package/lib/ui/icons.d.ts.map +1 -0
- package/lib/ui/icons.js +3 -0
- package/lib/ui/icons.js.map +1 -0
- package/package.json +3 -3
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
"use strict";const yn=require("@mlightcad/cad-simple-viewer"),D=require("./cad-llm-plugin-cad-llm-plugin-register-BMfUTRMq.js");var Rs="vercel.ai.error",Dc=Symbol.for(Rs),ni,ri,te=class Ps extends(ri=Error,ni=Dc,ri){constructor({name:t,message:n,cause:r}){super(n),this[ni]=!0,this.name=t,this.cause=r}static isInstance(t){return Ps.hasMarker(t,Rs)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}},Ms="AI_APICallError",zs=`vercel.ai.error.${Ms}`,Zc=Symbol.for(zs),oi,ii,$e=class extends(ii=te,oi=Zc,ii){constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:o,responseBody:i,cause:a,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:l}){super({name:Ms,message:e,cause:a}),this[oi]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=o,this.responseBody=i,this.isRetryable=s,this.data=l}static isInstance(e){return te.hasMarker(e,zs)}},Ls="AI_EmptyResponseBodyError",Ds=`vercel.ai.error.${Ls}`,jc=Symbol.for(Ds),ai,si,Uc=class extends(si=te,ai=jc,si){constructor({message:e="Empty response body"}={}){super({name:Ls,message:e}),this[ai]=!0}static isInstance(e){return te.hasMarker(e,Ds)}};function Cn(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Zs="AI_InvalidArgumentError",js=`vercel.ai.error.${Zs}`,Bc=Symbol.for(js),li,ui,Us=class extends(ui=te,li=Bc,ui){constructor({message:t,cause:n,argument:r}){super({name:Zs,message:t,cause:n}),this[li]=!0,this.argument=r}static isInstance(t){return te.hasMarker(t,js)}},Bs="AI_InvalidPromptError",Vs=`vercel.ai.error.${Bs}`,Vc=Symbol.for(Vs),ci,di,xt=class extends(di=te,ci=Vc,di){constructor({prompt:e,message:t,cause:n}){super({name:Bs,message:`Invalid prompt: ${t}`,cause:n}),this[ci]=!0,this.prompt=e}static isInstance(e){return te.hasMarker(e,Vs)}},Fs="AI_InvalidResponseDataError",qs=`vercel.ai.error.${Fs}`,Fc=Symbol.for(qs),pi,hi,br=class extends(hi=te,pi=Fc,hi){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Fs,message:t}),this[pi]=!0,this.data=e}static isInstance(e){return te.hasMarker(e,qs)}},Gs="AI_JSONParseError",Hs=`vercel.ai.error.${Gs}`,qc=Symbol.for(Hs),fi,mi,qn=class extends(mi=te,fi=qc,mi){constructor({text:e,cause:t}){super({name:Gs,message:`JSON parsing failed: Text: ${e}.
|
|
2
|
+
Error message: ${Cn(t)}`,cause:t}),this[fi]=!0,this.text=e}static isInstance(e){return te.hasMarker(e,Hs)}},Ws="AI_LoadAPIKeyError",Js=`vercel.ai.error.${Ws}`,Gc=Symbol.for(Js),_i,gi,zn=class extends(gi=te,_i=Gc,gi){constructor({message:e}){super({name:Ws,message:e}),this[_i]=!0}static isInstance(e){return te.hasMarker(e,Js)}},Ks="AI_NoSuchModelError",Ys=`vercel.ai.error.${Ks}`,Hc=Symbol.for(Ys),yi,vi,bi=class extends(vi=te,yi=Hc,vi){constructor({errorName:e=Ks,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[yi]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return te.hasMarker(e,Ys)}},Xs="AI_TooManyEmbeddingValuesForCallError",Qs=`vercel.ai.error.${Xs}`,Wc=Symbol.for(Qs),wi,xi,Jc=class extends(xi=te,wi=Wc,xi){constructor(e){super({name:Xs,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[wi]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return te.hasMarker(e,Qs)}},el="AI_TypeValidationError",tl=`vercel.ai.error.${el}`,Kc=Symbol.for(tl),ki,Ii,vn=class jr extends(Ii=te,ki=Kc,Ii){constructor({value:t,cause:n}){super({name:el,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
3
|
+
Error message: ${Cn(n)}`,cause:n}),this[ki]=!0,this.value=t}static isInstance(t){return te.hasMarker(t,tl)}static wrap({value:t,cause:n}){return jr.isInstance(n)&&n.value===t?n:new jr({value:t,cause:n})}},nl="AI_UnsupportedFunctionalityError",rl=`vercel.ai.error.${nl}`,Yc=Symbol.for(rl),Ti,Si,je=class extends(Si=te,Ti=Yc,Si){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:nl,message:t}),this[Ti]=!0,this.functionality=e}static isInstance(e){return te.hasMarker(e,rl)}};class wr extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}const Ei=10,Xc=13,Dt=32;function xr(e){}function Qc(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:t=xr,onError:n=xr,onRetry:r=xr,onComment:o,maxBufferSize:i}=e,a=[];let s=0,l=!0,c,p="",g=0,x,T=!1;function I(b){if(T)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,b.charCodeAt(0)===239&&b.charCodeAt(1)===187&&b.charCodeAt(2)===191&&(b=b.slice(3))),a.length===0){const N=k(b);N!==""&&(a.push(N),s=N.length),E();return}if(b.indexOf(`
|
|
4
|
+
`)===-1&&b.indexOf("\r")===-1){a.push(b),s+=b.length,E();return}a.push(b);const S=a.join("");a.length=0,s=0;const m=k(S);m!==""&&(a.push(m),s=m.length),E()}function E(){i!==void 0&&(s+p.length<=i||(T=!0,a.length=0,s=0,c=void 0,p="",g=0,x=void 0,n(new wr(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function k(b){let S=0;if(b.indexOf("\r")===-1){let m=b.indexOf(`
|
|
5
|
+
`,S);for(;m!==-1;){if(S===m){g>0&&t({id:c,event:x,data:p}),c=void 0,p="",g=0,x=void 0,S=m+1,m=b.indexOf(`
|
|
6
|
+
`,S);continue}const N=b.charCodeAt(S);if(Ci(b,S,N)){const Z=b.charCodeAt(S+5)===Dt?S+6:S+5,B=b.slice(Z,m);if(g===0&&b.charCodeAt(m+1)===Ei){t({id:c,event:x,data:B}),c=void 0,p="",x=void 0,S=m+2,m=b.indexOf(`
|
|
7
|
+
`,S);continue}p=g===0?B:`${p}
|
|
8
|
+
${B}`,g++}else Ai(b,S,N)?x=b.slice(b.charCodeAt(S+6)===Dt?S+7:S+6,m)||void 0:_(b,S,m);S=m+1,m=b.indexOf(`
|
|
9
|
+
`,S)}return b.slice(S)}for(;S<b.length;){const m=b.indexOf("\r",S),N=b.indexOf(`
|
|
10
|
+
`,S);let Z=-1;if(m!==-1&&N!==-1?Z=m<N?m:N:m!==-1?m===b.length-1?Z=-1:Z=m:N!==-1&&(Z=N),Z===-1)break;_(b,S,Z),S=Z+1,b.charCodeAt(S-1)===Xc&&b.charCodeAt(S)===Ei&&S++}return b.slice(S)}function _(b,S,m){if(S===m){y();return}const N=b.charCodeAt(S);if(Ci(b,S,N)){const V=b.charCodeAt(S+5)===Dt?S+6:S+5,W=b.slice(V,m);p=g===0?W:`${p}
|
|
11
|
+
${W}`,g++;return}if(Ai(b,S,N)){x=b.slice(b.charCodeAt(S+6)===Dt?S+7:S+6,m)||void 0;return}if(N===105&&b.charCodeAt(S+1)===100&&b.charCodeAt(S+2)===58){const V=b.slice(b.charCodeAt(S+3)===Dt?S+4:S+3,m);c=V.includes("\0")?void 0:V;return}if(N===58){if(o){const V=b.slice(S,m);o(V.slice(b.charCodeAt(S+1)===Dt?2:1))}return}const Z=b.slice(S,m),B=Z.indexOf(":");if(B===-1){v(Z,"",Z);return}const L=Z.slice(0,B),oe=Z.charCodeAt(B+1)===Dt?2:1,z=Z.slice(B+oe);v(L,z,Z)}function v(b,S,m){switch(b){case"event":x=S||void 0;break;case"data":p=g===0?S:`${p}
|
|
12
|
+
${S}`,g++;break;case"id":c=S.includes("\0")?void 0:S;break;case"retry":/^\d+$/.test(S)?r(parseInt(S,10)):n(new wr(`Invalid \`retry\` value: "${S}"`,{type:"invalid-retry",value:S,line:m}));break;default:n(new wr(`Unknown field "${b.length>20?`${b.slice(0,20)}…`:b}"`,{type:"unknown-field",field:b,value:S,line:m}));break}}function y(){g>0&&t({id:c,event:x,data:p}),c=void 0,p="",g=0,x=void 0}function $(b={}){if(b.consume&&a.length>0){const S=a.join("");_(S,0,S.length)}l=!0,c=void 0,p="",g=0,x=void 0,a.length=0,s=0,T=!1}return{feed:I,reset:$}}function Ci(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Ai(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}class ed extends TransformStream{constructor({onError:t,onRetry:n,onComment:r,maxBufferSize:o}={}){let i;super({start(a){i=Qc({onEvent:s=>{a.enqueue(s)},onError(s){typeof t=="function"&&t(s),(t==="terminate"||s.type==="max-buffer-size-exceeded")&&a.error(s)},onRetry:n,onComment:r,maxBufferSize:o})},transform(a){i.feed(a)}})}}function A(e,t,n){function r(s,l){var c;Object.defineProperty(s,"_zod",{value:s._zod??{},enumerable:!1}),(c=s._zod).traits??(c.traits=new Set),s._zod.traits.add(e),t(s,l);for(const p in a.prototype)p in s||Object.defineProperty(s,p,{value:a.prototype[p].bind(s)});s._zod.constr=a,s._zod.def=l}const o=(n==null?void 0:n.Parent)??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function a(s){var l;const c=n!=null&&n.Parent?new i:this;r(c,s),(l=c._zod).deferred??(l.deferred=[]);for(const p of c._zod.deferred)p();return c}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>{var l,c;return n!=null&&n.Parent&&s instanceof n.Parent?!0:(c=(l=s==null?void 0:s._zod)==null?void 0:l.traits)==null?void 0:c.has(e)}}),Object.defineProperty(a,"name",{value:e}),a}class bn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const ol={};function Ot(e){return ol}function il(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function td(e,t){return typeof t=="bigint"?t.toString():t}function uo(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function co(e){return e==null}function po(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function nd(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return i%a/10**o}function fe(e,t,n){Object.defineProperty(e,t,{get(){{const r=n();return e[t]=r,r}},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function lr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function un(e){return JSON.stringify(e)}const al=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const rd=uo(()=>{var e;if(typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Hn(e){if(Gn(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(Gn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}const od=new Set(["string","number","symbol"]);function An(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ft(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function q(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function id(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const ad={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function sd(e,t){const n={},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(n[o]=r.shape[o])}return Ft(e,{...e._zod.def,shape:n,checks:[]})}function ld(e,t){const n={...e._zod.def.shape},r=e._zod.def;for(const o in t){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete n[o]}return Ft(e,{...e._zod.def,shape:n,checks:[]})}function ud(e,t){if(!Hn(t))throw new Error("Invalid input to extend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return lr(this,"shape",r),r},checks:[]};return Ft(e,n)}function cd(e,t){return Ft(e,{...e._zod.def,get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return lr(this,"shape",n),n},catchall:t._zod.def.catchall,checks:[]})}function dd(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=e?new e({type:"optional",innerType:r[i]}):r[i])}else for(const i in r)o[i]=e?new e({type:"optional",innerType:r[i]}):r[i];return Ft(t,{...t._zod.def,shape:o,checks:[]})}function pd(e,t,n){const r=t._zod.def.shape,o={...r};if(n)for(const i in n){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=new e({type:"nonoptional",innerType:r[i]}))}else for(const i in r)o[i]=new e({type:"nonoptional",innerType:r[i]});return Ft(t,{...t._zod.def,shape:o,checks:[]})}function mn(e,t=0){var n;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function It(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function Ln(e){return typeof e=="string"?e:e==null?void 0:e.message}function $t(e,t,n){var o,i,a,s,l,c;const r={...e,path:e.path??[]};if(!e.message){const p=Ln((a=(i=(o=e.inst)==null?void 0:o._zod.def)==null?void 0:i.error)==null?void 0:a.call(i,e))??Ln((s=t==null?void 0:t.error)==null?void 0:s.call(t,e))??Ln((l=n.customError)==null?void 0:l.call(n,e))??Ln((c=n.localeError)==null?void 0:c.call(n,e))??"Invalid input";r.message=p}return delete r.inst,delete r.continue,t!=null&&t.reportInput||delete r.input,r}function ho(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function wn(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const sl=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,td,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ll=A("$ZodError",sl),ul=A("$ZodError",sl,{Parent:Error});function hd(e,t=n=>n.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}function fd(e,t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>o({issues:s}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)r._errors.push(n(a));else{let s=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(n(a))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(e),r}const md=e=>(t,n,r,o)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new bn;if(a.issues.length){const s=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>$t(l,i,Ot())));throw al(s,o==null?void 0:o.callee),s}return a.value},_d=e=>async(t,n,r,o)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const s=new((o==null?void 0:o.Err)??e)(a.issues.map(l=>$t(l,i,Ot())));throw al(s,o==null?void 0:o.callee),s}return a.value},cl=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new bn;return i.issues.length?{success:!1,error:new(e??ll)(i.issues.map(a=>$t(a,o,Ot())))}:{success:!0,data:i.value}},gd=cl(ul),dl=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>$t(a,o,Ot())))}:{success:!0,data:i.value}},yd=dl(ul),vd=/^[cC][^\s-]{8,}$/,bd=/^[0-9a-z]+$/,wd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xd=/^[0-9a-vA-V]{20}$/,kd=/^[A-Za-z0-9]{27}$/,Id=/^[a-zA-Z0-9_-]{21}$/,Td=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Sd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Oi=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Ed=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ad(){return new RegExp(Cd,"u")}const Od=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$d=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Nd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Rd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Pd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,pl=/^[A-Za-z0-9_-]*$/,Md=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,zd=/^\+(?:[0-9]){6,14}[0-9]$/,hl="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ld=new RegExp(`^${hl}$`);function fl(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Dd(e){return new RegExp(`^${fl(e)}$`)}function Zd(e){const t=fl({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-]\\d{2}:\\d{2})");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${hl}T(?:${r})$`)}const jd=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Ud=/^\d+$/,Bd=/^-?\d+(?:\.\d+)?/i,Vd=/true|false/i,Fd=/null/i,qd=/^[^A-Z]*$/,Gd=/^[^a-z]*$/,Ve=A("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ml={number:"number",bigint:"bigint",object:"date"},_l=A("$ZodCheckLessThan",(e,t)=>{Ve.init(e,t);const n=ml[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),gl=A("$ZodCheckGreaterThan",(e,t)=>{Ve.init(e,t);const n=ml[typeof t.value];e._zod.onattach.push(r=>{const o=r._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Hd=A("$ZodCheckMultipleOf",(e,t)=>{Ve.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):nd(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Wd=A("$ZodCheckNumberFormat",(e,t)=>{var a;Ve.init(e,t),t.format=t.format||"float64";const n=(a=t.format)==null?void 0:a.includes("int"),r=n?"int":"number",[o,i]=ad[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=o,l.maximum=i,n&&(l.pattern=Ud)}),e._zod.check=s=>{const l=s.value;if(n){if(!Number.isInteger(l)){s.issues.push({expected:r,format:t.format,code:"invalid_type",input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}l<o&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>i&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:i,inst:e})}}),Jd=A("$ZodCheckMaxLength",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!co(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const o=r.value;if(o.length<=t.maximum)return;const a=ho(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Kd=A("$ZodCheckMinLength",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!co(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const o=r.value;if(o.length>=t.minimum)return;const a=ho(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Yd=A("$ZodCheckLengthEquals",(e,t)=>{var n;Ve.init(e,t),(n=e._zod.def).when??(n.when=r=>{const o=r.value;return!co(o)&&o.length!==void 0}),e._zod.onattach.push(r=>{const o=r._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=r=>{const o=r.value,i=o.length;if(i===t.length)return;const a=ho(o),s=i>t.length;r.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),ur=A("$ZodCheckStringFormat",(e,t)=>{var n,r;Ve.init(e,t),e._zod.onattach.push(o=>{const i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Xd=A("$ZodCheckRegex",(e,t)=>{ur.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Qd=A("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=qd),ur.init(e,t)}),ep=A("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Gd),ur.init(e,t)}),tp=A("$ZodCheckIncludes",(e,t)=>{Ve.init(e,t);const n=An(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(o=>{const i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),np=A("$ZodCheckStartsWith",(e,t)=>{Ve.init(e,t);const n=new RegExp(`^${An(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),rp=A("$ZodCheckEndsWith",(e,t)=>{Ve.init(e,t);const n=new RegExp(`.*${An(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),op=A("$ZodCheckOverwrite",(e,t)=>{Ve.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class ip{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(`
|
|
13
|
+
`).filter(a=>a),o=Math.min(...r.map(a=>a.length-a.trimStart().length)),i=r.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of i)this.content.push(a)}compile(){const t=Function,n=this==null?void 0:this.args,o=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new t(...n,o.join(`
|
|
14
|
+
`))}}const ap={major:4,minor:0,patch:0},_e=A("$ZodType",(e,t)=>{var o;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ap;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const a of i._zod.onattach)a(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(o=e._zod.deferred)==null||o.push(()=>{e._zod.run=e._zod.parse});else{const i=(a,s,l)=>{let c=mn(a),p;for(const g of s){if(g._zod.def.when){if(!g._zod.def.when(a))continue}else if(c)continue;const x=a.issues.length,T=g._zod.check(a);if(T instanceof Promise&&(l==null?void 0:l.async)===!1)throw new bn;if(p||T instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await T,a.issues.length!==x&&(c||(c=mn(a,x)))});else{if(a.issues.length===x)continue;c||(c=mn(a,x))}}return p?p.then(()=>a):a};e._zod.run=(a,s)=>{const l=e._zod.parse(a,s);if(l instanceof Promise){if(s.async===!1)throw new bn;return l.then(c=>i(c,r,s))}return i(l,r,s)}}e["~standard"]={validate:i=>{var a;try{const s=gd(e,i);return s.success?{value:s.data}:{issues:(a=s.error)==null?void 0:a.issues}}catch{return yd(e,i).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),fo=A("$ZodString",(e,t)=>{var n;_e.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??jd(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),xe=A("$ZodStringFormat",(e,t)=>{ur.init(e,t),fo.init(e,t)}),sp=A("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Sd),xe.init(e,t)}),lp=A("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Oi(r))}else t.pattern??(t.pattern=Oi());xe.init(e,t)}),up=A("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ed),xe.init(e,t)}),cp=A("$ZodURL",(e,t)=>{xe.init(e,t),e._zod.check=n=>{try{const r=n.value,o=new URL(r),i=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Md.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),!r.endsWith("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),dp=A("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ad()),xe.init(e,t)}),pp=A("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Id),xe.init(e,t)}),hp=A("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=vd),xe.init(e,t)}),fp=A("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=bd),xe.init(e,t)}),mp=A("$ZodULID",(e,t)=>{t.pattern??(t.pattern=wd),xe.init(e,t)}),_p=A("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xd),xe.init(e,t)}),gp=A("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=kd),xe.init(e,t)}),yp=A("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Zd(t)),xe.init(e,t)}),vp=A("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ld),xe.init(e,t)}),bp=A("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Dd(t)),xe.init(e,t)}),wp=A("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Td),xe.init(e,t)}),xp=A("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Od),xe.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv4"})}),kp=A("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=$d),xe.init(e,t),e._zod.onattach.push(n=>{const r=n._zod.bag;r.format="ipv6"}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Ip=A("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Nd),xe.init(e,t)}),Tp=A("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Rd),xe.init(e,t),e._zod.check=n=>{const[r,o]=n.value.split("/");try{if(!o)throw new Error;const i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function yl(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Sp=A("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Pd),xe.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),e._zod.check=n=>{yl(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Ep(e){if(!pl.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return yl(n)}const Cp=A("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=pl),xe.init(e,t),e._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),e._zod.check=n=>{Ep(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ap=A("$ZodE164",(e,t)=>{t.pattern??(t.pattern=zd),xe.init(e,t)});function Op(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const $p=A("$ZodJWT",(e,t)=>{xe.init(e,t),e._zod.check=n=>{Op(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),vl=A("$ZodNumber",(e,t)=>{_e.init(e,t),e._zod.pattern=e._zod.bag.pattern??Bd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Np=A("$ZodNumber",(e,t)=>{Wd.init(e,t),vl.init(e,t)}),Rp=A("$ZodBoolean",(e,t)=>{_e.init(e,t),e._zod.pattern=Vd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Pp=A("$ZodNull",(e,t)=>{_e.init(e,t),e._zod.pattern=Fd,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Mp=A("$ZodAny",(e,t)=>{_e.init(e,t),e._zod.parse=n=>n}),zp=A("$ZodUnknown",(e,t)=>{_e.init(e,t),e._zod.parse=n=>n}),Lp=A("$ZodNever",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function $i(e,t,n){e.issues.length&&t.issues.push(...It(n,e.issues)),t.value[n]=e.value}const Dp=A("$ZodArray",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let a=0;a<o.length;a++){const s=o[a],l=t.element._zod.run({value:s,issues:[]},r);l instanceof Promise?i.push(l.then(c=>$i(c,n,a))):$i(l,n,a)}return i.length?Promise.all(i).then(()=>n):n}});function Dn(e,t,n){e.issues.length&&t.issues.push(...It(n,e.issues)),t.value[n]=e.value}function Ni(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...It(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}const Zp=A("$ZodObject",(e,t)=>{_e.init(e,t);const n=uo(()=>{const g=Object.keys(t.shape);for(const T of g)if(!(t.shape[T]instanceof _e))throw new Error(`Invalid element at key "${T}": expected a Zod schema`);const x=id(t.shape);return{shape:t.shape,keys:g,keySet:new Set(g),numKeys:g.length,optionalKeys:new Set(x)}});fe(e._zod,"propValues",()=>{const g=t.shape,x={};for(const T in g){const I=g[T]._zod;if(I.values){x[T]??(x[T]=new Set);for(const E of I.values)x[T].add(E)}}return x});const r=g=>{const x=new ip(["shape","payload","ctx"]),T=n.value,I=v=>{const y=un(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};x.write("const input = payload.value;");const E=Object.create(null);let k=0;for(const v of T.keys)E[v]=`key_${k++}`;x.write("const newResult = {}");for(const v of T.keys)if(T.optionalKeys.has(v)){const y=E[v];x.write(`const ${y} = ${I(v)};`);const $=un(v);x.write(`
|
|
15
|
+
if (${y}.issues.length) {
|
|
16
|
+
if (input[${$}] === undefined) {
|
|
17
|
+
if (${$} in input) {
|
|
18
|
+
newResult[${$}] = undefined;
|
|
19
|
+
}
|
|
20
|
+
} else {
|
|
21
|
+
payload.issues = payload.issues.concat(
|
|
22
|
+
${y}.issues.map((iss) => ({
|
|
23
|
+
...iss,
|
|
24
|
+
path: iss.path ? [${$}, ...iss.path] : [${$}],
|
|
25
|
+
}))
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
} else if (${y}.value === undefined) {
|
|
29
|
+
if (${$} in input) newResult[${$}] = undefined;
|
|
30
|
+
} else {
|
|
31
|
+
newResult[${$}] = ${y}.value;
|
|
32
|
+
}
|
|
33
|
+
`)}else{const y=E[v];x.write(`const ${y} = ${I(v)};`),x.write(`
|
|
34
|
+
if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
|
|
35
|
+
...iss,
|
|
36
|
+
path: iss.path ? [${un(v)}, ...iss.path] : [${un(v)}]
|
|
37
|
+
})));`),x.write(`newResult[${un(v)}] = ${y}.value`)}x.write("payload.value = newResult;"),x.write("return payload;");const _=x.compile();return(v,y)=>_(g,v,y)};let o;const i=Gn,a=!ol.jitless,l=a&&rd.value,c=t.catchall;let p;e._zod.parse=(g,x)=>{p??(p=n.value);const T=g.value;if(!i(T))return g.issues.push({expected:"object",code:"invalid_type",input:T,inst:e}),g;const I=[];if(a&&l&&(x==null?void 0:x.async)===!1&&x.jitless!==!0)o||(o=r(t.shape)),g=o(g,x);else{g.value={};const y=p.shape;for(const $ of p.keys){const b=y[$],S=b._zod.run({value:T[$],issues:[]},x),m=b._zod.optin==="optional"&&b._zod.optout==="optional";S instanceof Promise?I.push(S.then(N=>m?Ni(N,g,$,T):Dn(N,g,$))):m?Ni(S,g,$,T):Dn(S,g,$)}}if(!c)return I.length?Promise.all(I).then(()=>g):g;const E=[],k=p.keySet,_=c._zod,v=_.def.type;for(const y of Object.keys(T)){if(k.has(y))continue;if(v==="never"){E.push(y);continue}const $=_.run({value:T[y],issues:[]},x);$ instanceof Promise?I.push($.then(b=>Dn(b,g,y))):Dn($,g,y)}return E.length&&g.issues.push({code:"unrecognized_keys",keys:E,input:T,inst:e}),I.length?Promise.all(I).then(()=>g):g}});function Ri(e,t,n,r){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(o=>o.issues.map(i=>$t(i,r,Ot())))}),t}const bl=A("$ZodUnion",(e,t)=>{_e.init(e,t),fe(e._zod,"optin",()=>t.options.some(n=>n._zod.optin==="optional")?"optional":void 0),fe(e._zod,"optout",()=>t.options.some(n=>n._zod.optout==="optional")?"optional":void 0),fe(e._zod,"values",()=>{if(t.options.every(n=>n._zod.values))return new Set(t.options.flatMap(n=>Array.from(n._zod.values)))}),fe(e._zod,"pattern",()=>{if(t.options.every(n=>n._zod.pattern)){const n=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>po(r.source)).join("|")})$`)}}),e._zod.parse=(n,r)=>{let o=!1;const i=[];for(const a of t.options){const s=a._zod.run({value:n.value,issues:[]},r);if(s instanceof Promise)i.push(s),o=!0;else{if(s.issues.length===0)return s;i.push(s)}}return o?Promise.all(i).then(a=>Ri(a,n,e,r)):Ri(i,n,e,r)}}),jp=A("$ZodDiscriminatedUnion",(e,t)=>{bl.init(e,t);const n=e._zod.parse;fe(e._zod,"propValues",()=>{const o={};for(const i of t.options){const a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[s,l]of Object.entries(a)){o[s]||(o[s]=new Set);for(const c of l)o[s].add(c)}}return o});const r=uo(()=>{const o=t.options,i=new Map;for(const a of o){const s=a._zod.propValues[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of s){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,a)}}return i});e._zod.parse=(o,i)=>{const a=o.value;if(!Gn(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const s=r.value.get(a==null?void 0:a[t.discriminator]);return s?s._zod.run(o,i):t.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),Up=A("$ZodIntersection",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=n.value,i=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([l,c])=>Pi(n,l,c)):Pi(n,i,a)}});function Ur(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Hn(e)&&Hn(t)){const n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(const i of r){const a=Ur(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=e[r],i=t[r],a=Ur(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Pi(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),mn(e))return e;const r=Ur(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const Bp=A("$ZodTuple",(e,t)=>{_e.init(e,t);const n=t.items,r=n.length-[...n].reverse().findIndex(o=>o._zod.optin!=="optional");e._zod.parse=(o,i)=>{const a=o.value;if(!Array.isArray(a))return o.issues.push({input:a,inst:e,expected:"tuple",code:"invalid_type"}),o;o.value=[];const s=[];if(!t.rest){const c=a.length>n.length,p=a.length<r-1;if(c||p)return o.issues.push({input:a,inst:e,origin:"array",...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),o}let l=-1;for(const c of n){if(l++,l>=a.length&&l>=r)continue;const p=c._zod.run({value:a[l],issues:[]},i);p instanceof Promise?s.push(p.then(g=>Zn(g,o,l))):Zn(p,o,l)}if(t.rest){const c=a.slice(n.length);for(const p of c){l++;const g=t.rest._zod.run({value:p,issues:[]},i);g instanceof Promise?s.push(g.then(x=>Zn(x,o,l))):Zn(g,o,l)}}return s.length?Promise.all(s).then(()=>o):o}});function Zn(e,t,n){e.issues.length&&t.issues.push(...It(n,e.issues)),t.value[n]=e.value}const Vp=A("$ZodRecord",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Hn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const i=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;n.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?i.push(c.then(p=>{p.issues.length&&n.issues.push(...It(l,p.issues)),n.value[l]=p.value})):(c.issues.length&&n.issues.push(...It(l,c.issues)),n.value[l]=c.value)}let s;for(const l in o)a.has(l)||(s=s??[],s.push(l));s&&s.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:s})}else{n.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const s=t.keyType._zod.run({value:a,issues:[]},r);if(s instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(s.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:s.issues.map(c=>$t(c,r,Ot())),input:a,path:[a],inst:e}),n.value[s.value]=s.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?i.push(l.then(c=>{c.issues.length&&n.issues.push(...It(a,c.issues)),n.value[s.value]=c.value})):(l.issues.length&&n.issues.push(...It(a,l.issues)),n.value[s.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Fp=A("$ZodEnum",(e,t)=>{_e.init(e,t);const n=il(t.entries);e._zod.values=new Set(n),e._zod.pattern=new RegExp(`^(${n.filter(r=>od.has(typeof r)).map(r=>typeof r=="string"?An(r):r.toString()).join("|")})$`),e._zod.parse=(r,o)=>{const i=r.value;return e._zod.values.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:e}),r}}),qp=A("$ZodLiteral",(e,t)=>{_e.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?An(n):n?n.toString():String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const o=n.value;return e._zod.values.has(o)||n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),Gp=A("$ZodTransform",(e,t)=>{_e.init(e,t),e._zod.parse=(n,r)=>{const o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(n.value=a,n));if(o instanceof Promise)throw new bn;return n.value=o,n}}),Hp=A("$ZodOptional",(e,t)=>{_e.init(e,t),e._zod.optin="optional",e._zod.optout="optional",fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),fe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${po(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(n,r):n.value===void 0?n:t.innerType._zod.run(n,r)}),Wp=A("$ZodNullable",(e,t)=>{_e.init(e,t),fe(e._zod,"optin",()=>t.innerType._zod.optin),fe(e._zod,"optout",()=>t.innerType._zod.optout),fe(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${po(n.source)}|null)$`):void 0}),fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),Jp=A("$ZodDefault",(e,t)=>{_e.init(e,t),e._zod.optin="optional",fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Mi(i,t)):Mi(o,t)}});function Mi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Kp=A("$ZodPrefault",(e,t)=>{_e.init(e,t),e._zod.optin="optional",fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),Yp=A("$ZodNonOptional",(e,t)=>{_e.init(e,t),fe(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>zi(i,e)):zi(o,e)}});function zi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Xp=A("$ZodCatch",(e,t)=>{_e.init(e,t),e._zod.optin="optional",fe(e._zod,"optout",()=>t.innerType._zod.optout),fe(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(a=>$t(a,r,Ot()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(i=>$t(i,r,Ot()))},input:n.value}),n.issues=[]),n)}}),Qp=A("$ZodPipe",(e,t)=>{_e.init(e,t),fe(e._zod,"values",()=>t.in._zod.values),fe(e._zod,"optin",()=>t.in._zod.optin),fe(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(n,r)=>{const o=t.in._zod.run(n,r);return o instanceof Promise?o.then(i=>Li(i,t,r)):Li(o,t,r)}});function Li(e,t,n){return mn(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}const eh=A("$ZodReadonly",(e,t)=>{_e.init(e,t),fe(e._zod,"propValues",()=>t.innerType._zod.propValues),fe(e._zod,"values",()=>t.innerType._zod.values),fe(e._zod,"optin",()=>t.innerType._zod.optin),fe(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(Di):Di(o)}});function Di(e){return e.value=Object.freeze(e.value),e}const th=A("$ZodLazy",(e,t)=>{_e.init(e,t),fe(e._zod,"innerType",()=>t.getter()),fe(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),fe(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),fe(e._zod,"optin",()=>e._zod.innerType._zod.optin),fe(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),nh=A("$ZodCustom",(e,t)=>{Ve.init(e,t),_e.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(i=>Zi(i,n,r,e));Zi(o,n,r,e)}});function Zi(e,t,n,r){if(!e){const o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(wn(o))}}class wl{constructor(){this._map=new Map,this._idmap=new Map}add(t,...n){const r=n[0];if(this._map.set(t,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function rh(){return new wl}const hn=rh();function oh(e,t){return new e({type:"string",...q(t)})}function ih(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...q(t)})}function ji(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...q(t)})}function ah(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...q(t)})}function sh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(t)})}function lh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(t)})}function uh(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(t)})}function ch(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...q(t)})}function dh(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...q(t)})}function ph(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(t)})}function hh(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...q(t)})}function fh(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(t)})}function mh(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...q(t)})}function _h(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...q(t)})}function gh(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(t)})}function yh(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(t)})}function vh(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(t)})}function bh(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(t)})}function wh(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(t)})}function xh(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...q(t)})}function kh(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...q(t)})}function Ih(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...q(t)})}function Th(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...q(t)})}function Sh(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(t)})}function Eh(e,t){return new e({type:"string",format:"date",check:"string_format",...q(t)})}function Ch(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...q(t)})}function Ah(e,t){return new e({type:"string",format:"duration",check:"string_format",...q(t)})}function Oh(e,t){return new e({type:"number",checks:[],...q(t)})}function $h(e,t){return new e({type:"number",coerce:!0,checks:[],...q(t)})}function Nh(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...q(t)})}function Rh(e,t){return new e({type:"boolean",...q(t)})}function Ph(e,t){return new e({type:"null",...q(t)})}function Mh(e){return new e({type:"any"})}function zh(e){return new e({type:"unknown"})}function Lh(e,t){return new e({type:"never",...q(t)})}function Ui(e,t){return new _l({check:"less_than",...q(t),value:e,inclusive:!1})}function kr(e,t){return new _l({check:"less_than",...q(t),value:e,inclusive:!0})}function Bi(e,t){return new gl({check:"greater_than",...q(t),value:e,inclusive:!1})}function Ir(e,t){return new gl({check:"greater_than",...q(t),value:e,inclusive:!0})}function Vi(e,t){return new Hd({check:"multiple_of",...q(t),value:e})}function xl(e,t){return new Jd({check:"max_length",...q(t),maximum:e})}function Wn(e,t){return new Kd({check:"min_length",...q(t),minimum:e})}function kl(e,t){return new Yd({check:"length_equals",...q(t),length:e})}function Dh(e,t){return new Xd({check:"string_format",format:"regex",...q(t),pattern:e})}function Zh(e){return new Qd({check:"string_format",format:"lowercase",...q(e)})}function jh(e){return new ep({check:"string_format",format:"uppercase",...q(e)})}function Uh(e,t){return new tp({check:"string_format",format:"includes",...q(t),includes:e})}function Bh(e,t){return new np({check:"string_format",format:"starts_with",...q(t),prefix:e})}function Vh(e,t){return new rp({check:"string_format",format:"ends_with",...q(t),suffix:e})}function On(e){return new op({check:"overwrite",tx:e})}function Fh(e){return On(t=>t.normalize(e))}function qh(){return On(e=>e.trim())}function Gh(){return On(e=>e.toLowerCase())}function Hh(){return On(e=>e.toUpperCase())}function Wh(e,t,n){return new e({type:"array",element:t,...q(n)})}function Jh(e,t,n){const r=q(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}function Kh(e,t,n){return new e({type:"custom",check:"custom",fn:t,...q(n)})}class Fi{constructor(t){this.counter=0,this.metadataRegistry=(t==null?void 0:t.metadata)??hn,this.target=(t==null?void 0:t.target)??"draft-2020-12",this.unrepresentable=(t==null?void 0:t.unrepresentable)??"throw",this.override=(t==null?void 0:t.override)??(()=>{}),this.io=(t==null?void 0:t.io)??"output",this.seen=new Map}process(t,n={path:[],schemaPath:[]}){var g,x,T;var r;const o=t._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,n.schemaPath.includes(t)&&(a.cycle=n.path),a.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(t,s);const l=(x=(g=t._zod).toJSONSchema)==null?void 0:x.call(g);if(l)s.schema=l;else{const I={...n,schemaPath:[...n.schemaPath,t],path:n.path},E=t._zod.parent;if(E)s.ref=E,this.process(E,I),this.seen.get(E).isParent=!0;else{const k=s.schema;switch(o.type){case"string":{const _=k;_.type="string";const{minimum:v,maximum:y,format:$,patterns:b,contentEncoding:S}=t._zod.bag;if(typeof v=="number"&&(_.minLength=v),typeof y=="number"&&(_.maxLength=y),$&&(_.format=i[$]??$,_.format===""&&delete _.format),S&&(_.contentEncoding=S),b&&b.size>0){const m=[...b];m.length===1?_.pattern=m[0].source:m.length>1&&(s.schema.allOf=[...m.map(N=>({...this.target==="draft-7"?{type:"string"}:{},pattern:N.source}))])}break}case"number":{const _=k,{minimum:v,maximum:y,format:$,multipleOf:b,exclusiveMaximum:S,exclusiveMinimum:m}=t._zod.bag;typeof $=="string"&&$.includes("int")?_.type="integer":_.type="number",typeof m=="number"&&(_.exclusiveMinimum=m),typeof v=="number"&&(_.minimum=v,typeof m=="number"&&(m>=v?delete _.minimum:delete _.exclusiveMinimum)),typeof S=="number"&&(_.exclusiveMaximum=S),typeof y=="number"&&(_.maximum=y,typeof S=="number"&&(S<=y?delete _.maximum:delete _.exclusiveMaximum)),typeof b=="number"&&(_.multipleOf=b);break}case"boolean":{const _=k;_.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{k.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{k.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const _=k,{minimum:v,maximum:y}=t._zod.bag;typeof v=="number"&&(_.minItems=v),typeof y=="number"&&(_.maxItems=y),_.type="array",_.items=this.process(o.element,{...I,path:[...I.path,"items"]});break}case"object":{const _=k;_.type="object",_.properties={};const v=o.shape;for(const b in v)_.properties[b]=this.process(v[b],{...I,path:[...I.path,"properties",b]});const y=new Set(Object.keys(v)),$=new Set([...y].filter(b=>{const S=o.shape[b]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));$.size>0&&(_.required=Array.from($)),((T=o.catchall)==null?void 0:T._zod.def.type)==="never"?_.additionalProperties=!1:o.catchall?o.catchall&&(_.additionalProperties=this.process(o.catchall,{...I,path:[...I.path,"additionalProperties"]})):this.io==="output"&&(_.additionalProperties=!1);break}case"union":{const _=k;_.anyOf=o.options.map((v,y)=>this.process(v,{...I,path:[...I.path,"anyOf",y]}));break}case"intersection":{const _=k,v=this.process(o.left,{...I,path:[...I.path,"allOf",0]}),y=this.process(o.right,{...I,path:[...I.path,"allOf",1]}),$=S=>"allOf"in S&&Object.keys(S).length===1,b=[...$(v)?v.allOf:[v],...$(y)?y.allOf:[y]];_.allOf=b;break}case"tuple":{const _=k;_.type="array";const v=o.items.map((b,S)=>this.process(b,{...I,path:[...I.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?_.prefixItems=v:_.items=v,o.rest){const b=this.process(o.rest,{...I,path:[...I.path,"items"]});this.target==="draft-2020-12"?_.items=b:_.additionalItems=b}o.rest&&(_.items=this.process(o.rest,{...I,path:[...I.path,"items"]}));const{minimum:y,maximum:$}=t._zod.bag;typeof y=="number"&&(_.minItems=y),typeof $=="number"&&(_.maxItems=$);break}case"record":{const _=k;_.type="object",_.propertyNames=this.process(o.keyType,{...I,path:[...I.path,"propertyNames"]}),_.additionalProperties=this.process(o.valueType,{...I,path:[...I.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const _=k,v=il(o.entries);v.every(y=>typeof y=="number")&&(_.type="number"),v.every(y=>typeof y=="string")&&(_.type="string"),_.enum=v;break}case"literal":{const _=k,v=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");v.push(Number(y))}else v.push(y);if(v.length!==0)if(v.length===1){const y=v[0];_.type=y===null?"null":typeof y,_.const=y}else v.every(y=>typeof y=="number")&&(_.type="number"),v.every(y=>typeof y=="string")&&(_.type="string"),v.every(y=>typeof y=="boolean")&&(_.type="string"),v.every(y=>y===null)&&(_.type="null"),_.enum=v;break}case"file":{const _=k,v={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:$,mime:b}=t._zod.bag;y!==void 0&&(v.minLength=y),$!==void 0&&(v.maxLength=$),b?b.length===1?(v.contentMediaType=b[0],Object.assign(_,v)):_.anyOf=b.map(S=>({...v,contentMediaType:S})):Object.assign(_,v);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const _=this.process(o.innerType,I);k.anyOf=[_,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,I),s.ref=o.innerType;break}case"success":{const _=k;_.type="boolean";break}case"default":{this.process(o.innerType,I),s.ref=o.innerType,k.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,I),s.ref=o.innerType,this.io==="input"&&(k._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,I),s.ref=o.innerType;let _;try{_=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}k.default=_;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const _=k,v=t._zod.pattern;if(!v)throw new Error("Pattern not found in template literal");_.type="string",_.pattern=v.source;break}case"pipe":{const _=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(_,I),s.ref=_;break}case"readonly":{this.process(o.innerType,I),s.ref=o.innerType,k.readOnly=!0;break}case"promise":{this.process(o.innerType,I),s.ref=o.innerType;break}case"optional":{this.process(o.innerType,I),s.ref=o.innerType;break}case"lazy":{const _=t._zod.innerType;this.process(_,I),s.ref=_;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(s.schema,c),this.io==="input"&&Oe(t)&&(delete s.schema.examples,delete s.schema.default),this.io==="input"&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,this.seen.get(t).schema}emit(t,n){var p,g,x,T,I,E;const r={cycles:(n==null?void 0:n.cycles)??"ref",reused:(n==null?void 0:n.reused)??"inline",external:(n==null?void 0:n.external)??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=k=>{var b;const _=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const S=(b=r.external.registry.get(k[0]))==null?void 0:b.id,m=r.external.uri??(Z=>Z);if(S)return{ref:m(S)};const N=k[1].defId??k[1].schema.id??`schema${this.counter++}`;return k[1].defId=N,{defId:N,ref:`${m("__shared")}#/${_}/${N}`}}if(k[1]===o)return{ref:"#"};const y=`#/${_}/`,$=k[1].schema.id??`__schema${this.counter++}`;return{defId:$,ref:y+$}},a=k=>{if(k[1].schema.$ref)return;const _=k[1],{ref:v,defId:y}=i(k);_.def={..._.schema},y&&(_.defId=y);const $=_.schema;for(const b in $)delete $[b];$.$ref=v};if(r.cycles==="throw")for(const k of this.seen.entries()){const _=k[1];if(_.cycle)throw new Error(`Cycle detected: #/${(p=_.cycle)==null?void 0:p.join("/")}/<root>
|
|
38
|
+
|
|
39
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const k of this.seen.entries()){const _=k[1];if(t===k[0]){a(k);continue}if(r.external){const y=(g=r.external.registry.get(k[0]))==null?void 0:g.id;if(t!==k[0]&&y){a(k);continue}}if((x=this.metadataRegistry.get(k[0]))==null?void 0:x.id){a(k);continue}if(_.cycle){a(k);continue}if(_.count>1&&r.reused==="ref"){a(k);continue}}const s=(k,_)=>{const v=this.seen.get(k),y=v.def??v.schema,$={...y};if(v.ref===null)return;const b=v.ref;if(v.ref=null,b){s(b,_);const S=this.seen.get(b).schema;S.$ref&&_.target==="draft-7"?(y.allOf=y.allOf??[],y.allOf.push(S)):(Object.assign(y,S),Object.assign(y,$))}v.isParent||this.override({zodSchema:k,jsonSchema:y,path:v.path??[]})};for(const k of[...this.seen.entries()].reverse())s(k[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),(T=r.external)!=null&&T.uri){const k=(I=r.external.registry.get(t))==null?void 0:I.id;if(!k)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(k)}Object.assign(l,o.def);const c=((E=r.external)==null?void 0:E.defs)??{};for(const k of this.seen.entries()){const _=k[1];_.def&&_.defId&&(c[_.defId]=_.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}function Yh(e,t){if(e instanceof wl){const r=new Fi(t),o={};for(const s of e._idmap.entries()){const[l,c]=s;r.process(c)}const i={},a={registry:e,uri:t==null?void 0:t.uri,defs:o};for(const s of e._idmap.entries()){const[l,c]=s;i[l]=r.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const s=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[s]:o}}return{schemas:i}}const n=new Fi(t);return n.process(e),n.emit(e,t)}function Oe(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Oe(o.element,n);case"object":{for(const i in o.shape)if(Oe(o.shape[i],n))return!0;return!1}case"union":{for(const i of o.options)if(Oe(i,n))return!0;return!1}case"intersection":return Oe(o.left,n)||Oe(o.right,n);case"tuple":{for(const i of o.items)if(Oe(i,n))return!0;return!!(o.rest&&Oe(o.rest,n))}case"record":return Oe(o.keyType,n)||Oe(o.valueType,n);case"map":return Oe(o.keyType,n)||Oe(o.valueType,n);case"set":return Oe(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Oe(o.innerType,n);case"lazy":return Oe(o.getter(),n);case"default":return Oe(o.innerType,n);case"prefault":return Oe(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Oe(o.in,n)||Oe(o.out,n);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const Xh=A("ZodISODateTime",(e,t)=>{yp.init(e,t),Te.init(e,t)});function Qh(e){return Sh(Xh,e)}const ef=A("ZodISODate",(e,t)=>{vp.init(e,t),Te.init(e,t)});function tf(e){return Eh(ef,e)}const nf=A("ZodISOTime",(e,t)=>{bp.init(e,t),Te.init(e,t)});function rf(e){return Ch(nf,e)}const of=A("ZodISODuration",(e,t)=>{wp.init(e,t),Te.init(e,t)});function af(e){return Ah(of,e)}const sf=(e,t)=>{ll.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>fd(e,n)},flatten:{value:n=>hd(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},cr=A("ZodError",sf,{Parent:Error}),lf=md(cr),uf=_d(cr),cf=cl(cr),Il=dl(cr),ve=A("ZodType",(e,t)=>(_e.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>Ft(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>lf(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>cf(e,n,r),e.parseAsync=async(n,r)=>uf(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Il(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(am(n,r)),e.superRefine=n=>e.check(sm(n)),e.overwrite=n=>e.check(On(n)),e.optional=()=>Hi(e),e.nullable=()=>Wi(e),e.nullish=()=>Hi(Wi(e)),e.nonoptional=n=>Yf(e,n),e.array=()=>R(e),e.or=n=>ee([e,n]),e.and=n=>jf(e,n),e.transform=n=>Ji(e,qf(n)),e.default=n=>Wf(e,n),e.prefault=n=>Kf(e,n),e.catch=n=>Qf(e,n),e.pipe=n=>Ji(e,n),e.readonly=()=>nm(e),e.describe=n=>{const r=e.clone();return hn.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=hn.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return hn.get(e);const r=e.clone();return hn.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Tl=A("_ZodString",(e,t)=>{fo.init(e,t),ve.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(Dh(...r)),e.includes=(...r)=>e.check(Uh(...r)),e.startsWith=(...r)=>e.check(Bh(...r)),e.endsWith=(...r)=>e.check(Vh(...r)),e.min=(...r)=>e.check(Wn(...r)),e.max=(...r)=>e.check(xl(...r)),e.length=(...r)=>e.check(kl(...r)),e.nonempty=(...r)=>e.check(Wn(1,...r)),e.lowercase=r=>e.check(Zh(r)),e.uppercase=r=>e.check(jh(r)),e.trim=()=>e.check(qh()),e.normalize=(...r)=>e.check(Fh(...r)),e.toLowerCase=()=>e.check(Gh()),e.toUpperCase=()=>e.check(Hh())}),df=A("ZodString",(e,t)=>{fo.init(e,t),Tl.init(e,t),e.email=n=>e.check(ih(pf,n)),e.url=n=>e.check(ch(hf,n)),e.jwt=n=>e.check(Th(Cf,n)),e.emoji=n=>e.check(dh(ff,n)),e.guid=n=>e.check(ji(qi,n)),e.uuid=n=>e.check(ah(jn,n)),e.uuidv4=n=>e.check(sh(jn,n)),e.uuidv6=n=>e.check(lh(jn,n)),e.uuidv7=n=>e.check(uh(jn,n)),e.nanoid=n=>e.check(ph(mf,n)),e.guid=n=>e.check(ji(qi,n)),e.cuid=n=>e.check(hh(_f,n)),e.cuid2=n=>e.check(fh(gf,n)),e.ulid=n=>e.check(mh(yf,n)),e.base64=n=>e.check(xh(Tf,n)),e.base64url=n=>e.check(kh(Sf,n)),e.xid=n=>e.check(_h(vf,n)),e.ksuid=n=>e.check(gh(bf,n)),e.ipv4=n=>e.check(yh(wf,n)),e.ipv6=n=>e.check(vh(xf,n)),e.cidrv4=n=>e.check(bh(kf,n)),e.cidrv6=n=>e.check(wh(If,n)),e.e164=n=>e.check(Ih(Ef,n)),e.datetime=n=>e.check(Qh(n)),e.date=n=>e.check(tf(n)),e.time=n=>e.check(rf(n)),e.duration=n=>e.check(af(n))});function u(e){return oh(df,e)}const Te=A("ZodStringFormat",(e,t)=>{xe.init(e,t),Tl.init(e,t)}),pf=A("ZodEmail",(e,t)=>{up.init(e,t),Te.init(e,t)}),qi=A("ZodGUID",(e,t)=>{sp.init(e,t),Te.init(e,t)}),jn=A("ZodUUID",(e,t)=>{lp.init(e,t),Te.init(e,t)}),hf=A("ZodURL",(e,t)=>{cp.init(e,t),Te.init(e,t)}),ff=A("ZodEmoji",(e,t)=>{dp.init(e,t),Te.init(e,t)}),mf=A("ZodNanoID",(e,t)=>{pp.init(e,t),Te.init(e,t)}),_f=A("ZodCUID",(e,t)=>{hp.init(e,t),Te.init(e,t)}),gf=A("ZodCUID2",(e,t)=>{fp.init(e,t),Te.init(e,t)}),yf=A("ZodULID",(e,t)=>{mp.init(e,t),Te.init(e,t)}),vf=A("ZodXID",(e,t)=>{_p.init(e,t),Te.init(e,t)}),bf=A("ZodKSUID",(e,t)=>{gp.init(e,t),Te.init(e,t)}),wf=A("ZodIPv4",(e,t)=>{xp.init(e,t),Te.init(e,t)}),xf=A("ZodIPv6",(e,t)=>{kp.init(e,t),Te.init(e,t)}),kf=A("ZodCIDRv4",(e,t)=>{Ip.init(e,t),Te.init(e,t)}),If=A("ZodCIDRv6",(e,t)=>{Tp.init(e,t),Te.init(e,t)}),Tf=A("ZodBase64",(e,t)=>{Sp.init(e,t),Te.init(e,t)}),Sf=A("ZodBase64URL",(e,t)=>{Cp.init(e,t),Te.init(e,t)}),Ef=A("ZodE164",(e,t)=>{Ap.init(e,t),Te.init(e,t)}),Cf=A("ZodJWT",(e,t)=>{$p.init(e,t),Te.init(e,t)}),mo=A("ZodNumber",(e,t)=>{vl.init(e,t),ve.init(e,t),e.gt=(r,o)=>e.check(Bi(r,o)),e.gte=(r,o)=>e.check(Ir(r,o)),e.min=(r,o)=>e.check(Ir(r,o)),e.lt=(r,o)=>e.check(Ui(r,o)),e.lte=(r,o)=>e.check(kr(r,o)),e.max=(r,o)=>e.check(kr(r,o)),e.int=r=>e.check(Gi(r)),e.safe=r=>e.check(Gi(r)),e.positive=r=>e.check(Bi(0,r)),e.nonnegative=r=>e.check(Ir(0,r)),e.negative=r=>e.check(Ui(0,r)),e.nonpositive=r=>e.check(kr(0,r)),e.multipleOf=(r,o)=>e.check(Vi(r,o)),e.step=(r,o)=>e.check(Vi(r,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function f(e){return Oh(mo,e)}const Af=A("ZodNumberFormat",(e,t)=>{Np.init(e,t),mo.init(e,t)});function Gi(e){return Nh(Af,e)}const Of=A("ZodBoolean",(e,t)=>{Rp.init(e,t),ve.init(e,t)});function ue(e){return Rh(Of,e)}const $f=A("ZodNull",(e,t)=>{Pp.init(e,t),ve.init(e,t)});function Nf(e){return Ph($f,e)}const Rf=A("ZodAny",(e,t)=>{Mp.init(e,t),ve.init(e,t)});function He(){return Mh(Rf)}const Pf=A("ZodUnknown",(e,t)=>{zp.init(e,t),ve.init(e,t)});function ze(){return zh(Pf)}const Mf=A("ZodNever",(e,t)=>{Lp.init(e,t),ve.init(e,t)});function zf(e){return Lh(Mf,e)}const Lf=A("ZodArray",(e,t)=>{Dp.init(e,t),ve.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(Wn(n,r)),e.nonempty=n=>e.check(Wn(1,n)),e.max=(n,r)=>e.check(xl(n,r)),e.length=(n,r)=>e.check(kl(n,r)),e.unwrap=()=>e.element});function R(e,t){return Wh(Lf,e,t)}const Sl=A("ZodObject",(e,t)=>{Zp.init(e,t),ve.init(e,t),fe(e,"shape",()=>t.shape),e.keyof=()=>X(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ze()}),e.loose=()=>e.clone({...e._zod.def,catchall:ze()}),e.strict=()=>e.clone({...e._zod.def,catchall:zf()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>ud(e,n),e.merge=n=>cd(e,n),e.pick=n=>sd(e,n),e.omit=n=>ld(e,n),e.partial=(...n)=>dd(Cl,e,n[0]),e.required=(...n)=>pd(Al,e,n[0])});function d(e,t){const n={type:"object",get shape(){return lr(this,"shape",{...e}),this.shape},...q(t)};return new Sl(n)}function Br(e,t){return new Sl({type:"object",get shape(){return lr(this,"shape",{...e}),this.shape},catchall:ze(),...q(t)})}const El=A("ZodUnion",(e,t)=>{bl.init(e,t),ve.init(e,t),e.options=t.options});function ee(e,t){return new El({type:"union",options:e,...q(t)})}const Df=A("ZodDiscriminatedUnion",(e,t)=>{El.init(e,t),jp.init(e,t)});function se(e,t,n){return new Df({type:"union",options:t,discriminator:e,...q(n)})}const Zf=A("ZodIntersection",(e,t)=>{Up.init(e,t),ve.init(e,t)});function jf(e,t){return new Zf({type:"intersection",left:e,right:t})}const Uf=A("ZodTuple",(e,t)=>{Bp.init(e,t),ve.init(e,t),e.rest=n=>e.clone({...e._zod.def,rest:n})});function Vr(e,t,n){const r=t instanceof _e,o=r?n:t,i=r?t:null;return new Uf({type:"tuple",items:e,rest:i,...q(o)})}const Bf=A("ZodRecord",(e,t)=>{Vp.init(e,t),ve.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Se(e,t,n){return new Bf({type:"record",keyType:e,valueType:t,...q(n)})}const Fr=A("ZodEnum",(e,t)=>{Fp.init(e,t),ve.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{const i={};for(const a of r)if(n.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Fr({...t,checks:[],...q(o),entries:i})},e.exclude=(r,o)=>{const i={...t.entries};for(const a of r)if(n.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new Fr({...t,checks:[],...q(o),entries:i})}});function X(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Fr({type:"enum",entries:n,...q(t)})}const Vf=A("ZodLiteral",(e,t)=>{qp.init(e,t),ve.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function h(e,t){return new Vf({type:"literal",values:Array.isArray(e)?e:[e],...q(t)})}const Ff=A("ZodTransform",(e,t)=>{Gp.init(e,t),ve.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=i=>{if(typeof i=="string")n.issues.push(wn(i,n.value,t));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),n.issues.push(wn(a))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n)):(n.value=o,n)}});function qf(e){return new Ff({type:"transform",transform:e})}const Cl=A("ZodOptional",(e,t)=>{Hp.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Hi(e){return new Cl({type:"optional",innerType:e})}const Gf=A("ZodNullable",(e,t)=>{Wp.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Wi(e){return new Gf({type:"nullable",innerType:e})}const Hf=A("ZodDefault",(e,t)=>{Jp.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Wf(e,t){return new Hf({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Jf=A("ZodPrefault",(e,t)=>{Kp.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Kf(e,t){return new Jf({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const Al=A("ZodNonOptional",(e,t)=>{Yp.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Yf(e,t){return new Al({type:"nonoptional",innerType:e,...q(t)})}const Xf=A("ZodCatch",(e,t)=>{Xp.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Qf(e,t){return new Xf({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const em=A("ZodPipe",(e,t)=>{Qp.init(e,t),ve.init(e,t),e.in=t.in,e.out=t.out});function Ji(e,t){return new em({type:"pipe",in:e,out:t})}const tm=A("ZodReadonly",(e,t)=>{eh.init(e,t),ve.init(e,t)});function nm(e){return new tm({type:"readonly",innerType:e})}const rm=A("ZodLazy",(e,t)=>{th.init(e,t),ve.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Ol(e){return new rm({type:"lazy",getter:e})}const _o=A("ZodCustom",(e,t)=>{nh.init(e,t),ve.init(e,t)});function om(e){const t=new Ve({check:"custom"});return t._zod.check=e,t}function im(e,t){return Jh(_o,e??(()=>!0),t)}function am(e,t={}){return Kh(_o,e,t)}function sm(e){const t=om(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(wn(r,n.value,t._zod.def));else{const o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(wn(o))}},e(n.value,n)));return t}function Jn(e,t={error:`Input not instance of ${e.name}`}){const n=new _o({type:"custom",check:"custom",fn:r=>r instanceof e,abort:!0,...q(t)});return n._zod.bag.Class=e,n}function lm(e){return $h(mo,e)}var pe;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const a of o)i[a]=a;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),a={};for(const s of i)a[s]=o[s];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},e.find=(o,i)=>{for(const a of o)if(i(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(pe||(pe={}));var Ki;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ki||(Ki={}));const F=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kt=e=>{switch(typeof e){case"undefined":return F.undefined;case"string":return F.string;case"number":return Number.isNaN(e)?F.nan:F.number;case"boolean":return F.boolean;case"function":return F.function;case"bigint":return F.bigint;case"symbol":return F.symbol;case"object":return Array.isArray(e)?F.array:e===null?F.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?F.promise:typeof Map<"u"&&e instanceof Map?F.map:typeof Set<"u"&&e instanceof Set?F.set:typeof Date<"u"&&e instanceof Date?F.date:F.object;default:return F.unknown}},P=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class _t extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let s=r,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(n(a))):s[c]=s[c]||{_errors:[]},s=s[c],l++}}};return o(this),r}static assert(t){if(!(t instanceof _t))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const o of this.issues)if(o.path.length>0){const i=o.path[0];n[i]=n[i]||[],n[i].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}_t.create=e=>new _t(e);const qr=(e,t)=>{let n;switch(e.code){case P.invalid_type:e.received===F.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,pe.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${pe.joinValues(e.keys,", ")}`;break;case P.invalid_union:n="Invalid input";break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${pe.joinValues(e.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${pe.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:n="Invalid function arguments";break;case P.invalid_return_type:n="Invalid function return type";break;case P.invalid_date:n="Invalid date";break;case P.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:pe.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case P.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case P.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case P.custom:n="Invalid input";break;case P.invalid_intersection_types:n="Intersection results could not be merged";break;case P.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:n="Number must be finite";break;default:n=t.defaultError,pe.assertNever(e)}return{message:n}};let um=qr;function cm(){return um}const dm=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let s="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)s=c(a,{data:t,defaultError:s}).message;return{...o,path:i,message:s}};function U(e,t){const n=cm(),r=dm({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===qr?void 0:qr].filter(o=>!!o)});e.common.issues.push(r)}class Je{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Q;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n){const i=await o.key,a=await o.value;r.push({key:i,value:a})}return Je.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return Q;i.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:t.value,value:r}}}const Q=Object.freeze({status:"aborted"}),fn=e=>({status:"dirty",value:e}),tt=e=>({status:"valid",value:e}),Yi=e=>e.status==="aborted",Xi=e=>e.status==="dirty",Qt=e=>e.status==="valid",Kn=e=>typeof Promise<"u"&&e instanceof Promise;var G;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(G||(G={}));class Nt{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Qi=(e,t)=>{if(Qt(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new _t(e.common.issues);return this._error=n,this._error}}};function ae(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,s)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??r??s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:l??n??s.defaultError}},description:o}}class ce{get description(){return this._def.description}_getType(t){return kt(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Je,ctx:{common:t.parent.common,data:t.data,parsedType:kt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Kn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kt(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Qi(r,o)}"~validate"(t){var r,o;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kt(t)};if(!this["~standard"].async)try{const i=this._parseSync({data:t,path:[],parent:n});return Qt(i)?{value:i.value}:{issues:n.common.issues}}catch(i){(o=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(i=>Qt(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kt(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(Kn(o)?o:Promise.resolve(o));return Qi(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const a=t(o),s=()=>i.addIssue({code:P.custom,...r(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new nn({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Ct.create(this,this._def)}nullable(){return rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dt.create(this)}promise(){return er.create(this,this._def)}or(t){return Xn.create([this,t],this._def)}and(t){return Qn.create(this,t,this._def)}transform(t){return new nn({...ae(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Hr({...ae(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Pm({typeName:M.ZodBranded,type:this,...ae(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Wr({...ae(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return go.create(this,t)}readonly(){return Jr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const pm=/^c[^\s-]{8,}$/i,hm=/^[0-9a-z]+$/,fm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mm=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,_m=/^[a-z0-9_-]{21}$/i,gm=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ym=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,vm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,bm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Tr;const wm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xm=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,km=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Im=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Tm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$l="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Em=new RegExp(`^${$l}$`);function Nl(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Cm(e){return new RegExp(`^${Nl(e)}$`)}function Am(e){let t=`${$l}T${Nl(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Om(e,t){return!!((t==="v4"||!t)&&wm.test(e)||(t==="v6"||!t)&&km.test(e))}function $m(e,t){if(!gm.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Nm(e,t){return!!((t==="v4"||!t)&&xm.test(e)||(t==="v6"||!t)&&Im.test(e))}class Tt extends ce{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==F.string){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_type,expected:F.string,received:i.parsedType}),Q}const r=new Je;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=t.data.length>i.value,s=t.data.length<i.value;(a||s)&&(o=this._getOrReturnCtx(t,o),a?U(o,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&U(o,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")vm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"email",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Tr||(Tr=new RegExp(bm,"u")),Tr.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"emoji",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")mm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"uuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")_m.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"nanoid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")pm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")hm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cuid2",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")fm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ulid",code:P.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),U(o,{validation:"url",code:P.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"regex",code:P.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Am(i).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Em.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Cm(i).test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{code:P.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?ym.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"duration",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Om(t.data,i.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"ip",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?$m(t.data,i.alg)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"jwt",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Nm(t.data,i.version)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"cidr",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Tm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64",code:P.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Sm.test(t.data)||(o=this._getOrReturnCtx(t,o),U(o,{validation:"base64url",code:P.invalid_string,message:i.message}),r.dirty()):pe.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:P.invalid_string,...G.errToObj(r)})}_addCheck(t){return new Tt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...G.errToObj(t)})}url(t){return this._addCheck({kind:"url",...G.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...G.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...G.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...G.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...G.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...G.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...G.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...G.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...G.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...G.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...G.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...G.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...G.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...G.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...G.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...G.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...G.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...G.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...G.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...G.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...G.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...G.errToObj(n)})}nonempty(t){return this.min(1,G.errToObj(t))}trim(){return new Tt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Tt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Tt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Tt.create=e=>new Tt({checks:[],typeName:M.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...ae(e)});function Rm(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return i%a/10**o}class en extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==F.number){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_type,expected:F.number,received:i.parsedType}),Q}let r;const o=new Je;for(const i of this._def.checks)i.kind==="int"?pe.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:P.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Rm(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),U(r,{code:P.not_finite,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,G.toString(n))}gt(t,n){return this.setLimit("min",t,!1,G.toString(n))}lte(t,n){return this.setLimit("max",t,!0,G.toString(n))}lt(t,n){return this.setLimit("max",t,!1,G.toString(n))}setLimit(t,n,r,o){return new en({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:G.toString(o)}]})}_addCheck(t){return new en({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:G.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:G.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:G.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&pe.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}en.create=e=>new en({checks:[],typeName:M.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...ae(e)});class xn extends ce{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==F.bigint)return this._getInvalidInput(t);let r;const o=new Je;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),U(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return U(n,{code:P.invalid_type,expected:F.bigint,received:n.parsedType}),Q}gte(t,n){return this.setLimit("min",t,!0,G.toString(n))}gt(t,n){return this.setLimit("min",t,!1,G.toString(n))}lte(t,n){return this.setLimit("max",t,!0,G.toString(n))}lt(t,n){return this.setLimit("max",t,!1,G.toString(n))}setLimit(t,n,r,o){return new xn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:G.toString(o)}]})}_addCheck(t){return new xn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:G.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}xn.create=e=>new xn({checks:[],typeName:M.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...ae(e)});class ea extends ce{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==F.boolean){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.boolean,received:r.parsedType}),Q}return tt(t.data)}}ea.create=e=>new ea({typeName:M.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...ae(e)});class Yn extends ce{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==F.date){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_type,expected:F.date,received:i.parsedType}),Q}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return U(i,{code:P.invalid_date}),Q}const r=new Je;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(o=this._getOrReturnCtx(t,o),U(o,{code:P.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):pe.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Yn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:G.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:G.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}Yn.create=e=>new Yn({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:M.ZodDate,...ae(e)});class ta extends ce{_parse(t){if(this._getType(t)!==F.symbol){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.symbol,received:r.parsedType}),Q}return tt(t.data)}}ta.create=e=>new ta({typeName:M.ZodSymbol,...ae(e)});class na extends ce{_parse(t){if(this._getType(t)!==F.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.undefined,received:r.parsedType}),Q}return tt(t.data)}}na.create=e=>new na({typeName:M.ZodUndefined,...ae(e)});class ra extends ce{_parse(t){if(this._getType(t)!==F.null){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.null,received:r.parsedType}),Q}return tt(t.data)}}ra.create=e=>new ra({typeName:M.ZodNull,...ae(e)});class oa extends ce{constructor(){super(...arguments),this._any=!0}_parse(t){return tt(t.data)}}oa.create=e=>new oa({typeName:M.ZodAny,...ae(e)});class ia extends ce{constructor(){super(...arguments),this._unknown=!0}_parse(t){return tt(t.data)}}ia.create=e=>new ia({typeName:M.ZodUnknown,...ae(e)});class Rt extends ce{_parse(t){const n=this._getOrReturnCtx(t);return U(n,{code:P.invalid_type,expected:F.never,received:n.parsedType}),Q}}Rt.create=e=>new Rt({typeName:M.ZodNever,...ae(e)});class aa extends ce{_parse(t){if(this._getType(t)!==F.undefined){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.void,received:r.parsedType}),Q}return tt(t.data)}}aa.create=e=>new aa({typeName:M.ZodVoid,...ae(e)});class dt extends ce{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==F.array)return U(n,{code:P.invalid_type,expected:F.array,received:n.parsedType}),Q;if(o.exactLength!==null){const a=n.data.length>o.exactLength.value,s=n.data.length<o.exactLength.value;(a||s)&&(U(n,{code:a?P.too_big:P.too_small,minimum:s?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(U(n,{code:P.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(U(n,{code:P.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,s)=>o.type._parseAsync(new Nt(n,a,n.path,s)))).then(a=>Je.mergeArray(r,a));const i=[...n.data].map((a,s)=>o.type._parseSync(new Nt(n,a,n.path,s)));return Je.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new dt({...this._def,minLength:{value:t,message:G.toString(n)}})}max(t,n){return new dt({...this._def,maxLength:{value:t,message:G.toString(n)}})}length(t,n){return new dt({...this._def,exactLength:{value:t,message:G.toString(n)}})}nonempty(t){return this.min(1,t)}}dt.create=(e,t)=>new dt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ae(t)});function Kt(e){if(e instanceof Ae){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Ct.create(Kt(r))}return new Ae({...e._def,shape:()=>t})}else return e instanceof dt?new dt({...e._def,type:Kt(e.element)}):e instanceof Ct?Ct.create(Kt(e.unwrap())):e instanceof rn?rn.create(Kt(e.unwrap())):e instanceof Ut?Ut.create(e.items.map(t=>Kt(t))):e}class Ae extends ce{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=pe.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==F.object){const c=this._getOrReturnCtx(t);return U(c,{code:P.invalid_type,expected:F.object,received:c.parsedType}),Q}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Rt&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||s.push(c);const l=[];for(const c of a){const p=i[c],g=o.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new Nt(o,g,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Rt){const c=this._def.unknownKeys;if(c==="passthrough")for(const p of s)l.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(c==="strict")s.length>0&&(U(o,{code:P.unrecognized_keys,keys:s}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const p of s){const g=o.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new Nt(o,g,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const p of l){const g=await p.key,x=await p.value;c.push({key:g,value:x,alwaysSet:p.alwaysSet})}return c}).then(c=>Je.mergeObjectSync(r,c)):Je.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return G.errToObj,new Ae({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var i,a;const o=((a=(i=this._def).errorMap)==null?void 0:a.call(i,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:G.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ae({...this._def,unknownKeys:"strip"})}passthrough(){return new Ae({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ae({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ae({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:M.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Ae({...this._def,catchall:t})}pick(t){const n={};for(const r of pe.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Ae({...this._def,shape:()=>n})}omit(t){const n={};for(const r of pe.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new Ae({...this._def,shape:()=>n})}deepPartial(){return Kt(this)}partial(t){const n={};for(const r of pe.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new Ae({...this._def,shape:()=>n})}required(t){const n={};for(const r of pe.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ct;)i=i._def.innerType;n[r]=i}return new Ae({...this._def,shape:()=>n})}keyof(){return Rl(pe.objectKeys(this.shape))}}Ae.create=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strip",catchall:Rt.create(),typeName:M.ZodObject,...ae(t)});Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:Rt.create(),typeName:M.ZodObject,...ae(t)});Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:Rt.create(),typeName:M.ZodObject,...ae(t)});class Xn extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const s of i)if(s.result.status==="valid")return s.result;for(const s of i)if(s.result.status==="dirty")return n.common.issues.push(...s.ctx.common.issues),s.result;const a=i.map(s=>new _t(s.ctx.common.issues));return U(n,{code:P.invalid_union,unionErrors:a}),Q}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(o);{let i;const a=[];for(const l of r){const c={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const s=a.map(l=>new _t(l));return U(n,{code:P.invalid_union,unionErrors:s}),Q}}get options(){return this._def.options}}Xn.create=(e,t)=>new Xn({options:e,typeName:M.ZodUnion,...ae(t)});function Gr(e,t){const n=kt(e),r=kt(t);if(e===t)return{valid:!0,data:e};if(n===F.object&&r===F.object){const o=pe.objectKeys(t),i=pe.objectKeys(e).filter(s=>o.indexOf(s)!==-1),a={...e,...t};for(const s of i){const l=Gr(e[s],t[s]);if(!l.valid)return{valid:!1};a[s]=l.data}return{valid:!0,data:a}}else if(n===F.array&&r===F.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i<e.length;i++){const a=e[i],s=t[i],l=Gr(a,s);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===F.date&&r===F.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Qn extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=(i,a)=>{if(Yi(i)||Yi(a))return Q;const s=Gr(i.value,a.value);return s.valid?((Xi(i)||Xi(a))&&n.dirty(),{status:n.value,value:s.data}):(U(r,{code:P.invalid_intersection_types}),Q)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Qn.create=(e,t,n)=>new Qn({left:e,right:t,typeName:M.ZodIntersection,...ae(n)});class Ut extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==F.array)return U(r,{code:P.invalid_type,expected:F.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return U(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&r.data.length>this._def.items.length&&(U(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,s)=>{const l=this._def.items[s]||this._def.rest;return l?l._parse(new Nt(r,a,r.path,s)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Je.mergeArray(n,a)):Je.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ut({...this._def,rest:t})}}Ut.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ut({items:e,typeName:M.ZodTuple,rest:null,...ae(t)})};class sa extends ce{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==F.map)return U(r,{code:P.invalid_type,expected:F.map,received:r.parsedType}),Q;const o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([s,l],c)=>({key:o._parse(new Nt(r,s,r.path,[c,"key"])),value:i._parse(new Nt(r,l,r.path,[c,"value"]))}));if(r.common.async){const s=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,p=await l.value;if(c.status==="aborted"||p.status==="aborted")return Q;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(c.value,p.value)}return{status:n.value,value:s}})}else{const s=new Map;for(const l of a){const c=l.key,p=l.value;if(c.status==="aborted"||p.status==="aborted")return Q;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),s.set(c.value,p.value)}return{status:n.value,value:s}}}}sa.create=(e,t,n)=>new sa({valueType:t,keyType:e,typeName:M.ZodMap,...ae(n)});class kn extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==F.set)return U(r,{code:P.invalid_type,expected:F.set,received:r.parsedType}),Q;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(U(r,{code:P.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(U(r,{code:P.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function a(l){const c=new Set;for(const p of l){if(p.status==="aborted")return Q;p.status==="dirty"&&n.dirty(),c.add(p.value)}return{status:n.value,value:c}}const s=[...r.data.values()].map((l,c)=>i._parse(new Nt(r,l,r.path,c)));return r.common.async?Promise.all(s).then(l=>a(l)):a(s)}min(t,n){return new kn({...this._def,minSize:{value:t,message:G.toString(n)}})}max(t,n){return new kn({...this._def,maxSize:{value:t,message:G.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}kn.create=(e,t)=>new kn({valueType:e,minSize:null,maxSize:null,typeName:M.ZodSet,...ae(t)});class la extends ce{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}la.create=(e,t)=>new la({getter:e,typeName:M.ZodLazy,...ae(t)});class ua extends ce{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return U(n,{received:n.data,code:P.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:t.data}}get value(){return this._def.value}}ua.create=(e,t)=>new ua({value:e,typeName:M.ZodLiteral,...ae(t)});function Rl(e,t){return new tn({values:e,typeName:M.ZodEnum,...ae(t)})}class tn extends ce{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{expected:pe.joinValues(r),received:n.parsedType,code:P.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return U(n,{received:n.data,code:P.invalid_enum_value,options:r}),Q}return tt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return tn.create(t,{...this._def,...n})}exclude(t,n=this._def){return tn.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}tn.create=Rl;class ca extends ce{_parse(t){const n=pe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==F.string&&r.parsedType!==F.number){const o=pe.objectValues(n);return U(r,{expected:pe.joinValues(o),received:r.parsedType,code:P.invalid_type}),Q}if(this._cache||(this._cache=new Set(pe.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=pe.objectValues(n);return U(r,{received:r.data,code:P.invalid_enum_value,options:o}),Q}return tt(t.data)}get enum(){return this._def.values}}ca.create=(e,t)=>new ca({values:e,typeName:M.ZodNativeEnum,...ae(t)});class er extends ce{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==F.promise&&n.common.async===!1)return U(n,{code:P.invalid_type,expected:F.promise,received:n.parsedType}),Q;const r=n.parsedType===F.promise?n.data:Promise.resolve(n.data);return tt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}er.create=(e,t)=>new er({type:e,typeName:M.ZodPromise,...ae(t)});class nn extends ce{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:a=>{U(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async s=>{if(n.value==="aborted")return Q;const l=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});return l.status==="aborted"?Q:l.status==="dirty"||n.value==="dirty"?fn(l.value):l});{if(n.value==="aborted")return Q;const s=this._def.schema._parseSync({data:a,path:r.path,parent:r});return s.status==="aborted"?Q:s.status==="dirty"||n.value==="dirty"?fn(s.value):s}}if(o.type==="refinement"){const a=s=>{const l=o.refinement(s,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Q:(s.status==="dirty"&&n.dirty(),a(s.value),{status:n.value,value:s.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>s.status==="aborted"?Q:(s.status==="dirty"&&n.dirty(),a(s.value).then(()=>({status:n.value,value:s.value}))))}if(o.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Qt(a))return Q;const s=o.transform(a.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Qt(a)?Promise.resolve(o.transform(a.value,i)).then(s=>({status:n.value,value:s})):Q);pe.assertNever(o)}}nn.create=(e,t,n)=>new nn({schema:e,typeName:M.ZodEffects,effect:t,...ae(n)});nn.createWithPreprocess=(e,t,n)=>new nn({schema:t,effect:{type:"preprocess",transform:e},typeName:M.ZodEffects,...ae(n)});class Ct extends ce{_parse(t){return this._getType(t)===F.undefined?tt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Ct.create=(e,t)=>new Ct({innerType:e,typeName:M.ZodOptional,...ae(t)});class rn extends ce{_parse(t){return this._getType(t)===F.null?tt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}rn.create=(e,t)=>new rn({innerType:e,typeName:M.ZodNullable,...ae(t)});class Hr extends ce{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===F.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Hr.create=(e,t)=>new Hr({innerType:e,typeName:M.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ae(t)});class Wr extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Kn(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new _t(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Wr.create=(e,t)=>new Wr({innerType:e,typeName:M.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ae(t)});class da extends ce{_parse(t){if(this._getType(t)!==F.nan){const r=this._getOrReturnCtx(t);return U(r,{code:P.invalid_type,expected:F.nan,received:r.parsedType}),Q}return{status:"valid",value:t.data}}}da.create=e=>new da({typeName:M.ZodNaN,...ae(e)});class Pm extends ce{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class go extends ce{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Q:i.status==="dirty"?(n.dirty(),fn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Q:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new go({in:t,out:n,typeName:M.ZodPipeline})}}class Jr extends ce{_parse(t){const n=this._def.innerType._parse(t),r=o=>(Qt(o)&&(o.value=Object.freeze(o.value)),o);return Kn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}}Jr.create=(e,t)=>new Jr({innerType:e,typeName:M.ZodReadonly,...ae(t)});var M;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(M||(M={}));const ye=Tt.create,ct=en.create;Rt.create;const At=dt.create,at=Ae.create,yo=Xn.create;Qn.create;Ut.create;const dr=tn.create;er.create;Ct.create;rn.create;function Le(...e){return e.reduce((t,n)=>({...t,...n??{}}),{})}async function Mm(e,t){if(e==null)return Promise.resolve();const n=t==null?void 0:t.abortSignal;return new Promise((r,o)=>{if(n!=null&&n.aborted){o(pa());return}const i=setTimeout(()=>{a(),r()},e),a=()=>{clearTimeout(i),n==null||n.removeEventListener("abort",s)},s=()=>{a(),o(pa())};n==null||n.addEventListener("abort",s)})}function pa(){return new DOMException("Delay was aborted","AbortError")}function sn(e){return Object.fromEntries([...e.headers])}var Pl="AI_DownloadError",Ml=`vercel.ai.error.${Pl}`,zm=Symbol.for(Ml),ha,fa,qe=class extends(fa=te,ha=zm,fa){constructor({url:e,statusCode:t,statusText:n,cause:r,message:o=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:Pl,message:o,cause:r}),this[ha]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return te.hasMarker(e,Ml)}};async function vo(e){var t;try{await((t=e.body)==null?void 0:t.cancel())}catch{}}function Lm(e=globalThis){return e.window!=null}function Dm(e){let t;try{t=new URL(e)}catch{throw new qe({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new qe({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const n=t.hostname.toLowerCase().replace(/\.+$/,"");if(!n)throw new qe({url:e,message:"URL must have a hostname"});if(n==="localhost"||n.endsWith(".local")||n.endsWith(".localhost"))throw new qe({url:e,message:`URL with hostname ${n} is not allowed`});if(n.startsWith("[")&&n.endsWith("]")){const r=n.slice(1,-1);if(jm(r))throw new qe({url:e,message:`URL with IPv6 address ${n} is not allowed`});return}if(zl(n)){if(Ll(n))throw new qe({url:e,message:`URL with IP address ${n} is not allowed`});return}}function zl(e){const t=e.split(".");return t.length!==4?!1:t.every(n=>{const r=Number(n);return Number.isInteger(r)&&r>=0&&r<=255&&String(r)===n})}function Ll(e){const t=e.split(".").map(Number),[n,r,o]=t;return n===0||n===10||n===100&&r>=64&&r<=127||n===127||n===169&&r===254||n===172&&r>=16&&r<=31||n===192&&r===0&&o===0||n===192&&r===168||n===198&&(r===18||r===19)||n>=240}function Zm(e){let t=e.toLowerCase();const n=t.indexOf("%");n!==-1&&(t=t.slice(0,n));const r=t.split("::");if(r.length>2)return null;const o=a=>{if(a==="")return[];const s=[],l=a.split(":");for(let c=0;c<l.length;c++){const p=l[c];if(p.includes(".")){if(c!==l.length-1||!zl(p))return null;const[g,x,T,I]=p.split(".").map(Number);s.push(g<<8|x,T<<8|I);continue}if(!/^[0-9a-f]{1,4}$/.test(p))return null;s.push(parseInt(p,16))}return s},i=o(r[0]);if(i===null)return null;if(r.length===2){const a=o(r[1]);if(a===null)return null;const s=8-i.length-a.length;return s<0?null:[...i,...new Array(s).fill(0),...a]}return i.length===8?i:null}function jm(e){const t=Zm(e);if(t===null)return!0;const n=o=>t.slice(0,o).every(i=>i===0);if(n(7)&&(t[7]===0||t[7]===1)||(t[0]&65024)===64512||(t[0]&65472)===65152||(t[0]&65472)===65216||(t[0]&65280)===65280)return!0;if(n(6)||n(5)&&t[5]===65535||n(4)&&t[4]===65535&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0||t[0]===100&&t[1]===65435&&t[2]===1){const o=t[6]>>8&255,i=t[6]&255,a=t[7]>>8&255,s=t[7]&255;return Ll(`${o}.${i}.${a}.${s}`)}return!1}var Um=10;async function Bm({url:e,headers:t,abortSignal:n,maxRedirects:r=Um}){const o={signal:n};t!==void 0&&(o.headers=t);let i=e;for(let a=0;a<=r;a++){Dm(i);const s=await fetch(i,{...o,redirect:"manual"});if(s.type==="opaqueredirect"){if(!Lm())throw new qe({url:e,message:`Redirect from ${i} could not be validated and was blocked`});return await fetch(i,{...o,redirect:"follow"})}const l=s.headers.get("location");if(s.status>=300&&s.status<400&&l){await vo(s),i=new URL(l,i).toString();continue}return s}throw new qe({url:e,message:`Too many redirects (max ${r})`})}var Dl=2*1024*1024*1024;async function Zl({response:e,url:t,maxBytes:n=Dl}){const r=e.headers.get("content-length");if(r!=null){const p=parseInt(r,10);if(!isNaN(p)&&p>n)throw await vo(e),new qe({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes (Content-Length: ${p}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const i=o.getReader(),a=[];let s=0;try{for(;;){const{done:p,value:g}=await i.read();if(p)break;if(s+=g.length,s>n)throw new qe({url:t,message:`Download of ${t} exceeded maximum size of ${n} bytes.`});a.push(g)}}finally{try{await i.cancel()}finally{i.releaseLock()}}const l=new Uint8Array(s);let c=0;for(const p of a)l.set(p,c),c+=p.length;return l}var $n=({prefix:e,size:t=16,alphabet:n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:r="-"}={})=>{const o=()=>{const i=n.length,a=new Array(t);for(let s=0;s<t;s++)a[s]=n[Math.random()*i|0];return a.join("")};if(e==null)return o;if(n.includes(r))throw new Us({argument:"separator",message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${o()}`},Ge=$n();function jl(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function on(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var Vm=["fetch failed","failed to fetch"];function Ul({error:e,url:t,requestBodyValues:n}){if(on(e))return e;if(e instanceof TypeError&&Vm.includes(e.message.toLowerCase())){const r=e.cause;if(r!=null)return new $e({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function bo(e=globalThis){var t,n,r;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(r=(n=e.process)==null?void 0:n.versions)!=null&&r.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Fm(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((n,r)=>{t[r.toLowerCase()]=n});else{Array.isArray(e)||(e=Object.entries(e));for(const[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}function qt(e,...t){const n=new Headers(Fm(e)),r=n.get("user-agent")||"";return n.set("user-agent",[r,...t].filter(Boolean).join(" ")),Object.fromEntries(n.entries())}var Bl="3.0.28",qm=()=>globalThis.fetch,tr=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:o,fetch:i=qm()})=>{try{const a=await i(e,{method:"GET",headers:qt(t,`ai-sdk/provider-utils/${Bl}`,bo()),signal:o}),s=sn(a);if(!a.ok){let l;try{l=await r({response:a,url:e,requestBodyValues:{}})}catch(c){throw on(c)||$e.isInstance(c)?c:new $e({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw l.value}try{return await n({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(on(l)||$e.isInstance(l))?l:new $e({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(a){throw Ul({error:a,url:e,requestBodyValues:{}})}};function Gm({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([r,o])=>{const i=r.toLowerCase();return i==="*"||i==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:i.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:r})=>e.startsWith(r)).flatMap(({regexes:r})=>r).some(r=>r.test(t))}function Vl({apiKey:e,environmentVariableName:t,apiKeyParameterName:n="apiKey",description:r}){if(typeof e=="string")return e;if(e!=null)throw new zn({message:`${r} API key must be a string.`});if(typeof process>"u")throw new zn({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new zn({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new zn({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Zt({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function Hm(e){var t;const[n,r=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[r])!=null?t:r}var Wm=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,Jm=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function ma(e){const t=JSON.parse(e);return t===null||typeof t!="object"||Wm.test(e)===!1&&Jm.test(e)===!1?t:Km(t)}function Km(e){let t=[e];for(;t.length;){const n=t;t=[];for(const r of n){if(Object.prototype.hasOwnProperty.call(r,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(r,"constructor")&&r.constructor!==null&&typeof r.constructor=="object"&&Object.prototype.hasOwnProperty.call(r.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in r){const i=r[o];i&&typeof i=="object"&&t.push(i)}}}return e}function wo(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return ma(e)}try{return ma(e)}finally{Error.stackTraceLimit=t}}var nr=Symbol.for("vercel.ai.validator");function Ym(e){return{[nr]:!0,validate:e}}function Xm(e){return typeof e=="object"&&e!==null&&nr in e&&e[nr]===!0&&"validate"in e}function Ee(e){let t;return()=>(t==null&&(t=e()),t)}function Qm(e){return Xm(e)?e:typeof e=="function"?e():e_(e)}function e_(e){return Ym(async t=>{const n=await e["~standard"].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new vn({value:t,cause:n.issues})}})}async function Me({value:e,schema:t}){const n=await gt({value:e,schema:t});if(!n.success)throw vn.wrap({value:e,cause:n.error});return n.value}async function gt({value:e,schema:t}){const n=Qm(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const r=await n.validate(e);return r.success?{success:!0,value:r.value,rawValue:e}:{success:!1,error:vn.wrap({value:e,cause:r.error}),rawValue:e}}catch(r){return{success:!1,error:vn.wrap({value:e,cause:r}),rawValue:e}}}async function t_({text:e,schema:t}){try{const n=wo(e);return t==null?n:Me({value:n,schema:t})}catch(n){throw qn.isInstance(n)||vn.isInstance(n)?n:new qn({text:e,cause:n})}}async function Bt({text:e,schema:t}){try{const n=wo(e);return t==null?{success:!0,value:n,rawValue:n}:await gt({value:n,schema:t})}catch(n){return{success:!1,error:qn.isInstance(n)?n:new qn({text:e,cause:n}),rawValue:void 0}}}function _a(e){try{return wo(e),!0}catch{return!1}}function n_({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new ed).pipeThrough(new TransformStream({async transform({data:n},r){n!=="[DONE]"&&r.enqueue(await Bt({text:n,schema:t}))}}))}async function We({provider:e,providerOptions:t,schema:n}){if((t==null?void 0:t[e])==null)return;const r=await gt({value:t[e],schema:n});if(!r.success)throw new Us({argument:"providerOptions",message:`invalid ${e} provider options`,cause:r.error});return r.value}var r_=()=>globalThis.fetch,De=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a})=>Fl({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a}),o_=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a})=>Fl({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:o,abortSignal:i,fetch:a}),Fl=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:o,abortSignal:i,fetch:a=r_()})=>{try{const s=await a(e,{method:"POST",headers:qt(t,`ai-sdk/provider-utils/${Bl}`,bo()),body:n.content,signal:i}),l=sn(s);if(!s.ok){let c;try{c=await o({response:s,url:e,requestBodyValues:n.values})}catch(p){throw on(p)||$e.isInstance(p)?p:new $e({message:"Failed to process error response",cause:p,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:n.values})}throw c.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(c){throw c instanceof Error&&(on(c)||$e.isInstance(c))?c:new $e({message:"Failed to process successful response",cause:c,statusCode:s.status,url:e,responseHeaders:l,requestBodyValues:n.values})}}catch(s){throw Ul({error:s,url:e,requestBodyValues:n.values})}};function yt({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:n,outputSchema:o,execute:r,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l})}function Ye({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l,...c})=>({type:"provider-defined",id:e,name:t,args:c,inputSchema:n,outputSchema:r,execute:o,toModelOutput:i,onInputStart:a,onInputDelta:s,onInputAvailable:l})}async function Ue(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var i_=new TextDecoder;async function ql({response:e,url:t}){return i_.decode(await Zl({response:e,url:t}))}var pt=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:o,requestBodyValues:i})=>{const a=await ql({response:r,url:o}),s=sn(r);if(a.trim()==="")return{responseHeaders:s,value:new $e({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:s,responseBody:a,isRetryable:n==null?void 0:n(r)})};try{const l=await t_({text:a,schema:e});return{responseHeaders:s,value:new $e({message:t(l),url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:s,responseBody:a,data:l,isRetryable:n==null?void 0:n(r,l)})}}catch{return{responseHeaders:s,value:new $e({message:r.statusText,url:o,requestBodyValues:i,statusCode:r.status,responseHeaders:s,responseBody:a,isRetryable:n==null?void 0:n(r)})}}},Nn=e=>async({response:t})=>{const n=sn(t);if(t.body==null)throw new Uc({});return{responseHeaders:n,value:n_({stream:t.body,schema:e})}},Be=e=>async({response:t,url:n,requestBodyValues:r})=>{const o=await ql({response:t,url:n}),i=await Bt({text:o,schema:e}),a=sn(t);if(!i.success)throw new $e({message:"Invalid JSON response",cause:i.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:n,requestBodyValues:r});return{responseHeaders:a,value:i.value,rawValue:i.rawValue}},a_=()=>async({response:e,url:t,requestBodyValues:n})=>{const r=sn(e);if(!e.body)throw new $e({message:"Response body is empty",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(o)}}catch(o){throw new $e({message:"Failed to read response as array buffer",url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:o})}},Kr=Symbol.for("vercel.ai.schema");function K(e){let t;return()=>(t==null&&(t=e()),t)}function xo(e,{validate:t}={}){return{[Kr]:!0,_type:void 0,[nr]:!0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Vn(e){if(e.type==="object"){e.additionalProperties=!1;const t=e.properties;if(t!=null)for(const n in t)t[n]=Vn(t[n])}return e.type==="array"&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(t=>Vn(t)):e.items=Vn(e.items)),e}var s_=Symbol("Let zodToJsonSchema decide on which parser to use"),ga={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},l_=e=>typeof e=="string"?{...ga,name:e}:{...ga,...e};function Ke(){return{}}function u_(e,t){var n,r,o;const i={type:"array"};return(n=e.type)!=null&&n._def&&((o=(r=e.type)==null?void 0:r._def)==null?void 0:o.typeName)!==M.ZodAny&&(i.items=me(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(i.minItems=e.minLength.value),e.maxLength&&(i.maxItems=e.maxLength.value),e.exactLength&&(i.minItems=e.exactLength.value,i.maxItems=e.exactLength.value),i}function c_(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function d_(){return{type:"boolean"}}function Gl(e,t){return me(e.type._def,t)}var p_=(e,t)=>me(e.innerType._def,t);function Hl(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,i)=>Hl(e,t,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return h_(e)}}var h_=e=>{const t={type:"integer",format:"unix-time"};for(const n of e.checks)switch(n.kind){case"min":t.minimum=n.value;break;case"max":t.maximum=n.value;break}return t};function f_(e,t){return{...me(e.innerType._def,t),default:e.defaultValue()}}function m_(e,t){return t.effectStrategy==="input"?me(e.schema._def,t):Ke()}function __(e){return{type:"string",enum:Array.from(e.values)}}var g_=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function y_(e,t){const n=[me(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),me(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),r=[];return n.forEach(o=>{if(g_(o))r.push(...o.allOf);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...s}=o;i=s}r.push(i)}}),r.length?{allOf:r}:void 0}function v_(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Sr=void 0,ot={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Sr===void 0&&(Sr=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sr),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Wl(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value;break;case"max":n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"email":switch(t.emailStrategy){case"format:email":it(n,"email",r.message,t);break;case"format:idn-email":it(n,"idn-email",r.message,t);break;case"pattern:zod":Pe(n,ot.email,r.message,t);break}break;case"url":it(n,"uri",r.message,t);break;case"uuid":it(n,"uuid",r.message,t);break;case"regex":Pe(n,r.regex,r.message,t);break;case"cuid":Pe(n,ot.cuid,r.message,t);break;case"cuid2":Pe(n,ot.cuid2,r.message,t);break;case"startsWith":Pe(n,RegExp(`^${Er(r.value,t)}`),r.message,t);break;case"endsWith":Pe(n,RegExp(`${Er(r.value,t)}$`),r.message,t);break;case"datetime":it(n,"date-time",r.message,t);break;case"date":it(n,"date",r.message,t);break;case"time":it(n,"time",r.message,t);break;case"duration":it(n,"duration",r.message,t);break;case"length":n.minLength=typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value;break;case"includes":{Pe(n,RegExp(Er(r.value,t)),r.message,t);break}case"ip":{r.version!=="v6"&&it(n,"ipv4",r.message,t),r.version!=="v4"&&it(n,"ipv6",r.message,t);break}case"base64url":Pe(n,ot.base64url,r.message,t);break;case"jwt":Pe(n,ot.jwt,r.message,t);break;case"cidr":{r.version!=="v6"&&Pe(n,ot.ipv4Cidr,r.message,t),r.version!=="v4"&&Pe(n,ot.ipv6Cidr,r.message,t);break}case"emoji":Pe(n,ot.emoji(),r.message,t);break;case"ulid":{Pe(n,ot.ulid,r.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{it(n,"binary",r.message,t);break}case"contentEncoding:base64":{n.contentEncoding="base64";break}case"pattern:zod":{Pe(n,ot.base64,r.message,t);break}}break}case"nanoid":Pe(n,ot.nanoid,r.message,t)}return n}function Er(e,t){return t.patternStrategy==="escape"?w_(e):e}var b_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function w_(e){let t="";for(let n=0;n<e.length;n++)b_.has(e[n])||(t+="\\"),t+=e[n];return t}function it(e,t,n,r){var o;e.format||(o=e.anyOf)!=null&&o.some(i=>i.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function Pe(e,t,n,r){var o;e.pattern||(o=e.allOf)!=null&&o.some(i=>i.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:ya(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=ya(t,r)}function ya(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=r.i?e.source.toLowerCase():e.source;let i="",a=!1,s=!1,l=!1;for(let c=0;c<o.length;c++){if(a){i+=o[c],a=!1;continue}if(r.i){if(s){if(o[c].match(/[a-z]/)){l?(i+=o[c],i+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((n=o[c+2])!=null&&n.match(/[a-z]/))?(i+=o[c],l=!0):i+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){i+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){i+=`(^|(?<=[\r
|
|
40
|
+
]))`;continue}else if(o[c]==="$"){i+=`($|(?=[\r
|
|
41
|
+
]))`;continue}}if(r.s&&o[c]==="."){i+=s?`${o[c]}\r
|
|
42
|
+
`:`[${o[c]}\r
|
|
43
|
+
]`;continue}i+=o[c],o[c]==="\\"?a=!0:s&&o[c]==="]"?s=!1:!s&&o[c]==="["&&(s=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Jl(e,t){var n,r,o,i,a,s;const l={type:"object",additionalProperties:(n=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?n:t.allowedAdditionalProperties};if(((r=e.keyType)==null?void 0:r._def.typeName)===M.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...p}=Wl(e.keyType._def,t);return{...l,propertyNames:p}}else{if(((i=e.keyType)==null?void 0:i._def.typeName)===M.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===M.ZodBranded&&e.keyType._def.type._def.typeName===M.ZodString&&((s=e.keyType._def.type._def.checks)!=null&&s.length)){const{type:c,...p}=Gl(e.keyType._def,t);return{...l,propertyNames:p}}}return l}function x_(e,t){if(t.mapStrategy==="record")return Jl(e,t);const n=me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(),r=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke();return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function k_(e){const t=e.values,r=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(r.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function I_(){return{not:Ke()}}function T_(){return{type:"null"}}var Yr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function S_(e,t){const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in Yr&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((o,i)=>{const a=Yr[i._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((o,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){const o=r.filter((i,a,s)=>s.indexOf(i)===a);return{type:o.length>1?o:o[0],enum:n.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return E_(e,t)}var E_=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,o)=>me(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function C_(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Yr[e.innerType._def.typeName],"null"]};const n=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function A_(e){const t={type:"number"};if(!e.checks)return t;for(const n of e.checks)switch(n.kind){case"int":t.type="integer";break;case"min":n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case"max":n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case"multipleOf":t.multipleOf=n.value;break}return t}function O_(e,t){const n={type:"object",properties:{}},r=[],o=e.shape();for(const a in o){let s=o[a];if(s===void 0||s._def===void 0)continue;const l=N_(s),c=me(s._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(n.properties[a]=c,l||r.push(a))}r.length&&(n.required=r);const i=$_(e,t);return i!==void 0&&(n.additionalProperties=i),n}function $_(e,t){if(e.catchall._def.typeName!=="ZodNever")return me(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function N_(e){try{return e.isOptional()}catch{return!0}}var R_=(e,t)=>{var n;if(t.currentPath.toString()===((n=t.propertyPath)==null?void 0:n.toString()))return me(e.innerType._def,t);const r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke()},r]}:Ke()},P_=(e,t)=>{if(t.pipeStrategy==="input")return me(e.in._def,t);if(t.pipeStrategy==="output")return me(e.out._def,t);const n=me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function M_(e,t){return me(e.type._def,t)}function z_(e,t){const r={type:"array",uniqueItems:!0,items:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function L_(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>me(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>me(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function D_(){return{not:Ke()}}function Z_(){return Ke()}var j_=(e,t)=>me(e.innerType._def,t),U_=(e,t,n)=>{switch(t){case M.ZodString:return Wl(e,n);case M.ZodNumber:return A_(e);case M.ZodObject:return O_(e,n);case M.ZodBigInt:return c_(e);case M.ZodBoolean:return d_();case M.ZodDate:return Hl(e,n);case M.ZodUndefined:return D_();case M.ZodNull:return T_();case M.ZodArray:return u_(e,n);case M.ZodUnion:case M.ZodDiscriminatedUnion:return S_(e,n);case M.ZodIntersection:return y_(e,n);case M.ZodTuple:return L_(e,n);case M.ZodRecord:return Jl(e,n);case M.ZodLiteral:return v_(e);case M.ZodEnum:return __(e);case M.ZodNativeEnum:return k_(e);case M.ZodNullable:return C_(e,n);case M.ZodOptional:return R_(e,n);case M.ZodMap:return x_(e,n);case M.ZodSet:return z_(e,n);case M.ZodLazy:return()=>e.getter()._def;case M.ZodPromise:return M_(e,n);case M.ZodNaN:case M.ZodNever:return I_();case M.ZodEffects:return m_(e,n);case M.ZodAny:return Ke();case M.ZodUnknown:return Z_();case M.ZodDefault:return f_(e,n);case M.ZodBranded:return Gl(e,n);case M.ZodReadonly:return j_(e,n);case M.ZodCatch:return p_(e,n);case M.ZodPipeline:return P_(e,n);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(r=>{})()}},B_=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function me(e,t,n=!1){var r;const o=t.seen.get(e);if(t.override){const l=(r=t.override)==null?void 0:r.call(t,e,t,o,n);if(l!==s_)return l}if(o&&!n){const l=V_(o,t);if(l!==void 0)return l}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const a=U_(e,e.typeName,t),s=typeof a=="function"?me(a(),t):a;if(s&&F_(e,t,s),t.postProcess){const l=t.postProcess(s,e,t);return i.jsonSchema=s,l}return i.jsonSchema=s,s}var V_=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:B_(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ke()):t.$refStrategy==="seen"?Ke():void 0}},F_=(e,t,n)=>(e.description&&(n.description=e.description),n),q_=e=>{const t=l_(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,r],jsonSchema:void 0}]))}},G_=(e,t)=>{var n;const r=q_(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[p,g])=>{var x;return{...c,[p]:(x=me(g._def,{...r,currentPath:[...r.basePath,r.definitionPath,p]},!0))!=null?x:Ke()}},{}):void 0;const i=typeof t=="string"?t:(t==null?void 0:t.nameStrategy)==="title"||t==null?void 0:t.name,a=(n=me(e._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1))!=null?n:Ke(),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(a.title=s);const l=i===void 0?o?{...a,[r.definitionPath]:o}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...o,[i]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},H_=G_;function W_(e,t){var n;const r=(n=void 0)!=null?n:!1;return xo(()=>H_(e,{$refStrategy:r?"root":"none"}),{validate:async o=>{const i=await e.safeParseAsync(o);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function J_(e,t){var n;const r=(n=void 0)!=null?n:!1;return xo(()=>Vn(Yh(e,{target:"draft-7",io:"input",reused:r?"ref":"inline"})),{validate:async o=>{const i=await Il(e,o);return i.success?{success:!0,value:i.data}:{success:!1,error:i.error}}})}function K_(e){return"_zod"in e}function j(e,t){return K_(e)?J_(e):W_(e)}function Y_(e){return typeof e=="object"&&e!==null&&Kr in e&&e[Kr]===!0&&"jsonSchema"in e&&"validate"in e}function pr(e){return e==null?xo({properties:{},additionalProperties:!1}):Y_(e)?e:typeof e=="function"?e():j(e)}var{btoa:X_,atob:Q_}=globalThis;function hr(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=Q_(t);return Uint8Array.from(n,r=>r.codePointAt(0))}function rr(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return X_(t)}function St(e){return e instanceof Uint8Array?rr(e):e}function ko(e){return e==null?void 0:e.replace(/\/$/,"")}function eg(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*tg({execute:e,input:t,options:n}){const r=e(t,n);if(eg(r)){let o;for await(const i of r)o=i,yield{type:"preliminary",output:i};yield{type:"final",output:o}}else yield{type:"final",output:await r}}var Cr,va;function ng(){if(va)return Cr;va=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=(p,g)=>{for(var x in g)e(p,x,{get:g[x],enumerable:!0})},i=(p,g,x,T)=>{if(g&&typeof g=="object"||typeof g=="function")for(let I of n(g))!r.call(p,I)&&I!==x&&e(p,I,{get:()=>g[I],enumerable:!(T=t(g,I))||T.enumerable});return p},a=p=>i(e({},"__esModule",{value:!0}),p),s={};o(s,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Cr=a(s);const l=Symbol.for("@vercel/request-context");function c(){var g,x;return((x=(g=globalThis[l])==null?void 0:g.get)==null?void 0:x.call(g))??{}}return Cr}var Ar,ba;function rg(){if(ba)return Ar;ba=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=(g,x)=>{for(var T in x)e(g,T,{get:x[T],enumerable:!0})},i=(g,x,T,I)=>{if(x&&typeof x=="object"||typeof x=="function")for(let E of n(x))!r.call(g,E)&&E!==T&&e(g,E,{get:()=>x[E],enumerable:!(I=t(x,E))||I.enumerable});return g},a=g=>i(e({},"__esModule",{value:!0}),g),s={};o(s,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>p}),Ar=a(s);var l=ng();async function c(){return""}function p(){return""}return Ar}var Kl=rg(),og="vercel.ai.gateway.error",Or=Symbol.for(og),wa,xa,Ne=class Yl extends(xa=Error,wa=Or,xa){constructor({message:t,statusCode:n=500,cause:r}){super(t),this[wa]=!0,this.statusCode=n,this.cause=r}static isInstance(t){return Yl.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Or in t&&t[Or]===!0}},Xl="GatewayAuthenticationError",ig=`vercel.ai.gateway.error.${Xl}`,ka=Symbol.for(ig),Ia,Ta,Io=class Ql extends(Ta=Ne,Ia=ka,Ta){constructor({message:t="Authentication failed",statusCode:n=401,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Ia]=!0,this.name=Xl,this.type="authentication_error"}static isInstance(t){return Ne.hasMarker(t)&&ka in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r="Authentication failed",statusCode:o=401,cause:i}){let a;return t?a=`AI Gateway authentication failed: Invalid API key.
|
|
44
|
+
|
|
45
|
+
Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
46
|
+
|
|
47
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?a=`AI Gateway authentication failed: Invalid OIDC token.
|
|
48
|
+
|
|
49
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
|
|
50
|
+
|
|
51
|
+
Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`:a=`AI Gateway authentication failed: No authentication provided.
|
|
52
|
+
|
|
53
|
+
Option 1 - API key:
|
|
54
|
+
Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
|
|
55
|
+
Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
56
|
+
|
|
57
|
+
Option 2 - OIDC token:
|
|
58
|
+
Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new Ql({message:a,statusCode:o,cause:i})}},eu="GatewayForbiddenError",ag=`vercel.ai.gateway.error.${eu}`,Sa=Symbol.for(ag),Ea,Ca,sg=class extends(Ca=Ne,Ea=Sa,Ca){constructor({message:e="Forbidden",statusCode:t=403,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Ea]=!0,this.name=eu,this.type="forbidden"}static isInstance(e){return Ne.hasMarker(e)&&Sa in e}},tu="GatewayInvalidRequestError",lg=`vercel.ai.gateway.error.${tu}`,Aa=Symbol.for(lg),Oa,$a,ug=class extends($a=Ne,Oa=Aa,$a){constructor({message:e="Invalid request",statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Oa]=!0,this.name=tu,this.type="invalid_request_error"}static isInstance(e){return Ne.hasMarker(e)&&Aa in e}},nu="GatewayRateLimitError",cg=`vercel.ai.gateway.error.${nu}`,Na=Symbol.for(cg),Ra,Pa,dg=class extends(Pa=Ne,Ra=Na,Pa){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Ra]=!0,this.name=nu,this.type="rate_limit_exceeded"}static isInstance(e){return Ne.hasMarker(e)&&Na in e}},ru="GatewayModelNotFoundError",pg=`vercel.ai.gateway.error.${ru}`,Ma=Symbol.for(pg),hg=Ee(()=>j(d({modelId:u()}))),za,La,fg=class extends(La=Ne,za=Ma,La){constructor({message:e="Model not found",statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[za]=!0,this.name=ru,this.type="model_not_found",this.modelId=n}static isInstance(e){return Ne.hasMarker(e)&&Ma in e}},ou="GatewayInternalServerError",mg=`vercel.ai.gateway.error.${ou}`,Da=Symbol.for(mg),Za,ja,Ua=class extends(ja=Ne,Za=Da,ja){constructor({message:e="Internal server error",statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[Za]=!0,this.name=ou,this.type="internal_server_error"}static isInstance(e){return Ne.hasMarker(e)&&Da in e}},iu="GatewayResponseError",_g=`vercel.ai.gateway.error.${iu}`,Ba=Symbol.for(_g),Va,Fa,gg=class extends(Fa=Ne,Va=Ba,Fa){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:n,validationError:r,cause:o}={}){super({message:e,statusCode:t,cause:o}),this[Va]=!0,this.name=iu,this.type="response_error",this.response=n,this.validationError=r}static isInstance(e){return Ne.hasMarker(e)&&Ba in e}};async function qa({response:e,statusCode:t,defaultMessage:n="Gateway request failed",cause:r,authMethod:o}){const i=await gt({value:e,schema:yg});if(!i.success)return new gg({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:i.error,cause:r});const a=i.value,s=a.error.type,l=a.error.message;switch(s){case"authentication_error":return Io.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:r});case"invalid_request_error":return new ug({message:l,statusCode:t,cause:r});case"rate_limit_exceeded":return new dg({message:l,statusCode:t,cause:r});case"model_not_found":{const c=await gt({value:a.error.param,schema:hg});return new fg({message:l,statusCode:t,modelId:c.success?c.value.modelId:void 0,cause:r})}case"internal_server_error":return new Ua({message:l,statusCode:t,cause:r});case"forbidden":return new sg({message:l,statusCode:t,cause:r});default:return new Ua({message:l,statusCode:t,cause:r})}}var yg=Ee(()=>j(d({error:d({message:u(),type:u().nullish(),param:ze().nullish(),code:ee([u(),f()]).nullish()})})));function vg(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 au="GatewayTimeoutError",bg=`vercel.ai.gateway.error.${au}`,Ga=Symbol.for(bg),Ha,Wa,Ja=class su extends(Wa=Ne,Ha=Ga,Wa){constructor({message:t="Request timed out",statusCode:n=408,cause:r}={}){super({message:t,statusCode:n,cause:r}),this[Ha]=!0,this.name=au,this.type="timeout_error"}static isInstance(t){return Ne.hasMarker(t)&&Ga in t}static createTimeoutError({originalMessage:t,statusCode:n=408,cause:r}){const o=`Gateway request timed out: ${t}
|
|
59
|
+
|
|
60
|
+
This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new su({message:o,statusCode:n,cause:r})}};function Ka(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function Qe(e,t){var n;return Ne.isInstance(e)?e:Ka(e)?Ja.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):$e.isInstance(e)?e.cause&&Ka(e.cause)?Ja.createTimeoutError({originalMessage:e.message,cause:e}):await qa({response:vg(e),statusCode:(n=e.statusCode)!=null?n:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await qa({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}var lu="ai-gateway-auth-method";async function Et(e){const t=await gt({value:e[lu],schema:wg});return t.success?t.value:void 0}var wg=Ee(()=>j(ee([h("api-key"),h("oidc")]))),xg=["embedding","image","language"],Ya=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await tr({url:`${this.config.baseURL}/config`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(kg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await Qe(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await tr({url:`${e.origin}/v1/credits`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(Ig),failedResponseHandler:pt({errorSchema:He(),errorToMessage:n=>n}),fetch:this.config.fetch});return t}catch(e){throw await Qe(e)}}},kg=Ee(()=>j(d({models:R(d({id:u(),name:u(),description:u().nullish(),pricing:d({input:u(),output:u(),input_cache_read:u().nullish(),input_cache_write:u().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:d({specificationVersion:h("v2"),provider:u(),modelId:u()}),modelType:u().nullish()})).transform(e=>e.filter(t=>t.modelType==null||xg.includes(t.modelType)))}))),Ig=Ee(()=>j(d({balance:u(),total_used:u()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),Tg=class{constructor(e){this.config=e}async getSpendReport(e){try{const 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(","));const{value:r}=await tr({url:`${t.origin}/v1/report?${n.toString()}`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(Sg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:o=>o}),fetch:this.config.fetch});return r}catch(t){throw await Qe(t)}}},Sg=K(()=>j(d({results:R(d({day:u().optional(),hour:u().optional(),user:u().optional(),model:u().optional(),tag:u().optional(),provider:u().optional(),credential_type:X(["byok","system"]).optional(),total_cost:f(),market_cost:f().optional(),input_tokens:f().optional(),output_tokens:f().optional(),cached_input_tokens:f().optional(),cache_creation_input_tokens:f().optional(),reasoning_tokens:f().optional(),request_count:f().optional()}).transform(({credential_type:e,total_cost:t,market_cost:n,input_tokens:r,output_tokens:o,cached_input_tokens:i,cache_creation_input_tokens:a,reasoning_tokens:s,request_count:l,...c})=>({...c,...e!==void 0?{credentialType:e}:{},totalCost:t,...n!==void 0?{marketCost:n}:{},...r!==void 0?{inputTokens:r}:{},...o!==void 0?{outputTokens:o}:{},...i!==void 0?{cachedInputTokens:i}:{},...a!==void 0?{cacheCreationInputTokens:a}:{},...s!==void 0?{reasoningTokens:s}:{},...l!==void 0?{requestCount:l}:{}})))}))),Eg=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:n}=await tr({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await Ue(this.config.headers()),successfulResponseHandler:Be(Cg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:r=>r}),fetch:this.config.fetch});return n}catch(t){throw await Qe(t)}}},Cg=K(()=>j(d({data:d({id:u(),total_cost:f(),upstream_inference_cost:f(),usage:f(),created_at:u(),model:u(),is_byok:ue(),provider_name:u(),streamed:ue(),finish_reason:u(),latency:f(),generation_time:f(),native_tokens_prompt:f(),native_tokens_completion:f(),native_tokens_reasoning:f(),native_tokens_cached:f(),native_tokens_cache_creation:f(),billable_web_search_calls:f()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:n,is_byok:r,provider_name:o,finish_reason:i,generation_time:a,native_tokens_prompt:s,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:p,native_tokens_cache_creation:g,billable_web_search_calls:x,...T})=>({...T,totalCost:e,upstreamInferenceCost:t,createdAt:n,isByok:r,providerName:o,finishReason:i,generationTime:a,promptTokens:s,completionTokens:l,reasoningTokens:c,cachedTokens:p,cacheCreationTokens:g,billableWebSearchCalls:x}))}).transform(({data:e})=>e))),Ag=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Ue(this.config.headers());try{const{responseHeaders:i,value:a,rawValue:s}=await De({url:this.getUrl(),headers:Le(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Ue(this.config.o11yHeaders)),body:t,successfulResponseHandler:Be(He()),failedResponseHandler:pt({errorSchema:He(),errorToMessage:l=>l}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:i,body:s},warnings:n}}catch(i){throw await Qe(i,await Et(o))}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,o=await Ue(this.config.headers());try{const{value:i,responseHeaders:a}=await De({url:this.getUrl(),headers:Le(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Ue(this.config.o11yHeaders)),body:t,successfulResponseHandler:Nn(He()),failedResponseHandler:pt({errorSchema:He(),errorToMessage:s=>s}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:i.pipeThrough(new TransformStream({start(s){n.length>0&&s.enqueue({type:"stream-start",warnings:n})},transform(s,l){if(s.success){const c=s.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(s.error)}})),request:{body:t},response:{headers:a}}}catch(i){throw await Qe(i,await Et(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const n of t.content)if(this.isFilePart(n)){const r=n;if(r.data instanceof Uint8Array){const o=Uint8Array.from(r.data),i=Buffer.from(o).toString("base64");r.data=new URL(`data:${r.mediaType||"application/octet-stream"};base64,${i}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"2","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Og=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;const i=await Ue(this.config.headers());try{const{responseHeaders:a,value:s,rawValue:l}=await De({url:this.getUrl(),headers:Le(i,t??{},this.getModelConfigHeaders(),await Ue(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r?{providerOptions:r}:{}},successfulResponseHandler:Be($g),failedResponseHandler:pt({errorSchema:He(),errorToMessage:c=>c}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(o=s.usage)!=null?o:void 0,providerMetadata:s.providerMetadata,response:{headers:a,body:l}}}catch(a){throw await Qe(a,await Et(i))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},$g=Ee(()=>j(d({embeddings:R(R(f())),usage:d({tokens:f()}).nullish(),providerMetadata:Se(u(),Se(u(),ze())).optional()}))),Ng=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:i,headers:a,abortSignal:s}){var l,c,p,g;const x=await Ue(this.config.headers());try{const{responseHeaders:T,value:I,rawValue:E}=await De({url:this.getUrl(),headers:Le(x,a??{},this.getModelConfigHeaders(),await Ue(this.config.o11yHeaders)),body:{prompt:e,n:t,...n&&{size:n},...r&&{aspectRatio:r},...o&&{seed:o},...i&&{providerOptions:i}},successfulResponseHandler:Be(Mg),failedResponseHandler:pt({errorSchema:He(),errorToMessage:k=>k}),...s&&{abortSignal:s},fetch:this.config.fetch});return{images:I.images,warnings:(l=I.warnings)!=null?l:[],providerMetadata:I.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:T},...I.usage!=null&&{usage:{inputTokens:(c=I.usage.inputTokens)!=null?c:void 0,outputTokens:(p=I.usage.outputTokens)!=null?p:void 0,totalTokens:(g=I.usage.totalTokens)!=null?g:void 0}}}}catch(T){throw await Qe(T,await Et(x))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"2","ai-model-id":this.modelId}}},Rg=d({images:R(ze()).optional()}).catchall(ze()),Pg=d({inputTokens:f().nullish(),outputTokens:f().nullish(),totalTokens:f().nullish()}),Mg=d({images:R(u()),warnings:R(d({type:h("other"),message:u()})).optional(),providerMetadata:Se(u(),Rg).optional(),usage:Pg.optional()}),zg=K(()=>j(at({objective:ye().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:At(ye()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:dr(["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:ct().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:at({include_domains:At(ye()).optional().describe("List of domains to include in search results."),exclude_domains:At(ye()).optional().describe("List of domains to exclude from search results."),after_date:ye().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:at({max_chars_per_result:ct().optional().describe("Maximum characters per result."),max_chars_total:ct().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:at({max_age_seconds:ct().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.")}))),Lg=K(()=>j(yo([at({searchId:ye(),results:At(at({url:ye(),title:ye(),excerpt:ye(),publishDate:ye().nullable().optional(),relevanceScore:ct().optional()}))}),at({error:dr(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:ct().optional(),message:ye()})]))),Dg=Ye({id:"gateway.parallel_search",name:"parallel_search",inputSchema:zg,outputSchema:Lg}),Zg=(e={})=>Dg(e),jg=K(()=>j(at({query:yo([ye(),At(ye())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:ct().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:ct().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:ct().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:ye().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:At(ye()).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:At(ye()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:ye().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:ye().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:ye().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:ye().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:dr(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),Ug=K(()=>j(yo([at({results:At(at({title:ye(),url:ye(),snippet:ye(),date:ye().optional(),lastUpdated:ye().optional()})),id:ye()}),at({error:dr(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:ct().optional(),message:ye()})]))),Bg=Ye({id:"gateway.perplexity_search",name:"perplexity_search",inputSchema:jg,outputSchema:Ug}),Vg=(e={})=>Bg(e),Fg={parallelSearch:Zg,perplexitySearch:Vg};async function qg(){var e;return(e=Kl.getContext().headers)==null?void 0:e["x-vercel-id"]}var Gg="2.0.107",Hg="0.0.1";function Wg(e={}){var t,n;let r=null,o=null;const i=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const s=(n=ko(e.baseURL))!=null?n:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const k=await Kg(e);if(k)return qt({Authorization:`Bearer ${k.token}`,"ai-gateway-protocol-version":Hg,[lu]:k.authMethod,...e.headers},`ai-sdk/gateway/${Gg}`);throw Io.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const k=Zt({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),_=Zt({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),v=Zt({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),y=Zt({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const $=await qg();return{...k&&{"ai-o11y-deployment-id":k},..._&&{"ai-o11y-environment":_},...v&&{"ai-o11y-region":v},...$&&{"ai-o11y-request-id":$},...y&&{"ai-o11y-project-id":y}}}},p=k=>new Ag(k,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),g=async()=>{var k,_,v;const y=(v=(_=(k=e._internal)==null?void 0:k.currentDate)==null?void 0:_.call(k).getTime())!=null?v:Date.now();return(!r||y-a>i)&&(a=y,r=new Ya({baseURL:s,headers:l,fetch:e.fetch}).getAvailableModels().then($=>(o=$,$)).catch(async $=>{throw await Qe($,await Et(await l()))})),o?Promise.resolve(o):r},x=async()=>new Ya({baseURL:s,headers:l,fetch:e.fetch}).getCredits().catch(async k=>{throw await Qe(k,await Et(await l()))}),T=async k=>new Tg({baseURL:s,headers:l,fetch:e.fetch}).getSpendReport(k).catch(async _=>{throw await Qe(_,await Et(await l()))}),I=async k=>new Eg({baseURL:s,headers:l,fetch:e.fetch}).getGenerationInfo(k).catch(async _=>{throw await Qe(_,await Et(await l()))}),E=function(k){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return p(k)};return E.getAvailableModels=g,E.getCredits=x,E.getSpendReport=T,E.getGenerationInfo=I,E.imageModel=k=>new Ng(k,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),E.languageModel=p,E.textEmbeddingModel=k=>new Og(k,{provider:"gateway",baseURL:s,headers:l,fetch:e.fetch,o11yHeaders:c()}),E.tools=Fg,E}var Jg=Wg();async function Kg(e){const t=Zt({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(t)return{token:t,authMethod:"api-key"};try{return{token:await Kl.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var Yg=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},jt="1.9.0",Xa=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Xg(e){var t=new Set([e]),n=new Set,r=e.match(Xa);if(!r)return function(){return!1};var o={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(o.prerelease!=null)return function(l){return l===e};function i(s){return n.add(s),!1}function a(s){return t.add(s),!0}return function(l){if(t.has(l))return!0;if(n.has(l))return!1;var c=l.match(Xa);if(!c)return i(l);var p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||o.major!==p.major?i(l):o.major===0?o.minor===p.minor&&o.patch<=p.patch?a(l):i(l):o.minor<=p.minor?a(l):i(l)}}var Qg=Xg(jt),ey=jt.split(".")[0],In=Symbol.for("opentelemetry.js.api."+ey),Tn=Yg;function Rn(e,t,n,r){var o;r===void 0&&(r=!1);var i=Tn[In]=(o=Tn[In])!==null&&o!==void 0?o:{version:jt};if(!r&&i[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return n.error(a.stack||a.message),!1}if(i.version!==jt){var a=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+e+" does not match previously registered API v"+jt);return n.error(a.stack||a.message),!1}return i[e]=t,n.debug("@opentelemetry/api: Registered a global for "+e+" v"+jt+"."),!0}function Vt(e){var t,n,r=(t=Tn[In])===null||t===void 0?void 0:t.version;if(!(!r||!Qg(r)))return(n=Tn[In])===null||n===void 0?void 0:n[e]}function Pn(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+jt+".");var n=Tn[In];n&&delete n[e]}var ty=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},ny=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},ry=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return cn("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return cn("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return cn("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return cn("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return cn("verbose",this._namespace,t)},e})();function cn(e,t,n){var r=Vt("diag");if(r)return n.unshift(t),r[e].apply(r,ny([],ty(n),!1))}var Fe;(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"})(Fe||(Fe={}));function oy(e,t){e<Fe.NONE?e=Fe.NONE:e>Fe.ALL&&(e=Fe.ALL),t=t||{};function n(r,o){var i=t[r];return typeof i=="function"&&e>=o?i.bind(t):function(){}}return{error:n("error",Fe.ERROR),warn:n("warn",Fe.WARN),info:n("info",Fe.INFO),debug:n("debug",Fe.DEBUG),verbose:n("verbose",Fe.VERBOSE)}}var iy=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},ay=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},sy="diag",ht=(function(){function e(){function t(o){return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var s=Vt("diag");if(s)return s[o].apply(s,ay([],iy(i),!1))}}var n=this,r=function(o,i){var a,s,l;if(i===void 0&&(i={logLevel:Fe.INFO}),o===n){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return n.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof i=="number"&&(i={logLevel:i});var p=Vt("diag"),g=oy((s=i.logLevel)!==null&&s!==void 0?s:Fe.INFO,o);if(p&&!i.suppressOverrideMessage){var x=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+x),g.warn("Current logger will overwrite one already registered from "+x)}return Rn("diag",g,n,!0)};n.setLogger=r,n.disable=function(){Pn(sy,n)},n.createComponentLogger=function(o){return new ry(o)},n.verbose=t("verbose"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),ly=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},uy=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},cy=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var n=this._entries.get(t);if(n)return Object.assign({},n)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var n=ly(t,2),r=n[0],o=n[1];return[r,o]})},e.prototype.setEntry=function(t,n){var r=new e(this._entries);return r._entries.set(t,n),r},e.prototype.removeEntry=function(t){var n=new e(this._entries);return n._entries.delete(t),n},e.prototype.removeEntries=function(){for(var t,n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];var i=new e(this._entries);try{for(var a=uy(r),s=a.next();!s.done;s=a.next()){var l=s.value;i._entries.delete(l)}}catch(c){t={error:c}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}return i},e.prototype.clear=function(){return new e},e})();ht.instance();function dy(e){return e===void 0&&(e={}),new cy(new Map(Object.entries(e)))}function uu(e){return Symbol.for(e)}var py=(function(){function e(t){var n=this;n._currentContext=t?new Map(t):new Map,n.getValue=function(r){return n._currentContext.get(r)},n.setValue=function(r,o){var i=new e(n._currentContext);return i._currentContext.set(r,o),i},n.deleteValue=function(r){var o=new e(n._currentContext);return o._currentContext.delete(r),o}}return e})(),hy=new py,Gt=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(r[i]=o[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),fy=(function(){function e(){}return e.prototype.createGauge=function(t,n){return Iy},e.prototype.createHistogram=function(t,n){return Ty},e.prototype.createCounter=function(t,n){return ky},e.prototype.createUpDownCounter=function(t,n){return Sy},e.prototype.createObservableGauge=function(t,n){return Cy},e.prototype.createObservableCounter=function(t,n){return Ey},e.prototype.createObservableUpDownCounter=function(t,n){return Ay},e.prototype.addBatchObservableCallback=function(t,n){},e.prototype.removeBatchObservableCallback=function(t){},e})(),fr=(function(){function e(){}return e})(),my=(function(e){Gt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t})(fr),_y=(function(e){Gt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(n,r){},t})(fr),gy=(function(e){Gt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t})(fr),yy=(function(e){Gt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(n,r){},t})(fr),To=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),vy=(function(e){Gt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(To),by=(function(e){Gt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(To),wy=(function(e){Gt(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(To),xy=new fy,ky=new my,Iy=new gy,Ty=new yy,Sy=new _y,Ey=new vy,Cy=new by,Ay=new wy,Oy={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},$y={set:function(e,t,n){e!=null&&(e[t]=n)}},Ny=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},Ry=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},Py=(function(){function e(){}return e.prototype.active=function(){return hy},e.prototype.with=function(t,n,r){for(var o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return n.call.apply(n,Ry([r],Ny(o),!1))},e.prototype.bind=function(t,n){return n},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),My=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),o,i=[],a;try{for(;(t===void 0||t-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(s){a={error:s}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(a)throw a.error}}return i},zy=function(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,i;r<o;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},$r="context",Ly=new Py,mr=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return Rn($r,t,ht.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,n,r){for(var o,i=[],a=3;a<arguments.length;a++)i[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,zy([t,n,r],My(i),!1))},e.prototype.bind=function(t,n){return this._getContextManager().bind(t,n)},e.prototype._getContextManager=function(){return Vt($r)||Ly},e.prototype.disable=function(){this._getContextManager().disable(),Pn($r,ht.instance())},e})(),Xr;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(Xr||(Xr={}));var cu="0000000000000000",du="00000000000000000000000000000000",Dy={traceId:du,spanId:cu,traceFlags:Xr.NONE},_n=(function(){function e(t){t===void 0&&(t=Dy),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,n){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,n){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,n){},e})(),So=uu("OpenTelemetry Context Key SPAN");function Eo(e){return e.getValue(So)||void 0}function Zy(){return Eo(mr.getInstance().active())}function Co(e,t){return e.setValue(So,t)}function jy(e){return e.deleteValue(So)}function Uy(e,t){return Co(e,new _n(t))}function pu(e){var t;return(t=Eo(e))===null||t===void 0?void 0:t.spanContext()}var By=/^([0-9a-f]{32})$/i,Vy=/^[0-9a-f]{16}$/i;function Fy(e){return By.test(e)&&e!==du}function qy(e){return Vy.test(e)&&e!==cu}function hu(e){return Fy(e.traceId)&&qy(e.spanId)}function Gy(e){return new _n(e)}var Nr=mr.getInstance(),fu=(function(){function e(){}return e.prototype.startSpan=function(t,n,r){r===void 0&&(r=Nr.active());var o=!!(n!=null&&n.root);if(o)return new _n;var i=r&&pu(r);return Hy(i)&&hu(i)?new _n(i):new _n},e.prototype.startActiveSpan=function(t,n,r,o){var i,a,s;if(!(arguments.length<2)){arguments.length===2?s=n:arguments.length===3?(i=n,s=r):(i=n,a=r,s=o);var l=a??Nr.active(),c=this.startSpan(t,i,l),p=Co(l,c);return Nr.with(p,s,void 0,c)}},e})();function Hy(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var Wy=new fu,Jy=(function(){function e(t,n,r,o){this._provider=t,this.name=n,this.version=r,this.options=o}return e.prototype.startSpan=function(t,n,r){return this._getTracer().startSpan(t,n,r)},e.prototype.startActiveSpan=function(t,n,r,o){var i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):Wy},e})(),Ky=(function(){function e(){}return e.prototype.getTracer=function(t,n,r){return new fu},e})(),Yy=new Ky,Qa=(function(){function e(){}return e.prototype.getTracer=function(t,n,r){var o;return(o=this.getDelegateTracer(t,n,r))!==null&&o!==void 0?o:new Jy(this,t,n,r)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:Yy},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,n,r){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,n,r)},e})(),or;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(or||(or={}));mr.getInstance();ht.instance();var Xy=(function(){function e(){}return e.prototype.getMeter=function(t,n,r){return xy},e})(),Qy=new Xy,Rr="metrics",ev=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return Rn(Rr,t,ht.instance())},e.prototype.getMeterProvider=function(){return Vt(Rr)||Qy},e.prototype.getMeter=function(t,n,r){return this.getMeterProvider().getMeter(t,n,r)},e.prototype.disable=function(){Pn(Rr,ht.instance())},e})();ev.getInstance();var tv=(function(){function e(){}return e.prototype.inject=function(t,n){},e.prototype.extract=function(t,n){return t},e.prototype.fields=function(){return[]},e})(),Ao=uu("OpenTelemetry Baggage Key");function mu(e){return e.getValue(Ao)||void 0}function nv(){return mu(mr.getInstance().active())}function rv(e,t){return e.setValue(Ao,t)}function ov(e){return e.deleteValue(Ao)}var Pr="propagation",iv=new tv,av=(function(){function e(){this.createBaggage=dy,this.getBaggage=mu,this.getActiveBaggage=nv,this.setBaggage=rv,this.deleteBaggage=ov}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return Rn(Pr,t,ht.instance())},e.prototype.inject=function(t,n,r){return r===void 0&&(r=$y),this._getGlobalPropagator().inject(t,n,r)},e.prototype.extract=function(t,n,r){return r===void 0&&(r=Oy),this._getGlobalPropagator().extract(t,n,r)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){Pn(Pr,ht.instance())},e.prototype._getGlobalPropagator=function(){return Vt(Pr)||iv},e})();av.getInstance();var Mr="trace",sv=(function(){function e(){this._proxyTracerProvider=new Qa,this.wrapSpanContext=Gy,this.isSpanContextValid=hu,this.deleteSpan=jy,this.getSpan=Eo,this.getActiveSpan=Zy,this.getSpanContext=pu,this.setSpan=Co,this.setSpanContext=Uy}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var n=Rn(Mr,this._proxyTracerProvider,ht.instance());return n&&this._proxyTracerProvider.setDelegate(t),n},e.prototype.getTracerProvider=function(){return Vt(Mr)||this._proxyTracerProvider},e.prototype.getTracer=function(t,n){return this.getTracerProvider().getTracer(t,n)},e.prototype.disable=function(){Pn(Mr,ht.instance()),this._proxyTracerProvider=new Qa},e})(),lv=sv.getInstance(),uv=Object.defineProperty,cv=(e,t)=>{for(var n in t)uv(e,n,{get:t[n],enumerable:!0})},_u="AI_NoOutputSpecifiedError",gu=`vercel.ai.error.${_u}`,dv=Symbol.for(gu),yu,pv=class extends te{constructor({message:e="No output specified."}={}){super({name:_u,message:e}),this[yu]=!0}static isInstance(e){return te.hasMarker(e,gu)}};yu=dv;function hv(e){const t="AI SDK Warning:";switch(e.type){case"unsupported-setting":{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case"unsupported-tool":{const n="name"in e.tool?e.tool.name:"unknown tool";let r=`${t} The tool "${n}" is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case"other":return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var fv="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",es=!1,mv=e=>{if(e.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}es||(es=!0,console.info(fv));for(const n of e)console.warn(hv(n))}},vu="AI_InvalidArgumentError",bu=`vercel.ai.error.${vu}`,_v=Symbol.for(bu),wu,ut=class extends te{constructor({parameter:e,value:t,message:n}){super({name:vu,message:`Invalid argument for parameter ${e}: ${n}`}),this[wu]=!0,this.parameter=e,this.value=t}static isInstance(e){return te.hasMarker(e,bu)}};wu=_v;var xu="AI_InvalidToolInputError",ku=`vercel.ai.error.${xu}`,gv=Symbol.for(ku),Iu,Tu=class extends te{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${Cn(n)}`}){super({name:xu,message:r,cause:n}),this[Iu]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return te.hasMarker(e,ku)}};Iu=gv;var Su="AI_NoObjectGeneratedError",Eu=`vercel.ai.error.${Su}`,yv=Symbol.for(Eu),Cu,ts=class extends te{constructor({message:e="No object generated.",cause:t,text:n,response:r,usage:o,finishReason:i}){super({name:Su,message:e,cause:t}),this[Cu]=!0,this.text=n,this.response=r,this.usage=o,this.finishReason=i}static isInstance(e){return te.hasMarker(e,Eu)}};Cu=yv;var Au="AI_NoSuchToolError",Ou=`vercel.ai.error.${Au}`,vv=Symbol.for(Ou),$u,Qr=class extends te{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Au,message:n}),this[$u]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return te.hasMarker(e,Ou)}};$u=vv;var Nu="AI_ToolCallRepairError",Ru=`vercel.ai.error.${Nu}`,bv=Symbol.for(Ru),Pu,wv=class extends te{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${Cn(e)}`}){super({name:Nu,message:n,cause:e}),this[Pu]=!0,this.originalError=t}static isInstance(e){return te.hasMarker(e,Ru)}};Pu=bv;var xv=class extends te{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}},Mu="AI_InvalidMessageRoleError",zu=`vercel.ai.error.${Mu}`,kv=Symbol.for(zu),Lu,Iv=class extends te{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Mu,message:t}),this[Lu]=!0,this.role=e}static isInstance(e){return te.hasMarker(e,zu)}};Lu=kv;var Du="AI_RetryError",Zu=`vercel.ai.error.${Du}`,Tv=Symbol.for(Zu),ju,ns=class extends te{constructor({message:e,reason:t,errors:n}){super({name:Du,message:e}),this[ju]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return te.hasMarker(e,Zu)}};ju=Tv;function rs(e){if(typeof e!="string"){if(e.specificationVersion!=="v2")throw new xv({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return Sv().languageModel(e)}function Sv(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Jg}var Ev=[{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]}],Cv=e=>{const t=typeof e=="string"?hr(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function Av(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?Cv(e):e}function Ov({data:e,signatures:t}){const n=Av(e),r=typeof n=="string"?hr(n.substring(0,Math.min(n.length,24))):n;for(const o of t)if(r.length>=o.bytesPrefix.length&&o.bytesPrefix.every((i,a)=>i===null||r[a]===i))return o.mediaType}var Uu="5.0.208",Bu=async({url:e,maxBytes:t,abortSignal:n})=>{var r;const o=e.toString();try{const i=qt({},`ai-sdk/${Uu}`,bo()),a=await Bm({url:o,headers:i,abortSignal:n});if(!a.ok)throw await vo(a),new qe({url:o,statusCode:a.status,statusText:a.statusText});return{data:await Zl({response:a,url:o,maxBytes:t??Dl}),mediaType:(r=a.headers.get("content-type"))!=null?r:void 0}}catch(i){throw qe.isInstance(i)?i:new qe({url:o,cause:i})}},$v=(e=Bu)=>t=>Promise.all(t.map(async n=>n.isUrlSupportedByModel?null:e(n)));function Nv(e){try{const[t,n]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var Vu=ee([u(),Jn(Uint8Array),Jn(ArrayBuffer),im(e=>{var t,n;return(n=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?n:!1},{message:"Must be a Buffer"})]);function Fu(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:"){const{mediaType:t,base64Content:n}=Nv(e.toString());if(t==null||n==null)throw new te({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Rv(e){return typeof e=="string"?e:e instanceof ArrayBuffer?rr(new Uint8Array(e)):rr(e)}async function Pv({prompt:e,supportedUrls:t,download:n=$v()}){const r=await zv(e.messages,n,t);return[...e.system!=null?[{role:"system",content:e.system}]:[],...e.messages.map(o=>Mv({message:o,downloadedAssets:r}))]}function Mv({message:e,downloadedAssets:t}){const 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(r=>Lv(r,t)).filter(r=>r.type!=="text"||r.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(r=>r.type!=="text"||r.text!==""||r.providerOptions!=null).map(r=>{const o=r.providerOptions;switch(r.type){case"file":{const{data:i,mediaType:a}=Fu(r.data);return{type:"file",data:i,filename:r.filename,mediaType:a??r.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:r.text,providerOptions:o};case"text":return{type:"text",text:r.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName,input:r.input,providerExecuted:r.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.map(r=>({type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,providerOptions:r.providerOptions})),providerOptions:e.providerOptions};default:{const r=n;throw new Iv({role:r})}}}async function zv(e,t,n){const r=e.filter(i=>i.role==="user").map(i=>i.content).filter(i=>Array.isArray(i)).flat().filter(i=>i.type==="image"||i.type==="file").map(i=>{var a;const s=(a=i.mediaType)!=null?a:i.type==="image"?"image/*":void 0;let l=i.type==="image"?i.image:i.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:s,data:l}}).filter(i=>i.data instanceof URL).map(i=>({url:i.data,isUrlSupportedByModel:i.mediaType!=null&&Gm({url:i.data.toString(),mediaType:i.mediaType,supportedUrls:n})})),o=await t(r);return Object.fromEntries(o.map((i,a)=>i==null?null:[r[a].url.toString(),{data:i.data,mediaType:i.mediaType}]).filter(i=>i!=null))}function Lv(e,t){var n;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let r;const o=e.type;switch(o){case"image":r=e.image;break;case"file":r=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:i,mediaType:a}=Fu(r);let s=a??e.mediaType,l=i;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,s??(s=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(s=(n=Ov({data:l,signatures:Ev}))!=null?n:s),{type:"file",mediaType:s??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(s==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:s,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function os({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:i,seed:a,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new ut({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new ut({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new ut({parameter:"temperature",value:t,message:"temperature must be a number"});if(n!=null&&typeof n!="number")throw new ut({parameter:"topP",value:n,message:"topP must be a number"});if(r!=null&&typeof r!="number")throw new ut({parameter:"topK",value:r,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new ut({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(i!=null&&typeof i!="number")throw new ut({parameter:"frequencyPenalty",value:i,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new ut({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:o,frequencyPenalty:i,stopSequences:s,seed:a}}function Dv(e){return e!=null&&Object.keys(e).length>0}function Zv({tools:e,toolChoice:t,activeTools:n}){return Dv(e)?{tools:(n!=null?Object.entries(e).filter(([o])=>n.includes(o)):Object.entries(e)).map(([o,i])=>{const a=i.type;switch(a){case void 0:case"dynamic":case"function":return{type:"function",name:o,description:i.description,inputSchema:pr(i.inputSchema).jsonSchema,providerOptions:i.providerOptions};case"provider-defined":return{type:"provider-defined",name:o,id:i.id,args:i.args};default:{const s=a;throw new Error(`Unsupported tool type: ${s}`)}}}),toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}:{tools:void 0,toolChoice:void 0}}var Sn=Ol(()=>ee([Nf(),u(),f(),ue(),Se(u(),Sn),R(Sn)])),mt=Se(u(),Se(u(),Sn)),qu=d({type:h("text"),text:u(),providerOptions:mt.optional()}),jv=d({type:h("image"),image:ee([Vu,Jn(URL)]),mediaType:u().optional(),providerOptions:mt.optional()}),Gu=d({type:h("file"),data:ee([Vu,Jn(URL)]),filename:u().optional(),mediaType:u(),providerOptions:mt.optional()}),Uv=d({type:h("reasoning"),text:u(),providerOptions:mt.optional()}),Bv=d({type:h("tool-call"),toolCallId:u(),toolName:u(),input:ze(),providerOptions:mt.optional(),providerExecuted:ue().optional()}),Vv=se("type",[d({type:h("text"),value:u()}),d({type:h("json"),value:Sn}),d({type:h("error-text"),value:u()}),d({type:h("error-json"),value:Sn}),d({type:h("content"),value:R(ee([d({type:h("text"),text:u()}),d({type:h("media"),data:u(),mediaType:u()})]))})]),Hu=d({type:h("tool-result"),toolCallId:u(),toolName:u(),output:Vv,providerOptions:mt.optional()}),Fv=d({role:h("system"),content:u(),providerOptions:mt.optional()}),qv=d({role:h("user"),content:ee([u(),R(ee([qu,jv,Gu]))]),providerOptions:mt.optional()}),Gv=d({role:h("assistant"),content:ee([u(),R(ee([qu,Gu,Uv,Bv,Hu]))]),providerOptions:mt.optional()}),Hv=d({role:h("tool"),content:R(Hu),providerOptions:mt.optional()}),Wv=ee([Fv,qv,Gv,Hv]);async function Jv({allowSystemInMessages:e,system:t,prompt:n,messages:r}){if(n==null&&r==null)throw new xt({prompt:n,message:"prompt or messages must be defined"});if(n!=null&&r!=null)throw new xt({prompt:n,message:"prompt and messages cannot be defined at the same time"});if(t!=null&&typeof t!="string")throw new xt({prompt:n,message:"system must be a string"});if(n!=null&&typeof n=="string")r=[{role:"user",content:n}];else if(n!=null&&Array.isArray(n))r=n;else if(r==null)throw new xt({prompt:n,message:"prompt or messages must be defined"});if(r.length===0)throw new xt({prompt:n,message:"messages must not be empty"});if(r.some(i=>i.role==="system")){if(e===!1)throw new xt({prompt:n,message:"System messages are not allowed in the prompt or messages fields. Use the system option instead."});e===void 0&&console.warn("AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.")}const o=await gt({value:r,schema:R(Wv)});if(!o.success)throw new xt({prompt:n,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:o.error});return{messages:r,system:t}}function Kv(e){if(!Io.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",n="https://v5.ai-sdk.dev/unauthenticated-ai-gateway";return t?new te({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${n}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
|
|
61
|
+
|
|
62
|
+
To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
|
|
63
|
+
|
|
64
|
+
Alternatively, you can use a provider module instead of the AI Gateway.
|
|
65
|
+
|
|
66
|
+
Learn more: \x1B[34m${n}\x1B[0m
|
|
67
|
+
|
|
68
|
+
`),{name:"GatewayAuthenticationError"})}function eo({operationId:e,telemetry:t}){return{"operation.name":`${e}${(t==null?void 0:t.functionId)!=null?` ${t.functionId}`:""}`,"resource.name":t==null?void 0:t.functionId,"ai.operationId":e,"ai.telemetry.functionId":t==null?void 0:t.functionId}}function Yv({model:e,settings:t,telemetry:n,headers:r}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((i,[a,s])=>(i[`ai.settings.${a}`]=s,i),{}),...Object.entries((o=n==null?void 0:n.metadata)!=null?o:{}).reduce((i,[a,s])=>(i[`ai.telemetry.metadata.${a}`]=s,i),{}),...Object.entries(r??{}).reduce((i,[a,s])=>(s!==void 0&&(i[`ai.request.headers.${a}`]=s),i),{})}}var Xv={startSpan(){return Un},startActiveSpan(e,t,n,r){if(typeof t=="function")return t(Un);if(typeof n=="function")return n(Un);if(typeof r=="function")return r(Un)}},Un={spanContext(){return Qv},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}},Qv={traceId:"",spanId:"",traceFlags:0};function eb({isEnabled:e=!1,tracer:t}={}){return e?t||lv.getTracer("ai"):Xv}function to({name:e,tracer:t,attributes:n,fn:r,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:n},async i=>{try{const a=await r(i);return o&&i.end(),a}catch(a){try{Wu(i,a)}finally{i.end()}throw a}})}function Wu(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:or.ERROR,message:t.message})):e.setStatus({code:or.ERROR})}function Yt({telemetry:e,attributes:t}){return(e==null?void 0:e.isEnabled)!==!0?{}:Object.entries(t).reduce((n,[r,o])=>{if(o==null)return n;if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if((e==null?void 0:e.recordInputs)===!1)return n;const i=o.input();return i==null?n:{...n,[r]:i}}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if((e==null?void 0:e.recordOutputs)===!1)return n;const i=o.output();return i==null?n:{...n,[r]:i}}return{...n,[r]:o}},{})}function tb(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(n=>n.type==="file"?{...n,data:n.data instanceof Uint8Array?Rv(n.data):n.data}:n)})))}function nb(e,t){return{inputTokens:dn(e.inputTokens,t.inputTokens),outputTokens:dn(e.outputTokens,t.outputTokens),totalTokens:dn(e.totalTokens,t.totalTokens),reasoningTokens:dn(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:dn(e.cachedInputTokens,t.cachedInputTokens)}}function dn(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function rb(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function ob({error:e,exponentialBackoffDelay:t}){const n=e.responseHeaders;if(!n)return t;let r;const o=n["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(r=a)}const i=n["retry-after"];if(i&&r===void 0){const a=parseFloat(i);Number.isNaN(a)?r=Date.parse(i)-Date.now():r=a*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var ib=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async o=>Ju(o,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function Ju(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:o},i=[]){try{return await e()}catch(a){if(on(a)||t===0)throw a;const s=jl(a),l=[...i,a],c=l.length;if(c>t)throw new ns({message:`Failed after ${c} attempts. Last error: ${s}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&$e.isInstance(a)&&a.isRetryable===!0&&c<=t)return await Mm(ob({error:a,exponentialBackoffDelay:n}),{abortSignal:o}),Ju(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:o},l);throw c===1?a:new ns({message:`Failed after ${c} attempts with non-retryable error: '${s}'`,reason:"errorNotRetryable",errors:l})}}function ab({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new ut({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new ut({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const n=e??2;return{maxRetries:n,retry:ib({maxRetries:n,abortSignal:t})}}function is(e){const t=e.filter(n=>n.type==="text");if(t.length!==0)return t.map(n=>n.text).join("")}var sb=class{constructor({data:e,mediaType:t}){const n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=rr(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=hr(this.base64Data)),this.uint8ArrayData}};async function lb({toolCall:e,tools:t,repairToolCall:n,system:r,messages:o}){try{if(t==null)throw new Qr({toolName:e.toolName});try{return await as({toolCall:e,tools:t})}catch(i){if(n==null||!(Qr.isInstance(i)||Tu.isInstance(i)))throw i;let a=null;try{a=await n({toolCall:e,tools:t,inputSchema:({toolName:s})=>{const{inputSchema:l}=t[s];return pr(l).jsonSchema},system:r,messages:o,error:i})}catch(s){throw new wv({cause:s,originalError:i})}if(a==null)throw i;return await as({toolCall:a,tools:t})}}catch(i){const a=await Bt({text:e.input}),s=a.success?a.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s,dynamic:!0,invalid:!0,error:i,providerMetadata:e.providerMetadata}}}async function as({toolCall:e,tools:t}){const n=e.toolName,r=t[n];if(r==null)throw new Qr({toolName:e.toolName,availableTools:Object.keys(t)});const o=pr(r.inputSchema),i=e.input.trim()===""?await gt({value:{},schema:o}):await Bt({text:e.input,schema:o});if(i.success===!1)throw new Tu({toolName:n,toolInput:e.input,cause:i.error});return r.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:e.toolCallId,toolName:n,input:i.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var ub=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:o,response:i,providerMetadata:a}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=o,this.response=i,this.providerMetadata=a}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function cb(e){return({steps:t})=>t.length===e}async function db({stopConditions:e,steps:t}){return(await Promise.all(e.map(n=>n({steps:t})))).some(n=>n)}function zr({output:e,tool:t,errorMode:n}){return n==="text"?{type:"error-text",value:Cn(e)}:n==="json"?{type:"error-json",value:ss(e)}:t!=null&&t.toModelOutput?t.toModelOutput(e):typeof e=="string"?{type:"text",value:e}:{type:"json",value:ss(e)}}function ss(e){return e===void 0?null:e}function pb({content:e,tools:t}){const n=[],r=e.filter(i=>i.type!=="source").filter(i=>(i.type!=="tool-result"||i.providerExecuted)&&(i.type!=="tool-error"||i.providerExecuted)).filter(i=>i.type!=="text"||i.text.length>0).map(i=>{switch(i.type){case"text":return{type:"text",text:i.text,providerOptions:i.providerMetadata};case"reasoning":return{type:"reasoning",text:i.text,providerOptions:i.providerMetadata};case"file":return{type:"file",data:i.file.base64,mediaType:i.file.mediaType,providerOptions:i.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:i.toolCallId,toolName:i.toolName,input:i.input,providerExecuted:i.providerExecuted,providerOptions:i.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:zr({tool:t==null?void 0:t[i.toolName],output:i.output,errorMode:"none"}),providerExecuted:!0,providerOptions:i.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:zr({tool:t==null?void 0:t[i.toolName],output:i.error,errorMode:"json"}),providerOptions:i.providerMetadata}}});r.length>0&&n.push({role:"assistant",content:r});const o=e.filter(i=>i.type==="tool-result"||i.type==="tool-error").filter(i=>!i.providerExecuted).map(i=>({type:"tool-result",toolCallId:i.toolCallId,toolName:i.toolName,output:zr({tool:t==null?void 0:t[i.toolName],output:i.type==="tool-result"?i.output:i.error,errorMode:i.type==="tool-error"?"text":"none"}),...i.providerMetadata!=null?{providerOptions:i.providerMetadata}:{}}));return o.length>0&&n.push({role:"tool",content:o}),n}var hb=$n({prefix:"aitxt",size:24});async function Ku({model:e,tools:t,toolChoice:n,system:r,prompt:o,messages:i,allowSystemInMessages:a,maxRetries:s,abortSignal:l,headers:c,stopWhen:p=cb(1),experimental_output:g,experimental_telemetry:x,providerOptions:T,experimental_activeTools:I,activeTools:E=I,experimental_prepareStep:k,prepareStep:_=k,experimental_repairToolCall:v,experimental_download:y,experimental_context:$,_internal:{generateId:b=hb,currentDate:S=()=>new Date}={},onStepFinish:m,...N}){const Z=rs(e),B=rb(p),{maxRetries:L,retry:oe}=ab({maxRetries:s,abortSignal:l}),z=os(N),V=qt(c??{},`ai/${Uu}`),W=Yv({model:Z,telemetry:x,headers:V,settings:{...z,maxRetries:L}}),be=await Jv({system:r,prompt:o,messages:i,allowSystemInMessages:a}),Y=eb(x);try{return await to({name:"ai.generateText",attributes:Yt({telemetry:x,attributes:{...eo({operationId:"ai.generateText",telemetry:x}),...W,"ai.model.provider":Z.provider,"ai.model.id":Z.modelId,"ai.prompt":{input:()=>JSON.stringify({system:r,prompt:o,messages:i})}}}),tracer:Y,fn:async we=>{var ge,Ce,le,he,de,ke,O;const ne=os(N);let C,H=[],re=[];const w=[],ie=[];do{const rt=[...be.messages,...w],st=await(_==null?void 0:_({model:Z,steps:ie,stepNumber:ie.length,messages:rt})),zt=rs((ge=st==null?void 0:st.model)!=null?ge:Z),Fo=await Pv({prompt:{system:(Ce=st==null?void 0:st.system)!=null?Ce:be.system,messages:(le=st==null?void 0:st.messages)!=null?le:rt},supportedUrls:await zt.supportedUrls,download:y}),{toolChoice:yr,tools:vr}=Zv({tools:t,toolChoice:(he=st==null?void 0:st.toolChoice)!=null?he:n,activeTools:(de=st==null?void 0:st.activeTools)!=null?de:E});C=await oe(()=>{var Ie;return to({name:"ai.generateText.doGenerate",attributes:Yt({telemetry:x,attributes:{...eo({operationId:"ai.generateText.doGenerate",telemetry:x}),...W,"ai.model.provider":zt.provider,"ai.model.id":zt.modelId,"ai.prompt.messages":{input:()=>tb(Fo)},"ai.prompt.tools":{input:()=>vr==null?void 0:vr.map(Lt=>JSON.stringify(Lt))},"ai.prompt.toolChoice":{input:()=>yr!=null?JSON.stringify(yr):void 0},"gen_ai.system":zt.provider,"gen_ai.request.model":zt.modelId,"gen_ai.request.frequency_penalty":N.frequencyPenalty,"gen_ai.request.max_tokens":N.maxOutputTokens,"gen_ai.request.presence_penalty":N.presencePenalty,"gen_ai.request.stop_sequences":N.stopSequences,"gen_ai.request.temperature":(Ie=N.temperature)!=null?Ie:void 0,"gen_ai.request.top_k":N.topK,"gen_ai.request.top_p":N.topP}}),tracer:Y,fn:async Lt=>{var Ho,Wo,Jo,Ko,Yo,Xo,Qo,ei;const Re=await zt.doGenerate({...ne,tools:vr,toolChoice:yr,responseFormat:g==null?void 0:g.responseFormat,prompt:Fo,providerOptions:T,abortSignal:l,headers:V}),Jt={id:(Wo=(Ho=Re.response)==null?void 0:Ho.id)!=null?Wo:b(),timestamp:(Ko=(Jo=Re.response)==null?void 0:Jo.timestamp)!=null?Ko:S(),modelId:(Xo=(Yo=Re.response)==null?void 0:Yo.modelId)!=null?Xo:zt.modelId,headers:(Qo=Re.response)==null?void 0:Qo.headers,body:(ei=Re.response)==null?void 0:ei.body};return Lt.setAttributes(Yt({telemetry:x,attributes:{"ai.response.finishReason":Re.finishReason,"ai.response.text":{output:()=>is(Re.content)},"ai.response.toolCalls":{output:()=>{const ti=ls(Re.content);return ti==null?void 0:JSON.stringify(ti)}},"ai.response.id":Jt.id,"ai.response.model":Jt.modelId,"ai.response.timestamp":Jt.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(Re.providerMetadata),"ai.usage.promptTokens":Re.usage.inputTokens,"ai.usage.completionTokens":Re.usage.outputTokens,"gen_ai.response.finish_reasons":[Re.finishReason],"gen_ai.response.id":Jt.id,"gen_ai.response.model":Jt.modelId,"gen_ai.usage.input_tokens":Re.usage.inputTokens,"gen_ai.usage.output_tokens":Re.usage.outputTokens}})),{...Re,response:Jt}}})});const Mn=await Promise.all(C.content.filter(Ie=>Ie.type==="tool-call").map(Ie=>lb({toolCall:Ie,tools:t,repairToolCall:v,system:r,messages:rt})));for(const Ie of Mn){if(Ie.invalid)continue;const Lt=t[Ie.toolName];(Lt==null?void 0:Lt.onInputAvailable)!=null&&await Lt.onInputAvailable({input:Ie.input,toolCallId:Ie.toolCallId,messages:rt,abortSignal:l,experimental_context:$})}const Lc=Mn.filter(Ie=>Ie.invalid&&Ie.dynamic);re=[];for(const Ie of Lc)re.push({type:"tool-error",toolCallId:Ie.toolCallId,toolName:Ie.toolName,input:Ie.input,error:jl(Ie.error),dynamic:!0});H=Mn.filter(Ie=>!Ie.providerExecuted),t!=null&&re.push(...await fb({toolCalls:H.filter(Ie=>!Ie.invalid),tools:t,tracer:Y,telemetry:x,messages:rt,abortSignal:l,experimental_context:$}));const qo=_b({content:C.content,toolCalls:Mn,toolOutputs:re});w.push(...pb({content:qo,tools:t}));const Go=new ub({content:qo,finishReason:C.finishReason,usage:C.usage,warnings:C.warnings,providerMetadata:C.providerMetadata,request:(ke=C.request)!=null?ke:{},response:{...C.response,messages:structuredClone(w)}});mv((O=C.warnings)!=null?O:[]),ie.push(Go),await(m==null?void 0:m(Go))}while(H.length>0&&re.length===H.length&&!await db({stopConditions:B,steps:ie}));we.setAttributes(Yt({telemetry:x,attributes:{"ai.response.finishReason":C.finishReason,"ai.response.text":{output:()=>is(C.content)},"ai.response.toolCalls":{output:()=>{const rt=ls(C.content);return rt==null?void 0:JSON.stringify(rt)}},"ai.response.providerMetadata":JSON.stringify(C.providerMetadata),"ai.usage.promptTokens":C.usage.inputTokens,"ai.usage.completionTokens":C.usage.outputTokens}}));const nt=ie[ie.length-1];let Mt;return nt.finishReason==="stop"&&(Mt=await(g==null?void 0:g.parseOutput({text:nt.text},{response:nt.response,usage:nt.usage,finishReason:nt.finishReason}))),new mb({steps:ie,resolvedOutput:Mt})}})}catch(we){throw Kv(we)}}async function fb({toolCalls:e,tools:t,tracer:n,telemetry:r,messages:o,abortSignal:i,experimental_context:a}){return(await Promise.all(e.map(async({toolCallId:l,toolName:c,input:p})=>{const g=t[c];if((g==null?void 0:g.execute)!=null)return to({name:"ai.toolCall",attributes:Yt({telemetry:r,attributes:{...eo({operationId:"ai.toolCall",telemetry:r}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(p)}}}),tracer:n,fn:async x=>{try{const T=tg({execute:g.execute.bind(g),input:p,options:{toolCallId:l,messages:o,abortSignal:i,experimental_context:a}});let I;for await(const E of T)E.type==="final"&&(I=E.output);try{x.setAttributes(Yt({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(I)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:p,output:I,dynamic:g.type==="dynamic"}}catch(T){return Wu(x,T),{type:"tool-error",toolCallId:l,toolName:c,input:p,error:T,dynamic:g.type==="dynamic"}}}})}))).filter(l=>l!=null)}var mb=class{constructor(e){this.steps=e.steps,this.resolvedOutput=e.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((e,t)=>nb(e,t.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new pv;return this.resolvedOutput}};function ls(e){const t=e.filter(n=>n.type==="tool-call");if(t.length!==0)return t.map(n=>({toolCallId:n.toolCallId,toolName:n.toolName,input:n.input}))}function _b({content:e,toolCalls:t,toolOutputs:n}){return[...e.map(r=>{switch(r.type){case"text":case"reasoning":case"source":return r;case"file":return{type:"file",file:new sb(r)};case"tool-call":return t.find(o=>o.toolCallId===r.toolCallId);case"tool-result":{const o=t.find(i=>i.toolCallId===r.toolCallId);if(o==null)throw new Error(`Tool call ${r.toolCallId} not found.`);return r.isError?{type:"tool-error",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,error:r.result,providerExecuted:!0,dynamic:o.dynamic}:{type:"tool-result",toolCallId:r.toolCallId,toolName:r.toolName,input:o.input,output:r.result,providerExecuted:!0,dynamic:o.dynamic}}}}),...n]}(class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
69
|
+
|
|
70
|
+
`)},flush(e){e.enqueue(`data: [DONE]
|
|
71
|
+
|
|
72
|
+
`)}})}});function gb(e){const t=["ROOT"];let n=-1,r=null;function o(l,c,p){switch(l){case'"':{n=c,t.pop(),t.push(p),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=c,r=c,t.pop(),t.push(p),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c,t.pop(),t.push(p),t.push("INSIDE_NUMBER");break}case"{":{n=c,t.pop(),t.push(p),t.push("INSIDE_OBJECT_START");break}case"[":{n=c,t.pop(),t.push(p),t.push("INSIDE_ARRAY_START");break}}}function i(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,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":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{n=l,t.pop();break}default:{n=l,o(c,l,"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=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;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=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(r,l+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):n=l;break}}}let s=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){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":{const p=e.substring(r,e.length);"true".startsWith(p)?s+="true".slice(p.length):"false".startsWith(p)?s+="false".slice(p.length):"null".startsWith(p)&&(s+="null".slice(p.length))}}return s}async function yb(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Bt({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Bt({text:gb(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}$n({prefix:"aitxt",size:24});$n({prefix:"aiobj",size:24});function vb(e){return({url:t,abortSignal:n})=>Bu({url:t,maxBytes:void 0,abortSignal:n})}$n({prefix:"aiobj",size:24});var bb={};cv(bb,{object:()=>xb,text:()=>wb});var wb=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),xb=({schema:e})=>{const t=pr(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await yb(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const o=r.state;throw new Error(`Unsupported parse state: ${o}`)}}},async parseOutput({text:n},r){const o=await Bt({text:n});if(!o.success)throw new ts({message:"No object generated: could not parse the response.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const i=await gt({value:o.value,schema:t});if(!i.success)throw new ts({message:"No object generated: response did not match schema.",cause:i.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return i.value}}},kb="2.0.84",Ib=K(()=>j(d({type:h("error"),error:d({type:u(),message:u()})}))),us=pt({errorSchema:Ib,errorToMessage:e=>e.error.message}),Yu=d({type:u(),category:u().nullish(),explanation:u().nullish(),recommended_model:u().nullish()}),Tb=K(()=>j(d({type:h("message"),id:u().nullish(),model:u().nullish(),content:R(se("type",[d({type:h("text"),text:u(),citations:R(se("type",[d({type:h("web_search_result_location"),cited_text:u(),url:u(),title:u(),encrypted_index:u()}),d({type:h("page_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_page_number:f(),end_page_number:f()}),d({type:h("char_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_char_index:f(),end_char_index:f()})])).optional()}),d({type:h("thinking"),thinking:u(),signature:u()}),d({type:h("redacted_thinking"),data:u()}),d({type:h("compaction"),content:u()}),d({type:h("tool_use"),id:u(),name:u(),input:ze()}),d({type:h("server_tool_use"),id:u(),name:u(),input:Se(u(),ze()).nullish()}),d({type:h("web_fetch_tool_result"),tool_use_id:u(),content:ee([d({type:h("web_fetch_result"),url:u(),retrieved_at:u(),content:d({type:h("document"),title:u().nullable(),citations:d({enabled:ue()}).optional(),source:ee([d({type:h("base64"),media_type:h("application/pdf"),data:u()}),d({type:h("text"),media_type:h("text/plain"),data:u()})])})}),d({type:h("web_fetch_tool_result_error"),error_code:u()})])}),d({type:h("web_search_tool_result"),tool_use_id:u(),content:ee([R(d({type:h("web_search_result"),url:u(),title:u(),encrypted_content:u(),page_age:u().nullish()})),d({type:h("web_search_tool_result_error"),error_code:u()})])}),d({type:h("code_execution_tool_result"),tool_use_id:u(),content:ee([d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f()}),d({type:h("code_execution_tool_result_error"),error_code:u()})])}),d({type:h("bash_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()})])}),d({type:h("text_editor_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})])}),d({type:h("fallback")})])),stop_reason:u().nullish(),stop_sequence:u().nullish(),stop_details:Yu.nullish(),usage:Br({input_tokens:f(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish(),iterations:R(d({type:ee([h("compaction"),h("message"),h("advisor_message"),h("fallback_message")]),model:u().nullish(),input_tokens:f(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish()})).nullish()}),context_management:d({applied_edits:R(ee([d({type:h("clear_tool_uses_20250919"),cleared_tool_uses:f(),cleared_input_tokens:f()}),d({type:h("clear_thinking_20251015"),cleared_thinking_turns:f(),cleared_input_tokens:f()}),d({type:h("compact_20260112")})]))}).nullish(),container:d({expires_at:u(),id:u(),skills:R(d({type:ee([h("anthropic"),h("custom")]),skill_id:u(),version:u()})).nullish()}).nullish()}))),Sb=K(()=>j(se("type",[d({type:h("message_start"),message:d({id:u().nullish(),model:u().nullish(),usage:Br({input_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish()})})}),d({type:h("content_block_start"),index:f(),content_block:se("type",[d({type:h("text"),text:u()}),d({type:h("thinking"),thinking:u()}),d({type:h("tool_use"),id:u(),name:u()}),d({type:h("redacted_thinking"),data:u()}),d({type:h("compaction"),content:u().nullish()}),d({type:h("server_tool_use"),id:u(),name:u(),input:Se(u(),ze()).nullish()}),d({type:h("web_fetch_tool_result"),tool_use_id:u(),content:ee([d({type:h("web_fetch_result"),url:u(),retrieved_at:u(),content:d({type:h("document"),title:u().nullable(),citations:d({enabled:ue()}).optional(),source:ee([d({type:h("base64"),media_type:h("application/pdf"),data:u()}),d({type:h("text"),media_type:h("text/plain"),data:u()})])})}),d({type:h("web_fetch_tool_result_error"),error_code:u()})])}),d({type:h("web_search_tool_result"),tool_use_id:u(),content:ee([R(d({type:h("web_search_result"),url:u(),title:u(),encrypted_content:u(),page_age:u().nullish()})),d({type:h("web_search_tool_result_error"),error_code:u()})])}),d({type:h("code_execution_tool_result"),tool_use_id:u(),content:ee([d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f()}),d({type:h("code_execution_tool_result_error"),error_code:u()})])}),d({type:h("bash_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()})])}),d({type:h("text_editor_code_execution_tool_result"),tool_use_id:u(),content:se("type",[d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})])}),d({type:h("fallback")})])}),d({type:h("content_block_delta"),index:f(),delta:se("type",[d({type:h("input_json_delta"),partial_json:u()}),d({type:h("text_delta"),text:u()}),d({type:h("thinking_delta"),thinking:u()}),d({type:h("signature_delta"),signature:u()}),d({type:h("compaction_delta"),content:u().nullish()}),d({type:h("citations_delta"),citation:se("type",[d({type:h("web_search_result_location"),cited_text:u(),url:u(),title:u(),encrypted_index:u()}),d({type:h("page_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_page_number:f(),end_page_number:f()}),d({type:h("char_location"),cited_text:u(),document_index:f(),document_title:u().nullable(),start_char_index:f(),end_char_index:f()})])})])}),d({type:h("content_block_stop"),index:f()}),d({type:h("error"),error:d({type:u(),message:u()})}),d({type:h("message_delta"),delta:d({stop_reason:u().nullish(),stop_sequence:u().nullish(),stop_details:Yu.nullish(),container:d({expires_at:u(),id:u(),skills:R(d({type:ee([h("anthropic"),h("custom")]),skill_id:u(),version:u()})).nullish()}).nullish()}),usage:Br({input_tokens:f().nullish(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish(),iterations:R(d({type:ee([h("compaction"),h("message"),h("advisor_message"),h("fallback_message")]),model:u().nullish(),input_tokens:f(),output_tokens:f(),cache_creation_input_tokens:f().nullish(),cache_read_input_tokens:f().nullish()})).nullish()}),context_management:d({applied_edits:R(ee([d({type:h("clear_tool_uses_20250919"),cleared_tool_uses:f(),cleared_input_tokens:f()}),d({type:h("clear_thinking_20251015"),cleared_thinking_turns:f(),cleared_input_tokens:f()}),d({type:h("compact_20260112")})]))}).nullish()}),d({type:h("message_stop")}),d({type:h("ping")})]))),Eb=K(()=>j(d({signature:u().optional(),redactedData:u().optional()}))),cs=d({citations:d({enabled:ue()}).optional(),title:u().optional(),context:u().optional()}),Cb=d({sendReasoning:ue().optional(),structuredOutputMode:X(["outputFormat","jsonTool","auto"]).optional(),thinking:se("type",[d({type:h("adaptive"),display:X(["omitted","summarized"]).optional()}),d({type:h("enabled"),budgetTokens:f().optional()}),d({type:h("disabled")})]).optional(),disableParallelToolUse:ue().optional(),cacheControl:d({type:h("ephemeral"),ttl:ee([h("5m"),h("1h")]).optional()}).optional(),metadata:d({userId:u().optional()}).optional(),container:d({id:u().optional(),skills:R(d({type:ee([h("anthropic"),h("custom")]),skillId:u(),version:u().optional()})).optional()}).optional(),effort:X(["low","medium","high","xhigh","max"]).optional(),taskBudget:d({type:h("tokens"),total:f().int().min(2e4),remaining:f().int().min(0).optional()}).optional(),speed:X(["fast","standard"]).optional(),inferenceGeo:X(["us","global"]).optional(),fallbacks:R(d({model:u(),max_tokens:f().int().optional(),thinking:Se(u(),ze()).optional(),output_config:Se(u(),ze()).optional(),speed:X(["fast","standard"]).optional()})).optional(),contextManagement:d({edits:R(se("type",[d({type:h("clear_tool_uses_20250919"),trigger:se("type",[d({type:h("input_tokens"),value:f()}),d({type:h("tool_uses"),value:f()})]).optional(),keep:d({type:h("tool_uses"),value:f()}).optional(),clearAtLeast:d({type:h("input_tokens"),value:f()}).optional(),clearToolInputs:ue().optional(),excludeTools:R(u()).optional()}),d({type:h("clear_thinking_20251015"),keep:ee([h("all"),d({type:h("thinking_turns"),value:f()})]).optional()}),d({type:h("compact_20260112"),trigger:d({type:h("input_tokens"),value:f()}).optional(),pauseAfterCompaction:ue().optional(),instructions:u().optional()})]))}).optional(),anthropicBeta:R(u()).optional()}),ds=4;function Ab(e){var t;const n=e==null?void 0:e.anthropic;return(t=n==null?void 0:n.cacheControl)!=null?t:n==null?void 0:n.cache_control}var Oo=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){const n=Ab(e);if(n){if(!t.canCache){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>ds){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`Maximum ${ds} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},Ob=K(()=>j(d({maxCharacters:f().optional()}))),$b=K(()=>j(d({command:X(["view","create","str_replace","insert"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),Nb=yt({id:"anthropic.text_editor_20250728",name:"str_replace_based_edit_tool",inputSchema:$b}),Rb=(e={})=>Nb(e),Pb=K(()=>j(d({maxUses:f().optional(),allowedDomains:R(u()).optional(),blockedDomains:R(u()).optional(),userLocation:d({type:h("approximate"),city:u().optional(),region:u().optional(),country:u().optional(),timezone:u().optional()}).optional()}))),Xu=K(()=>j(R(d({url:u(),title:u().nullable(),pageAge:u().nullable(),encryptedContent:u(),type:h("web_search_result")})))),Mb=K(()=>j(d({query:u()}))),zb=Ye({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:Mb,outputSchema:Xu}),Lb=(e={})=>zb(e),Db=K(()=>j(d({maxUses:f().optional(),allowedDomains:R(u()).optional(),blockedDomains:R(u()).optional(),citations:d({enabled:ue()}).optional(),maxContentTokens:f().optional()}))),Qu=K(()=>j(d({type:h("web_fetch_result"),url:u(),content:d({type:h("document"),title:u().nullable(),citations:d({enabled:ue()}).optional(),source:ee([d({type:h("base64"),mediaType:h("application/pdf"),data:u()}),d({type:h("text"),mediaType:h("text/plain"),data:u()})])}),retrievedAt:u().nullable()}))),Zb=K(()=>j(d({url:u()}))),jb=Ye({id:"anthropic.web_fetch_20250910",name:"web_fetch",inputSchema:Zb,outputSchema:Qu}),Ub=(e={})=>jb(e);async function Bb({tools:e,toolChoice:t,disableParallelToolUse:n,cacheControlValidator:r}){var o;e=e!=null&&e.length?e:void 0;const i=[],a=new Set,s=r||new Oo;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};const l=[];for(const p of e)switch(p.type){case"function":{const g=s.getCacheControl(p.providerOptions,{type:"tool definition",canCache:!0}),x=(o=p.providerOptions)==null?void 0:o.anthropic,T=x==null?void 0:x.eagerInputStreaming;l.push({name:p.name,description:p.description,input_schema:p.inputSchema,cache_control:g,...T?{eager_input_streaming:!0}:{}});break}case"provider-defined":{switch(p.id){case"anthropic.code_execution_20250522":{a.add("code-execution-2025-05-22"),l.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{a.add("code-execution-2025-08-25"),l.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{l.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{a.add("computer-use-2025-01-24"),l.push({name:"computer",type:"computer_20250124",display_width_px:p.args.displayWidthPx,display_height_px:p.args.displayHeightPx,display_number:p.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{a.add("computer-use-2024-10-22"),l.push({name:"computer",type:"computer_20241022",display_width_px:p.args.displayWidthPx,display_height_px:p.args.displayHeightPx,display_number:p.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{a.add("computer-use-2025-01-24"),l.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{a.add("computer-use-2024-10-22"),l.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{a.add("computer-use-2025-01-24"),l.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{const g=await Me({value:p.args,schema:Ob});l.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:g.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{a.add("computer-use-2025-01-24"),l.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{a.add("computer-use-2024-10-22"),l.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{a.add("context-management-2025-06-27"),l.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{a.add("web-fetch-2025-09-10");const g=await Me({value:p.args,schema:Db});l.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,citations:g.citations,max_content_tokens:g.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{const g=await Me({value:p.args,schema:Pb});l.push({type:"web_search_20250305",name:"web_search",max_uses:g.maxUses,allowed_domains:g.allowedDomains,blocked_domains:g.blockedDomains,user_location:g.userLocation,cache_control:void 0});break}default:{i.push({type:"unsupported-tool",tool:p});break}}break}default:{i.push({type:"unsupported-tool",tool:p});break}}if(t==null)return{tools:l,toolChoice:n?{type:"auto",disable_parallel_tool_use:n}:void 0,toolWarnings:i,betas:a};const c=t.type;switch(c){case"auto":return{tools:l,toolChoice:{type:"auto",disable_parallel_tool_use:n},toolWarnings:i,betas:a};case"required":return{tools:l,toolChoice:{type:"any",disable_parallel_tool_use:n},toolWarnings:i,betas:a};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:i,betas:a};case"tool":return{tools:l,toolChoice:{type:"tool",name:t.toolName,disable_parallel_tool_use:n},toolWarnings:i,betas:a};default:{const p=c;throw new je({functionality:`tool choice type: ${p}`})}}}var ec=K(()=>j(d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f()}))),Vb=K(()=>j(d({code:u()}))),Fb=Ye({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:Vb,outputSchema:ec}),qb=(e={})=>Fb(e),tc=K(()=>j(se("type",[d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})]))),Gb=K(()=>j(se("type",[d({type:h("bash_code_execution"),command:u()}),se("command",[d({type:h("text_editor_code_execution"),command:h("view"),path:u()}),d({type:h("text_editor_code_execution"),command:h("create"),path:u(),file_text:u().nullish()}),d({type:h("text_editor_code_execution"),command:h("str_replace"),path:u(),old_str:u(),new_str:u()})])]))),Hb=Ye({id:"anthropic.code_execution_20250825",name:"code_execution",inputSchema:Gb,outputSchema:tc}),Wb=(e={})=>Hb(e);function Jb(e){if(typeof e=="string")return Buffer.from(e,"base64").toString("utf-8");if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new je({functionality:"URL-based text documents are not supported for citations"}):new je({functionality:`unsupported data type for text documents: ${typeof e}`})}async function Kb({prompt:e,sendReasoning:t,warnings:n,cacheControlValidator:r}){var o,i,a,s,l,c;const p=new Set,g=Yb(e),x=r||new Oo;let T;const I=[];async function E(_){var v,y;const $=await We({provider:"anthropic",providerOptions:_,schema:cs});return(y=(v=$==null?void 0:$.citations)==null?void 0:v.enabled)!=null?y:!1}async function k(_){const v=await We({provider:"anthropic",providerOptions:_,schema:cs});return{title:v==null?void 0:v.title,context:v==null?void 0:v.context}}for(let _=0;_<g.length;_++){const v=g[_],y=_===g.length-1,$=v.type;switch($){case"system":{const b=v.messages.map(({content:S,providerOptions:m})=>({type:"text",text:S,cache_control:x.getCacheControl(m,{type:"system message",canCache:!0})}));T==null?T=b:(I.push({role:"system",content:b}),p.add("mid-conversation-system-2026-04-07"));break}case"user":{const b=[];for(const S of v.messages){const{role:m,content:N}=S;switch(m){case"user":{for(let Z=0;Z<N.length;Z++){const B=N[Z],L=Z===N.length-1,oe=(o=x.getCacheControl(B.providerOptions,{type:"user message part",canCache:!0}))!=null?o:L?x.getCacheControl(S.providerOptions,{type:"user message",canCache:!0}):void 0;switch(B.type){case"text":{b.push({type:"text",text:B.text,cache_control:oe});break}case"file":{if(B.mediaType.startsWith("image/"))b.push({type:"image",source:B.data instanceof URL?{type:"url",url:B.data.toString()}:{type:"base64",media_type:B.mediaType==="image/*"?"image/jpeg":B.mediaType,data:St(B.data)},cache_control:oe});else if(B.mediaType==="application/pdf"){p.add("pdfs-2024-09-25");const z=await E(B.providerOptions),V=await k(B.providerOptions);b.push({type:"document",source:B.data instanceof URL?{type:"url",url:B.data.toString()}:{type:"base64",media_type:"application/pdf",data:St(B.data)},title:(i=V.title)!=null?i:B.filename,...V.context&&{context:V.context},...z&&{citations:{enabled:!0}},cache_control:oe})}else if(B.mediaType==="text/plain"){const z=await E(B.providerOptions),V=await k(B.providerOptions);b.push({type:"document",source:B.data instanceof URL?{type:"url",url:B.data.toString()}:{type:"text",media_type:"text/plain",data:Jb(B.data)},title:(a=V.title)!=null?a:B.filename,...V.context&&{context:V.context},...z&&{citations:{enabled:!0}},cache_control:oe})}else throw new je({functionality:`media type: ${B.mediaType}`});break}}}break}case"tool":{for(let Z=0;Z<N.length;Z++){const B=N[Z],L=Z===N.length-1,oe=(s=x.getCacheControl(B.providerOptions,{type:"tool result part",canCache:!0}))!=null?s:L?x.getCacheControl(S.providerOptions,{type:"tool result message",canCache:!0}):void 0,z=B.output;let V;switch(z.type){case"content":V=z.value.map(W=>{switch(W.type){case"text":return{type:"text",text:W.text};case"media":{if(W.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:W.mediaType,data:W.data}};if(W.mediaType==="application/pdf")return p.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:W.mediaType,data:W.data}};throw new je({functionality:`media type: ${W.mediaType}`})}}});break;case"text":case"error-text":V=z.value;break;case"json":case"error-json":default:V=JSON.stringify(z.value);break}b.push({type:"tool_result",tool_use_id:B.toolCallId,content:V,is_error:z.type==="error-text"||z.type==="error-json"?!0:void 0,cache_control:oe})}break}default:{const Z=m;throw new Error(`Unsupported role: ${Z}`)}}}I.push({role:"user",content:b});break}case"assistant":{const b=[];for(let S=0;S<v.messages.length;S++){const m=v.messages[S],N=S===v.messages.length-1,{content:Z}=m;for(let B=0;B<Z.length;B++){const L=Z[B],oe=B===Z.length-1,z=(l=x.getCacheControl(L.providerOptions,{type:"assistant message part",canCache:!0}))!=null?l:oe?x.getCacheControl(m.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(L.type){case"text":{const V=(c=L.providerOptions)==null?void 0:c.anthropic;(V==null?void 0:V.type)==="compaction"?b.push({type:"compaction",content:L.text,cache_control:z}):b.push({type:"text",text:y&&N&&oe?L.text.trim():L.text,cache_control:z});break}case"reasoning":{if(t){const V=await We({provider:"anthropic",providerOptions:L.providerOptions,schema:Eb});V!=null?V.signature!=null?(x.getCacheControl(L.providerOptions,{type:"thinking block",canCache:!1}),b.push({type:"thinking",thinking:L.text,signature:V.signature})):V.redactedData!=null?(x.getCacheControl(L.providerOptions,{type:"redacted thinking block",canCache:!1}),b.push({type:"redacted_thinking",data:V.redactedData})):n.push({type:"other",message:"unsupported reasoning metadata"}):n.push({type:"other",message:"unsupported reasoning metadata"})}else n.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(L.providerExecuted){L.toolName==="code_execution"&&L.input!=null&&typeof L.input=="object"&&"type"in L.input&&typeof L.input.type=="string"&&(L.input.type==="bash_code_execution"||L.input.type==="text_editor_code_execution")?b.push({type:"server_tool_use",id:L.toolCallId,name:L.input.type,input:L.input,cache_control:z}):L.toolName==="code_execution"||L.toolName==="web_fetch"||L.toolName==="web_search"?b.push({type:"server_tool_use",id:L.toolCallId,name:L.toolName,input:L.input,cache_control:z}):n.push({type:"other",message:`provider executed tool call for tool ${L.toolName} is not supported`});break}b.push({type:"tool_use",id:L.toolCallId,name:L.toolName,input:L.input,cache_control:z});break}case"tool-result":{if(L.toolName==="code_execution"){const V=L.output;if(V.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${V.type} for tool ${L.toolName} is not supported`});break}if(V.value==null||typeof V.value!="object"||!("type"in V.value)||typeof V.value.type!="string"){n.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${L.toolName}`});break}if(V.value.type==="code_execution_result"){const W=await Me({value:V.value,schema:ec});b.push({type:"code_execution_tool_result",tool_use_id:L.toolCallId,content:{type:W.type,stdout:W.stdout,stderr:W.stderr,return_code:W.return_code},cache_control:z})}else{const W=await Me({value:V.value,schema:tc});b.push(W.type==="bash_code_execution_result"||W.type==="bash_code_execution_tool_result_error"?{type:"bash_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:z,content:W}:{type:"text_editor_code_execution_tool_result",tool_use_id:L.toolCallId,cache_control:z,content:W})}break}if(L.toolName==="web_fetch"){const V=L.output;if(V.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${V.type} for tool ${L.toolName} is not supported`});break}const W=await Me({value:V.value,schema:Qu});b.push({type:"web_fetch_tool_result",tool_use_id:L.toolCallId,content:{type:"web_fetch_result",url:W.url,retrieved_at:W.retrievedAt,content:{type:"document",title:W.content.title,citations:W.content.citations,source:{type:W.content.source.type,media_type:W.content.source.mediaType,data:W.content.source.data}}},cache_control:z});break}if(L.toolName==="web_search"){const V=L.output;if(V.type!=="json"){n.push({type:"other",message:`provider executed tool result output type ${V.type} for tool ${L.toolName} is not supported`});break}const W=await Me({value:V.value,schema:Xu});b.push({type:"web_search_tool_result",tool_use_id:L.toolCallId,content:W.map(be=>({url:be.url,title:be.title,page_age:be.pageAge,encrypted_content:be.encryptedContent,type:be.type})),cache_control:z});break}n.push({type:"other",message:`provider executed tool result for tool ${L.toolName} is not supported`});break}}}}I.push({role:"assistant",content:b});break}default:{const b=$;throw new Error(`content type: ${b}`)}}}return{prompt:{system:T,messages:I},betas:p}}function Yb(e){const t=[];let n;for(const r of e){const{role:o}=r;switch(o){case"system":{(n==null?void 0:n.type)!=="system"&&(n={type:"system",messages:[]},t.push(n)),n.messages.push(r);break}case"assistant":{(n==null?void 0:n.type)!=="assistant"&&(n={type:"assistant",messages:[]},t.push(n)),n.messages.push(r);break}case"user":{(n==null?void 0:n.type)!=="user"&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break}case"tool":{(n==null?void 0:n.type)!=="user"&&(n={type:"user",messages:[]},t.push(n)),n.messages.push(r);break}default:{const i=o;throw new Error(`Unsupported role: ${i}`)}}}return t}function ps({finishReason:e,isJsonResponseFromTool:t}){switch(e){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return t?"stop":"tool-calls";case"max_tokens":return"length";case"compaction":return"other";default:return"unknown"}}var nc=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),Xb=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];function Qb(e){return rc(e)}function bt(e){return typeof e=="boolean"||!rw(e)?e:rc(e)}function rc(e){const t={},n=e;if(e.$ref!=null)return{$ref:e.$ref};if(e.$schema!=null&&(t.$schema=e.$schema),e.$id!=null&&(t.$id=e.$id),e.title!=null&&(t.title=e.title),e.description!=null&&(t.description=e.description),e.default!==void 0&&(t.default=e.default),e.const!==void 0&&(t.const=e.const),e.enum!=null&&(t.enum=e.enum),e.type!=null&&(t.type=e.type),e.anyOf!=null?t.anyOf=e.anyOf.map(bt):e.oneOf!=null&&(t.anyOf=e.oneOf.map(bt)),e.allOf!=null&&(t.allOf=e.allOf.map(bt)),e.definitions!=null&&(t.definitions=Object.fromEntries(Object.entries(e.definitions).map(([o,i])=>[o,bt(i)]))),n.$defs!=null){const o=t;o.$defs=Object.fromEntries(Object.entries(n.$defs).map(([i,a])=>[i,bt(a)]))}(e.type==="object"||e.properties!=null)&&(e.properties!=null&&(t.properties=Object.fromEntries(Object.entries(e.properties).map(([o,i])=>[o,bt(i)]))),t.additionalProperties=!1,e.required!=null&&(t.required=e.required)),e.items!=null&&(t.items=Array.isArray(e.items)?e.items.map(bt):bt(e.items)),typeof e.format=="string"&&nc.has(e.format)&&(t.format=e.format);const r=ew(e);return r!=null&&(t.description=t.description==null?r:`${t.description}
|
|
73
|
+
${r}`),t}function ew(e){const t=Xb.flatMap(n=>{const r=e[n];return r==null||r===!1?[]:`${tw(n)}: ${nw(r)}`});return typeof e.format=="string"&&!nc.has(e.format)&&t.push(`format: ${e.format}`),t.length===0?void 0:`${t.join("; ")}.`}function tw(e){return e.replace(/[A-Z]/g,t=>` ${t.toLowerCase()}`)}function nw(e){return typeof e=="string"?e:JSON.stringify(e)}function rw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hs(e,t,n){var r;if(e.type!=="page_location"&&e.type!=="char_location")return;const o=t[e.document_index];if(o)return{type:"source",sourceType:"document",id:n(),mediaType:o.mediaType,title:(r=e.document_title)!=null?r:o.title,filename:o.filename,providerMetadata:{anthropic:e.type==="page_location"?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}var ow=class{constructor(e,t){this.specificationVersion="v2";var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)!=null?n:Ge}supportsUrl(e){return e.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?n:{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:r,topP:o,topK:i,frequencyPenalty:a,presencePenalty:s,stopSequences:l,responseFormat:c,seed:p,tools:g,toolChoice:x,providerOptions:T}){var I,E,k,_,v,y,$,b;const S=[];a!=null&&S.push({type:"unsupported-setting",setting:"frequencyPenalty"}),s!=null&&S.push({type:"unsupported-setting",setting:"presencePenalty"}),p!=null&&S.push({type:"unsupported-setting",setting:"seed"}),r!=null&&r>1?(S.push({type:"unsupported-setting",setting:"temperature",details:`${r} exceeds anthropic maximum of 1.0. clamped to 1.0`}),r=1):r!=null&&r<0&&(S.push({type:"unsupported-setting",setting:"temperature",details:`${r} is below anthropic minimum of 0. clamped to 0`}),r=0),(c==null?void 0:c.type)==="json"&&(c.schema==null?S.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."}):g!=null&&S.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."}));const m=await We({provider:"anthropic",providerOptions:T,schema:Cb}),{maxOutputTokens:N,supportsStructuredOutput:Z,rejectsSamplingParameters:B,isKnownModel:L}=iw(this.modelId);B&&(r!=null&&(S.push({type:"unsupported-setting",setting:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),r=void 0),i!=null&&(S.push({type:"unsupported-setting",setting:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),i=void 0),o!=null&&(S.push({type:"unsupported-setting",setting:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),o=void 0)),L||this.modelId.startsWith("claude-");const oe=(I=m==null?void 0:m.structuredOutputMode)!=null?I:"jsonTool",z=oe==="outputFormat"||oe==="auto"&&Z,V=(c==null?void 0:c.type)==="json"&&c.schema!=null&&!z?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:c.schema}:void 0,W=new Oo,{prompt:be,betas:Y}=await Kb({prompt:t,sendReasoning:(E=m==null?void 0:m.sendReasoning)!=null?E:!0,warnings:S,cacheControlValidator:W}),we=(k=m==null?void 0:m.thinking)==null?void 0:k.type,ge=we==="enabled"||we==="adaptive";let Ce=we==="enabled"?(_=m==null?void 0:m.thinking)==null?void 0:_.budgetTokens:void 0;const le=we==="adaptive"?(v=m==null?void 0:m.thinking)==null?void 0:v.display:void 0,he=n??N,de={model:this.modelId,max_tokens:he,temperature:r,top_k:i,top_p:o,stop_sequences:l,...ge&&{thinking:{type:we,...Ce!=null&&{budget_tokens:Ce},...le!=null&&{display:le}}},...((m==null?void 0:m.effort)||(m==null?void 0:m.taskBudget)||z&&(c==null?void 0:c.type)==="json"&&c.schema!=null)&&{output_config:{...(m==null?void 0:m.effort)&&{effort:m.effort},...(m==null?void 0:m.taskBudget)&&{task_budget:{type:m.taskBudget.type,total:m.taskBudget.total,...m.taskBudget.remaining!=null&&{remaining:m.taskBudget.remaining}}},...z&&(c==null?void 0:c.type)==="json"&&c.schema!=null&&{format:{type:"json_schema",schema:Qb(c.schema)}}}},...(m==null?void 0:m.speed)&&{speed:m.speed},...(m==null?void 0:m.inferenceGeo)&&{inference_geo:m.inferenceGeo},...(m==null?void 0:m.fallbacks)&&m.fallbacks.length>0&&{fallbacks:m.fallbacks},...(m==null?void 0:m.cacheControl)&&{cache_control:m.cacheControl},...((y=m==null?void 0:m.metadata)==null?void 0:y.userId)!=null&&{metadata:{user_id:m.metadata.userId}},...(m==null?void 0:m.container)&&{container:{id:m.container.id,skills:($=m.container.skills)==null?void 0:$.map(w=>({type:w.type,skill_id:w.skillId,version:w.version}))}},...(m==null?void 0:m.contextManagement)&&{context_management:{edits:m.contextManagement.edits.map(w=>{const ie=w.type;switch(ie){case"clear_tool_uses_20250919":return{type:w.type,...w.trigger!==void 0&&{trigger:w.trigger},...w.keep!==void 0&&{keep:w.keep},...w.clearAtLeast!==void 0&&{clear_at_least:w.clearAtLeast},...w.clearToolInputs!==void 0&&{clear_tool_inputs:w.clearToolInputs},...w.excludeTools!==void 0&&{exclude_tools:w.excludeTools}};case"clear_thinking_20251015":return{type:w.type,...w.keep!==void 0&&{keep:w.keep}};case"compact_20260112":return{type:w.type,...w.trigger!==void 0&&{trigger:w.trigger},...w.pauseAfterCompaction!==void 0&&{pause_after_compaction:w.pauseAfterCompaction},...w.instructions!==void 0&&{instructions:w.instructions}};default:S.push({type:"other",message:`Unknown context management strategy: ${ie}`});return}}).filter(w=>w!==void 0)}},system:be.system,messages:be.messages};ge&&(we==="enabled"&&Ce==null&&(S.push({type:"other",message:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),de.thinking={type:"enabled",budget_tokens:1024},Ce=1024),de.temperature!=null&&(de.temperature=void 0,S.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),i!=null&&(de.top_k=void 0,S.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(de.top_p=void 0,S.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),de.max_tokens=he+(Ce??0)),L&&de.max_tokens>N&&(n!=null&&S.push({type:"unsupported-setting",setting:"maxOutputTokens",details:`${de.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${N} max output tokens. The max output tokens have been limited to ${N}.`}),de.max_tokens=N),m!=null&&m.container&&m.container.skills&&m.container.skills.length>0&&(Y.add("code-execution-2025-08-25"),Y.add("skills-2025-10-02"),Y.add("files-api-2025-04-14"),g!=null&&g.some(w=>w.type==="provider-defined"&&(w.id==="anthropic.code_execution_20250825"||w.id==="anthropic.code_execution_20260120"))||S.push({type:"other",message:"code execution tool is required when using skills"})),m!=null&&m.effort&&Y.add("effort-2025-11-24"),m!=null&&m.taskBudget&&Y.add("task-budgets-2026-03-13"),(m==null?void 0:m.speed)==="fast"&&Y.add("fast-mode-2026-02-01"),m!=null&&m.fallbacks&&m.fallbacks.length>0&&Y.add("server-side-fallback-2026-06-01"),z&&Y.add("structured-outputs-2025-11-13");const ke=m==null?void 0:m.contextManagement;ke&&(Y.add("context-management-2025-06-27"),ke.edits.some(w=>w.type==="compact_20260112")&&Y.add("compact-2026-01-12"));const{tools:O,toolChoice:ne,toolWarnings:C,betas:H}=await Bb(V!=null?{tools:[V],toolChoice:{type:"tool",toolName:V.name},disableParallelToolUse:!0,cacheControlValidator:W}:{tools:g??[],toolChoice:x,disableParallelToolUse:m==null?void 0:m.disableParallelToolUse,cacheControlValidator:W}),re=W.getWarnings();return{args:{...de,tools:O,tool_choice:ne},warnings:[...S,...C,...re],betas:new Set([...Y,...H,...e,...(b=m==null?void 0:m.anthropicBeta)!=null?b:[]]),usesJsonResponseTool:V!=null}}async getHeaders({betas:e,headers:t}){return Le(await Ue(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(",")}:{})}async getBetasFromHeaders(e){var t,n;const o=(t=(await Ue(this.config.headers))["anthropic-beta"])!=null?t:"",i=(n=e==null?void 0:e["anthropic-beta"])!=null?n:"";return new Set([...o.toLowerCase().split(","),...i.toLowerCase().split(",")].map(a=>a.trim()).filter(a=>a!==""))}buildRequestUrl(e){var t,n,r;return(r=(n=(t=this.config).buildRequestUrl)==null?void 0:n.call(t,this.config.baseURL,e))!=null?r:`${this.config.baseURL}/messages`}transformRequestBody(e,t){var n,r,o;return(o=(r=(n=this.config).transformRequestBody)==null?void 0:r.call(n,e,t))!=null?o:e}extractCitationDocuments(e){const t=n=>{var r,o;if(n.type!=="file"||n.mediaType!=="application/pdf"&&n.mediaType!=="text/plain")return!1;const i=(r=n.providerOptions)==null?void 0:r.anthropic,a=i==null?void 0:i.citations;return(o=a==null?void 0:a.enabled)!=null?o:!1};return e.filter(n=>n.role==="user").flatMap(n=>n.content).filter(t).map(n=>{var r;const o=n;return{title:(r=o.filename)!=null?r:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(e){var t,n,r,o,i,a,s,l,c;const{args:p,warnings:g,betas:x,usesJsonResponseTool:T}=await this.getArgs({...e,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),I=this.extractCitationDocuments(e.prompt),{responseHeaders:E,value:k,rawValue:_}=await De({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:x,headers:e.headers}),body:this.transformRequestBody(p,x),failedResponseHandler:us,successfulResponseHandler:Be(Tb),abortSignal:e.abortSignal,fetch:this.config.fetch}),v=[];for(const m of k.content)switch(m.type){case"text":{if(!T&&(v.push({type:"text",text:m.text}),m.citations))for(const N of m.citations){const Z=hs(N,I,this.generateId);Z&&v.push(Z)}break}case"thinking":{v.push({type:"reasoning",text:m.thinking,providerMetadata:{anthropic:{signature:m.signature}}});break}case"redacted_thinking":{v.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:m.data}}});break}case"compaction":{v.push({type:"text",text:m.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{v.push(T?{type:"text",text:JSON.stringify(m.input)}:{type:"tool-call",toolCallId:m.id,toolName:m.name,input:JSON.stringify(m.input)});break}case"server_tool_use":{m.name==="text_editor_code_execution"||m.name==="bash_code_execution"?v.push({type:"tool-call",toolCallId:m.id,toolName:"code_execution",input:JSON.stringify({type:m.name,...m.input}),providerExecuted:!0}):(m.name==="web_search"||m.name==="code_execution"||m.name==="web_fetch")&&v.push({type:"tool-call",toolCallId:m.id,toolName:m.name,input:JSON.stringify(m.input),providerExecuted:!0});break}case"web_fetch_tool_result":{m.content.type==="web_fetch_result"?v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:m.content.url,retrievedAt:m.content.retrieved_at,content:{type:m.content.content.type,title:m.content.content.title,citations:m.content.content.citations,source:{type:m.content.content.source.type,mediaType:m.content.content.source.media_type,data:m.content.content.source.data}}},providerExecuted:!0}):m.content.type==="web_fetch_tool_result_error"&&v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:m.content.error_code},providerExecuted:!0});break}case"web_search_tool_result":{if(Array.isArray(m.content)){v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_search",result:m.content.map(N=>{var Z;return{url:N.url,title:N.title,pageAge:(Z=N.page_age)!=null?Z:null,encryptedContent:N.encrypted_content,type:N.type}}),providerExecuted:!0});for(const N of m.content)v.push({type:"source",sourceType:"url",id:this.generateId(),url:N.url,title:N.title,providerMetadata:{anthropic:{pageAge:(t=N.page_age)!=null?t:null}}})}else v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:m.content.error_code},providerExecuted:!0});break}case"code_execution_tool_result":{m.content.type==="code_execution_result"?v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"code_execution",result:{type:m.content.type,stdout:m.content.stdout,stderr:m.content.stderr,return_code:m.content.return_code},providerExecuted:!0}):m.content.type==="code_execution_tool_result_error"&&v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:m.content.error_code},providerExecuted:!0});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{v.push({type:"tool-result",toolCallId:m.tool_use_id,toolName:"code_execution",result:m.content,providerExecuted:!0});break}}let y,$;const b=(n=k.usage.iterations)==null?void 0:n.some(m=>m.type==="fallback_message");if(k.usage.iterations&&k.usage.iterations.length>0&&!b){const m=k.usage.iterations.reduce((N,Z)=>({input:N.input+Z.input_tokens,output:N.output+Z.output_tokens}),{input:0,output:0});y=m.input,$=m.output}else y=k.usage.input_tokens,$=k.usage.output_tokens;const S=fs(k.stop_details);return{content:v,finishReason:ps({finishReason:k.stop_reason,isJsonResponseFromTool:T}),usage:{inputTokens:y,outputTokens:$,totalTokens:y+$,cachedInputTokens:(r=k.usage.cache_read_input_tokens)!=null?r:void 0},request:{body:p},response:{id:(o=k.id)!=null?o:void 0,modelId:(i=k.model)!=null?i:void 0,headers:E,body:_},warnings:g,providerMetadata:{anthropic:{usage:k.usage,cacheCreationInputTokens:(a=k.usage.cache_creation_input_tokens)!=null?a:null,stopSequence:(s=k.stop_sequence)!=null?s:null,...S!=null?{stopDetails:S}:{},iterations:k.usage.iterations?k.usage.iterations.map(m=>({type:m.type,...m.model!=null?{model:m.model}:{},inputTokens:m.input_tokens,outputTokens:m.output_tokens})):null,container:k.container?{expiresAt:k.container.expires_at,id:k.container.id,skills:(c=(l=k.container.skills)==null?void 0:l.map(m=>({type:m.type,skillId:m.skill_id,version:m.version})))!=null?c:null}:null,contextManagement:k.context_management?{appliedEdits:k.context_management.applied_edits.map(m=>{switch(m.type){case"clear_tool_uses_20250919":return{type:m.type,clearedToolUses:m.cleared_tool_uses,clearedInputTokens:m.cleared_input_tokens};case"clear_thinking_20251015":return{type:m.type,clearedThinkingTurns:m.cleared_thinking_turns,clearedInputTokens:m.cleared_input_tokens};case"compact_20260112":return{type:m.type}}}).filter(m=>m!==void 0)}:null}}}}async doStream(e){var t,n;const{args:r,warnings:o,betas:i,usesJsonResponseTool:a}=await this.getArgs({...e,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),s=this.extractCitationDocuments(e.prompt),l={...r,stream:!0},c=this.buildRequestUrl(!0),{responseHeaders:p,value:g}=await De({url:c,headers:await this.getHeaders({betas:i,headers:e.headers}),body:this.transformRequestBody(l,i),failedResponseHandler:us,successfulResponseHandler:Nn(Sb),abortSignal:e.abortSignal,fetch:this.config.fetch});let x="unknown";const T={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},I={};let E,k=null,_=null,v,y=null,$=null,b=null,S;const m=this.generateId,N=g.pipeThrough(new TransformStream({start(oe){oe.enqueue({type:"stream-start",warnings:o})},transform(oe,z){var V,W,be,Y,we,ge,Ce,le,he,de,ke;if(e.includeRawChunks&&z.enqueue({type:"raw",rawValue:oe.rawValue}),!oe.success){z.enqueue({type:"error",error:oe.error});return}const O=oe.value;switch(O.type){case"ping":return;case"content_block_start":{const ne=O.content_block.type;if(ne==="fallback")return;switch(S=ne,ne){case"text":{I[O.index]={type:"text"},z.enqueue({type:"text-start",id:String(O.index)});return}case"thinking":{I[O.index]={type:"reasoning"},z.enqueue({type:"reasoning-start",id:String(O.index)});return}case"redacted_thinking":{I[O.index]={type:"reasoning"},z.enqueue({type:"reasoning-start",id:String(O.index),providerMetadata:{anthropic:{redactedData:O.content_block.data}}});return}case"compaction":{I[O.index]={type:"text"},z.enqueue({type:"text-start",id:String(O.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{I[O.index]=a?{type:"text"}:{type:"tool-call",toolCallId:O.content_block.id,toolName:O.content_block.name,input:"",firstDelta:!0},z.enqueue(a?{type:"text-start",id:String(O.index)}:{type:"tool-input-start",id:O.content_block.id,toolName:O.content_block.name});return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(O.content_block.name)){I[O.index]={type:"tool-call",toolCallId:O.content_block.id,toolName:O.content_block.name,input:"",providerExecuted:!0,firstDelta:!0};const C=O.content_block.name==="text_editor_code_execution"||O.content_block.name==="bash_code_execution"?"code_execution":O.content_block.name;z.enqueue({type:"tool-input-start",id:O.content_block.id,toolName:C,providerExecuted:!0})}return}case"web_fetch_tool_result":{const C=O.content_block;C.content.type==="web_fetch_result"?z.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:C.content.url,retrievedAt:C.content.retrieved_at,content:{type:C.content.content.type,title:C.content.content.title,citations:C.content.content.citations,source:{type:C.content.content.source.type,mediaType:C.content.content.source.media_type,data:C.content.content.source.data}}},providerExecuted:!0}):C.content.type==="web_fetch_tool_result_error"&&z.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:C.content.error_code},providerExecuted:!0});return}case"web_search_tool_result":{const C=O.content_block;if(Array.isArray(C.content)){z.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_search",result:C.content.map(H=>{var re;return{url:H.url,title:H.title,pageAge:(re=H.page_age)!=null?re:null,encryptedContent:H.encrypted_content,type:H.type}}),providerExecuted:!0});for(const H of C.content)z.enqueue({type:"source",sourceType:"url",id:m(),url:H.url,title:H.title,providerMetadata:{anthropic:{pageAge:(V=H.page_age)!=null?V:null}}})}else z.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:C.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{const C=O.content_block;C.content.type==="code_execution_result"?z.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"code_execution",result:{type:C.content.type,stdout:C.content.stdout,stderr:C.content.stderr,return_code:C.content.return_code},providerExecuted:!0}):C.content.type==="code_execution_tool_result_error"&&z.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:C.content.error_code},providerExecuted:!0});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{const C=O.content_block;z.enqueue({type:"tool-result",toolCallId:C.tool_use_id,toolName:"code_execution",result:C.content,providerExecuted:!0});return}default:{const C=ne;throw new Error(`Unsupported content block type: ${C}`)}}}case"content_block_stop":{if(I[O.index]!=null){const ne=I[O.index];switch(ne.type){case"text":{z.enqueue({type:"text-end",id:String(O.index)});break}case"reasoning":{z.enqueue({type:"reasoning-end",id:String(O.index)});break}case"tool-call":if(!a){z.enqueue({type:"tool-input-end",id:ne.toolCallId});const C=ne.toolName==="text_editor_code_execution"||ne.toolName==="bash_code_execution"?"code_execution":ne.toolName;z.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:C,input:ne.input===""?"{}":ne.input,providerExecuted:ne.providerExecuted})}break}delete I[O.index]}S=void 0;return}case"content_block_delta":{const ne=O.delta.type;switch(ne){case"text_delta":{if(a)return;z.enqueue({type:"text-delta",id:String(O.index),delta:O.delta.text});return}case"thinking_delta":{z.enqueue({type:"reasoning-delta",id:String(O.index),delta:O.delta.thinking});return}case"signature_delta":{S==="thinking"&&z.enqueue({type:"reasoning-delta",id:String(O.index),delta:"",providerMetadata:{anthropic:{signature:O.delta.signature}}});return}case"compaction_delta":{O.delta.content!=null&&z.enqueue({type:"text-delta",id:String(O.index),delta:O.delta.content});return}case"input_json_delta":{const C=I[O.index];let H=O.delta.partial_json;if(H.length===0)return;if(a){if((C==null?void 0:C.type)!=="text")return;z.enqueue({type:"text-delta",id:String(O.index),delta:H})}else{if((C==null?void 0:C.type)!=="tool-call")return;C.firstDelta&&(C.toolName==="bash_code_execution"||C.toolName==="text_editor_code_execution")&&(H=`{"type": "${C.toolName}",${H.substring(1)}`),z.enqueue({type:"tool-input-delta",id:C.toolCallId,delta:H}),C.input+=H,C.firstDelta=!1}return}case"citations_delta":{const C=O.delta.citation,H=hs(C,s,m);H&&z.enqueue(H);return}default:{const C=ne;throw new Error(`Unsupported delta type: ${C}`)}}}case"message_start":{T.inputTokens=O.message.usage.input_tokens,T.cachedInputTokens=(W=O.message.usage.cache_read_input_tokens)!=null?W:void 0,E={...O.message.usage},k=(be=O.message.usage.cache_creation_input_tokens)!=null?be:null,z.enqueue({type:"response-metadata",id:(Y=O.message.id)!=null?Y:void 0,modelId:(we=O.message.model)!=null?we:void 0});return}case"message_delta":{O.usage.cache_read_input_tokens!=null&&(T.cachedInputTokens=O.usage.cache_read_input_tokens),O.usage.cache_creation_input_tokens!=null&&(k=O.usage.cache_creation_input_tokens),O.usage.iterations!=null&&($=O.usage.iterations);const ne=(ge=O.usage.iterations)==null?void 0:ge.some(C=>C.type==="fallback_message");if(O.usage.iterations&&O.usage.iterations.length>0&&!ne){const C=O.usage.iterations.reduce((H,re)=>({input:H.input+re.input_tokens,output:H.output+re.output_tokens}),{input:0,output:0});T.inputTokens=C.input,T.outputTokens=C.output}else O.usage.input_tokens!=null&&T.inputTokens!==O.usage.input_tokens&&(T.inputTokens=O.usage.input_tokens),T.outputTokens=O.usage.output_tokens;T.totalTokens=((Ce=T.inputTokens)!=null?Ce:0)+((le=T.outputTokens)!=null?le:0),x=ps({finishReason:O.delta.stop_reason,isJsonResponseFromTool:a}),v=fs(O.delta.stop_details),_=(he=O.delta.stop_sequence)!=null?he:null,y=O.delta.container!=null?{expiresAt:O.delta.container.expires_at,id:O.delta.container.id,skills:(ke=(de=O.delta.container.skills)==null?void 0:de.map(C=>({type:C.type,skillId:C.skill_id,version:C.version})))!=null?ke:null}:null,O.context_management!=null&&(b={appliedEdits:O.context_management.applied_edits.map(C=>{switch(C.type){case"clear_tool_uses_20250919":return{type:C.type,clearedToolUses:C.cleared_tool_uses,clearedInputTokens:C.cleared_input_tokens};case"clear_thinking_20251015":return{type:C.type,clearedThinkingTurns:C.cleared_thinking_turns,clearedInputTokens:C.cleared_input_tokens};case"compact_20260112":return{type:C.type}}}).filter(C=>C!==void 0)}),E={...E,...O.usage};return}case"message_stop":{z.enqueue({type:"finish",finishReason:x,usage:T,providerMetadata:{anthropic:{usage:E??null,cacheCreationInputTokens:k,stopSequence:_,...v!=null?{stopDetails:v}:{},iterations:$?$.map(ne=>({type:ne.type,...ne.model!=null?{model:ne.model}:{},inputTokens:ne.input_tokens,outputTokens:ne.output_tokens})):null,container:y,contextManagement:b}}});return}case"error":{z.enqueue({type:"error",error:O.error});return}default:{const ne=O;throw new Error(`Unsupported chunk type: ${ne}`)}}}})),[Z,B]=N.tee(),L=Z.getReader();try{await L.read();let oe=await L.read();if(((t=oe.value)==null?void 0:t.type)==="raw"&&(oe=await L.read()),((n=oe.value)==null?void 0:n.type)==="error"){const z=oe.value.error;throw new $e({message:z.message,url:c,requestBodyValues:l,statusCode:z.type==="overloaded_error"?529:500,responseHeaders:p,responseBody:JSON.stringify(z),isRetryable:z.type==="overloaded_error"})}}finally{L.cancel().catch(()=>{}),L.releaseLock()}return{stream:B,request:{body:l},response:{headers:p}}}};function iw(e){return e.includes("claude-opus-4-8")||e.includes("claude-opus-4-7")||e.includes("claude-fable-5")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0}:e.includes("claude-sonnet-4-6")||e.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-5")||e.includes("claude-opus-4-5")||e.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-sonnet-4-")||e.includes("claude-3-7-sonnet")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-3-5-haiku")?{maxOutputTokens:8192,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:e.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}function fs(e){if(e!=null)return{type:e.type,...e.category!=null?{category:e.category}:{},...e.explanation!=null?{explanation:e.explanation}:{},...e.recommended_model!=null?{recommendedModel:e.recommended_model}:{}}}var aw=K(()=>j(d({command:u(),restart:ue().optional()}))),sw=yt({id:"anthropic.bash_20241022",name:"bash",inputSchema:aw}),lw=K(()=>j(d({command:u(),restart:ue().optional()}))),uw=yt({id:"anthropic.bash_20250124",name:"bash",inputSchema:lw}),cw=K(()=>j(se("type",[d({type:h("code_execution_result"),stdout:u(),stderr:u(),return_code:f(),content:R(d({type:h("code_execution_output"),file_id:u()})).optional().default([])}),d({type:h("bash_code_execution_result"),content:R(d({type:h("bash_code_execution_output"),file_id:u()})),stdout:u(),stderr:u(),return_code:f()}),d({type:h("bash_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_tool_result_error"),error_code:u()}),d({type:h("text_editor_code_execution_view_result"),content:u(),file_type:u(),num_lines:f().nullable(),start_line:f().nullable(),total_lines:f().nullable()}),d({type:h("text_editor_code_execution_create_result"),is_file_update:ue()}),d({type:h("text_editor_code_execution_str_replace_result"),lines:R(u()).nullable(),new_lines:f().nullable(),new_start:f().nullable(),old_lines:f().nullable(),old_start:f().nullable()})]))),dw=K(()=>j(se("type",[d({type:h("programmatic-tool-call"),code:u()}),d({type:h("bash_code_execution"),command:u()}),se("command",[d({type:h("text_editor_code_execution"),command:h("view"),path:u()}),d({type:h("text_editor_code_execution"),command:h("create"),path:u(),file_text:u().nullish()}),d({type:h("text_editor_code_execution"),command:h("str_replace"),path:u(),old_str:u(),new_str:u()})])]))),pw=Ye({id:"anthropic.code_execution_20260120",name:"code_execution",inputSchema:dw,outputSchema:cw}),hw=(e={})=>pw(e),fw=K(()=>j(d({action:X(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:R(f().int()).optional(),text:u().optional()}))),mw=yt({id:"anthropic.computer_20241022",name:"computer",inputSchema:fw}),_w=K(()=>j(d({action:X(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:Vr([f().int(),f().int()]).optional(),duration:f().optional(),scroll_amount:f().optional(),scroll_direction:X(["up","down","left","right"]).optional(),start_coordinate:Vr([f().int(),f().int()]).optional(),text:u().optional()}))),gw=yt({id:"anthropic.computer_20250124",name:"computer",inputSchema:_w}),yw=K(()=>j(se("command",[d({command:h("view"),path:u(),view_range:Vr([f(),f()]).optional()}),d({command:h("create"),path:u(),file_text:u()}),d({command:h("str_replace"),path:u(),old_str:u(),new_str:u()}),d({command:h("insert"),path:u(),insert_line:f(),insert_text:u()}),d({command:h("delete"),path:u()}),d({command:h("rename"),old_path:u(),new_path:u()})]))),vw=yt({id:"anthropic.memory_20250818",name:"memory",inputSchema:yw}),bw=K(()=>j(d({command:X(["view","create","str_replace","insert","undo_edit"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),ww=yt({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:bw}),xw=K(()=>j(d({command:X(["view","create","str_replace","insert","undo_edit"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),kw=yt({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:xw}),Iw=K(()=>j(d({command:X(["view","create","str_replace","insert"]),path:u(),file_text:u().optional(),insert_line:f().int().optional(),new_str:u().optional(),old_str:u().optional(),view_range:R(f().int()).optional()}))),Tw=yt({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:Iw}),Sw={bash_20241022:sw,bash_20250124:uw,codeExecution_20250522:qb,codeExecution_20250825:Wb,codeExecution_20260120:hw,computer_20241022:mw,computer_20250124:gw,memory_20250818:vw,textEditor_20241022:ww,textEditor_20250124:kw,textEditor_20250429:Tw,textEditor_20250728:Rb,webFetch_20250910:Ub,webSearch_20250305:Lb};function oc(e={}){var t,n;const r=(t=ko(Zt({settingValue:e.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?t:"https://api.anthropic.com/v1",o=(n=e.name)!=null?n:"anthropic.messages",i=()=>qt({"anthropic-version":"2023-06-01","x-api-key":Vl({apiKey:e.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...e.headers},`ai-sdk/anthropic/${kb}`),a=l=>{var c;return new ow(l,{provider:o,baseURL:r,headers:i,fetch:e.fetch,generateId:(c=e.generateId)!=null?c:Ge,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},s=function(l){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return a(l)};return s.languageModel=a,s.chat=a,s.messages=a,s.textEmbeddingModel=l=>{throw new bi({modelId:l,modelType:"textEmbeddingModel"})},s.imageModel=l=>{throw new bi({modelId:l,modelType:"imageModel"})},s.tools=Sw,s}oc();var $o=d({error:d({message:u(),type:u().nullish(),param:He().nullish(),code:ee([u(),f()]).nullish()})}),ft=pt({errorSchema:$o,errorToMessage:e=>e.error.message});function ic(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),n=e.startsWith("gpt-4")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")&&!e.startsWith("gpt-5.4-nano")||e.startsWith("o3")||e.startsWith("o4-mini"),r=!(e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("chatgpt-4o")||e.startsWith("gpt-5-chat")),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2")||e.startsWith("gpt-5.3")||e.startsWith("gpt-5.4");return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?"developer":"system",supportsNonReasoningParameters:o}}function Ew({prompt:e,systemMessageMode:t="system"}){const n=[],r=[];for(const{role:o,content:i}of e)switch(o){case"system":{switch(t){case"system":{n.push({role:"system",content:i});break}case"developer":{n.push({role:"developer",content:i});break}case"remove":{r.push({type:"other",message:"system messages are removed for this model"});break}default:{const a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case"user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,s)=>{var l,c,p;switch(a.type){case"text":return{type:"text",text:a.text};case"file":if(a.mediaType.startsWith("image/")){const g=a.mediaType==="image/*"?"image/jpeg":a.mediaType;return{type:"image_url",image_url:{url:a.data instanceof URL?a.data.toString():`data:${g};base64,${St(a.data)}`,detail:(c=(l=a.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(a.mediaType.startsWith("audio/")){if(a.data instanceof URL)throw new je({functionality:"audio file parts with URLs"});switch(a.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:St(a.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:St(a.data),format:"mp3"}};default:throw new je({functionality:`audio content parts with media type ${a.mediaType}`})}}else if(a.mediaType==="application/pdf"){if(a.data instanceof URL)throw new je({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof a.data=="string"&&a.data.startsWith("file-")?{file_id:a.data}:{filename:(p=a.filename)!=null?p:`part-${s}.pdf`,file_data:`data:application/pdf;base64,${St(a.data)}`}}}else throw new je({functionality:`file part media type ${a.mediaType}`})}})});break}case"assistant":{let a="";const s=[];for(const l of i)switch(l.type){case"text":{a+=l.text;break}case"tool-call":{s.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}n.push({role:"assistant",content:a,tool_calls:s.length>0?s:void 0});break}case"tool":{for(const a of i){const s=a.output;let l;switch(s.type){case"text":case"error-text":l=s.value;break;case"content":case"json":case"error-json":l=JSON.stringify(s.value);break}n.push({role:"tool",tool_call_id:a.toolCallId,content:l})}break}default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return{messages:n,warnings:r}}function Lr({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function ms(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Cw=Ee(()=>j(d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({message:d({role:h("assistant").nullish(),content:u().nullish(),tool_calls:R(d({id:u().nullish(),type:h("function"),function:d({name:u(),arguments:u()})})).nullish(),annotations:R(d({type:h("url_citation"),url_citation:d({start_index:f(),end_index:f(),url:u(),title:u()})})).nullish()}),index:f(),logprobs:d({content:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish()}).nullish(),finish_reason:u().nullish()})),usage:d({prompt_tokens:f().nullish(),completion_tokens:f().nullish(),total_tokens:f().nullish(),prompt_tokens_details:d({cached_tokens:f().nullish()}).nullish(),completion_tokens_details:d({reasoning_tokens:f().nullish(),accepted_prediction_tokens:f().nullish(),rejected_prediction_tokens:f().nullish()}).nullish()}).nullish()}))),Aw=Ee(()=>j(ee([d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({delta:d({role:X(["assistant"]).nullish(),content:u().nullish(),tool_calls:R(d({index:f(),id:u().nullish(),type:h("function").nullish(),function:d({name:u().nullish(),arguments:u().nullish()})})).nullish(),annotations:R(d({type:h("url_citation"),url_citation:d({start_index:f(),end_index:f(),url:u(),title:u()})})).nullish()}).nullish(),logprobs:d({content:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish()}).nullish(),finish_reason:u().nullish(),index:f()})),usage:d({prompt_tokens:f().nullish(),completion_tokens:f().nullish(),total_tokens:f().nullish(),prompt_tokens_details:d({cached_tokens:f().nullish()}).nullish(),completion_tokens_details:d({reasoning_tokens:f().nullish(),accepted_prediction_tokens:f().nullish(),rejected_prediction_tokens:f().nullish()}).nullish()}).nullish()}),$o]))),Ow=Ee(()=>j(d({logitBias:Se(lm(),f()).optional(),logprobs:ee([ue(),f()]).optional(),parallelToolCalls:ue().optional(),user:u().optional(),reasoningEffort:X(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:f().optional(),store:ue().optional(),metadata:Se(u().max(64),u().max(512)).optional(),prediction:Se(u(),He()).optional(),structuredOutputs:ue().optional(),serviceTier:X(["auto","flex","priority","default"]).optional(),strictJsonSchema:ue().optional(),textVerbosity:X(["low","medium","high"]).optional(),promptCacheKey:u().optional(),promptCacheRetention:X(["in_memory","24h"]).optional(),safetyIdentifier:u().optional()})));function $w({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e!=null&&e.length?e:void 0;const o=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const i=[];for(const s of e)switch(s.type){case"function":i.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,strict:n?r:void 0}});break;default:o.push({type:"unsupported-tool",tool:s});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:o};const a=t.type;switch(a){case"auto":case"none":case"required":return{tools:i,toolChoice:a,toolWarnings:o};case"tool":return{tools:i,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:o};default:{const s=a;throw new je({functionality:`tool choice type: ${s}`})}}}var Nw=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:l,seed:c,tools:p,toolChoice:g,providerOptions:x}){var T,I,E,k;const _=[],v=(T=await We({provider:"openai",providerOptions:x,schema:Ow}))!=null?T:{},y=(I=v.structuredOutputs)!=null?I:!0,$=ic(this.modelId);o!=null&&_.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!y&&_.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:S}=Ew({prompt:e,systemMessageMode:$.systemMessageMode});_.push(...S);const m=(E=v.strictJsonSchema)!=null?E:!1,N={model:this.modelId,logit_bias:v.logitBias,logprobs:v.logprobs===!0||typeof v.logprobs=="number"?!0:void 0,top_logprobs:typeof v.logprobs=="number"?v.logprobs:typeof v.logprobs=="boolean"&&v.logprobs?0:void 0,user:v.user,parallel_tool_calls:v.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:a,response_format:(l==null?void 0:l.type)==="json"?y&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:m,name:(k=l.name)!=null?k:"response",description:l.description}}:{type:"json_object"}:void 0,stop:s,seed:c,verbosity:v.textVerbosity,max_completion_tokens:v.maxCompletionTokens,store:v.store,metadata:v.metadata,prediction:v.prediction,reasoning_effort:v.reasoningEffort,service_tier:v.serviceTier,prompt_cache_key:v.promptCacheKey,prompt_cache_retention:v.promptCacheRetention,safety_identifier:v.safetyIdentifier,messages:b};$.isReasoningModel?((v.reasoningEffort!=="none"||!$.supportsNonReasoningParameters)&&(N.temperature!=null&&(N.temperature=void 0,_.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),N.top_p!=null&&(N.top_p=void 0,_.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),N.logprobs!=null&&(N.logprobs=void 0,_.push({type:"other",message:"logprobs is not supported for reasoning models"}))),N.frequency_penalty!=null&&(N.frequency_penalty=void 0,_.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),N.presence_penalty!=null&&(N.presence_penalty=void 0,_.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),N.logit_bias!=null&&(N.logit_bias=void 0,_.push({type:"other",message:"logitBias is not supported for reasoning models"})),N.top_logprobs!=null&&(N.top_logprobs=void 0,_.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),N.max_tokens!=null&&(N.max_completion_tokens==null&&(N.max_completion_tokens=N.max_tokens),N.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&N.temperature!=null&&(N.temperature=void 0,_.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),v.serviceTier==="flex"&&!$.supportsFlexProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),N.service_tier=void 0),v.serviceTier==="priority"&&!$.supportsPriorityProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),N.service_tier=void 0);const{tools:Z,toolChoice:B,toolWarnings:L}=$w({tools:p,toolChoice:g,structuredOutputs:y,strictJsonSchema:m});return{args:{...N,tools:Z,tool_choice:B},warnings:[..._,...L]}}async doGenerate(e){var t,n,r,o,i,a,s,l,c,p,g,x,T,I;const{args:E,warnings:k}=await this.getArgs(e),{responseHeaders:_,value:v,rawValue:y}=await De({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Le(this.config.headers(),e.headers),body:E,failedResponseHandler:ft,successfulResponseHandler:Be(Cw),abortSignal:e.abortSignal,fetch:this.config.fetch}),$=v.choices[0],b=[],S=$.message.content;S!=null&&S.length>0&&b.push({type:"text",text:S});for(const B of(t=$.message.tool_calls)!=null?t:[])b.push({type:"tool-call",toolCallId:(n=B.id)!=null?n:Ge(),toolName:B.function.name,input:B.function.arguments});for(const B of(r=$.message.annotations)!=null?r:[])b.push({type:"source",sourceType:"url",id:Ge(),url:B.url_citation.url,title:B.url_citation.title});const m=(o=v.usage)==null?void 0:o.completion_tokens_details,N=(i=v.usage)==null?void 0:i.prompt_tokens_details,Z={openai:{}};return(m==null?void 0:m.accepted_prediction_tokens)!=null&&(Z.openai.acceptedPredictionTokens=m==null?void 0:m.accepted_prediction_tokens),(m==null?void 0:m.rejected_prediction_tokens)!=null&&(Z.openai.rejectedPredictionTokens=m==null?void 0:m.rejected_prediction_tokens),((a=$.logprobs)==null?void 0:a.content)!=null&&(Z.openai.logprobs=$.logprobs.content),{content:b,finishReason:ms($.finish_reason),usage:{inputTokens:(l=(s=v.usage)==null?void 0:s.prompt_tokens)!=null?l:void 0,outputTokens:(p=(c=v.usage)==null?void 0:c.completion_tokens)!=null?p:void 0,totalTokens:(x=(g=v.usage)==null?void 0:g.total_tokens)!=null?x:void 0,reasoningTokens:(T=m==null?void 0:m.reasoning_tokens)!=null?T:void 0,cachedInputTokens:(I=N==null?void 0:N.cached_tokens)!=null?I:void 0},request:{body:E},response:{...Lr(v),headers:_,body:y},warnings:k,providerMetadata:Z}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await De({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Le(this.config.headers(),e.headers),body:r,failedResponseHandler:ft,successfulResponseHandler:Nn(Aw),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let s="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!1,p=!1;const g={openai:{}};return{stream:i.pipeThrough(new TransformStream({start(x){x.enqueue({type:"stream-start",warnings:n})},transform(x,T){var I,E,k,_,v,y,$,b,S,m,N,Z,B,L,oe,z,V,W,be,Y,we,ge,Ce,le;if(e.includeRawChunks&&T.enqueue({type:"raw",rawValue:x.rawValue}),!x.success){s="error",T.enqueue({type:"error",error:x.error});return}const he=x.value;if("error"in he){s="error",T.enqueue({type:"error",error:he.error});return}if(!c){const O=Lr(he);Object.values(O).some(Boolean)&&(c=!0,T.enqueue({type:"response-metadata",...Lr(he)}))}he.usage!=null&&(l.inputTokens=(I=he.usage.prompt_tokens)!=null?I:void 0,l.outputTokens=(E=he.usage.completion_tokens)!=null?E:void 0,l.totalTokens=(k=he.usage.total_tokens)!=null?k:void 0,l.reasoningTokens=(v=(_=he.usage.completion_tokens_details)==null?void 0:_.reasoning_tokens)!=null?v:void 0,l.cachedInputTokens=($=(y=he.usage.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?$:void 0,((b=he.usage.completion_tokens_details)==null?void 0:b.accepted_prediction_tokens)!=null&&(g.openai.acceptedPredictionTokens=(S=he.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens),((m=he.usage.completion_tokens_details)==null?void 0:m.rejected_prediction_tokens)!=null&&(g.openai.rejectedPredictionTokens=(N=he.usage.completion_tokens_details)==null?void 0:N.rejected_prediction_tokens));const de=he.choices[0];if((de==null?void 0:de.finish_reason)!=null&&(s=ms(de.finish_reason)),((Z=de==null?void 0:de.logprobs)==null?void 0:Z.content)!=null&&(g.openai.logprobs=de.logprobs.content),(de==null?void 0:de.delta)==null)return;const ke=de.delta;if(ke.content!=null&&(p||(T.enqueue({type:"text-start",id:"0"}),p=!0),T.enqueue({type:"text-delta",id:"0",delta:ke.content})),ke.tool_calls!=null)for(const O of ke.tool_calls){const ne=O.index;if(a[ne]==null){if(O.type!=null&&O.type!=="function")throw new br({data:O,message:"Expected 'function' type."});if(O.id==null)throw new br({data:O,message:"Expected 'id' to be a string."});if(((B=O.function)==null?void 0:B.name)==null)throw new br({data:O,message:"Expected 'function.name' to be a string."});T.enqueue({type:"tool-input-start",id:O.id,toolName:O.function.name}),a[ne]={id:O.id,type:"function",function:{name:O.function.name,arguments:(L=O.function.arguments)!=null?L:""},hasFinished:!1};const H=a[ne];((oe=H.function)==null?void 0:oe.name)!=null&&((z=H.function)==null?void 0:z.arguments)!=null&&(H.function.arguments.length>0&&T.enqueue({type:"tool-input-delta",id:H.id,delta:H.function.arguments}),_a(H.function.arguments)&&(T.enqueue({type:"tool-input-end",id:H.id}),T.enqueue({type:"tool-call",toolCallId:(V=H.id)!=null?V:Ge(),toolName:H.function.name,input:H.function.arguments}),H.hasFinished=!0));continue}const C=a[ne];C.hasFinished||(((W=O.function)==null?void 0:W.arguments)!=null&&(C.function.arguments+=(Y=(be=O.function)==null?void 0:be.arguments)!=null?Y:""),T.enqueue({type:"tool-input-delta",id:C.id,delta:(we=O.function.arguments)!=null?we:""}),((ge=C.function)==null?void 0:ge.name)!=null&&((Ce=C.function)==null?void 0:Ce.arguments)!=null&&_a(C.function.arguments)&&(T.enqueue({type:"tool-input-end",id:C.id}),T.enqueue({type:"tool-call",toolCallId:(le=C.id)!=null?le:Ge(),toolName:C.function.name,input:C.function.arguments}),C.hasFinished=!0))}if(ke.annotations!=null)for(const O of ke.annotations)T.enqueue({type:"source",sourceType:"url",id:Ge(),url:O.url_citation.url,title:O.url_citation.title})},flush(x){p&&x.enqueue({type:"text-end",id:"0"}),x.enqueue({type:"finish",finishReason:s,usage:l,...g!=null?{providerMetadata:g}:{}})}})),request:{body:r},response:{headers:o}}}};function Rw({prompt:e,user:t="user",assistant:n="assistant"}){let r="";e[0].role==="system"&&(r+=`${e[0].content}
|
|
74
|
+
|
|
75
|
+
`,e=e.slice(1));for(const{role:o,content:i}of e)switch(o){case"system":throw new xt({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=i.map(s=>{switch(s.type){case"text":return s.text}}).filter(Boolean).join("");r+=`${t}:
|
|
76
|
+
${a}
|
|
77
|
+
|
|
78
|
+
`;break}case"assistant":{const a=i.map(s=>{switch(s.type){case"text":return s.text;case"tool-call":throw new je({functionality:"tool-call messages"})}}).join("");r+=`${n}:
|
|
79
|
+
${a}
|
|
80
|
+
|
|
81
|
+
`;break}case"tool":throw new je({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return r+=`${n}:
|
|
82
|
+
`,{prompt:r,stopSequences:[`
|
|
83
|
+
${t}:`]}}function _s({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n!=null?new Date(n*1e3):void 0}}function gs(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Pw=Ee(()=>j(d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({text:u(),finish_reason:u(),logprobs:d({tokens:R(u()),token_logprobs:R(f()),top_logprobs:R(Se(u(),f())).nullish()}).nullish()})),usage:d({prompt_tokens:f(),completion_tokens:f(),total_tokens:f()}).nullish()}))),Mw=Ee(()=>j(ee([d({id:u().nullish(),created:f().nullish(),model:u().nullish(),choices:R(d({text:u(),finish_reason:u().nullish(),index:f(),logprobs:d({tokens:R(u()),token_logprobs:R(f()),top_logprobs:R(Se(u(),f())).nullish()}).nullish()})),usage:d({prompt_tokens:f(),completion_tokens:f(),total_tokens:f()}).nullish()}),$o]))),ys=Ee(()=>j(d({echo:ue().optional(),logitBias:Se(u(),f()).optional(),suffix:u().optional(),user:u().optional(),logprobs:ee([ue(),f()]).optional()}))),zw=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:o,frequencyPenalty:i,presencePenalty:a,stopSequences:s,responseFormat:l,tools:c,toolChoice:p,seed:g,providerOptions:x}){const T=[],I={...await We({provider:"openai",providerOptions:x,schema:ys}),...await We({provider:this.providerOptionsName,providerOptions:x,schema:ys})};o!=null&&T.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.length&&T.push({type:"unsupported-setting",setting:"tools"}),p!=null&&T.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&T.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:E,stopSequences:k}=Rw({prompt:e}),_=[...k??[],...s??[]];return{args:{model:this.modelId,echo:I.echo,logit_bias:I.logitBias,logprobs:(I==null?void 0:I.logprobs)===!0?0:(I==null?void 0:I.logprobs)===!1||I==null?void 0:I.logprobs,suffix:I.suffix,user:I.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:i,presence_penalty:a,seed:g,prompt:E,stop:_.length>0?_:void 0},warnings:T}}async doGenerate(e){var t,n,r;const{args:o,warnings:i}=await this.getArgs(e),{responseHeaders:a,value:s,rawValue:l}=await De({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Le(this.config.headers(),e.headers),body:o,failedResponseHandler:ft,successfulResponseHandler:Be(Pw),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=s.choices[0],p={openai:{}};return c.logprobs!=null&&(p.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(t=s.usage)==null?void 0:t.prompt_tokens,outputTokens:(n=s.usage)==null?void 0:n.completion_tokens,totalTokens:(r=s.usage)==null?void 0:r.total_tokens},finishReason:gs(c.finish_reason),request:{body:o},response:{..._s(s),headers:a,body:l},providerMetadata:p,warnings:i}}async doStream(e){const{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:i}=await De({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Le(this.config.headers(),e.headers),body:r,failedResponseHandler:ft,successfulResponseHandler:Nn(Mw),abortSignal:e.abortSignal,fetch:this.config.fetch});let a="unknown";const s={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:i.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:n})},transform(p,g){if(e.includeRawChunks&&g.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){a="error",g.enqueue({type:"error",error:p.error});return}const x=p.value;if("error"in x){a="error",g.enqueue({type:"error",error:x.error});return}c&&(c=!1,g.enqueue({type:"response-metadata",..._s(x)}),g.enqueue({type:"text-start",id:"0"})),x.usage!=null&&(l.inputTokens=x.usage.prompt_tokens,l.outputTokens=x.usage.completion_tokens,l.totalTokens=x.usage.total_tokens);const T=x.choices[0];(T==null?void 0:T.finish_reason)!=null&&(a=gs(T.finish_reason)),(T==null?void 0:T.logprobs)!=null&&(s.openai.logprobs=T.logprobs),(T==null?void 0:T.text)!=null&&T.text.length>0&&g.enqueue({type:"text-delta",id:"0",delta:T.text})},flush(p){c||p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:a,providerMetadata:s,usage:l})}})),request:{body:r},response:{headers:o}}}},Lw=Ee(()=>j(d({dimensions:f().optional(),user:u().optional()}))),Dw=Ee(()=>j(d({data:R(d({embedding:R(f())})),usage:d({prompt_tokens:f()}).nullish()}))),Zw=class{constructor(e,t){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new Jc({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const i=(o=await We({provider:"openai",providerOptions:r,schema:Lw}))!=null?o:{},{responseHeaders:a,value:s,rawValue:l}=await De({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Le(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:i.dimensions,user:i.user},failedResponseHandler:ft,successfulResponseHandler:Be(Dw),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.data.map(c=>c.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},jw=Ee(()=>j(d({created:f().nullish(),data:R(d({b64_json:u(),revised_prompt:u().nullish()})),background:u().nullish(),output_format:u().nullish(),size:u().nullish(),quality:u().nullish(),usage:d({input_tokens:f().nullish(),output_tokens:f().nullish(),total_tokens:f().nullish(),input_tokens_details:d({image_tokens:f().nullish(),text_tokens:f().nullish()}).nullish()}).nullish()}))),Uw={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10},Bw=new Set(["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2"]),Vw=d({quality:X(["standard","hd","low","medium","high","auto"]).optional(),background:X(["transparent","opaque","auto"]).optional(),outputFormat:X(["png","jpeg","webp"]).optional(),outputCompression:f().int().min(0).max(100).optional(),user:u().optional()}),Fw=Ee(()=>j(Vw.extend({style:X(["vivid","natural"]).optional(),moderation:X(["auto","low"]).optional()}))),qw=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get maxImagesPerCall(){var e;return(e=Uw[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:o,providerOptions:i,headers:a,abortSignal:s}){var l,c,p,g;const x=[];r!=null&&x.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&x.push({type:"unsupported-setting",setting:"seed"});const T=(p=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?p:new Date,I=(g=await We({provider:"openai",providerOptions:i,schema:Fw}))!=null?g:{},{value:E,responseHeaders:k}=await De({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Le(this.config.headers(),a),body:{model:this.modelId,prompt:e,n:t,size:n,quality:I.quality,style:I.style,background:I.background,moderation:I.moderation,output_format:I.outputFormat,output_compression:I.outputCompression,user:I.user,...Bw.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:ft,successfulResponseHandler:Be(jw),abortSignal:s,fetch:this.config.fetch});return{images:E.data.map(_=>_.b64_json),warnings:x,response:{timestamp:T,modelId:this.modelId,headers:k},providerMetadata:{openai:{images:E.data.map((_,v)=>({..._.revised_prompt?{revisedPrompt:_.revised_prompt}:{},...E.created!=null?{created:E.created}:{},...E.size!=null?{size:E.size}:{},...E.quality!=null?{quality:E.quality}:{},...E.background!=null?{background:E.background}:{},...E.output_format!=null?{outputFormat:E.output_format}:{},...Gw(E.usage,v,E.data.length)}))}}}}};function Gw(e,t,n){if(e==null)return{};const r={},o=e.input_tokens_details;if((o==null?void 0:o.image_tokens)!=null){const i=Math.floor(o.image_tokens/n),a=o.image_tokens-i*(n-1);r.imageTokens=t===n-1?a:i}if((o==null?void 0:o.text_tokens)!=null){const i=Math.floor(o.text_tokens/n),a=o.text_tokens-i*(n-1);r.textTokens=t===n-1?a:i}if(e.input_tokens!=null){const i=Math.floor(e.input_tokens/n),a=e.input_tokens-i*(n-1);r.inputTokens=t===n-1?a:i}if(e.output_tokens!=null){const i=Math.floor(e.output_tokens/n),a=e.output_tokens-i*(n-1);r.outputTokens=t===n-1?a:i}return r}var Hw=K(()=>j(d({code:u().nullish(),containerId:u()}))),Ww=K(()=>j(d({outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullish()}))),Jw=K(()=>j(d({container:ee([u(),d({fileIds:R(u()).optional()})]).optional()}))),Kw=Ye({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:Hw,outputSchema:Ww}),Yw=(e={})=>Kw(e),ac=d({key:u(),type:X(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ee([u(),f(),ue(),R(u())])}),sc=d({type:X(["and","or"]),filters:R(ee([ac,Ol(()=>sc)]))}),Xw=K(()=>j(d({vectorStoreIds:R(u()),maxNumResults:f().optional(),ranking:d({ranker:u().optional(),scoreThreshold:f().optional()}).optional(),filters:ee([ac,sc]).optional()}))),Qw=K(()=>j(d({queries:R(u()),results:R(d({attributes:Se(u(),ze()),fileId:u(),filename:u(),score:f(),text:u()})).nullable()}))),e0=Ye({id:"openai.file_search",name:"file_search",inputSchema:d({}),outputSchema:Qw}),t0=K(()=>j(d({background:X(["auto","opaque","transparent"]).optional(),inputFidelity:X(["low","high"]).optional(),inputImageMask:d({fileId:u().optional(),imageUrl:u().optional()}).optional(),model:u().optional(),moderation:X(["auto"]).optional(),outputCompression:f().int().min(0).max(100).optional(),outputFormat:X(["png","jpeg","webp"]).optional(),partialImages:f().int().min(0).max(3).optional(),quality:X(["auto","low","medium","high"]).optional(),size:X(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),n0=K(()=>j(d({}))),r0=K(()=>j(d({result:u()}))),o0=Ye({id:"openai.image_generation",name:"image_generation",inputSchema:n0,outputSchema:r0}),i0=(e={})=>o0(e),lc=K(()=>j(d({action:d({type:h("exec"),command:R(u()),timeoutMs:f().optional(),user:u().optional(),workingDirectory:u().optional(),env:Se(u(),u()).optional()})}))),uc=K(()=>j(d({output:u()}))),a0=Ye({id:"openai.local_shell",name:"local_shell",inputSchema:lc,outputSchema:uc}),s0=K(()=>j(d({externalWebAccess:ue().optional(),filters:d({allowedDomains:R(u()).optional()}).optional(),searchContextSize:X(["low","medium","high"]).optional(),userLocation:d({type:h("approximate"),country:u().optional(),city:u().optional(),region:u().optional(),timezone:u().optional()}).optional()}))),l0=K(()=>j(d({}))),u0=K(()=>j(d({action:se("type",[d({type:h("search"),query:u().optional()}),d({type:h("openPage"),url:u().nullish()}),d({type:h("findInPage"),url:u().nullish(),pattern:u().nullish()})]).optional(),sources:R(se("type",[d({type:h("url"),url:u()}),d({type:h("api"),name:u()})])).optional()}))),c0=Ye({id:"openai.web_search",name:"web_search",inputSchema:l0,outputSchema:u0}),d0=(e={})=>c0(e),p0=K(()=>j(d({searchContextSize:X(["low","medium","high"]).optional(),userLocation:d({type:h("approximate"),country:u().optional(),city:u().optional(),region:u().optional(),timezone:u().optional()}).optional()}))),h0=K(()=>j(d({}))),f0=K(()=>j(d({action:se("type",[d({type:h("search"),query:u().optional()}),d({type:h("openPage"),url:u().nullish()}),d({type:h("findInPage"),url:u().nullish(),pattern:u().nullish()})]).optional()}))),m0=Ye({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:h0,outputSchema:f0}),_0={codeInterpreter:Yw,fileSearch:e0,imageGeneration:i0,localShell:a0,webSearchPreview:m0,webSearch:d0};function vs(e,t){return t?t.some(n=>e.startsWith(n)):!1}async function g0({prompt:e,systemMessageMode:t,fileIdPrefixes:n,store:r,hasLocalShellTool:o=!1}){var i,a,s,l,c,p;let g=[];const x=[];for(const{role:T,content:I}of e)switch(T){case"system":{switch(t){case"system":{g.push({role:"system",content:I});break}case"developer":{g.push({role:"developer",content:I});break}case"remove":{x.push({type:"other",message:"system messages are removed for this model"});break}default:{const E=t;throw new Error(`Unsupported system message mode: ${E}`)}}break}case"user":{g.push({role:"user",content:I.map((E,k)=>{var _,v,y;switch(E.type){case"text":return{type:"input_text",text:E.text};case"file":if(E.mediaType.startsWith("image/")){const $=E.mediaType==="image/*"?"image/jpeg":E.mediaType;return{type:"input_image",...E.data instanceof URL?{image_url:E.data.toString()}:typeof E.data=="string"&&vs(E.data,n)?{file_id:E.data}:{image_url:`data:${$};base64,${St(E.data)}`},detail:(v=(_=E.providerOptions)==null?void 0:_.openai)==null?void 0:v.imageDetail}}else{if(E.mediaType==="application/pdf")return E.data instanceof URL?{type:"input_file",file_url:E.data.toString()}:{type:"input_file",...typeof E.data=="string"&&vs(E.data,n)?{file_id:E.data}:{filename:(y=E.filename)!=null?y:`part-${k}.pdf`,file_data:`data:application/pdf;base64,${St(E.data)}`}};throw new je({functionality:`file part media type ${E.mediaType}`})}}})});break}case"assistant":{const E={},k={};for(const _ of I)switch(_.type){case"text":{const v=(a=(i=_.providerOptions)==null?void 0:i.openai)==null?void 0:a.itemId,y=(l=(s=_.providerOptions)==null?void 0:s.openai)==null?void 0:l.phase;if(r&&v!=null){g.push({type:"item_reference",id:v});break}g.push({role:"assistant",content:[{type:"output_text",text:_.text}],id:v,...y!=null&&{phase:y}});break}case"tool-call":{if(k[_.toolCallId]=_,_.providerExecuted)break;const v=(p=(c=_.providerOptions)==null?void 0:c.openai)==null?void 0:p.itemId;if(r&&v!=null){g.push({type:"item_reference",id:v});break}if(o&&_.toolName==="local_shell"){const y=await Me({value:_.input,schema:lc});g.push({type:"local_shell_call",call_id:_.toolCallId,id:v,action:{type:"exec",command:y.action.command,timeout_ms:y.action.timeoutMs,user:y.action.user,working_directory:y.action.workingDirectory,env:y.action.env}});break}g.push({type:"function_call",call_id:_.toolCallId,name:_.toolName,arguments:JSON.stringify(_.input),id:v});break}case"tool-result":{r?g.push({type:"item_reference",id:_.toolCallId}):x.push({type:"other",message:`Results for OpenAI tool ${_.toolName} are not sent to the API when store is false`});break}case"reasoning":{const v=await We({provider:"openai",providerOptions:_.providerOptions,schema:y0}),y=v==null?void 0:v.itemId;if(y!=null){const $=E[y];if(r)$===void 0&&(g.push({type:"item_reference",id:y}),E[y]={type:"reasoning",id:y,summary:[]});else{const b=[];_.text.length>0?b.push({type:"summary_text",text:_.text}):$!==void 0&&x.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(_)}.`}),$===void 0?(E[y]={type:"reasoning",id:y,encrypted_content:v==null?void 0:v.reasoningEncryptedContent,summary:b},g.push(E[y])):($.summary.push(...b),(v==null?void 0:v.reasoningEncryptedContent)!=null&&($.encrypted_content=v.reasoningEncryptedContent))}}else x.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(_)}.`});break}}break}case"tool":{for(const E of I){const k=E.output;if(o&&E.toolName==="local_shell"&&k.type==="json"){const v=await Me({value:k.value,schema:uc});g.push({type:"local_shell_call_output",call_id:E.toolCallId,output:v.output});break}let _;switch(k.type){case"text":case"error-text":_=k.value;break;case"json":case"error-json":_=JSON.stringify(k.value);break;case"content":_=k.value.map(v=>{switch(v.type){case"text":return{type:"input_text",text:v.text};case"media":return v.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${v.mediaType};base64,${v.data}`}:{type:"input_file",filename:"data",file_data:`data:${v.mediaType};base64,${v.data}`}}});break}g.push({type:"function_call_output",call_id:E.toolCallId,output:_})}break}default:{const E=T;throw new Error(`Unsupported role: ${E}`)}}return!r&&g.some(T=>"type"in T&&T.type==="reasoning"&&T.encrypted_content==null)&&(x.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),g=g.filter(T=>!("type"in T)||T.type!=="reasoning"||T.encrypted_content!=null)),{input:g,warnings:x}}var y0=d({itemId:u().nullish(),reasoningEncryptedContent:u().nullish()});function bs({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"unknown"}}var v0=Ee(()=>j(ee([d({type:h("response.output_text.delta"),item_id:u(),delta:u(),logprobs:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish()}),d({type:X(["response.completed","response.incomplete"]),response:d({incomplete_details:d({reason:u()}).nullish(),usage:d({input_tokens:f(),input_tokens_details:d({cached_tokens:f().nullish(),orchestration_input_tokens:f().nullish(),orchestration_input_cached_tokens:f().nullish()}).nullish(),output_tokens:f(),output_tokens_details:d({reasoning_tokens:f().nullish(),orchestration_output_tokens:f().nullish()}).nullish()}),service_tier:u().nullish()})}),d({type:h("response.created"),response:d({id:u(),created_at:f(),model:u(),service_tier:u().nullish()})}),d({type:h("response.output_item.added"),output_index:f(),item:se("type",[d({type:h("message"),id:u(),phase:X(["commentary","final_answer"]).nullish()}),d({type:h("reasoning"),id:u(),encrypted_content:u().nullish()}),d({type:h("function_call"),id:u(),call_id:u(),name:u(),arguments:u()}),d({type:h("web_search_call"),id:u(),status:u()}),d({type:h("computer_call"),id:u(),status:u()}),d({type:h("file_search_call"),id:u()}),d({type:h("image_generation_call"),id:u()}),d({type:h("code_interpreter_call"),id:u(),container_id:u(),code:u().nullable(),outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullable(),status:u()})])}),d({type:h("response.output_item.done"),output_index:f(),item:se("type",[d({type:h("message"),id:u(),phase:X(["commentary","final_answer"]).nullish()}),d({type:h("reasoning"),id:u(),encrypted_content:u().nullish()}),d({type:h("function_call"),id:u(),call_id:u(),name:u(),arguments:u(),status:h("completed")}),d({type:h("code_interpreter_call"),id:u(),code:u().nullable(),container_id:u(),outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullable()}),d({type:h("image_generation_call"),id:u(),result:u()}),d({type:h("web_search_call"),id:u(),status:u(),action:se("type",[d({type:h("search"),query:u().nullish(),sources:R(se("type",[d({type:h("url"),url:u()}),d({type:h("api"),name:u()})])).nullish()}),d({type:h("open_page"),url:u().nullish()}),d({type:h("find_in_page"),url:u().nullish(),pattern:u().nullish()})]).nullish()}),d({type:h("file_search_call"),id:u(),queries:R(u()),results:R(d({attributes:Se(u(),ze()),file_id:u(),filename:u(),score:f(),text:u()})).nullish()}),d({type:h("local_shell_call"),id:u(),call_id:u(),action:d({type:h("exec"),command:R(u()),timeout_ms:f().optional(),user:u().optional(),working_directory:u().optional(),env:Se(u(),u()).optional()})}),d({type:h("computer_call"),id:u(),status:h("completed")})])}),d({type:h("response.function_call_arguments.delta"),item_id:u(),output_index:f(),delta:u()}),d({type:h("response.image_generation_call.partial_image"),item_id:u(),output_index:f(),partial_image_b64:u()}),d({type:h("response.code_interpreter_call_code.delta"),item_id:u(),output_index:f(),delta:u()}),d({type:h("response.code_interpreter_call_code.done"),item_id:u(),output_index:f(),code:u()}),d({type:h("response.output_text.annotation.added"),annotation:se("type",[d({type:h("url_citation"),start_index:f(),end_index:f(),url:u(),title:u()}),d({type:h("file_citation"),file_id:u(),filename:u().nullish(),index:f().nullish(),start_index:f().nullish(),end_index:f().nullish(),quote:u().nullish()})])}),d({type:h("response.reasoning_summary_part.added"),item_id:u(),summary_index:f()}),d({type:h("response.reasoning_summary_text.delta"),item_id:u(),summary_index:f(),delta:u()}),d({type:h("response.reasoning_summary_part.done"),item_id:u(),summary_index:f()}),d({type:h("error"),sequence_number:f(),error:d({type:u(),code:u(),message:u(),param:u().nullish()})}),d({type:u()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),b0=Ee(()=>j(d({id:u().optional(),created_at:f().optional(),error:d({message:u(),type:u(),param:u().nullish(),code:u()}).nullish(),model:u().optional(),output:R(se("type",[d({type:h("message"),role:h("assistant"),id:u(),phase:X(["commentary","final_answer"]).nullish(),content:R(d({type:h("output_text"),text:u(),logprobs:R(d({token:u(),logprob:f(),top_logprobs:R(d({token:u(),logprob:f()}))})).nullish(),annotations:R(se("type",[d({type:h("url_citation"),start_index:f(),end_index:f(),url:u(),title:u()}),d({type:h("file_citation"),file_id:u(),filename:u().nullish(),index:f().nullish(),start_index:f().nullish(),end_index:f().nullish(),quote:u().nullish()}),d({type:h("container_file_citation"),container_id:u(),file_id:u(),filename:u().nullish(),start_index:f().nullish(),end_index:f().nullish(),index:f().nullish()}),d({type:h("file_path"),file_id:u(),index:f().nullish()})]))}))}),d({type:h("web_search_call"),id:u(),status:u(),action:se("type",[d({type:h("search"),query:u().nullish(),sources:R(se("type",[d({type:h("url"),url:u()}),d({type:h("api"),name:u()})])).nullish()}),d({type:h("open_page"),url:u().nullish()}),d({type:h("find_in_page"),url:u().nullish(),pattern:u().nullish()})]).nullish()}),d({type:h("file_search_call"),id:u(),queries:R(u()),results:R(d({attributes:Se(u(),ee([u(),f(),ue()])),file_id:u(),filename:u(),score:f(),text:u()})).nullish()}),d({type:h("code_interpreter_call"),id:u(),code:u().nullable(),container_id:u(),outputs:R(se("type",[d({type:h("logs"),logs:u()}),d({type:h("image"),url:u()})])).nullable()}),d({type:h("image_generation_call"),id:u(),result:u()}),d({type:h("local_shell_call"),id:u(),call_id:u(),action:d({type:h("exec"),command:R(u()),timeout_ms:f().optional(),user:u().optional(),working_directory:u().optional(),env:Se(u(),u()).optional()})}),d({type:h("function_call"),call_id:u(),name:u(),arguments:u(),id:u()}),d({type:h("computer_call"),id:u(),status:u().optional()}),d({type:h("reasoning"),id:u(),encrypted_content:u().nullish(),summary:R(d({type:h("summary_text"),text:u()}))})])).optional(),service_tier:u().nullish(),incomplete_details:d({reason:u()}).nullish(),usage:d({input_tokens:f(),input_tokens_details:d({cached_tokens:f().nullish(),orchestration_input_tokens:f().nullish(),orchestration_input_cached_tokens:f().nullish()}).nullish(),output_tokens:f(),output_tokens_details:d({reasoning_tokens:f().nullish(),orchestration_output_tokens:f().nullish()}).nullish()}).optional()}))),cc=20,w0=Ee(()=>j(d({conversation:u().nullish(),include:R(X(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:u().nullish(),logprobs:ee([ue(),f().min(1).max(cc)]).optional(),maxToolCalls:f().nullish(),metadata:He().nullish(),parallelToolCalls:ue().nullish(),previousResponseId:u().nullish(),promptCacheKey:u().nullish(),promptCacheRetention:X(["in_memory","24h"]).nullish(),reasoningEffort:u().nullish(),reasoningSummary:u().nullish(),safetyIdentifier:u().nullish(),serviceTier:X(["auto","flex","priority","default"]).nullish(),store:ue().nullish(),strictJsonSchema:ue().nullish(),textVerbosity:X(["low","medium","high"]).nullish(),truncation:X(["auto","disabled"]).nullish(),user:u().nullish()})));async function x0({tools:e,toolChoice:t,strictJsonSchema:n}){e=e!=null&&e.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const o=[];for(const a of e)switch(a.type){case"function":o.push({type:"function",name:a.name,description:a.description,parameters:a.inputSchema,strict:n});break;case"provider-defined":{switch(a.id){case"openai.file_search":{const s=await Me({value:a.args,schema:Xw});o.push({type:"file_search",vector_store_ids:s.vectorStoreIds,max_num_results:s.maxNumResults,ranking_options:s.ranking?{ranker:s.ranking.ranker,score_threshold:s.ranking.scoreThreshold}:void 0,filters:s.filters});break}case"openai.local_shell":{o.push({type:"local_shell"});break}case"openai.web_search_preview":{const s=await Me({value:a.args,schema:p0});o.push({type:"web_search_preview",search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.web_search":{const s=await Me({value:a.args,schema:s0});o.push({type:"web_search",filters:s.filters!=null?{allowed_domains:s.filters.allowedDomains}:void 0,external_web_access:s.externalWebAccess,search_context_size:s.searchContextSize,user_location:s.userLocation});break}case"openai.code_interpreter":{const s=await Me({value:a.args,schema:Jw});o.push({type:"code_interpreter",container:s.container==null?{type:"auto",file_ids:void 0}:typeof s.container=="string"?s.container:{type:"auto",file_ids:s.container.fileIds}});break}case"openai.image_generation":{const s=await Me({value:a.args,schema:t0});o.push({type:"image_generation",background:s.background,input_fidelity:s.inputFidelity,input_image_mask:s.inputImageMask?{file_id:s.inputImageMask.fileId,image_url:s.inputImageMask.imageUrl}:void 0,model:s.model,size:s.size,quality:s.quality,moderation:s.moderation,output_format:s.outputFormat,output_compression:s.outputCompression});break}}break}default:r.push({type:"unsupported-tool",tool:a});break}if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:r};const i=t.type;switch(i){case"auto":case"none":case"required":return{tools:o,toolChoice:i,toolWarnings:r};case"tool":return{tools:o,toolChoice:t.toolName==="code_interpreter"||t.toolName==="file_search"||t.toolName==="image_generation"||t.toolName==="web_search_preview"||t.toolName==="web_search"?{type:t.toolName}:{type:"function",name:t.toolName},toolWarnings:r};default:{const a=i;throw new je({functionality:`tool choice type: ${a}`})}}}var k0=class{constructor(e,t){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:o,presencePenalty:i,frequencyPenalty:a,seed:s,prompt:l,providerOptions:c,tools:p,toolChoice:g,responseFormat:x}){var T,I,E,k;const _=[],v=ic(this.modelId);o!=null&&_.push({type:"unsupported-setting",setting:"topK"}),s!=null&&_.push({type:"unsupported-setting",setting:"seed"}),i!=null&&_.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&_.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&_.push({type:"unsupported-setting",setting:"stopSequences"});const y=await We({provider:"openai",providerOptions:c,schema:w0});y!=null&&y.conversation&&(y!=null&&y.previousResponseId)&&_.push({type:"unsupported-setting",setting:"conversation",details:"conversation and previousResponseId cannot be used together"});const{input:$,warnings:b}=await g0({prompt:l,systemMessageMode:v.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(T=y==null?void 0:y.store)!=null?T:!0,hasLocalShellTool:Z("openai.local_shell")});_.push(...b);const S=(I=y==null?void 0:y.strictJsonSchema)!=null?I:!1;let m=y==null?void 0:y.include;function N(Y){m==null?m=[Y]:m.includes(Y)||(m=[...m,Y])}function Z(Y){return(p==null?void 0:p.find(we=>we.type==="provider-defined"&&we.id===Y))!=null}const B=typeof(y==null?void 0:y.logprobs)=="number"?y==null?void 0:y.logprobs:(y==null?void 0:y.logprobs)===!0?cc:void 0;B&&N("message.output_text.logprobs");const L=(E=p==null?void 0:p.find(Y=>Y.type==="provider-defined"&&(Y.id==="openai.web_search"||Y.id==="openai.web_search_preview")))==null?void 0:E.name;L&&N("web_search_call.action.sources"),Z("openai.code_interpreter")&&N("code_interpreter_call.outputs");const oe=y==null?void 0:y.store;oe===!1&&v.isReasoningModel&&N("reasoning.encrypted_content");const z={model:this.modelId,input:$,temperature:t,top_p:r,max_output_tokens:e,...((x==null?void 0:x.type)==="json"||(y==null?void 0:y.textVerbosity))&&{text:{...(x==null?void 0:x.type)==="json"&&{format:x.schema!=null?{type:"json_schema",strict:S,name:(k=x.name)!=null?k:"response",description:x.description,schema:x.schema}:{type:"json_object"}},...(y==null?void 0:y.textVerbosity)&&{verbosity:y.textVerbosity}}},conversation:y==null?void 0:y.conversation,max_tool_calls:y==null?void 0:y.maxToolCalls,metadata:y==null?void 0:y.metadata,parallel_tool_calls:y==null?void 0:y.parallelToolCalls,previous_response_id:y==null?void 0:y.previousResponseId,store:oe,user:y==null?void 0:y.user,instructions:y==null?void 0:y.instructions,service_tier:y==null?void 0:y.serviceTier,include:m,prompt_cache_key:y==null?void 0:y.promptCacheKey,prompt_cache_retention:y==null?void 0:y.promptCacheRetention,safety_identifier:y==null?void 0:y.safetyIdentifier,top_logprobs:B,truncation:y==null?void 0:y.truncation,...v.isReasoningModel&&((y==null?void 0:y.reasoningEffort)!=null||(y==null?void 0:y.reasoningSummary)!=null)&&{reasoning:{...(y==null?void 0:y.reasoningEffort)!=null&&{effort:y.reasoningEffort},...(y==null?void 0:y.reasoningSummary)!=null&&{summary:y.reasoningSummary}}}};v.isReasoningModel?(y==null?void 0:y.reasoningEffort)==="none"&&v.supportsNonReasoningParameters||(z.temperature!=null&&(z.temperature=void 0,_.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,_.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((y==null?void 0:y.reasoningEffort)!=null&&_.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(y==null?void 0:y.reasoningSummary)!=null&&_.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(y==null?void 0:y.serviceTier)==="flex"&&!v.supportsFlexProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete z.service_tier),(y==null?void 0:y.serviceTier)==="priority"&&!v.supportsPriorityProcessing&&(_.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete z.service_tier);const{tools:V,toolChoice:W,toolWarnings:be}=await x0({tools:p,toolChoice:g,strictJsonSchema:S});return{webSearchToolName:L,args:{...z,tools:V,tool_choice:W},warnings:[..._,...be],store:oe}}async doGenerate(e){var t,n,r,o,i,a,s,l,c,p,g,x,T,I,E,k,_,v,y,$,b,S,m,N,Z,B,L,oe;const{args:z,warnings:V,webSearchToolName:W}=await this.getArgs(e),be=this.config.url({path:"/responses",modelId:this.modelId}),Y=this.config.provider.replace(".responses",""),{responseHeaders:we,value:ge,rawValue:Ce}=await De({url:be,headers:Le(this.config.headers(),e.headers),body:z,failedResponseHandler:ft,successfulResponseHandler:Be(b0),abortSignal:e.abortSignal,fetch:this.config.fetch});if(ge.error)throw new $e({message:ge.error.message,url:be,requestBodyValues:z,statusCode:400,responseHeaders:we,responseBody:Ce,isRetryable:!1});const le=[],he=[];let de=!1;for(const C of ge.output)switch(C.type){case"reasoning":{C.summary.length===0&&C.summary.push({type:"summary_text",text:""});for(const H of C.summary)le.push({type:"reasoning",text:H.text,providerMetadata:{[Y]:{itemId:C.id,reasoningEncryptedContent:(t=C.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"image_generation",result:{result:C.result},providerExecuted:!0});break}case"local_shell_call":{le.push({type:"tool-call",toolCallId:C.call_id,toolName:"local_shell",input:JSON.stringify({action:C.action}),providerMetadata:{[Y]:{itemId:C.id}}});break}case"message":{for(const H of C.content){(r=(n=e.providerOptions)==null?void 0:n.openai)!=null&&r.logprobs&&H.logprobs&&he.push(H.logprobs),le.push({type:"text",text:H.text,providerMetadata:{[Y]:{itemId:C.id,...C.phase!=null&&{phase:C.phase}}}});for(const re of H.annotations)re.type==="url_citation"?le.push({type:"source",sourceType:"url",id:(a=(i=(o=this.config).generateId)==null?void 0:i.call(o))!=null?a:Ge(),url:re.url,title:re.title}):re.type==="file_citation"?le.push({type:"source",sourceType:"document",id:(c=(l=(s=this.config).generateId)==null?void 0:l.call(s))!=null?c:Ge(),mediaType:"text/plain",title:(g=(p=re.quote)!=null?p:re.filename)!=null?g:"Document",filename:(x=re.filename)!=null?x:re.file_id,...re.file_id?{providerMetadata:{[Y]:{fileId:re.file_id}}}:{}}):re.type==="container_file_citation"?le.push({type:"source",sourceType:"document",id:(E=(I=(T=this.config).generateId)==null?void 0:I.call(T))!=null?E:Ge(),mediaType:"text/plain",title:(_=(k=re.filename)!=null?k:re.file_id)!=null?_:"Document",filename:(v=re.filename)!=null?v:re.file_id,providerMetadata:{[Y]:{fileId:re.file_id,containerId:re.container_id,...re.index!=null?{index:re.index}:{}}}}):re.type==="file_path"&&le.push({type:"source",sourceType:"document",id:(b=($=(y=this.config).generateId)==null?void 0:$.call(y))!=null?b:Ge(),mediaType:"application/octet-stream",title:re.file_id,filename:re.file_id,providerMetadata:{[Y]:{fileId:re.file_id,...re.index!=null?{index:re.index}:{}}}})}break}case"function_call":{de=!0,le.push({type:"tool-call",toolCallId:C.call_id,toolName:C.name,input:C.arguments,providerMetadata:{[Y]:{itemId:C.id}}});break}case"web_search_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:W??"web_search",input:JSON.stringify({}),providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:W??"web_search",result:xs(C.action),providerExecuted:!0});break}case"computer_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"computer_use",input:"",providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:C.status||"completed"},providerExecuted:!0});break}case"file_search_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"file_search",input:"{}",providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"file_search",result:{queries:C.queries,results:(m=(S=C.results)==null?void 0:S.map(H=>({attributes:H.attributes,fileId:H.file_id,filename:H.filename,score:H.score,text:H.text})))!=null?m:null},providerExecuted:!0});break}case"code_interpreter_call":{le.push({type:"tool-call",toolCallId:C.id,toolName:"code_interpreter",input:JSON.stringify({code:C.code,containerId:C.container_id}),providerExecuted:!0}),le.push({type:"tool-result",toolCallId:C.id,toolName:"code_interpreter",result:{outputs:C.outputs},providerExecuted:!0});break}}const ke={[Y]:{...ge.id!=null?{responseId:ge.id}:{}}};he.length>0&&(ke[Y].logprobs=he),typeof ge.service_tier=="string"&&(ke[Y].serviceTier=ge.service_tier);const O=ge.usage,ne=ks(O);return ne!=null&&(ke[Y].usage=ne),{content:le,finishReason:bs({finishReason:(N=ge.incomplete_details)==null?void 0:N.reason,hasFunctionCall:de}),usage:{inputTokens:O.input_tokens,outputTokens:O.output_tokens,totalTokens:O.input_tokens+O.output_tokens,reasoningTokens:(B=(Z=O.output_tokens_details)==null?void 0:Z.reasoning_tokens)!=null?B:void 0,cachedInputTokens:(oe=(L=O.input_tokens_details)==null?void 0:L.cached_tokens)!=null?oe:void 0},request:{body:z},response:{id:ge.id,timestamp:new Date(ge.created_at*1e3),modelId:ge.model,headers:we,body:Ce},providerMetadata:ke,warnings:V}}async doStream(e){const{args:t,warnings:n,webSearchToolName:r,store:o}=await this.getArgs(e),{responseHeaders:i,value:a}=await De({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Le(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:ft,successfulResponseHandler:Nn(v0),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=this,l=this.config.provider.replace(".responses","");let c="unknown";const p={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},g=[];let x=null;const T={},I=[];let E,k=!1;const _={};let v,y;return{stream:a.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:n})},transform($,b){var S,m,N,Z,B,L,oe,z,V,W,be,Y,we,ge,Ce,le,he,de,ke,O,ne,C,H,re;if(e.includeRawChunks&&b.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){c="error",b.enqueue({type:"error",error:$.error});return}const w=$.value;if(ws(w))w.item.type==="function_call"?(T[w.output_index]={toolName:w.item.name,toolCallId:w.item.call_id},b.enqueue({type:"tool-input-start",id:w.item.call_id,toolName:w.item.name})):w.item.type==="web_search_call"?(T[w.output_index]={toolName:r??"web_search",toolCallId:w.item.id},b.enqueue({type:"tool-input-start",id:w.item.id,toolName:r??"web_search",providerExecuted:!0}),b.enqueue({type:"tool-input-end",id:w.item.id}),b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:r??"web_search",input:JSON.stringify({}),providerExecuted:!0})):w.item.type==="computer_call"?(T[w.output_index]={toolName:"computer_use",toolCallId:w.item.id},b.enqueue({type:"tool-input-start",id:w.item.id,toolName:"computer_use",providerExecuted:!0})):w.item.type==="code_interpreter_call"?(T[w.output_index]={toolName:"code_interpreter",toolCallId:w.item.id,codeInterpreter:{containerId:w.item.container_id}},b.enqueue({type:"tool-input-start",id:w.item.id,toolName:"code_interpreter",providerExecuted:!0}),b.enqueue({type:"tool-input-delta",id:w.item.id,delta:`{"containerId":"${w.item.container_id}","code":"`})):w.item.type==="file_search_call"?b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):w.item.type==="image_generation_call"?b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):w.item.type==="message"?(I.splice(0,I.length),E=(S=w.item.phase)!=null?S:void 0,b.enqueue({type:"text-start",id:w.item.id,providerMetadata:{[l]:{itemId:w.item.id,...w.item.phase!=null&&{phase:w.item.phase}}}})):ws(w)&&w.item.type==="reasoning"&&(_[w.item.id]={encryptedContent:w.item.encrypted_content,summaryParts:{0:"active"}},b.enqueue({type:"reasoning-start",id:`${w.item.id}:0`,providerMetadata:{[l]:{itemId:w.item.id,reasoningEncryptedContent:(m=w.item.encrypted_content)!=null?m:null}}}));else if(T0(w)){if(w.item.type==="message"){const ie=(N=w.item.phase)!=null?N:E;E=void 0,b.enqueue({type:"text-end",id:w.item.id,providerMetadata:{[l]:{itemId:w.item.id,...ie!=null&&{phase:ie},...I.length>0&&{annotations:I}}}})}else if(w.item.type==="function_call")T[w.output_index]=void 0,k=!0,b.enqueue({type:"tool-input-end",id:w.item.call_id}),b.enqueue({type:"tool-call",toolCallId:w.item.call_id,toolName:w.item.name,input:w.item.arguments,providerMetadata:{[l]:{itemId:w.item.id}}});else if(w.item.type==="web_search_call")T[w.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:r??"web_search",result:xs(w.item.action),providerExecuted:!0});else if(w.item.type==="computer_call")T[w.output_index]=void 0,b.enqueue({type:"tool-input-end",id:w.item.id}),b.enqueue({type:"tool-call",toolCallId:w.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:w.item.status||"completed"},providerExecuted:!0});else if(w.item.type==="file_search_call")T[w.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"file_search",result:{queries:w.item.queries,results:(B=(Z=w.item.results)==null?void 0:Z.map(ie=>({attributes:ie.attributes,fileId:ie.file_id,filename:ie.filename,score:ie.score,text:ie.text})))!=null?B:null},providerExecuted:!0});else if(w.item.type==="code_interpreter_call")T[w.output_index]=void 0,b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"code_interpreter",result:{outputs:w.item.outputs},providerExecuted:!0});else if(w.item.type==="image_generation_call")b.enqueue({type:"tool-result",toolCallId:w.item.id,toolName:"image_generation",result:{result:w.item.result},providerExecuted:!0});else if(w.item.type==="local_shell_call")T[w.output_index]=void 0,b.enqueue({type:"tool-call",toolCallId:w.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:w.item.action.command,timeoutMs:w.item.action.timeout_ms,user:w.item.action.user,workingDirectory:w.item.action.working_directory,env:w.item.action.env}}),providerMetadata:{[l]:{itemId:w.item.id}}});else if(w.item.type==="reasoning"){const ie=_[w.item.id],nt=Object.entries(ie.summaryParts).filter(([Mt,rt])=>rt==="active"||rt==="can-conclude").map(([Mt])=>Mt);for(const Mt of nt)b.enqueue({type:"reasoning-end",id:`${w.item.id}:${Mt}`,providerMetadata:{[l]:{itemId:w.item.id,reasoningEncryptedContent:(L=w.item.encrypted_content)!=null?L:null}}});delete _[w.item.id]}}else if(C0(w)){const ie=T[w.output_index];ie!=null&&b.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:w.delta})}else if(A0(w)){const ie=T[w.output_index];ie!=null&&b.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:JSON.stringify(w.delta).slice(1,-1)})}else if(O0(w)){const ie=T[w.output_index];ie!=null&&(b.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:'"}'}),b.enqueue({type:"tool-input-end",id:ie.toolCallId}),b.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:w.code,containerId:ie.codeInterpreter.containerId}),providerExecuted:!0}))}else if(E0(w))x=w.response.id,b.enqueue({type:"response-metadata",id:w.response.id,timestamp:new Date(w.response.created_at*1e3),modelId:w.response.model});else if(I0(w))b.enqueue({type:"text-delta",id:w.item_id,delta:w.delta}),(z=(oe=e.providerOptions)==null?void 0:oe.openai)!=null&&z.logprobs&&w.logprobs&&g.push(w.logprobs);else if(w.type==="response.reasoning_summary_part.added"){if(w.summary_index>0){const ie=_[w.item_id];ie.summaryParts[w.summary_index]="active";for(const nt of Object.keys(ie.summaryParts))ie.summaryParts[nt]==="can-conclude"&&(b.enqueue({type:"reasoning-end",id:`${w.item_id}:${nt}`,providerMetadata:{[l]:{itemId:w.item_id}}}),ie.summaryParts[nt]="concluded");b.enqueue({type:"reasoning-start",id:`${w.item_id}:${w.summary_index}`,providerMetadata:{[l]:{itemId:w.item_id,reasoningEncryptedContent:(W=(V=_[w.item_id])==null?void 0:V.encryptedContent)!=null?W:null}}})}}else w.type==="response.reasoning_summary_text.delta"?b.enqueue({type:"reasoning-delta",id:`${w.item_id}:${w.summary_index}`,delta:w.delta,providerMetadata:{[l]:{itemId:w.item_id}}}):w.type==="response.reasoning_summary_part.done"?o?(b.enqueue({type:"reasoning-end",id:`${w.item_id}:${w.summary_index}`,providerMetadata:{[l]:{itemId:w.item_id}}}),_[w.item_id].summaryParts[w.summary_index]="concluded"):_[w.item_id].summaryParts[w.summary_index]="can-conclude":S0(w)?(c=bs({finishReason:(be=w.response.incomplete_details)==null?void 0:be.reason,hasFunctionCall:k}),p.inputTokens=w.response.usage.input_tokens,p.outputTokens=w.response.usage.output_tokens,p.totalTokens=w.response.usage.input_tokens+w.response.usage.output_tokens,p.reasoningTokens=(we=(Y=w.response.usage.output_tokens_details)==null?void 0:Y.reasoning_tokens)!=null?we:void 0,p.cachedInputTokens=(Ce=(ge=w.response.usage.input_tokens_details)==null?void 0:ge.cached_tokens)!=null?Ce:void 0,typeof w.response.service_tier=="string"&&(v=w.response.service_tier),y=ks(w.response.usage)):$0(w)?(I.push(w.annotation),w.annotation.type==="url_citation"?b.enqueue({type:"source",sourceType:"url",id:(de=(he=(le=s.config).generateId)==null?void 0:he.call(le))!=null?de:Ge(),url:w.annotation.url,title:w.annotation.title}):w.annotation.type==="file_citation"&&b.enqueue({type:"source",sourceType:"document",id:(ne=(O=(ke=s.config).generateId)==null?void 0:O.call(ke))!=null?ne:Ge(),mediaType:"text/plain",title:(H=(C=w.annotation.quote)!=null?C:w.annotation.filename)!=null?H:"Document",filename:(re=w.annotation.filename)!=null?re:w.annotation.file_id,...w.annotation.file_id?{providerMetadata:{[l]:{fileId:w.annotation.file_id}}}:{}})):N0(w)&&b.enqueue({type:"error",error:w})},flush($){const b={[l]:{responseId:x}};g.length>0&&(b[l].logprobs=g),v!==void 0&&(b[l].serviceTier=v),y!=null&&(b[l].usage=y),$.enqueue({type:"finish",finishReason:c,usage:p,providerMetadata:b})}})),request:{body:t},response:{headers:i}}}};function I0(e){return e.type==="response.output_text.delta"}function T0(e){return e.type==="response.output_item.done"}function S0(e){return e.type==="response.completed"||e.type==="response.incomplete"}function E0(e){return e.type==="response.created"}function C0(e){return e.type==="response.function_call_arguments.delta"}function A0(e){return e.type==="response.code_interpreter_call_code.delta"}function O0(e){return e.type==="response.code_interpreter_call_code.done"}function ws(e){return e.type==="response.output_item.added"}function $0(e){return e.type==="response.output_text.annotation.added"}function N0(e){return e.type==="error"}function xs(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function ks(e){var t,n,r;const o=(t=e==null?void 0:e.input_tokens_details)==null?void 0:t.orchestration_input_tokens,i=(n=e==null?void 0:e.input_tokens_details)==null?void 0:n.orchestration_input_cached_tokens,a=(r=e==null?void 0:e.output_tokens_details)==null?void 0:r.orchestration_output_tokens;if(!(o==null&&i==null&&a==null))return{...o!=null&&{orchestrationInputTokens:o},...i!=null&&{orchestrationInputCachedTokens:i},...a!=null&&{orchestrationOutputTokens:a}}}var R0=Ee(()=>j(d({instructions:u().nullish(),speed:f().min(.25).max(4).default(1).nullish()}))),P0=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:n="mp3",speed:r,instructions:o,language:i,providerOptions:a}){const s=[],l=await We({provider:"openai",providerOptions:a,schema:R0}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:r,instructions:o};if(n&&(["mp3","opus","aac","flac","wav","pcm"].includes(n)?c.response_format=n:s.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${n}. Using mp3 instead.`})),l){const p={};for(const g in p){const x=p[g];x!==void 0&&(c[g]=x)}}return i&&s.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${i}" was ignored.`}),{requestBody:c,warnings:s}}async doGenerate(e){var t,n,r;const o=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{requestBody:i,warnings:a}=await this.getArgs(e),{value:s,responseHeaders:l,rawValue:c}=await De({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Le(this.config.headers(),e.headers),body:i,failedResponseHandler:ft,successfulResponseHandler:a_(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:a,request:{body:JSON.stringify(i)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},M0=Ee(()=>j(d({text:u(),language:u().nullish(),duration:f().nullish(),words:R(d({word:u(),start:f(),end:f()})).nullish(),segments:R(d({id:f(),seek:f(),start:f(),end:f(),text:u(),tokens:R(f()),temperature:f(),avg_logprob:f(),compression_ratio:f(),no_speech_prob:f()})).nullish()}))),z0=Ee(()=>j(d({include:R(u()).optional(),language:u().optional(),prompt:u().optional(),temperature:f().min(0).max(1).default(0).optional(),timestampGranularities:R(X(["word","segment"])).default(["segment"]).optional()}))),Is={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},L0=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){const r=[],o=await We({provider:"openai",providerOptions:n,schema:z0}),i=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([hr(e)]);i.append("model",this.modelId);const s=Hm(t);if(i.append("file",new File([a],"audio",{type:t}),`audio.${s}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,p]of Object.entries(l))if(p!=null)if(Array.isArray(p))for(const g of p)i.append(`${c}[]`,String(g));else i.append(c,String(p))}return{formData:i,warnings:r}}async doGenerate(e){var t,n,r,o,i,a,s,l;const c=(r=(n=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:n.call(t))!=null?r:new Date,{formData:p,warnings:g}=await this.getArgs(e),{value:x,responseHeaders:T,rawValue:I}=await o_({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Le(this.config.headers(),e.headers),formData:p,failedResponseHandler:ft,successfulResponseHandler:Be(M0),abortSignal:e.abortSignal,fetch:this.config.fetch}),E=x.language!=null&&x.language in Is?Is[x.language]:void 0;return{text:x.text,segments:(s=(a=(o=x.segments)==null?void 0:o.map(k=>({text:k.text,startSecond:k.start,endSecond:k.end})))!=null?a:(i=x.words)==null?void 0:i.map(k=>({text:k.word,startSecond:k.start,endSecond:k.end})))!=null?s:[],language:E,durationInSeconds:(l=x.duration)!=null?l:void 0,warnings:g,response:{timestamp:c,modelId:this.modelId,headers:T,body:I}}}},D0="2.0.110";function Fn(e={}){var t,n;const r=(t=ko(Zt({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(n=e.name)!=null?n:"openai",i=()=>qt({Authorization:`Bearer ${Vl({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${D0}`),a=E=>new Nw(E,{provider:`${o}.chat`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),s=E=>new zw(E,{provider:`${o}.completion`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),l=E=>new Zw(E,{provider:`${o}.embedding`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),c=E=>new qw(E,{provider:`${o}.image`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),p=E=>new L0(E,{provider:`${o}.transcription`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),g=E=>new P0(E,{provider:`${o}.speech`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch}),x=E=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return T(E)},T=E=>new k0(E,{provider:`${o}.responses`,url:({path:k})=>`${r}${k}`,headers:i,fetch:e.fetch,fileIdPrefixes:["file-"]}),I=function(E){return x(E)};return I.languageModel=x,I.chat=a,I.completion=s,I.responses=T,I.embedding=l,I.textEmbedding=l,I.textEmbeddingModel=l,I.image=c,I.imageModel=c,I.transcription=p,I.transcriptionModel=p,I.speech=g,I.speechModel=g,I.tools=_0,I}Fn();const dc={"anthropic-dangerous-direct-browser-access":"true"};function No(e){const t=e.trim().replace(/\/+$/,"");if(t)try{const n=new URL(t);return!n.pathname||n.pathname==="/"?`${t}/v1`:t}catch{return t}}function Ts(e){if(e)for(const t of e)t.role==="developer"&&(t.role="system")}function Z0(e=globalThis.fetch.bind(globalThis)){return async(t,n)=>{if(!(n!=null&&n.body)||typeof n.body!="string"||!n.body.includes('"role":"developer"')&&!n.body.includes('"role": "developer"'))return e(t,n);try{const r=JSON.parse(n.body);return Ts(r.messages),Ts(r.input),e(t,{...n,body:JSON.stringify(r)})}catch{return e(t,n)}}}function Ro(e){if(!e.apiKey.trim())throw new Error("API key is required. Run LLMSETTINGS to configure a model.");const t=No(e.baseUrl);return e.protocol==="anthropic-messages"?oc({apiKey:e.apiKey,baseURL:t,headers:dc})(e.model):e.protocol==="openai-responses"?Fn({apiKey:e.apiKey,baseURL:t}).responses(e.model):e.kind==="builtin"&&e.provider==="openai"?Fn({apiKey:e.apiKey,baseURL:t}).chat(e.model):Fn({apiKey:e.apiKey,baseURL:t,fetch:Z0()}).chat(e.model)}const j0=vb(),Po=e=>Promise.all(e.map(async t=>t.isUrlSupportedByModel||t.url.protocol==="data:"?null:j0({url:t.url}))),pc=["openai-chat","openai-responses","anthropic-messages"],Mo=["deepseek","deepseek-vl","openai","anthropic"],U0=[{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",vision:!0},{id:"gpt-5.4",name:"GPT-5.4",vision:!0},{id:"gpt-5.5",name:"GPT-5.5",vision:!0},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",vision:!0},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",vision:!0},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",vision:!0}],Ht={deepseek:{protocol:"openai-chat",baseUrl:"https://api.deepseek.com/v1",models:[{id:"deepseek-v4-flash",name:"DeepSeek V4 Flash",vision:!1},{id:"deepseek-v4-pro",name:"DeepSeek V4 Pro",vision:!1},{id:"deepseek-chat",name:"DeepSeek Chat (legacy)",vision:!1},{id:"deepseek-reasoner",name:"DeepSeek Reasoner (legacy)",vision:!1}]},"deepseek-vl":{protocol:"openai-chat",baseUrl:"https://api.siliconflow.cn/v1",models:[{id:"deepseek-vl2",name:"DeepSeek VL2",vision:!0},{id:"deepseek-ai/deepseek-vl2-small",name:"DeepSeek VL2 Small",vision:!0},{id:"deepseek-ai/deepseek-vl2-tiny",name:"DeepSeek VL2 Tiny",vision:!0},{id:"deepseek-ai/deepseek-vl2",name:"DeepSeek VL2 (HF)",vision:!0}]},openai:{protocol:"openai-chat",baseUrl:"https://api.openai.com/v1",models:U0},anthropic:{protocol:"anthropic-messages",baseUrl:"https://api.anthropic.com/v1",models:[{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",vision:!0},{id:"claude-sonnet-5",name:"Claude Sonnet 5",vision:!0},{id:"claude-opus-4-6",name:"Claude Opus 4.6",vision:!0},{id:"claude-opus-4-7",name:"Claude Opus 4.7",vision:!0},{id:"claude-opus-4-8",name:"Claude Opus 4.8",vision:!0},{id:"claude-opus-5",name:"Claude Opus 5",vision:!0},{id:"claude-fable-5",name:"Claude Fable 5",vision:!0}]}};function et(e){return Mo.includes(e)}const B0=[/gpt-5/i,/gpt-4o/i,/gpt-4\.1/i,/gpt-4-turbo/i,/gpt-4-vision/i,/claude-3/i,/claude-sonnet/i,/claude-opus/i,/claude-haiku/i,/claude-fable/i,/gemini/i,/qwen.*vl/i,/deepseek-vl/i,/glm-4(\.\d+)?v/i,/kimi.*(vl|vision)/i,/llava/i,/pixtral/i];function an(e){return B0.some(t=>t.test(e))}function hc(e,t){return e.vision===an(e.id)?an(t):e.vision}function zo(e){var t;return((t=e.name)==null?void 0:t.trim())||e.id}const V0=1,fc="cad-agent-plugin-api-key-v1",no=12,ro=`enc:v${V0}:`;function F0(){var t;return`${typeof((t=globalThis.location)==null?void 0:t.origin)=="string"?globalThis.location.origin:"file://"}:${fc}`}async function mc(){const e=new TextEncoder,t=await crypto.subtle.importKey("raw",e.encode(F0()),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e.encode(fc),iterations:1e5,hash:"SHA-256"},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function q0(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t)}function G0(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}async function H0(e){if(!e)return"";const t=await mc(),n=crypto.getRandomValues(new Uint8Array(no)),r=new TextEncoder().encode(e),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,r),i=new Uint8Array(n.length+o.byteLength);return i.set(n,0),i.set(new Uint8Array(o),n.length),`${ro}${q0(i)}`}async function _c(e){if(!e)return"";if(!e.startsWith(ro))return e;try{const t=await mc(),n=G0(e.slice(ro.length)),r=n.slice(0,no),o=n.slice(no),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,o);return new TextDecoder().decode(i)}catch{return""}}const gc="cad-agent-plugin.llm-config",W0="cad-agent-plugin.llm-settings",ir="deepseek",Lo=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function gn(){return{providers:[],activeProviderId:ir,activeModel:Ht[ir].models[0].id}}function Pt(e){return{id:e,kind:"builtin",protocol:Ht[e].protocol,baseUrl:"",apiKey:"",models:null}}function ar(){return{id:"",kind:"custom",displayName:"",protocol:"openai-chat",baseUrl:"",apiKey:"",models:[]}}function Wt(e,t){const n=e.providers.find(r=>r.id===t);return n||(et(t)?Pt(t):void 0)}function vt(e){return e.models?e.models:e.kind==="builtin"&&et(e.id)?Ht[e.id].models:[]}function En(e){const t=e.baseUrl.trim();return t||(e.kind==="builtin"&&et(e.id)?Ht[e.id].baseUrl:"")}function Do(e){const t=Wt(e,e.activeProviderId)??Pt(ir);return{provider:t.id,kind:t.kind,protocol:t.protocol,apiKey:t.apiKey,baseUrl:En(t),model:e.activeModel}}function Zo(e){const t=Wt(e,e.activeProviderId),n=t?vt(t).find(r=>r.id===e.activeModel):void 0;return n?n.vision:an(e.activeModel)}function _r(e){const t=Do(e);if(t.apiKey.trim()&&Zo(e))return t;for(const n of e.providers){const r=jo(e,n.id);if(r)return r}}function jo(e,t){const n=Wt(e,t);if(!(n!=null&&n.apiKey.trim()))return;if(e.activeProviderId===t&&Zo(e))return Do(e);const r=vt(n).find(o=>o.vision);if(r)return vc(n,r.id)}function yc(e,t,n){const r=Wt(e,t);if(!(r!=null&&r.apiKey.trim()))return;const o=vt(r).find(i=>i.id===n&&i.vision);if(o)return vc(r,o.id)}function vc(e,t){return{provider:e.id,kind:e.kind,protocol:e.protocol,apiKey:e.apiKey,baseUrl:En(e),model:t}}function bc(e,t){var a;const r=e.providers.some(s=>s.id===t.id)?e.providers.map(s=>s.id===t.id?t:s):[...e.providers,t],o=vt(t),i=e.activeProviderId===t.id&&(o.length===0||o.some(s=>s.id===e.activeModel));return{providers:r,activeProviderId:t.id,activeModel:i?e.activeModel:((a=o[0])==null?void 0:a.id)??""}}function wc(e,t){const n=e.providers.filter(r=>r.id!==t);return e.activeProviderId!==t?{...e,providers:n}:Uo({providers:n,activeProviderId:"",activeModel:""})}function xc(e){var i,a,s;const t=e.apiKey??"",n=((i=e.baseUrl)==null?void 0:i.trim())??"",r=e.provider??"";if(et(r)){const l=Ht[r],c=((a=e.model)==null?void 0:a.trim())||l.models[0].id;return{providers:[{...Pt(r),apiKey:t,baseUrl:n===l.baseUrl?"":n}],activeProviderId:r,activeModel:c}}const o=(s=e.model)==null?void 0:s.trim();return r!=="openai-compatible"||!o?gn():{providers:[{...ar(),id:r,baseUrl:n,apiKey:t,models:[{id:o,vision:an(o)}]}],activeProviderId:r,activeModel:o}}function J0(e,t){const n=e.id??"";if(e.kind==="builtin"||et(n))return et(n)?{...Pt(n),baseUrl:e.baseUrl??"",apiKey:t,models:oo(e.models)}:void 0;if(Lo.test(n))return{id:n,kind:"custom",displayName:e.displayName??"",protocol:e.protocol??"openai-chat",baseUrl:e.baseUrl??"",apiKey:t,models:oo(e.models)??[]}}function oo(e){return Array.isArray(e)?e.flatMap(t=>{const n=t;if(!n||typeof n!="object")return[];if(typeof n.id!="string"||!n.id.trim())return[];const r=typeof n.name=="string"?n.name.trim():"",o=typeof n.contextWindow=="number"&&Number.isFinite(n.contextWindow)&&n.contextWindow>0?Math.round(n.contextWindow):void 0;return[{id:n.id,...r?{name:r}:{},vision:!!n.vision,...o!==void 0?{contextWindow:o}:{}}]}):null}function Uo(e){var n;if(Wt(e,e.activeProviderId))return e;const t=e.providers.find(r=>r.apiKey.trim())??Pt(ir);return{...e,activeProviderId:t.id,activeModel:((n=vt(t)[0])==null?void 0:n.id)??""}}async function K0(e){const t=JSON.parse(e),n=t.apiKeyEnc?await _c(t.apiKeyEnc):t.apiKey??"";return{...t,apiKey:n}}async function ln(){try{const e=localStorage.getItem(gc);if(!e){const o=localStorage.getItem(W0);return o?xc(await K0(o)):gn()}const t=JSON.parse(e),n=[];for(const o of t.providers??[]){const i=o.apiKeyEnc?await _c(o.apiKeyEnc):"",a=J0(o,i);a&&!n.some(s=>s.id===a.id)&&n.push(a)}const r=gn();return Uo({providers:n,activeProviderId:t.activeProviderId??r.activeProviderId,activeModel:t.activeModel??r.activeModel})}catch{return gn()}}async function io(e){const t=[];for(const r of e.providers)t.push({id:r.id,kind:r.kind,...r.kind==="custom"?{displayName:r.displayName,protocol:r.protocol}:{},baseUrl:r.baseUrl,models:r.models,apiKeyEnc:r.apiKey?await H0(r.apiKey):""});const n={version:2,providers:t,activeProviderId:e.activeProviderId,activeModel:e.activeModel};localStorage.setItem(gc,JSON.stringify(n)),so.dispatchEvent(new CustomEvent(ao,{detail:e}))}const ao="change",so=new EventTarget;function kc(e){const t=n=>e(n.detail);return so.addEventListener(ao,t),()=>so.removeEventListener(ao,t)}async function Y0(){const e=await ln();return{configured:e.providers.some(t=>t.apiKey.trim()),vision:!!_r(e)}}const X0=`You read text from images of CAD drawings.
|
|
84
|
+
|
|
85
|
+
The image shows one line of text drawn as strokes (for example SHX single-line
|
|
86
|
+
fonts), dark on white, upright. Reply with exactly the text shown, preserving
|
|
87
|
+
case, digits, punctuation, CAD symbols such as Ø ± ° and spaces between words.
|
|
88
|
+
Do not explain, translate, quote or add anything else. If nothing is legible,
|
|
89
|
+
reply with an empty message.`,Q0=`You read text from images of CAD drawings.
|
|
90
|
+
|
|
91
|
+
You get several numbered images. Each shows one line of text drawn as strokes
|
|
92
|
+
(for example SHX single-line fonts), dark on white, upright. Read every image
|
|
93
|
+
exactly: preserve case, digits, punctuation, CAD symbols such as Ø ± ° and
|
|
94
|
+
spaces between words. Do not explain, translate or correct the text.
|
|
95
|
+
|
|
96
|
+
Reply with only a JSON array of strings, one per image in the given order,
|
|
97
|
+
and exactly as many entries as images. Use "" for an image that is not legible.`,lo=12e4;async function Ic(e,t){const n=new AbortController,r=()=>n.abort(e==null?void 0:e.reason);e!=null&&e.aborted?r():e==null||e.addEventListener("abort",r,{once:!0});let o;const i=new Promise((a,s)=>{o=setTimeout(()=>{const l=new Error(D.llmT("recognitionTimeout",{seconds:Math.round(lo/1e3)}));n.abort(l),s(l)},lo)});try{return await Promise.race([t(n.signal),i])}finally{clearTimeout(o),e==null||e.removeEventListener("abort",r)}}const Ss=20,Es=3;async function Tc(e,t){const n=await ln(),r=Cc(n,t),o=e.images.map(()=>{});if(!r||e.images.length===0)return o;const i=[];for(let c=0;c<e.images.length;c+=Ss)i.push(e.images.slice(c,c+Ss));const a=async c=>{const{text:p}=await Ic(e.signal,g=>Ku({model:Ro(r),system:Q0,abortSignal:g,experimental_download:Po,messages:[{role:"user",content:[{type:"text",text:[`Read the text in these ${c.length} images.`,e.locale?`UI language: ${e.locale}.`:""].filter(Boolean).join(" ")},...c.flatMap((x,T)=>[{type:"text",text:`Image ${T+1}:`},{type:"image",image:x}])]}]}));return Sc(p,c.length)},s=[];for(let c=0;c<i.length;c+=Es)s.push(...await Promise.allSettled(i.slice(c,c+Es).map(a)));const l=s.find(c=>c.status==="rejected");if(l&&s.every(c=>c.status==="rejected"))throw l.reason;return s.flatMap((c,p)=>c.status==="fulfilled"?c.value:i[p].map(()=>{}))}function Sc(e,t){const n=e.indexOf("["),r=e.lastIndexOf("]"),o=n>=0&&r>n?JSON.parse(e.slice(n,r+1)):null;if(!Array.isArray(o))throw new Error(`Unexpected text recognition answer: ${e.trim().slice(0,80)}`);return Array.from({length:t},(i,a)=>typeof o[a]=="string"?Bo(o[a]):void 0)}async function Ec(e,t){const n=await ln(),r=Cc(n,t);if(!r)return;const o=[e.locale?`UI language: ${e.locale}.`:"",e.hint?`The previous line of this drawing read: "${e.hint}".`:""].filter(Boolean),{text:i}=await Ic(e.signal,a=>Ku({model:Ro(r),system:X0,abortSignal:a,experimental_download:Po,messages:[{role:"user",content:[{type:"text",text:["Read the text in this image.",...o].join(" ")},{type:"image",image:e.image}]}]}));return Bo(i)}function Bo(e){let t=e.trim();return t=t.replace(/^```[a-z]*\s*|\s*```$/gi,"").trim(),(/^(["'“”‘’`]).*\1$/.test(t)||/^“.*”$/.test(t))&&(t=t.slice(1,-1).trim()),t||void 0}function Cc(e,t){return t?t.modelId?yc(e,t.providerId,t.modelId):jo(e,t.providerId):_r(e)}const ex={deepseek:"providerDeepseek","deepseek-vl":"providerDeepseekVl",openai:"providerOpenai",anthropic:"providerAnthropic"};function Vo(e){return D.llmT(ex[e])}function gr(e){var t;return e.kind==="builtin"&&et(e.id)?Vo(e.id):((t=e.displayName)==null?void 0:t.trim())||e.id}const Dr=new Set;let Cs,pn;async function Ac(){return pn||(pn=nx().finally(()=>{pn=void 0}),pn)}function tx(){Cs||(Cs=kc(()=>{Ac()}))}async function nx(){const e=await ln(),t=new Set;for(const n of e.providers){if(!n.apiKey.trim())continue;const r=gr(n);for(const o of rx(n)){const i=D.acapLlmOcrRecognizerId(n.id,o.id);t.add(i);const a=zo(o),s=()=>`${r} — ${a}`;yn.AcApTextRecognitionService.register({id:i,label:s,keyword:()=>({display:s(),local:s(),global:`${n.id}/${o.id}`}),auto:!1,isAvailable:()=>!0,recognize:l=>Ec(l,{providerId:n.id,modelId:o.id}),recognizeBatch:l=>Tc(l,{providerId:n.id,modelId:o.id})}),Dr.add(i)}}for(const n of[...Dr])t.has(n)||(yn.AcApTextRecognitionService.unregister(n),Dr.delete(n))}function rx(e){return vt(e).filter(t=>t.vision)}const ox="1.8.0-preview.6",ix={version:ox};class Xt extends Error{constructor(t,n,r){super(`Model listing failed (${t}) at ${n}`),this.code=t,this.url=n,this.status=r,this.name="AcApLlmModelListingError"}}const ax="2023-06-01",sx=1e3;function Oc(e,t){const n=No(e)??"";return t!=="anthropic-messages"?`${n}/models`:`${n.endsWith("/v1")?n.slice(0,-3):n}/v1/models?limit=${sx}`}function As(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t}function $c(e,t=""){const n=e;let r;if(Array.isArray(n==null?void 0:n.data))r=n.data.map(i=>({raw:i}));else if(n!=null&&n.models&&typeof n.models=="object"&&!Array.isArray(n.models))r=Object.entries(n.models).filter(([,i])=>!!i&&typeof i=="object").map(([i,a])=>({key:i,raw:a}));else throw new Xt("format",t);const o=new Map;for(const{key:i,raw:a}of r){const s=a??{},l=As(i,s.id);if(!l||o.has(l))continue;const c=As(s.name,s.display_name,s.displayName);o.set(l,c&&c!==l?{id:l,name:c}:{id:l})}return[...o.values()]}async function Nc(e,t=globalThis.fetch.bind(globalThis),n){const r=Oc(e.baseUrl,e.protocol),o=e.apiKey.trim(),i=e.protocol==="anthropic-messages"?{"x-api-key":o,"anthropic-version":ax,...dc}:{Authorization:`Bearer ${o}`};let a;try{a=await t(r,{method:"GET",headers:i,signal:n})}catch(l){throw n!=null&&n.aborted?l:new Xt("network",r)}if(!a.ok)throw new Xt("http",r,a.status);let s;try{s=await a.json()}catch{throw new Xt("format",r)}return $c(s,r)}function lx(e,t){return e===null||t===null?e===t:e.length===t.length&&e.every((n,r)=>n.id===t[r].id&&(n.name??"")===(t[r].name??"")&&n.vision===t[r].vision&&(n.contextWindow??0)===(t[r].contextWindow??0))}function Rc(e,t){return e.id===t.id&&e.kind===t.kind&&(e.displayName??"")===(t.displayName??"")&&e.protocol===t.protocol&&e.baseUrl===t.baseUrl&&e.apiKey===t.apiKey&&lx(e.models,t.models)}function Pc(e){const{activeProviderId:t,activeModel:n}=e,r=e.providers.filter(o=>o.apiKey.trim()).map(o=>o.id);return r.includes(t)||r.unshift(t),r.flatMap(o=>{const i=Wt(e,o);if(!i)return[];const a=[...vt(i)];return o===t&&n&&!a.some(s=>s.id===n)&&a.push({id:n,vision:!1}),[{providerId:o,label:gr(i),options:a.map(s=>({providerId:o,modelId:s.id,label:zo(s),vision:s.vision}))}]})}const ux=`
|
|
98
|
+
.ml-ui-dialog.ml-llm-settings-dialog {
|
|
99
|
+
display: flex;
|
|
100
|
+
flex-direction: column;
|
|
101
|
+
width: min(860px, calc(100% - 32px));
|
|
102
|
+
max-width: none;
|
|
103
|
+
max-height: calc(100% - 24px);
|
|
104
|
+
overflow: hidden;
|
|
105
|
+
font-size: 12px;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
.ml-llm-settings-dialog .ml-ui-dialog-header {
|
|
109
|
+
flex-shrink: 0;
|
|
110
|
+
margin-bottom: 10px;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/* Only the body scrolls, and only on very short hosts: the footer buttons
|
|
114
|
+
always stay in view. */
|
|
115
|
+
.ml-llm-settings-dialog .ml-ui-dialog-body {
|
|
116
|
+
display: flex;
|
|
117
|
+
flex: 1 1 auto;
|
|
118
|
+
flex-direction: column;
|
|
119
|
+
gap: 8px;
|
|
120
|
+
min-height: 0;
|
|
121
|
+
overflow-y: auto;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
.ml-llm-settings-dialog .ml-ui-dialog-footer:not(:empty) {
|
|
125
|
+
flex-shrink: 0;
|
|
126
|
+
align-items: center;
|
|
127
|
+
margin-top: 10px;
|
|
128
|
+
padding-top: 10px;
|
|
129
|
+
border-top: 1px solid var(--ml-ui-border, #dcdfe6);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/* "Model in use": label and picker on one row. */
|
|
133
|
+
.ml-llm-section > .ml-llm-field {
|
|
134
|
+
flex-direction: row;
|
|
135
|
+
align-items: center;
|
|
136
|
+
gap: 10px;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
.ml-llm-section > .ml-llm-field > select {
|
|
140
|
+
flex: 1 1 auto;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
.ml-llm-columns {
|
|
144
|
+
display: grid;
|
|
145
|
+
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
|
146
|
+
gap: 16px;
|
|
147
|
+
align-items: start;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
.ml-llm-column {
|
|
151
|
+
display: flex;
|
|
152
|
+
flex-direction: column;
|
|
153
|
+
gap: 8px;
|
|
154
|
+
min-width: 0;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
@media (max-width: 720px) {
|
|
158
|
+
.ml-llm-columns {
|
|
159
|
+
grid-template-columns: minmax(0, 1fr);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
.ml-llm-footer-message {
|
|
164
|
+
display: flex;
|
|
165
|
+
flex: 1;
|
|
166
|
+
flex-direction: column;
|
|
167
|
+
min-width: 0;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
.ml-llm-settings-dialog input,
|
|
171
|
+
.ml-llm-settings-dialog select {
|
|
172
|
+
box-sizing: border-box;
|
|
173
|
+
min-width: 0;
|
|
174
|
+
padding: 6px 8px;
|
|
175
|
+
border: 1px solid var(--ml-ui-border, #dcdfe6);
|
|
176
|
+
border-radius: 4px;
|
|
177
|
+
background: var(--ml-ui-bg, #ffffff);
|
|
178
|
+
color: var(--ml-ui-text, #303133);
|
|
179
|
+
font: inherit;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
.ml-llm-settings-dialog input:focus,
|
|
183
|
+
.ml-llm-settings-dialog select:focus {
|
|
184
|
+
outline: none;
|
|
185
|
+
border-color: var(--ml-ui-accent, #0b84ff);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
.ml-llm-settings-dialog input:disabled {
|
|
189
|
+
color: var(--ml-ui-text-muted, #606266);
|
|
190
|
+
cursor: not-allowed;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
.ml-llm-settings-dialog input[type='checkbox'] {
|
|
194
|
+
margin: 0;
|
|
195
|
+
padding: 0;
|
|
196
|
+
accent-color: var(--ml-ui-accent, #0b84ff);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
.ml-llm-settings-dialog [hidden] {
|
|
200
|
+
display: none !important;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
.ml-llm-section,
|
|
204
|
+
.ml-llm-group,
|
|
205
|
+
.ml-llm-catalog {
|
|
206
|
+
display: flex;
|
|
207
|
+
flex-direction: column;
|
|
208
|
+
gap: 8px;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
.ml-llm-section-title,
|
|
212
|
+
.ml-llm-field-label {
|
|
213
|
+
font-weight: 600;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
.ml-llm-field-row {
|
|
217
|
+
display: grid;
|
|
218
|
+
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
|
219
|
+
gap: 8px;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
.ml-llm-field {
|
|
223
|
+
display: flex;
|
|
224
|
+
flex-direction: column;
|
|
225
|
+
gap: 4px;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
.ml-llm-hint,
|
|
229
|
+
.ml-llm-warning,
|
|
230
|
+
.ml-llm-error,
|
|
231
|
+
.ml-llm-validation,
|
|
232
|
+
.ml-llm-status {
|
|
233
|
+
margin: 0;
|
|
234
|
+
font-size: 11px;
|
|
235
|
+
line-height: 1.4;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
.ml-llm-hint,
|
|
239
|
+
.ml-llm-meta {
|
|
240
|
+
color: var(--ml-ui-text-muted, #606266);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
.ml-llm-meta {
|
|
244
|
+
font-size: 11px;
|
|
245
|
+
font-weight: normal;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
.ml-llm-warning,
|
|
249
|
+
.ml-llm-validation {
|
|
250
|
+
color: #b7791f;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
.ml-llm-error {
|
|
254
|
+
color: var(--ml-ui-danger, #f56c6c);
|
|
255
|
+
word-break: break-word;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
.ml-llm-status {
|
|
259
|
+
color: var(--ml-ui-accent, #0b84ff);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
.ml-llm-divider {
|
|
263
|
+
flex-shrink: 0;
|
|
264
|
+
height: 1px;
|
|
265
|
+
margin: 2px 0;
|
|
266
|
+
background: var(--ml-ui-border, #dcdfe6);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
.ml-llm-segmented {
|
|
270
|
+
display: flex;
|
|
271
|
+
gap: 2px;
|
|
272
|
+
padding: 2px;
|
|
273
|
+
border: 1px solid var(--ml-ui-border, #dcdfe6);
|
|
274
|
+
border-radius: 6px;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
.ml-llm-segmented-item {
|
|
278
|
+
flex: 1 1 0;
|
|
279
|
+
min-width: 0;
|
|
280
|
+
padding: 5px 8px;
|
|
281
|
+
border: 1px solid transparent;
|
|
282
|
+
border-radius: 4px;
|
|
283
|
+
background: transparent;
|
|
284
|
+
color: var(--ml-ui-text-muted, #606266);
|
|
285
|
+
font: inherit;
|
|
286
|
+
cursor: pointer;
|
|
287
|
+
white-space: nowrap;
|
|
288
|
+
overflow: hidden;
|
|
289
|
+
text-overflow: ellipsis;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
.ml-llm-segmented-item:hover:not(.is-active) {
|
|
293
|
+
color: var(--ml-ui-text, #303133);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
.ml-llm-segmented-item.is-active {
|
|
297
|
+
border-color: var(--ml-ui-accent, #0b84ff);
|
|
298
|
+
background: var(--ml-ui-accent, #0b84ff);
|
|
299
|
+
color: #ffffff;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
.ml-llm-disclosure {
|
|
303
|
+
display: inline-flex;
|
|
304
|
+
align-items: center;
|
|
305
|
+
align-self: flex-start;
|
|
306
|
+
gap: 4px;
|
|
307
|
+
padding: 2px 4px 2px 0;
|
|
308
|
+
border: none;
|
|
309
|
+
background: transparent;
|
|
310
|
+
color: var(--ml-ui-text, #303133);
|
|
311
|
+
font: inherit;
|
|
312
|
+
cursor: pointer;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
.ml-llm-disclosure-icon {
|
|
316
|
+
width: 16px;
|
|
317
|
+
height: 16px;
|
|
318
|
+
transition: transform 0.15s ease;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
.ml-llm-disclosure-icon.is-open {
|
|
322
|
+
transform: rotate(90deg);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
.ml-llm-link-btn {
|
|
326
|
+
padding: 2px 0;
|
|
327
|
+
border: none;
|
|
328
|
+
background: transparent;
|
|
329
|
+
color: var(--ml-ui-accent, #0b84ff);
|
|
330
|
+
font: inherit;
|
|
331
|
+
cursor: pointer;
|
|
332
|
+
white-space: nowrap;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
.ml-llm-link-btn:hover:not(:disabled) {
|
|
336
|
+
text-decoration: underline;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
.ml-llm-link-btn:disabled {
|
|
340
|
+
color: var(--ml-ui-text-muted, #606266);
|
|
341
|
+
opacity: 0.6;
|
|
342
|
+
cursor: not-allowed;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
.ml-llm-catalog-head {
|
|
346
|
+
display: flex;
|
|
347
|
+
align-items: flex-start;
|
|
348
|
+
justify-content: space-between;
|
|
349
|
+
gap: 8px;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
.ml-llm-catalog-heading {
|
|
353
|
+
display: flex;
|
|
354
|
+
flex-direction: column;
|
|
355
|
+
gap: 2px;
|
|
356
|
+
min-width: 0;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
.ml-llm-catalog-actions {
|
|
360
|
+
display: flex;
|
|
361
|
+
flex-shrink: 0;
|
|
362
|
+
gap: 12px;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
.ml-llm-empty {
|
|
366
|
+
margin: 0;
|
|
367
|
+
padding: 14px 10px;
|
|
368
|
+
border: 1px dashed var(--ml-ui-border, #dcdfe6);
|
|
369
|
+
border-radius: 6px;
|
|
370
|
+
color: var(--ml-ui-text-muted, #606266);
|
|
371
|
+
text-align: center;
|
|
372
|
+
line-height: 1.5;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
.ml-llm-model-rows,
|
|
376
|
+
.ml-llm-picker-list {
|
|
377
|
+
margin: 0;
|
|
378
|
+
padding: 0;
|
|
379
|
+
list-style: none;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
.ml-llm-model-rows {
|
|
383
|
+
max-height: 240px;
|
|
384
|
+
overflow-y: auto;
|
|
385
|
+
display: flex;
|
|
386
|
+
flex-direction: column;
|
|
387
|
+
gap: 6px;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
.ml-llm-model-row {
|
|
391
|
+
display: flex;
|
|
392
|
+
align-items: center;
|
|
393
|
+
gap: 6px;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
.ml-llm-settings-dialog .ml-llm-model-id {
|
|
397
|
+
flex: 1 1 auto;
|
|
398
|
+
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
.ml-llm-model-vision {
|
|
402
|
+
display: inline-flex;
|
|
403
|
+
flex-shrink: 0;
|
|
404
|
+
align-items: center;
|
|
405
|
+
gap: 4px;
|
|
406
|
+
font-size: 11px;
|
|
407
|
+
color: var(--ml-ui-text-muted, #606266);
|
|
408
|
+
cursor: pointer;
|
|
409
|
+
white-space: nowrap;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
.ml-llm-model-remove {
|
|
413
|
+
display: inline-flex;
|
|
414
|
+
flex-shrink: 0;
|
|
415
|
+
align-items: center;
|
|
416
|
+
justify-content: center;
|
|
417
|
+
width: 24px;
|
|
418
|
+
height: 24px;
|
|
419
|
+
padding: 0;
|
|
420
|
+
border: none;
|
|
421
|
+
border-radius: 4px;
|
|
422
|
+
background: transparent;
|
|
423
|
+
color: var(--ml-ui-text-muted, #606266);
|
|
424
|
+
cursor: pointer;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
.ml-llm-model-remove:hover {
|
|
428
|
+
color: var(--ml-ui-danger, #f56c6c);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
.ml-llm-model-remove svg,
|
|
432
|
+
.ml-llm-add-model svg {
|
|
433
|
+
width: 14px;
|
|
434
|
+
height: 14px;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
.ml-llm-settings-dialog .ml-llm-add-model {
|
|
438
|
+
display: inline-flex;
|
|
439
|
+
align-items: center;
|
|
440
|
+
align-self: flex-start;
|
|
441
|
+
gap: 4px;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
.ml-llm-picker {
|
|
445
|
+
display: flex;
|
|
446
|
+
flex-direction: column;
|
|
447
|
+
gap: 8px;
|
|
448
|
+
padding: 8px;
|
|
449
|
+
border: 1px solid var(--ml-ui-border, #dcdfe6);
|
|
450
|
+
border-radius: 6px;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
.ml-llm-picker-title {
|
|
454
|
+
display: flex;
|
|
455
|
+
align-items: baseline;
|
|
456
|
+
justify-content: space-between;
|
|
457
|
+
gap: 8px;
|
|
458
|
+
font-weight: 600;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
.ml-llm-picker-toolbar {
|
|
462
|
+
display: flex;
|
|
463
|
+
align-items: center;
|
|
464
|
+
gap: 8px;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
.ml-llm-picker-toolbar input {
|
|
468
|
+
flex: 1 1 auto;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
.ml-llm-picker-list {
|
|
472
|
+
max-height: 180px;
|
|
473
|
+
overflow-y: auto;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
.ml-llm-picker-item {
|
|
477
|
+
display: flex;
|
|
478
|
+
align-items: center;
|
|
479
|
+
gap: 8px;
|
|
480
|
+
padding: 4px 6px;
|
|
481
|
+
border-radius: 4px;
|
|
482
|
+
cursor: pointer;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
.ml-llm-picker-item:hover {
|
|
486
|
+
background: color-mix(in srgb, var(--ml-ui-accent, #0b84ff) 10%, transparent);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
.ml-llm-picker-id {
|
|
490
|
+
min-width: 0;
|
|
491
|
+
overflow: hidden;
|
|
492
|
+
text-overflow: ellipsis;
|
|
493
|
+
white-space: nowrap;
|
|
494
|
+
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
.ml-llm-picker-footer {
|
|
498
|
+
display: flex;
|
|
499
|
+
justify-content: flex-end;
|
|
500
|
+
gap: 8px;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
.ml-llm-settings-dialog .ml-ui-dialog-btn:disabled {
|
|
504
|
+
opacity: 0.5;
|
|
505
|
+
filter: none;
|
|
506
|
+
cursor: not-allowed;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
.ml-llm-settings-dialog .ml-llm-danger {
|
|
510
|
+
color: var(--ml-ui-danger, #f56c6c);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
`.trim(),cx={"openai-chat":"protocolOpenaiChat","openai-responses":"protocolOpenaiResponses","anthropic-messages":"protocolAnthropicMessages"},Bn=`
|
|
514
|
+
`,dx="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6z",px="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z",hx="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z";function Os(e){return{...e,models:e.models?e.models.map(t=>({...t})):null}}function $s(e){var r;const t=new Set,n=[];for(const o of e){const i=o.id.trim();if(!i||t.has(i))continue;t.add(i);const a=(r=o.name)==null?void 0:r.trim(),s=typeof o.contextWindow=="number"&&Number.isFinite(o.contextWindow)&&o.contextWindow>0?Math.round(o.contextWindow):void 0;n.push({id:i,...a?{name:a}:{},vision:o.vision,...s!==void 0?{contextWindow:s}:{}})}return n}function fx(e){try{const t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}function J(e,t="",n){const r=document.createElement(e);return t&&(r.className=t),n!==void 0&&(r.textContent=n),r}function Zr(e,t=""){const n="http://www.w3.org/2000/svg",r=document.createElementNS(n,"svg");r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("aria-hidden","true"),t&&r.setAttribute("class",t);const o=document.createElementNS(n,"path");return o.setAttribute("fill","currentColor"),o.setAttribute("d",e),r.appendChild(o),r}function Xe(e,t,n){const r=J("button",e,t);return r.type="button",r.addEventListener("click",n),r}function wt(e,t,n={}){const r=J("input");return r.type=n.type??"text",r.value=e,r.spellcheck=!1,n.secret&&(r.autocomplete="off"),n.placeholder&&(r.placeholder=n.placeholder),r.addEventListener("input",()=>t(r.value)),r}function lt(e,t){const n=J("label","ml-llm-field");return n.append(J("span","ml-llm-field-label",e),t),n}function Ns(...e){const t=J("div","ml-llm-field-row");return t.append(...e),t}const Ze=class Ze extends yn.AcUiDialog{constructor(t,n){var i,a;super({host:n.host,title:D.llmT("title"),closeLabel:D.llmT("close"),dialogClassName:"ml-llm-settings-dialog"}),this.fetching=!1,this.fetchError="",this.candidates=null,this.flipped=new Set,this.candidateQuery="",this.statusMessage="",this.updaters=[],Ze.ensureSettingsStyles(),this.config=t;const r=t.activeProviderId;this.mode=et(r)?"builtin":"custom",this.builtinId=et(r)?r:"deepseek",this.customId=((i=this.storedProvider(r))==null?void 0:i.kind)==="custom"?r:((a=this.customProviders()[0])==null?void 0:a.id)??"",this.builtinDraft=this.loadBuiltin(this.builtinId),this.customDraft=this.loadCustom(this.customId),this.showAdvanced=this.builtinDraft.baseUrl.trim().length>0,this.render();const o=this.bodyEl.querySelector("select, input");o&&this.focusAfterOpen(o)}static async open(t={}){if(Ze.openInstance)return Ze.openInstance.show();const n=await ln(),r=new Ze(n,t);return Ze.openInstance=r,r.show()}close(){var t;Ze.openInstance===this&&this.isDirty()&&!window.confirm(D.llmT("discardChangesConfirm"))||(Ze.openInstance===this&&(Ze.openInstance=null),(t=this.fetchAbort)==null||t.abort(),super.close())}storedProvider(t){return this.config.providers.find(n=>n.id===t)}customProviders(){return this.config.providers.filter(t=>t.kind==="custom")}loadBuiltin(t){return Os(this.storedProvider(t)??Pt(t))}loadCustom(t){const n=t?this.storedProvider(t):void 0;return Os(n??ar())}get draft(){return this.mode==="builtin"?this.builtinDraft:this.customDraft}isNewCustom(){return this.mode==="custom"&&!this.storedProvider(this.customId)}isDirty(){const t=this.mode==="builtin"?this.storedProvider(this.builtinId)??Pt(this.builtinId):this.storedProvider(this.customId)??ar();return!Rc(this.draft,t)}displayModels(){return vt(this.draft)}setModels(t){this.draft.models=t}fetchBlockedReason(){return En(this.draft)?this.draft.apiKey.trim()?"":D.llmT("fetchNeedsKey"):D.llmT("fetchNeedsBaseUrl")}providerIdError(){if(!this.isNewCustom())return"";const t=this.customDraft.id;return t?Lo.test(t)?et(t)||this.storedProvider(t)?D.llmT("providerIdTaken"):"":D.llmT("providerIdInvalid"):""}baseUrlError(){const t=this.draft.baseUrl.trim();return t&&!fx(t)?D.llmT("baseUrlInvalid"):""}validationMessage(){if(this.providerIdError()||this.baseUrlError())return"";if(this.mode==="custom"){if(!this.customDraft.id)return D.llmT("needsProviderId");if(!this.customDraft.baseUrl.trim())return D.llmT("needsBaseUrl")}return $s(this.displayModels()).length?"":D.llmT("needsModels")}canSave(){return!this.fetching&&!this.candidates&&!this.providerIdError()&&!this.baseUrlError()&&!this.validationMessage()}render(){this.updaters=[];const t=J("div","ml-llm-column");t.append(J("div","ml-llm-section-title",D.llmT("providerSettings")),...this.renderEditor());const n=J("div","ml-llm-column");n.appendChild(this.renderCatalog());const r=J("div","ml-llm-columns");r.append(t,n),this.bodyEl.replaceChildren(this.renderActiveModel(),J("div","ml-llm-divider"),r),this.footerEl.replaceChildren(...this.renderFooter()),this.refresh()}refresh(){for(const t of this.updaters)t()}onDraftEdited(){this.statusMessage="",this.refresh()}watchedText(t,n,r){const o=J(t,n);return this.updaters.push(()=>{const i=r();o.textContent=i,o.hidden=!i}),o}errorOrHint(t,n){const r=this.watchedText("p","ml-llm-error",t),o=J("p","ml-llm-hint",n);return this.updaters.push(()=>{o.hidden=!!t()}),[r,o]}renderActiveModel(){const t=J("section","ml-llm-section"),n=J("select"),r=Pc(this.config);for(const i of r){const a=J("optgroup");a.label=i.label;for(const s of i.options){const l=J("option","",s.label);l.value=`${s.providerId}${Bn}${s.modelId}`,a.appendChild(l)}n.appendChild(a)}return n.value=`${this.config.activeProviderId}${Bn}${this.config.activeModel}`,n.addEventListener("change",()=>{this.selectActiveModel(n.value)}),t.appendChild(lt(D.llmT("activeModel"),n)),this.config.providers.some(i=>i.apiKey.trim())?_r(this.config)||t.appendChild(J("p","ml-llm-warning",D.llmT("visionMissing"))):t.appendChild(J("p","ml-llm-warning",D.llmT("activeModelNone"))),t.appendChild(J("p","ml-llm-hint",D.llmT("activeModelHint"))),t}renderEditor(){const t=J("div","ml-llm-segmented");t.setAttribute("role","tablist");for(const[r,o]of[["builtin","tabBuiltin"],["custom","tabCustom"]]){const i=Xe("ml-llm-segmented-item",D.llmT(o),()=>this.switchMode(r));i.setAttribute("role","tab"),i.setAttribute("aria-selected",String(this.mode===r)),this.mode===r&&i.classList.add("is-active"),t.appendChild(i)}const n=J("p","ml-llm-hint",D.llmT(this.mode==="builtin"?"builtinIntro":"customIntro"));return[t,n,...this.mode==="builtin"?this.renderBuiltinFields():this.renderCustomFields()]}renderBuiltinFields(){var s;const t=this.builtinDraft,n=J("select");for(const l of Mo){const c=Vo(l),p=J("option","",(s=this.storedProvider(l))!=null&&s.apiKey.trim()?`${c} · ${D.llmT("providerConfigured")}`:c);p.value=l,n.appendChild(p)}n.value=this.builtinId,n.addEventListener("change",()=>{const l=n.value;et(l)&&(this.resetFetch(),this.builtinId=l,this.builtinDraft=this.loadBuiltin(l),this.showAdvanced=this.builtinDraft.baseUrl.trim().length>0,this.statusMessage="",this.render())});const r=wt(t.apiKey,l=>{t.apiKey=l,this.onDraftEdited()},{type:"password",secret:!0,placeholder:D.llmT("apiKeyPlaceholder")}),o=this.watchedText("p","ml-llm-warning",()=>t.apiKey.trim()?"":D.llmT("apiKeyRequired")),i=Xe("ml-llm-disclosure","",()=>{this.showAdvanced=!this.showAdvanced,this.render()});i.setAttribute("aria-expanded",String(this.showAdvanced)),i.append(Zr(dx,`ml-llm-disclosure-icon${this.showAdvanced?" is-open":""}`),document.createTextNode(D.llmT("advancedSettings")));const a=[lt(D.llmT("provider"),n),lt(D.llmT("apiKey"),r),o,i];if(this.showAdvanced){const l=Ht[this.builtinId].baseUrl,c=J("div","ml-llm-group");c.append(lt(D.llmT("baseUrl"),wt(t.baseUrl,p=>{t.baseUrl=p,this.onDraftEdited()},{placeholder:l})),...this.errorOrHint(()=>this.baseUrlError(),D.llmT("baseUrlDefault",{url:l}))),this.builtinId==="deepseek-vl"&&c.appendChild(J("p","ml-llm-hint",D.llmT("providerDeepseekVlHint"))),a.push(c)}return a}renderCustomFields(){const t=this.customDraft,n=[],r=this.customProviders();if(r.length){const l=J("select");for(const p of r){const g=J("option","",gr(p));g.value=p.id,l.appendChild(g)}const c=J("option","",D.llmT("newCustomProvider"));c.value="",l.appendChild(c),l.value=this.customId,l.addEventListener("change",()=>{this.resetFetch(),this.customId=l.value,this.customDraft=this.loadCustom(this.customId),this.statusMessage="",this.render()}),n.push(lt(D.llmT("customProvider"),l))}const o=wt(t.id,l=>{t.id=l.trim(),this.onDraftEdited()},{placeholder:"acme-gateway",secret:!0});o.disabled=!this.isNewCustom();const i=wt(t.displayName??"",l=>{t.displayName=l,this.onDraftEdited()},{placeholder:D.llmT("displayName")}),a=J("select");for(const l of pc){const c=J("option","",D.llmT(cx[l]));c.value=l,a.appendChild(c)}a.value=t.protocol,a.addEventListener("change",()=>{t.protocol=a.value,this.onDraftEdited()});const s=wt(t.apiKey,l=>{t.apiKey=l,this.onDraftEdited()},{type:"password",secret:!0,placeholder:D.llmT("apiKeyPlaceholder")});return n.push(Ns(lt(D.llmT("providerId"),o),lt(D.llmT("displayName"),i)),...this.errorOrHint(()=>this.providerIdError(),D.llmT("providerIdHint")),lt(D.llmT("baseUrl"),wt(t.baseUrl,l=>{t.baseUrl=l,this.onDraftEdited()},{placeholder:"https://gateway.example/v1"})),...this.errorOrHint(()=>this.baseUrlError(),D.llmT("baseUrlHint")),Ns(lt(D.llmT("protocol"),a),lt(D.llmT("apiKey"),s))),n}renderCatalog(){const t=J("section","ml-llm-catalog");t.setAttribute("aria-label",D.llmT("models"));const n=J("div","ml-llm-catalog-head"),r=J("div","ml-llm-catalog-heading");r.appendChild(J("span","ml-llm-field-label",D.llmT("models"))),this.mode==="builtin"&&r.appendChild(this.watchedText("span","ml-llm-meta",()=>D.llmT(this.builtinDraft.models===null?"modelsDefault":"modelsCustomized")));const o=J("div","ml-llm-catalog-actions");if(this.mode==="builtin"){const a=Xe("ml-llm-link-btn",D.llmT("resetModels"),()=>{this.closePicker(),this.builtinDraft.models=null,this.statusMessage="",this.render()});this.updaters.push(()=>{a.hidden=this.builtinDraft.models===null,a.disabled=this.fetching}),o.appendChild(a)}const i=Xe("ml-llm-link-btn","",()=>{this.fetchModels()});return this.updaters.push(()=>{const a=this.fetchBlockedReason();i.textContent=D.llmT(this.fetching?"fetching":"fetchModels"),i.disabled=this.fetching||!!a||!!this.candidates,i.title=a}),o.appendChild(i),n.append(r,o),t.appendChild(n),t.append(...this.candidates?this.renderPicker():this.renderModelRows(),this.watchedText("p","ml-llm-error",()=>this.fetchError)),t}renderModelRows(){const t=this.displayModels();if(!t.length)return[J("div","ml-llm-empty",D.llmT("modelsEmpty"))];const n=J("ul","ml-llm-model-rows");return t.forEach((r,o)=>{const i=J("li","ml-llm-model-row"),a=J("input");a.type="checkbox",a.checked=r.vision;const s=wt(r.id,p=>{const g=this.displayModels()[o],x=hc(g,p);a.checked=x,this.updateModel(o,{id:p,vision:x})});s.className="ml-llm-model-id",s.title=r.name??r.id,s.placeholder=D.llmT("modelId"),s.setAttribute("aria-label",`${D.llmT("modelId")} ${o+1}`),a.addEventListener("change",()=>this.updateModel(o,{vision:a.checked}));const l=J("label","ml-llm-model-vision");l.title=D.llmT("modelVisionHint"),l.append(a,document.createTextNode(D.llmT("modelVision")));const c=Xe("ml-llm-model-remove","",()=>{this.setModels(this.displayModels().filter((p,g)=>g!==o).map(p=>({...p}))),this.statusMessage="",this.render()});c.title=D.llmT("removeModel"),c.setAttribute("aria-label",`${D.llmT("removeModel")} ${o+1}`),c.appendChild(Zr(px)),i.append(s,l,c),n.appendChild(i)}),[n,this.renderAddModelButton()]}renderAddModelButton(){const t=Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary ml-llm-add-model","",()=>{var r;this.setModels([...this.displayModels().map(o=>({...o})),{id:"",vision:!1}]),this.statusMessage="",this.render();const n=this.bodyEl.querySelectorAll(".ml-llm-model-id");(r=n[n.length-1])==null||r.focus()});return t.append(Zr(hx),document.createTextNode(D.llmT("addModel"))),t}updateModel(t,n){this.setModels(this.displayModels().map((r,o)=>o===t?{...r,...n}:{...r})),this.onDraftEdited()}renderPicker(){const t=J("div","ml-llm-picker"),n=J("div","ml-llm-picker-title",D.llmT("fetchTitle"));n.appendChild(this.watchedText("span","ml-llm-meta",()=>this.pickedSummary()));const r=J("div","ml-llm-picker-toolbar"),o=J("div"),i=wt(this.candidateQuery,c=>{this.candidateQuery=c,this.renderPickerList(o),this.refresh()},{type:"search",placeholder:D.llmT("fetchSearch")});i.setAttribute("aria-label",D.llmT("fetchSearch"));const a=Xe("ml-llm-link-btn","",()=>{this.toggleVisibleCandidates(),this.renderPickerList(o),this.refresh()});this.updaters.push(()=>{a.textContent=D.llmT(this.allVisiblePicked()?"fetchDeselectAll":"fetchSelectAll"),a.disabled=!this.visibleCandidates().length}),r.append(i,a),this.renderPickerList(o);const s=J("div","ml-llm-picker-footer"),l=Xe("ml-ui-dialog-btn",D.llmT("fetchAdopt"),()=>{const c=this.pickedModels();c.length&&(this.setModels(c),this.closePicker(),this.statusMessage="",this.render())});return this.updaters.push(()=>{const c=!this.pickedModels().length;l.disabled=c,l.title=c?D.llmT("fetchKeepOne"):""}),s.append(Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary",D.llmT("cancel"),()=>{this.closePicker(),this.render()}),l),t.append(n,r,o,s),[t]}renderPickerList(t){const n=this.visibleCandidates();if(!n.length){t.replaceChildren(J("p","ml-llm-empty",D.llmT("fetchNoMatches")));return}const r=J("ul","ml-llm-picker-list");for(const o of n){const i=J("li"),a=J("label","ml-llm-picker-item"),s=J("input");s.type="checkbox",s.checked=this.isPicked(o.id),s.addEventListener("change",()=>{this.flipped.delete(o.id)||this.flipped.add(o.id),this.refresh()});const l=J("span","ml-llm-picker-id",o.id);l.title=o.name??o.id,a.append(s,l),i.appendChild(a),r.appendChild(i)}t.replaceChildren(r)}configuredIds(){return new Set(this.displayModels().map(t=>t.id).filter(Boolean))}pickedByDefault(t,n=this.configuredIds()){return n.size===0||n.has(t)}isPicked(t,n=this.configuredIds()){return this.pickedByDefault(t,n)!==this.flipped.has(t)}visibleCandidates(){const t=this.candidateQuery.trim().toLowerCase(),n=this.candidates??[];return t?n.filter(r=>{var o;return r.id.toLowerCase().includes(t)||!!((o=r.name)!=null&&o.toLowerCase().includes(t))}):n}allVisiblePicked(){const t=this.visibleCandidates(),n=this.configuredIds();return t.length>0&&t.every(r=>this.isPicked(r.id,n))}pickedSummary(){const t=this.candidates??[],n=this.configuredIds();return`${t.filter(o=>this.isPicked(o.id,n)).length} / ${t.length}`}toggleVisibleCandidates(){const t=!this.allVisiblePicked(),n=this.configuredIds();for(const r of this.visibleCandidates())this.pickedByDefault(r.id,n)===t?this.flipped.delete(r.id):this.flipped.add(r.id)}pickedModels(){const t=this.candidates??[],n=this.configuredIds(),r=new Set(t.map(s=>s.id)),o=this.displayModels().filter(s=>!r.has(s.id)||this.isPicked(s.id,n)).map(s=>({...s})),i=new Set(o.map(s=>s.id)),a=t.filter(s=>this.isPicked(s.id,n)&&!i.has(s.id)).map(s=>({id:s.id,...s.name?{name:s.name}:{},vision:an(s.id)}));return[...o,...a]}closePicker(){this.candidates=null,this.flipped=new Set,this.candidateQuery=""}resetFetch(){var t;(t=this.fetchAbort)==null||t.abort(),this.fetchAbort=void 0,this.fetching=!1,this.fetchError="",this.closePicker()}listingErrorMessage(t){return t instanceof Xt?t.code==="network"?D.llmT("fetchFailedNetwork",{url:t.url}):t.code==="http"?D.llmT("fetchFailedHttp",{status:String(t.status??"")}):D.llmT("fetchFailedFormat"):D.llmT("fetchFailedFormat")}async fetchModels(){var n;if(this.fetching||this.fetchBlockedReason())return;(n=this.fetchAbort)==null||n.abort();const t=new AbortController;this.fetchAbort=t,this.fetching=!0,this.fetchError="",this.refresh();try{const r=await Nc({protocol:this.draft.protocol,baseUrl:En(this.draft),apiKey:this.draft.apiKey},void 0,t.signal);if(t.signal.aborted)return;if(!r.length){this.fetchError=D.llmT("fetchEmpty");return}this.flipped=new Set,this.candidateQuery="",this.candidates=r}catch(r){t.signal.aborted||(this.fetchError=this.listingErrorMessage(r))}finally{this.fetchAbort===t&&(this.fetching=!1,this.fetchAbort=void 0,this.render())}}switchMode(t){t!==this.mode&&(this.resetFetch(),this.mode=t,this.statusMessage="",this.render())}renderFooter(){const t=[];this.mode==="custom"&&!this.isNewCustom()&&t.push(Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary ml-llm-danger",D.llmT("deleteProvider"),()=>void this.deleteProvider()));const n=J("div","ml-llm-footer-message");n.append(this.watchedText("span","ml-llm-validation",()=>this.validationMessage()),this.watchedText("span","ml-llm-status",()=>this.statusMessage)),t.push(n),t.push(Xe("ml-ui-dialog-btn ml-ui-dialog-btn-secondary",D.llmT("close"),()=>this.close()));const r=Xe("ml-ui-dialog-btn",D.llmT(this.isNewCustom()?"createProvider":"save"),()=>void this.save());return this.updaters.push(()=>{r.disabled=!this.canSave()}),t.push(r),t}async commit(t){this.config=t,await io(t),this.builtinDraft=this.loadBuiltin(this.builtinId),this.customDraft=this.loadCustom(this.customId),this.statusMessage=D.llmT("saved"),this.render()}async save(){var r;if(!this.canSave())return;const t=this.draft,n={...t,id:t.id.trim(),displayName:(r=t.displayName)==null?void 0:r.trim(),baseUrl:t.baseUrl.trim(),apiKey:t.apiKey.trim(),models:t.models?$s(t.models):null};n.kind==="builtin"&&delete n.displayName,n.kind==="custom"&&(this.customId=n.id),await this.commit(bc(this.config,n))}async deleteProvider(){var r;const t=this.customId;if(!this.storedProvider(t)||!window.confirm(D.llmT("deleteProviderConfirm",{id:t})))return;const n=wc(this.config,t);this.customId=((r=n.providers.find(o=>o.kind==="custom"))==null?void 0:r.id)??"",await this.commit(n)}async selectActiveModel(t){const n=t.indexOf(Bn);if(n<0)return;const r=t.slice(0,n),o=t.slice(n+Bn.length);r===this.config.activeProviderId&&o===this.config.activeModel||(this.config={...this.config,activeProviderId:r,activeModel:o},await io(this.config),this.statusMessage=D.llmT("saved"),this.render())}static ensureSettingsStyles(){if(document.getElementById(Ze.settingsStyleId))return;const t=document.createElement("style");t.id=Ze.settingsStyleId,t.textContent=ux,document.head.appendChild(t)}};Ze.settingsStyleId="ml-llm-settings-styles",Ze.openInstance=null;let sr=Ze;class Mc extends yn.AcEdCommand{constructor(){super(...arguments),this.recordsUndoStack=!1}async execute(t){var n;await sr.open({host:((n=t.view)==null?void 0:n.container)??document.body})}}class zc{constructor(){this.name=D.LLM_PLUGIN_NAME,this.version=ix.version,this.description="Shared AI model settings (llmsettings) and LLM text recognition",this.registeredCommands=[]}onLoad(t,n){const r=yn.AcEdCommandStack.SYSTEMT_COMMAND_GROUP_NAME;n.addCommand(r,"llmsettings","llmsettings",new Mc),this.registeredCommands.push({group:r,name:"llmsettings"})}onUnload(t,n){for(const r of this.registeredCommands)n.removeCmd(r.group,r.name);this.registeredCommands=[]}}async function mx(){return new zc}const _x='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><rect x="2.5" y="2.5" width="10" height="10" rx="1.6" fill="none" stroke="currentColor" stroke-width="1.25"/><path d="M5.5 0.8v1.7M9.5 0.8v1.7M5.5 12.5v1.7M0.8 5.5h1.7M0.8 9.5h1.7M12.5 5.5h1.7" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/><path d="M7.5 4.3l0.75 2.45 2.45 0.75-2.45 0.75-0.75 2.45-0.75-2.45-2.45-0.75 2.45-0.75z" fill="currentColor"/><circle cx="15" cy="15" r="3.4" fill="none" stroke="currentColor" stroke-width="1.8" stroke-dasharray="1.5 1.17"/><circle cx="15" cy="15" r="1.9" fill="none" stroke="currentColor" stroke-width="1.25"/></svg>';exports.ACAP_LLM_API_PROTOCOLS=pc;exports.ACAP_LLM_BUILTIN_PROVIDERS=Ht;exports.ACAP_LLM_BUILTIN_PROVIDER_IDS=Mo;exports.ACAP_LLM_CUSTOM_PROVIDER_ID_PATTERN=Lo;exports.ACAP_LLM_RECOGNITION_TIMEOUT_MS=lo;exports.AcApLlmModelListingError=Xt;exports.AcApLlmPlugin=zc;exports.AcApLlmSettingsCmd=Mc;exports.AcUiLlmSettingsDialog=sr;exports.LLM_SETTINGS_ICON=_x;exports.acapLlmActiveModelSupportsVision=Zo;exports.acapLlmAreProvidersEqual=Rc;exports.acapLlmBuiltinProviderLabel=Vo;exports.acapLlmCleanRecognizedText=Bo;exports.acapLlmCreateBuiltinProvider=Pt;exports.acapLlmCreateCustomProvider=ar;exports.acapLlmCreateDefaultConfig=gn;exports.acapLlmCreateModel=Ro;exports.acapLlmEffectiveBaseUrl=En;exports.acapLlmEffectiveModels=vt;exports.acapLlmEnsureActiveProvider=Uo;exports.acapLlmFetchAvailableModels=Nc;exports.acapLlmFindProvider=Wt;exports.acapLlmGetStatus=Y0;exports.acapLlmGuessModelVision=an;exports.acapLlmIsBuiltinProviderId=et;exports.acapLlmLoadConfig=ln;exports.acapLlmMigrateLegacySettings=xc;exports.acapLlmModelChoices=Pc;exports.acapLlmModelLabel=zo;exports.acapLlmModelListingUrl=Oc;exports.acapLlmNormalizeBaseUrl=No;exports.acapLlmOnConfigChange=kc;exports.acapLlmParseBatchText=Sc;exports.acapLlmParseModelListing=$c;exports.acapLlmProviderLabel=gr;exports.acapLlmRecognizeText=Ec;exports.acapLlmRecognizeTextBatch=Tc;exports.acapLlmRemoveProvider=wc;exports.acapLlmResolveActiveSettings=Do;exports.acapLlmResolveVisionSettings=_r;exports.acapLlmResolveVisionSettingsForModel=yc;exports.acapLlmResolveVisionSettingsForProvider=jo;exports.acapLlmRestoreModelEntries=oo;exports.acapLlmSaveConfig=io;exports.acapLlmSkipDataUrlDownload=Po;exports.acapLlmSyncOcrRecognizers=Ac;exports.acapLlmUpsertProvider=bc;exports.acapLlmVisionAfterIdEdit=hc;exports.acapLlmWatchOcrRecognizers=tx;exports.createLlmPlugin=mx;
|