@sylphx/flow 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/{chunk-bmfd3jzw.js → chunk-1xab6sdr.js} +2 -2
  2. package/dist/{chunk-bmfd3jzw.js.map → chunk-1xab6sdr.js.map} +2 -2
  3. package/dist/chunk-4knr4n3j.js +25 -0
  4. package/dist/chunk-4knr4n3j.js.map +75 -0
  5. package/dist/chunk-6ggenak0.js +3 -0
  6. package/dist/{chunk-7d3pwe6x.js.map → chunk-6ggenak0.js.map} +2 -2
  7. package/dist/chunk-cbbj1pmn.js +10 -0
  8. package/dist/{chunk-fphp2agv.js.map → chunk-cbbj1pmn.js.map} +2 -2
  9. package/dist/chunk-cnvv0c4d.js +4 -0
  10. package/dist/{chunk-d6cgnb03.js.map → chunk-cnvv0c4d.js.map} +2 -2
  11. package/dist/{chunk-vttjr3cg.js → chunk-ee4f98fc.js} +3 -3
  12. package/dist/{chunk-vttjr3cg.js.map → chunk-ee4f98fc.js.map} +1 -1
  13. package/dist/{chunk-cshxyqvc.js → chunk-fn18x0qs.js} +2 -2
  14. package/dist/{chunk-cshxyqvc.js.map → chunk-fn18x0qs.js.map} +2 -2
  15. package/dist/{chunk-mbhd0326.js → chunk-h7z58r4g.js} +2 -2
  16. package/dist/{chunk-mbhd0326.js.map → chunk-h7z58r4g.js.map} +1 -1
  17. package/dist/{chunk-84x5fbqe.js → chunk-jb5m0k5j.js} +2 -2
  18. package/dist/{chunk-84x5fbqe.js.map → chunk-jb5m0k5j.js.map} +1 -1
  19. package/dist/chunk-k9r8f523.js +43 -0
  20. package/dist/chunk-k9r8f523.js.map +31 -0
  21. package/dist/chunk-nkra2wr9.js +3 -0
  22. package/dist/{chunk-zwsaqnr2.js.map → chunk-nkra2wr9.js.map} +2 -2
  23. package/dist/chunk-q44jnn91.js +4 -0
  24. package/dist/{chunk-zx3gqx7b.js.map → chunk-q44jnn91.js.map} +2 -2
  25. package/dist/chunk-thaa90qh.js +161 -0
  26. package/dist/chunk-thaa90qh.js.map +85 -0
  27. package/dist/chunk-w1j1nhaa.js +3 -0
  28. package/dist/{chunk-nmg7vhjj.js.map → chunk-w1j1nhaa.js.map} +2 -2
  29. package/dist/{chunk-pxh2vz4k.js → chunk-z7grzkjq.js} +2 -2
  30. package/dist/{chunk-pxh2vz4k.js.map → chunk-z7grzkjq.js.map} +1 -1
  31. package/dist/index.js +440 -404
  32. package/dist/index.js.map +135 -119
  33. package/package.json +11 -6
  34. package/dist/chunk-7d3pwe6x.js +0 -3
  35. package/dist/chunk-90tmk3w7.js +0 -183
  36. package/dist/chunk-90tmk3w7.js.map +0 -151
  37. package/dist/chunk-d6cgnb03.js +0 -4
  38. package/dist/chunk-fphp2agv.js +0 -10
  39. package/dist/chunk-nmg7vhjj.js +0 -3
  40. package/dist/chunk-zwsaqnr2.js +0 -3
  41. package/dist/chunk-zx3gqx7b.js +0 -4
@@ -0,0 +1,43 @@
1
+ import{$ as O4,_ as S4,ba as X}from"./chunk-4knr4n3j.js";import"./chunk-z7grzkjq.js";var k1="vercel.ai.error",N9=Symbol.for(k1),T1,M9=class $ extends Error{constructor({name:Q,message:Y,cause:G}){super(Y);this[T1]=!0,this.name=Q,this.cause=G}static isInstance(Q){return $.hasMarker(Q,k1)}static hasMarker(Q,Y){let G=Symbol.for(Y);return Q!=null&&typeof Q==="object"&&G in Q&&typeof Q[G]==="boolean"&&Q[G]===!0}};T1=N9;var J0=M9,Z1="AI_APICallError",x1=`vercel.ai.error.${Z1}`,A9=Symbol.for(x1),v1,E0=class extends J0{constructor({message:$,url:Q,requestBodyValues:Y,statusCode:G,responseHeaders:J,responseBody:W,cause:q,isRetryable:L=G!=null&&(G===408||G===409||G===429||G>=500),data:H}){super({name:Z1,message:$,cause:q});this[v1]=!0,this.url=Q,this.requestBodyValues=Y,this.statusCode=G,this.responseHeaders=J,this.responseBody=W,this.isRetryable=L,this.data=H}static isInstance($){return J0.hasMarker($,x1)}};v1=A9;var f1="AI_EmptyResponseBodyError",y1=`vercel.ai.error.${f1}`,w9=Symbol.for(y1),g1,h1=class extends J0{constructor({message:$="Empty response body"}={}){super({name:f1,message:$});this[g1]=!0}static isInstance($){return J0.hasMarker($,y1)}};g1=w9;function m1($){if($==null)return"unknown error";if(typeof $==="string")return $;if($ instanceof Error)return $.message;return JSON.stringify($)}var u1="AI_InvalidArgumentError",c1=`vercel.ai.error.${u1}`,D9=Symbol.for(c1),d1,b$=class extends J0{constructor({message:$,cause:Q,argument:Y}){super({name:u1,message:$,cause:Q});this[d1]=!0,this.argument=Y}static isInstance($){return J0.hasMarker($,c1)}};d1=D9;var i1="AI_InvalidPromptError",p1=`vercel.ai.error.${i1}`,V9=Symbol.for(p1),l1,n1=class extends J0{constructor({prompt:$,message:Q,cause:Y}){super({name:i1,message:`Invalid prompt: ${Q}`,cause:Y});this[l1]=!0,this.prompt=$}static isInstance($){return J0.hasMarker($,p1)}};l1=V9;var r1="AI_InvalidResponseDataError",a1=`vercel.ai.error.${r1}`,K9=Symbol.for(a1),s1,C$=class extends J0{constructor({data:$,message:Q=`Invalid response data: ${JSON.stringify($)}.`}){super({name:r1,message:Q});this[s1]=!0,this.data=$}static isInstance($){return J0.hasMarker($,a1)}};s1=K9;var t1="AI_JSONParseError",o1=`vercel.ai.error.${t1}`,F9=Symbol.for(o1),e1,L$=class extends J0{constructor({text:$,cause:Q}){super({name:t1,message:`JSON parsing failed: Text: ${$}.
2
+ Error message: ${m1(Q)}`,cause:Q});this[e1]=!0,this.text=$}static isInstance($){return J0.hasMarker($,o1)}};e1=F9;var $4="AI_LoadAPIKeyError",X4=`vercel.ai.error.${$4}`,R9=Symbol.for(X4),Q4,H$=class extends J0{constructor({message:$}){super({name:$4,message:$});this[Q4]=!0}static isInstance($){return J0.hasMarker($,X4)}};Q4=R9;var S9="AI_LoadSettingError",O9=`vercel.ai.error.${S9}`,P9=Symbol.for(O9),b9;b9=P9;var C9="AI_NoContentGeneratedError",I9=`vercel.ai.error.${C9}`,_9=Symbol.for(I9),k9;k9=_9;var Y4="AI_NoSuchModelError",G4=`vercel.ai.error.${Y4}`,T9=Symbol.for(G4),J4,s$=class extends J0{constructor({errorName:$=Y4,modelId:Q,modelType:Y,message:G=`No such ${Y}: ${Q}`}){super({name:$,message:G});this[J4]=!0,this.modelId=Q,this.modelType=Y}static isInstance($){return J0.hasMarker($,G4)}};J4=T9;var W4="AI_TooManyEmbeddingValuesForCallError",q4=`vercel.ai.error.${W4}`,Z9=Symbol.for(q4),L4,I$=class extends J0{constructor($){super({name:W4,message:`Too many values for a single embedding call. The ${$.provider} model "${$.modelId}" can only embed up to ${$.maxEmbeddingsPerCall} values per call, but ${$.values.length} values were provided.`});this[L4]=!0,this.provider=$.provider,this.modelId=$.modelId,this.maxEmbeddingsPerCall=$.maxEmbeddingsPerCall,this.values=$.values}static isInstance($){return J0.hasMarker($,q4)}};L4=Z9;var H4="AI_TypeValidationError",E4=`vercel.ai.error.${H4}`,x9=Symbol.for(E4),U4,v9=class $ extends J0{constructor({value:Q,cause:Y}){super({name:H4,message:`Type validation failed: Value: ${JSON.stringify(Q)}.
3
+ Error message: ${m1(Y)}`,cause:Y});this[U4]=!0,this.value=Q}static isInstance(Q){return J0.hasMarker(Q,E4)}static wrap({value:Q,cause:Y}){return $.isInstance(Y)&&Y.value===Q?Y:new $({value:Q,cause:Y})}};U4=x9;var c0=v9,j4="AI_UnsupportedFunctionalityError",B4=`vercel.ai.error.${j4}`,f9=Symbol.for(B4),z4,o=class extends J0{constructor({functionality:$,message:Q=`'${$}' functionality not supported.`}){super({name:j4,message:Q});this[z4]=!0,this.functionality=$}static isInstance($){return J0.hasMarker($,B4)}};z4=f9;class o$ extends Error{constructor($,Q){super($),this.name="ParseError",this.type=Q.type,this.field=Q.field,this.value=Q.value,this.line=Q.line}}function t$($){}function N4($){if(typeof $=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:Q=t$,onError:Y=t$,onRetry:G=t$,onComment:J}=$,W="",q=!0,L,H="",E="";function U(z){let A=q?z.replace(/^\xEF\xBB\xBF/,""):z,[j,N]=y9(`${W}${A}`);for(let M of j)V(M);W=N,q=!1}function V(z){if(z===""){B();return}if(z.startsWith(":")){J&&J(z.slice(z.startsWith(": ")?2:1));return}let A=z.indexOf(":");if(A!==-1){let j=z.slice(0,A),N=z[A+1]===" "?2:1,M=z.slice(A+N);w(j,M,z);return}w(z,"",z)}function w(z,A,j){switch(z){case"event":E=A;break;case"data":H=`${H}${A}
4
+ `;break;case"id":L=A.includes("\x00")?void 0:A;break;case"retry":/^\d+$/.test(A)?G(parseInt(A,10)):Y(new o$(`Invalid \`retry\` value: "${A}"`,{type:"invalid-retry",value:A,line:j}));break;default:Y(new o$(`Unknown field "${z.length>20?`${z.slice(0,20)}…`:z}"`,{type:"unknown-field",field:z,value:A,line:j}));break}}function B(){H.length>0&&Q({id:L,event:E||void 0,data:H.endsWith(`
5
+ `)?H.slice(0,-1):H}),L=void 0,H="",E=""}function K(z={}){W&&z.consume&&V(W),q=!0,L=void 0,H="",E="",W=""}return{feed:U,reset:K}}function y9($){let Q=[],Y="",G=0;for(;G<$.length;){let J=$.indexOf("\r",G),W=$.indexOf(`
6
+ `,G),q=-1;if(J!==-1&&W!==-1?q=Math.min(J,W):J!==-1?J===$.length-1?q=-1:q=J:W!==-1&&(q=W),q===-1){Y=$.slice(G);break}else{let L=$.slice(G,q);Q.push(L),G=q+1,$[G-1]==="\r"&&$[G]===`
7
+ `&&G++}}return[Q,Y]}class e$ extends TransformStream{constructor({onError:$,onRetry:Q,onComment:Y}={}){let G;super({start(J){G=N4({onEvent:(W)=>{J.enqueue(W)},onError(W){$==="terminate"?J.error(W):typeof $=="function"&&$(W)},onRetry:Q,onComment:Y})},transform(J){G.feed(J)}})}}var t;(function($){$.assertEqual=(J)=>{};function Q(J){}$.assertIs=Q;function Y(J){throw Error()}$.assertNever=Y,$.arrayToEnum=(J)=>{let W={};for(let q of J)W[q]=q;return W},$.getValidEnumValues=(J)=>{let W=$.objectKeys(J).filter((L)=>typeof J[J[L]]!=="number"),q={};for(let L of W)q[L]=J[L];return $.objectValues(q)},$.objectValues=(J)=>{return $.objectKeys(J).map(function(W){return J[W]})},$.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let W=[];for(let q in J)if(Object.prototype.hasOwnProperty.call(J,q))W.push(q);return W},$.find=(J,W)=>{for(let q of J)if(W(q))return q;return},$.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&Number.isFinite(J)&&Math.floor(J)===J;function G(J,W=" | "){return J.map((q)=>typeof q==="string"?`'${q}'`:q).join(W)}$.joinValues=G,$.jsonStringifyReplacer=(J,W)=>{if(typeof W==="bigint")return W.toString();return W}})(t||(t={}));var M4;(function($){$.mergeShapes=(Q,Y)=>{return{...Q,...Y}}})(M4||(M4={}));var _=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),v0=($)=>{switch(typeof $){case"undefined":return _.undefined;case"string":return _.string;case"number":return Number.isNaN($)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":if(Array.isArray($))return _.array;if($===null)return _.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return _.promise;if(typeof Map<"u"&&$ instanceof Map)return _.map;if(typeof Set<"u"&&$ instanceof Set)return _.set;if(typeof Date<"u"&&$ instanceof Date)return _.date;return _.object;default:return _.unknown}};var S=t.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 F0 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(Y)=>{this.issues=[...this.issues,Y]},this.addIssues=(Y=[])=>{this.issues=[...this.issues,...Y]};let Q=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,Q);else this.__proto__=Q;this.name="ZodError",this.issues=$}format($){let Q=$||function(J){return J.message},Y={_errors:[]},G=(J)=>{for(let W of J.issues)if(W.code==="invalid_union")W.unionErrors.map(G);else if(W.code==="invalid_return_type")G(W.returnTypeError);else if(W.code==="invalid_arguments")G(W.argumentsError);else if(W.path.length===0)Y._errors.push(Q(W));else{let q=Y,L=0;while(L<W.path.length){let H=W.path[L];if(L!==W.path.length-1)q[H]=q[H]||{_errors:[]};else q[H]=q[H]||{_errors:[]},q[H]._errors.push(Q(W));q=q[H],L++}}};return G(this),Y}static assert($){if(!($ instanceof F0))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,t.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(Q)=>Q.message){let Q=Object.create(null),Y=[];for(let G of this.issues)if(G.path.length>0){let J=G.path[0];Q[J]=Q[J]||[],Q[J].push($(G))}else Y.push($(G));return{formErrors:Y,fieldErrors:Q}}get formErrors(){return this.flatten()}}F0.create=($)=>{return new F0($)};var g9=($,Q)=>{let Y;switch($.code){case S.invalid_type:if($.received===_.undefined)Y="Required";else Y=`Expected ${$.expected}, received ${$.received}`;break;case S.invalid_literal:Y=`Invalid literal value, expected ${JSON.stringify($.expected,t.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:Y=`Unrecognized key(s) in object: ${t.joinValues($.keys,", ")}`;break;case S.invalid_union:Y="Invalid input";break;case S.invalid_union_discriminator:Y=`Invalid discriminator value. Expected ${t.joinValues($.options)}`;break;case S.invalid_enum_value:Y=`Invalid enum value. Expected ${t.joinValues($.options)}, received '${$.received}'`;break;case S.invalid_arguments:Y="Invalid function arguments";break;case S.invalid_return_type:Y="Invalid function return type";break;case S.invalid_date:Y="Invalid date";break;case S.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(Y=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")Y=`${Y} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)Y=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)Y=`Invalid input: must end with "${$.validation.endsWith}"`;else t.assertNever($.validation);else if($.validation!=="regex")Y=`Invalid ${$.validation}`;else Y="Invalid";break;case S.too_small:if($.type==="array")Y=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")Y=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")Y=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")Y=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")Y=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else Y="Invalid input";break;case S.too_big:if($.type==="array")Y=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")Y=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")Y=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")Y=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")Y=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else Y="Invalid input";break;case S.custom:Y="Invalid input";break;case S.invalid_intersection_types:Y="Intersection results could not be merged";break;case S.not_multiple_of:Y=`Number must be a multiple of ${$.multipleOf}`;break;case S.not_finite:Y="Number must be finite";break;default:Y=Q.defaultError,t.assertNever($)}return{message:Y}},d0=g9;var h9=d0;function E$(){return h9}var _$=($)=>{let{data:Q,path:Y,errorMaps:G,issueData:J}=$,W=[...Y,...J.path||[]],q={...J,path:W};if(J.message!==void 0)return{...J,path:W,message:J.message};let L="",H=G.filter((E)=>!!E).slice().reverse();for(let E of H)L=E(q,{data:Q,defaultError:L}).message;return{...J,path:W,message:L}};function f($,Q){let Y=E$(),G=_$({issueData:Q,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Y,Y===d0?void 0:d0].filter((J)=>!!J)});$.common.issues.push(G)}class A0{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,Q){let Y=[];for(let G of Q){if(G.status==="aborted")return i;if(G.status==="dirty")$.dirty();Y.push(G.value)}return{status:$.value,value:Y}}static async mergeObjectAsync($,Q){let Y=[];for(let G of Q){let J=await G.key,W=await G.value;Y.push({key:J,value:W})}return A0.mergeObjectSync($,Y)}static mergeObjectSync($,Q){let Y={};for(let G of Q){let{key:J,value:W}=G;if(J.status==="aborted")return i;if(W.status==="aborted")return i;if(J.status==="dirty")$.dirty();if(W.status==="dirty")$.dirty();if(J.value!=="__proto__"&&(typeof W.value<"u"||G.alwaysSet))Y[J.value]=W.value}return{status:$.value,value:Y}}}var i=Object.freeze({status:"aborted"}),o0=($)=>({status:"dirty",value:$}),w0=($)=>({status:"valid",value:$}),$1=($)=>$.status==="aborted",X1=($)=>$.status==="dirty",a0=($)=>$.status==="valid",U$=($)=>typeof Promise<"u"&&$ instanceof Promise;var u;(function($){$.errToObj=(Q)=>typeof Q==="string"?{message:Q}:Q||{},$.toString=(Q)=>typeof Q==="string"?Q:Q?.message})(u||(u={}));class S0{constructor($,Q,Y,G){this._cachedPath=[],this.parent=$,this.data=Q,this._path=Y,this._key=G}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var A4=($,Q)=>{if(a0(Q))return{success:!0,data:Q.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let Y=new F0($.common.issues);return this._error=Y,this._error}}}};function r($){if(!$)return{};let{errorMap:Q,invalid_type_error:Y,required_error:G,description:J}=$;if(Q&&(Y||G))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(Q)return{errorMap:Q,description:J};return{errorMap:(q,L)=>{let{message:H}=$;if(q.code==="invalid_enum_value")return{message:H??L.defaultError};if(typeof L.data>"u")return{message:H??G??L.defaultError};if(q.code!=="invalid_type")return{message:L.defaultError};return{message:H??Y??L.defaultError}},description:J}}class a{get description(){return this._def.description}_getType($){return v0($.data)}_getOrReturnCtx($,Q){return Q||{common:$.parent.common,data:$.data,parsedType:v0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new A0,ctx:{common:$.parent.common,data:$.data,parsedType:v0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let Q=this._parse($);if(U$(Q))throw Error("Synchronous parse encountered promise.");return Q}_parseAsync($){let Q=this._parse($);return Promise.resolve(Q)}parse($,Q){let Y=this.safeParse($,Q);if(Y.success)return Y.data;throw Y.error}safeParse($,Q){let Y={common:{issues:[],async:Q?.async??!1,contextualErrorMap:Q?.errorMap},path:Q?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:v0($)},G=this._parseSync({data:$,path:Y.path,parent:Y});return A4(Y,G)}"~validate"($){let Q={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:v0($)};if(!this["~standard"].async)try{let Y=this._parseSync({data:$,path:[],parent:Q});return a0(Y)?{value:Y.value}:{issues:Q.common.issues}}catch(Y){if(Y?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;Q.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:Q}).then((Y)=>a0(Y)?{value:Y.value}:{issues:Q.common.issues})}async parseAsync($,Q){let Y=await this.safeParseAsync($,Q);if(Y.success)return Y.data;throw Y.error}async safeParseAsync($,Q){let Y={common:{issues:[],contextualErrorMap:Q?.errorMap,async:!0},path:Q?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:v0($)},G=this._parse({data:$,path:Y.path,parent:Y}),J=await(U$(G)?G:Promise.resolve(G));return A4(Y,J)}refine($,Q){let Y=(G)=>{if(typeof Q==="string"||typeof Q>"u")return{message:Q};else if(typeof Q==="function")return Q(G);else return Q};return this._refinement((G,J)=>{let W=$(G),q=()=>J.addIssue({code:S.custom,...Y(G)});if(typeof Promise<"u"&&W instanceof Promise)return W.then((L)=>{if(!L)return q(),!1;else return!0});if(!W)return q(),!1;else return!0})}refinement($,Q){return this._refinement((Y,G)=>{if(!$(Y))return G.addIssue(typeof Q==="function"?Q(Y,G):Q),!1;else return!0})}_refinement($){return new k0({schema:this,typeName:O.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:(Q)=>this["~validate"](Q)}}optional(){return _0.create(this,this._def)}nullable(){return i0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return I0.create(this)}promise(){return Y$.create(this,this._def)}or($){return M$.create([this,$],this._def)}and($){return A$.create(this,$,this._def)}transform($){return new k0({...r(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:$}})}default($){let Q=typeof $==="function"?$:()=>$;return new K$({...r(this._def),innerType:this,defaultValue:Q,typeName:O.ZodDefault})}brand(){return new J1({typeName:O.ZodBranded,type:this,...r(this._def)})}catch($){let Q=typeof $==="function"?$:()=>$;return new F$({...r(this._def),innerType:this,catchValue:Q,typeName:O.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return g$.create(this,$)}readonly(){return R$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var m9=/^c[^\s-]{8,}$/i,u9=/^[0-9a-z]+$/,c9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,d9=/^[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,i9=/^[a-z0-9_-]{21}$/i,p9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,l9=/^[-+]?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)?)??$/,n9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,r9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Q1,a9=/^(?:(?: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])$/,s9=/^(?:(?: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])$/,t9=/^(([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]))$/,o9=/^(([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])$/,e9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$X=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,w4="((\\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])))",XX=new RegExp(`^${w4}$`);function D4($){let Q="[0-5]\\d";if($.precision)Q=`${Q}\\.\\d{${$.precision}}`;else if($.precision==null)Q=`${Q}(\\.\\d+)?`;let Y=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${Q})${Y}`}function QX($){return new RegExp(`^${D4($)}$`)}function YX($){let Q=`${w4}T${D4($)}`,Y=[];if(Y.push($.local?"Z?":"Z"),$.offset)Y.push("([+-]\\d{2}:?\\d{2})");return Q=`${Q}(${Y.join("|")})`,new RegExp(`^${Q}$`)}function GX($,Q){if((Q==="v4"||!Q)&&a9.test($))return!0;if((Q==="v6"||!Q)&&t9.test($))return!0;return!1}function JX($,Q){if(!p9.test($))return!1;try{let[Y]=$.split(".");if(!Y)return!1;let G=Y.replace(/-/g,"+").replace(/_/g,"/").padEnd(Y.length+(4-Y.length%4)%4,"="),J=JSON.parse(atob(G));if(typeof J!=="object"||J===null)return!1;if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(Q&&J.alg!==Q)return!1;return!0}catch{return!1}}function WX($,Q){if((Q==="v4"||!Q)&&s9.test($))return!0;if((Q==="v6"||!Q)&&o9.test($))return!0;return!1}class y0 extends a{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==_.string){let J=this._getOrReturnCtx($);return f(J,{code:S.invalid_type,expected:_.string,received:J.parsedType}),i}let Y=new A0,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.length<J.value)G=this._getOrReturnCtx($,G),f(G,{code:S.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),Y.dirty()}else if(J.kind==="max"){if($.data.length>J.value)G=this._getOrReturnCtx($,G),f(G,{code:S.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),Y.dirty()}else if(J.kind==="length"){let W=$.data.length>J.value,q=$.data.length<J.value;if(W||q){if(G=this._getOrReturnCtx($,G),W)f(G,{code:S.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(q)f(G,{code:S.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});Y.dirty()}}else if(J.kind==="email"){if(!n9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"email",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="emoji"){if(!Q1)Q1=new RegExp(r9,"u");if(!Q1.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"emoji",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="uuid"){if(!d9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"uuid",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="nanoid"){if(!i9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"nanoid",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="cuid"){if(!m9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"cuid",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="cuid2"){if(!u9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"cuid2",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="ulid"){if(!c9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"ulid",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="url")try{new URL($.data)}catch{G=this._getOrReturnCtx($,G),f(G,{validation:"url",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"regex",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="trim")$.data=$.data.trim();else if(J.kind==="includes"){if(!$.data.includes(J.value,J.position))G=this._getOrReturnCtx($,G),f(G,{code:S.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),Y.dirty()}else if(J.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(J.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(J.kind==="startsWith"){if(!$.data.startsWith(J.value))G=this._getOrReturnCtx($,G),f(G,{code:S.invalid_string,validation:{startsWith:J.value},message:J.message}),Y.dirty()}else if(J.kind==="endsWith"){if(!$.data.endsWith(J.value))G=this._getOrReturnCtx($,G),f(G,{code:S.invalid_string,validation:{endsWith:J.value},message:J.message}),Y.dirty()}else if(J.kind==="datetime"){if(!YX(J).test($.data))G=this._getOrReturnCtx($,G),f(G,{code:S.invalid_string,validation:"datetime",message:J.message}),Y.dirty()}else if(J.kind==="date"){if(!XX.test($.data))G=this._getOrReturnCtx($,G),f(G,{code:S.invalid_string,validation:"date",message:J.message}),Y.dirty()}else if(J.kind==="time"){if(!QX(J).test($.data))G=this._getOrReturnCtx($,G),f(G,{code:S.invalid_string,validation:"time",message:J.message}),Y.dirty()}else if(J.kind==="duration"){if(!l9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"duration",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="ip"){if(!GX($.data,J.version))G=this._getOrReturnCtx($,G),f(G,{validation:"ip",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="jwt"){if(!JX($.data,J.alg))G=this._getOrReturnCtx($,G),f(G,{validation:"jwt",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="cidr"){if(!WX($.data,J.version))G=this._getOrReturnCtx($,G),f(G,{validation:"cidr",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="base64"){if(!e9.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"base64",code:S.invalid_string,message:J.message}),Y.dirty()}else if(J.kind==="base64url"){if(!$X.test($.data))G=this._getOrReturnCtx($,G),f(G,{validation:"base64url",code:S.invalid_string,message:J.message}),Y.dirty()}else t.assertNever(J);return{status:Y.value,value:$.data}}_regex($,Q,Y){return this.refinement((G)=>$.test(G),{validation:Q,code:S.invalid_string,...u.errToObj(Y)})}_addCheck($){return new y0({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...u.errToObj($)})}url($){return this._addCheck({kind:"url",...u.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...u.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...u.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...u.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...u.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...u.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...u.errToObj($)})}base64($){return this._addCheck({kind:"base64",...u.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...u.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...u.errToObj($)})}ip($){return this._addCheck({kind:"ip",...u.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...u.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...u.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...u.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...u.errToObj($)})}regex($,Q){return this._addCheck({kind:"regex",regex:$,...u.errToObj(Q)})}includes($,Q){return this._addCheck({kind:"includes",value:$,position:Q?.position,...u.errToObj(Q?.message)})}startsWith($,Q){return this._addCheck({kind:"startsWith",value:$,...u.errToObj(Q)})}endsWith($,Q){return this._addCheck({kind:"endsWith",value:$,...u.errToObj(Q)})}min($,Q){return this._addCheck({kind:"min",value:$,...u.errToObj(Q)})}max($,Q){return this._addCheck({kind:"max",value:$,...u.errToObj(Q)})}length($,Q){return this._addCheck({kind:"length",value:$,...u.errToObj(Q)})}nonempty($){return this.min(1,u.errToObj($))}trim(){return new y0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new y0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new y0({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $}get maxLength(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $}}y0.create=($)=>{return new y0({checks:[],typeName:O.ZodString,coerce:$?.coerce??!1,...r($)})};function qX($,Q){let Y=($.toString().split(".")[1]||"").length,G=(Q.toString().split(".")[1]||"").length,J=Y>G?Y:G,W=Number.parseInt($.toFixed(J).replace(".","")),q=Number.parseInt(Q.toFixed(J).replace(".",""));return W%q/10**J}class $$ extends a{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==_.number){let J=this._getOrReturnCtx($);return f(J,{code:S.invalid_type,expected:_.number,received:J.parsedType}),i}let Y=void 0,G=new A0;for(let J of this._def.checks)if(J.kind==="int"){if(!t.isInteger($.data))Y=this._getOrReturnCtx($,Y),f(Y,{code:S.invalid_type,expected:"integer",received:"float",message:J.message}),G.dirty()}else if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)Y=this._getOrReturnCtx($,Y),f(Y,{code:S.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)Y=this._getOrReturnCtx($,Y),f(Y,{code:S.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if(qX($.data,J.value)!==0)Y=this._getOrReturnCtx($,Y),f(Y,{code:S.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else if(J.kind==="finite"){if(!Number.isFinite($.data))Y=this._getOrReturnCtx($,Y),f(Y,{code:S.not_finite,message:J.message}),G.dirty()}else t.assertNever(J);return{status:G.value,value:$.data}}gte($,Q){return this.setLimit("min",$,!0,u.toString(Q))}gt($,Q){return this.setLimit("min",$,!1,u.toString(Q))}lte($,Q){return this.setLimit("max",$,!0,u.toString(Q))}lt($,Q){return this.setLimit("max",$,!1,u.toString(Q))}setLimit($,Q,Y,G){return new $$({...this._def,checks:[...this._def.checks,{kind:$,value:Q,inclusive:Y,message:u.toString(G)}]})}_addCheck($){return new $$({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:u.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:u.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:u.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:u.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:u.toString($)})}multipleOf($,Q){return this._addCheck({kind:"multipleOf",value:$,message:u.toString(Q)})}finite($){return this._addCheck({kind:"finite",message:u.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:u.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:u.toString($)})}get minValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $}get maxValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&t.isInteger($.value))}get isFinite(){let $=null,Q=null;for(let Y of this._def.checks)if(Y.kind==="finite"||Y.kind==="int"||Y.kind==="multipleOf")return!0;else if(Y.kind==="min"){if(Q===null||Y.value>Q)Q=Y.value}else if(Y.kind==="max"){if($===null||Y.value<$)$=Y.value}return Number.isFinite(Q)&&Number.isFinite($)}}$$.create=($)=>{return new $$({checks:[],typeName:O.ZodNumber,coerce:$?.coerce||!1,...r($)})};class X$ extends a{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==_.bigint)return this._getInvalidInput($);let Y=void 0,G=new A0;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)Y=this._getOrReturnCtx($,Y),f(Y,{code:S.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)Y=this._getOrReturnCtx($,Y),f(Y,{code:S.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if($.data%J.value!==BigInt(0))Y=this._getOrReturnCtx($,Y),f(Y,{code:S.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else t.assertNever(J);return{status:G.value,value:$.data}}_getInvalidInput($){let Q=this._getOrReturnCtx($);return f(Q,{code:S.invalid_type,expected:_.bigint,received:Q.parsedType}),i}gte($,Q){return this.setLimit("min",$,!0,u.toString(Q))}gt($,Q){return this.setLimit("min",$,!1,u.toString(Q))}lte($,Q){return this.setLimit("max",$,!0,u.toString(Q))}lt($,Q){return this.setLimit("max",$,!1,u.toString(Q))}setLimit($,Q,Y,G){return new X$({...this._def,checks:[...this._def.checks,{kind:$,value:Q,inclusive:Y,message:u.toString(G)}]})}_addCheck($){return new X$({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:u.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:u.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:u.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:u.toString($)})}multipleOf($,Q){return this._addCheck({kind:"multipleOf",value:$,message:u.toString(Q)})}get minValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $}get maxValue(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $}}X$.create=($)=>{return new X$({checks:[],typeName:O.ZodBigInt,coerce:$?.coerce??!1,...r($)})};class k$ extends a{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==_.boolean){let Y=this._getOrReturnCtx($);return f(Y,{code:S.invalid_type,expected:_.boolean,received:Y.parsedType}),i}return w0($.data)}}k$.create=($)=>{return new k$({typeName:O.ZodBoolean,coerce:$?.coerce||!1,...r($)})};class B$ extends a{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==_.date){let J=this._getOrReturnCtx($);return f(J,{code:S.invalid_type,expected:_.date,received:J.parsedType}),i}if(Number.isNaN($.data.getTime())){let J=this._getOrReturnCtx($);return f(J,{code:S.invalid_date}),i}let Y=new A0,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.getTime()<J.value)G=this._getOrReturnCtx($,G),f(G,{code:S.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),Y.dirty()}else if(J.kind==="max"){if($.data.getTime()>J.value)G=this._getOrReturnCtx($,G),f(G,{code:S.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),Y.dirty()}else t.assertNever(J);return{status:Y.value,value:new Date($.data.getTime())}}_addCheck($){return new B$({...this._def,checks:[...this._def.checks,$]})}min($,Q){return this._addCheck({kind:"min",value:$.getTime(),message:u.toString(Q)})}max($,Q){return this._addCheck({kind:"max",value:$.getTime(),message:u.toString(Q)})}get minDate(){let $=null;for(let Q of this._def.checks)if(Q.kind==="min"){if($===null||Q.value>$)$=Q.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let Q of this._def.checks)if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return $!=null?new Date($):null}}B$.create=($)=>{return new B$({checks:[],coerce:$?.coerce||!1,typeName:O.ZodDate,...r($)})};class T$ extends a{_parse($){if(this._getType($)!==_.symbol){let Y=this._getOrReturnCtx($);return f(Y,{code:S.invalid_type,expected:_.symbol,received:Y.parsedType}),i}return w0($.data)}}T$.create=($)=>{return new T$({typeName:O.ZodSymbol,...r($)})};class z$ extends a{_parse($){if(this._getType($)!==_.undefined){let Y=this._getOrReturnCtx($);return f(Y,{code:S.invalid_type,expected:_.undefined,received:Y.parsedType}),i}return w0($.data)}}z$.create=($)=>{return new z$({typeName:O.ZodUndefined,...r($)})};class N$ extends a{_parse($){if(this._getType($)!==_.null){let Y=this._getOrReturnCtx($);return f(Y,{code:S.invalid_type,expected:_.null,received:Y.parsedType}),i}return w0($.data)}}N$.create=($)=>{return new N$({typeName:O.ZodNull,...r($)})};class Z$ extends a{constructor(){super(...arguments);this._any=!0}_parse($){return w0($.data)}}Z$.create=($)=>{return new Z$({typeName:O.ZodAny,...r($)})};class s0 extends a{constructor(){super(...arguments);this._unknown=!0}_parse($){return w0($.data)}}s0.create=($)=>{return new s0({typeName:O.ZodUnknown,...r($)})};class g0 extends a{_parse($){let Q=this._getOrReturnCtx($);return f(Q,{code:S.invalid_type,expected:_.never,received:Q.parsedType}),i}}g0.create=($)=>{return new g0({typeName:O.ZodNever,...r($)})};class x$ extends a{_parse($){if(this._getType($)!==_.undefined){let Y=this._getOrReturnCtx($);return f(Y,{code:S.invalid_type,expected:_.void,received:Y.parsedType}),i}return w0($.data)}}x$.create=($)=>{return new x$({typeName:O.ZodVoid,...r($)})};class I0 extends a{_parse($){let{ctx:Q,status:Y}=this._processInputParams($),G=this._def;if(Q.parsedType!==_.array)return f(Q,{code:S.invalid_type,expected:_.array,received:Q.parsedType}),i;if(G.exactLength!==null){let W=Q.data.length>G.exactLength.value,q=Q.data.length<G.exactLength.value;if(W||q)f(Q,{code:W?S.too_big:S.too_small,minimum:q?G.exactLength.value:void 0,maximum:W?G.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:G.exactLength.message}),Y.dirty()}if(G.minLength!==null){if(Q.data.length<G.minLength.value)f(Q,{code:S.too_small,minimum:G.minLength.value,type:"array",inclusive:!0,exact:!1,message:G.minLength.message}),Y.dirty()}if(G.maxLength!==null){if(Q.data.length>G.maxLength.value)f(Q,{code:S.too_big,maximum:G.maxLength.value,type:"array",inclusive:!0,exact:!1,message:G.maxLength.message}),Y.dirty()}if(Q.common.async)return Promise.all([...Q.data].map((W,q)=>{return G.type._parseAsync(new S0(Q,W,Q.path,q))})).then((W)=>{return A0.mergeArray(Y,W)});let J=[...Q.data].map((W,q)=>{return G.type._parseSync(new S0(Q,W,Q.path,q))});return A0.mergeArray(Y,J)}get element(){return this._def.type}min($,Q){return new I0({...this._def,minLength:{value:$,message:u.toString(Q)}})}max($,Q){return new I0({...this._def,maxLength:{value:$,message:u.toString(Q)}})}length($,Q){return new I0({...this._def,exactLength:{value:$,message:u.toString(Q)}})}nonempty($){return this.min(1,$)}}I0.create=($,Q)=>{return new I0({type:$,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...r(Q)})};function e0($){if($ instanceof W0){let Q={};for(let Y in $.shape){let G=$.shape[Y];Q[Y]=_0.create(e0(G))}return new W0({...$._def,shape:()=>Q})}else if($ instanceof I0)return new I0({...$._def,type:e0($.element)});else if($ instanceof _0)return _0.create(e0($.unwrap()));else if($ instanceof i0)return i0.create(e0($.unwrap()));else if($ instanceof h0)return h0.create($.items.map((Q)=>e0(Q)));else return $}class W0 extends a{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),Q=t.objectKeys($);return this._cached={shape:$,keys:Q},this._cached}_parse($){if(this._getType($)!==_.object){let H=this._getOrReturnCtx($);return f(H,{code:S.invalid_type,expected:_.object,received:H.parsedType}),i}let{status:Y,ctx:G}=this._processInputParams($),{shape:J,keys:W}=this._getCached(),q=[];if(!(this._def.catchall instanceof g0&&this._def.unknownKeys==="strip")){for(let H in G.data)if(!W.includes(H))q.push(H)}let L=[];for(let H of W){let E=J[H],U=G.data[H];L.push({key:{status:"valid",value:H},value:E._parse(new S0(G,U,G.path,H)),alwaysSet:H in G.data})}if(this._def.catchall instanceof g0){let H=this._def.unknownKeys;if(H==="passthrough")for(let E of q)L.push({key:{status:"valid",value:E},value:{status:"valid",value:G.data[E]}});else if(H==="strict"){if(q.length>0)f(G,{code:S.unrecognized_keys,keys:q}),Y.dirty()}else if(H==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let H=this._def.catchall;for(let E of q){let U=G.data[E];L.push({key:{status:"valid",value:E},value:H._parse(new S0(G,U,G.path,E)),alwaysSet:E in G.data})}}if(G.common.async)return Promise.resolve().then(async()=>{let H=[];for(let E of L){let U=await E.key,V=await E.value;H.push({key:U,value:V,alwaysSet:E.alwaysSet})}return H}).then((H)=>{return A0.mergeObjectSync(Y,H)});else return A0.mergeObjectSync(Y,L)}get shape(){return this._def.shape()}strict($){return u.errToObj,new W0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(Q,Y)=>{let G=this._def.errorMap?.(Q,Y).message??Y.defaultError;if(Q.code==="unrecognized_keys")return{message:u.errToObj($).message??G};return{message:G}}}:{}})}strip(){return new W0({...this._def,unknownKeys:"strip"})}passthrough(){return new W0({...this._def,unknownKeys:"passthrough"})}extend($){return new W0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new W0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:O.ZodObject})}setKey($,Q){return this.augment({[$]:Q})}catchall($){return new W0({...this._def,catchall:$})}pick($){let Q={};for(let Y of t.objectKeys($))if($[Y]&&this.shape[Y])Q[Y]=this.shape[Y];return new W0({...this._def,shape:()=>Q})}omit($){let Q={};for(let Y of t.objectKeys(this.shape))if(!$[Y])Q[Y]=this.shape[Y];return new W0({...this._def,shape:()=>Q})}deepPartial(){return e0(this)}partial($){let Q={};for(let Y of t.objectKeys(this.shape)){let G=this.shape[Y];if($&&!$[Y])Q[Y]=G;else Q[Y]=G.optional()}return new W0({...this._def,shape:()=>Q})}required($){let Q={};for(let Y of t.objectKeys(this.shape))if($&&!$[Y])Q[Y]=this.shape[Y];else{let J=this.shape[Y];while(J instanceof _0)J=J._def.innerType;Q[Y]=J}return new W0({...this._def,shape:()=>Q})}keyof(){return V4(t.objectKeys(this.shape))}}W0.create=($,Q)=>{return new W0({shape:()=>$,unknownKeys:"strip",catchall:g0.create(),typeName:O.ZodObject,...r(Q)})};W0.strictCreate=($,Q)=>{return new W0({shape:()=>$,unknownKeys:"strict",catchall:g0.create(),typeName:O.ZodObject,...r(Q)})};W0.lazycreate=($,Q)=>{return new W0({shape:$,unknownKeys:"strip",catchall:g0.create(),typeName:O.ZodObject,...r(Q)})};class M$ extends a{_parse($){let{ctx:Q}=this._processInputParams($),Y=this._def.options;function G(J){for(let q of J)if(q.result.status==="valid")return q.result;for(let q of J)if(q.result.status==="dirty")return Q.common.issues.push(...q.ctx.common.issues),q.result;let W=J.map((q)=>new F0(q.ctx.common.issues));return f(Q,{code:S.invalid_union,unionErrors:W}),i}if(Q.common.async)return Promise.all(Y.map(async(J)=>{let W={...Q,common:{...Q.common,issues:[]},parent:null};return{result:await J._parseAsync({data:Q.data,path:Q.path,parent:W}),ctx:W}})).then(G);else{let J=void 0,W=[];for(let L of Y){let H={...Q,common:{...Q.common,issues:[]},parent:null},E=L._parseSync({data:Q.data,path:Q.path,parent:H});if(E.status==="valid")return E;else if(E.status==="dirty"&&!J)J={result:E,ctx:H};if(H.common.issues.length)W.push(H.common.issues)}if(J)return Q.common.issues.push(...J.ctx.common.issues),J.result;let q=W.map((L)=>new F0(L));return f(Q,{code:S.invalid_union,unionErrors:q}),i}}get options(){return this._def.options}}M$.create=($,Q)=>{return new M$({options:$,typeName:O.ZodUnion,...r(Q)})};var f0=($)=>{if($ instanceof w$)return f0($.schema);else if($ instanceof k0)return f0($.innerType());else if($ instanceof D$)return[$.value];else if($ instanceof t0)return $.options;else if($ instanceof V$)return t.objectValues($.enum);else if($ instanceof K$)return f0($._def.innerType);else if($ instanceof z$)return[void 0];else if($ instanceof N$)return[null];else if($ instanceof _0)return[void 0,...f0($.unwrap())];else if($ instanceof i0)return[null,...f0($.unwrap())];else if($ instanceof J1)return f0($.unwrap());else if($ instanceof R$)return f0($.unwrap());else if($ instanceof F$)return f0($._def.innerType);else return[]};class G1 extends a{_parse($){let{ctx:Q}=this._processInputParams($);if(Q.parsedType!==_.object)return f(Q,{code:S.invalid_type,expected:_.object,received:Q.parsedType}),i;let Y=this.discriminator,G=Q.data[Y],J=this.optionsMap.get(G);if(!J)return f(Q,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Y]}),i;if(Q.common.async)return J._parseAsync({data:Q.data,path:Q.path,parent:Q});else return J._parseSync({data:Q.data,path:Q.path,parent:Q})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,Q,Y){let G=new Map;for(let J of Q){let W=f0(J.shape[$]);if(!W.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let q of W){if(G.has(q))throw Error(`Discriminator property ${String($)} has duplicate value ${String(q)}`);G.set(q,J)}}return new G1({typeName:O.ZodDiscriminatedUnion,discriminator:$,options:Q,optionsMap:G,...r(Y)})}}function Y1($,Q){let Y=v0($),G=v0(Q);if($===Q)return{valid:!0,data:$};else if(Y===_.object&&G===_.object){let J=t.objectKeys(Q),W=t.objectKeys($).filter((L)=>J.indexOf(L)!==-1),q={...$,...Q};for(let L of W){let H=Y1($[L],Q[L]);if(!H.valid)return{valid:!1};q[L]=H.data}return{valid:!0,data:q}}else if(Y===_.array&&G===_.array){if($.length!==Q.length)return{valid:!1};let J=[];for(let W=0;W<$.length;W++){let q=$[W],L=Q[W],H=Y1(q,L);if(!H.valid)return{valid:!1};J.push(H.data)}return{valid:!0,data:J}}else if(Y===_.date&&G===_.date&&+$===+Q)return{valid:!0,data:$};else return{valid:!1}}class A$ extends a{_parse($){let{status:Q,ctx:Y}=this._processInputParams($),G=(J,W)=>{if($1(J)||$1(W))return i;let q=Y1(J.value,W.value);if(!q.valid)return f(Y,{code:S.invalid_intersection_types}),i;if(X1(J)||X1(W))Q.dirty();return{status:Q.value,value:q.data}};if(Y.common.async)return Promise.all([this._def.left._parseAsync({data:Y.data,path:Y.path,parent:Y}),this._def.right._parseAsync({data:Y.data,path:Y.path,parent:Y})]).then(([J,W])=>G(J,W));else return G(this._def.left._parseSync({data:Y.data,path:Y.path,parent:Y}),this._def.right._parseSync({data:Y.data,path:Y.path,parent:Y}))}}A$.create=($,Q,Y)=>{return new A$({left:$,right:Q,typeName:O.ZodIntersection,...r(Y)})};class h0 extends a{_parse($){let{status:Q,ctx:Y}=this._processInputParams($);if(Y.parsedType!==_.array)return f(Y,{code:S.invalid_type,expected:_.array,received:Y.parsedType}),i;if(Y.data.length<this._def.items.length)return f(Y,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i;if(!this._def.rest&&Y.data.length>this._def.items.length)f(Y,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q.dirty();let J=[...Y.data].map((W,q)=>{let L=this._def.items[q]||this._def.rest;if(!L)return null;return L._parse(new S0(Y,W,Y.path,q))}).filter((W)=>!!W);if(Y.common.async)return Promise.all(J).then((W)=>{return A0.mergeArray(Q,W)});else return A0.mergeArray(Q,J)}get items(){return this._def.items}rest($){return new h0({...this._def,rest:$})}}h0.create=($,Q)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new h0({items:$,typeName:O.ZodTuple,rest:null,...r(Q)})};class v$ extends a{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:Q,ctx:Y}=this._processInputParams($);if(Y.parsedType!==_.object)return f(Y,{code:S.invalid_type,expected:_.object,received:Y.parsedType}),i;let G=[],J=this._def.keyType,W=this._def.valueType;for(let q in Y.data)G.push({key:J._parse(new S0(Y,q,Y.path,q)),value:W._parse(new S0(Y,Y.data[q],Y.path,q)),alwaysSet:q in Y.data});if(Y.common.async)return A0.mergeObjectAsync(Q,G);else return A0.mergeObjectSync(Q,G)}get element(){return this._def.valueType}static create($,Q,Y){if(Q instanceof a)return new v$({keyType:$,valueType:Q,typeName:O.ZodRecord,...r(Y)});return new v$({keyType:y0.create(),valueType:$,typeName:O.ZodRecord,...r(Q)})}}class f$ extends a{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:Q,ctx:Y}=this._processInputParams($);if(Y.parsedType!==_.map)return f(Y,{code:S.invalid_type,expected:_.map,received:Y.parsedType}),i;let G=this._def.keyType,J=this._def.valueType,W=[...Y.data.entries()].map(([q,L],H)=>{return{key:G._parse(new S0(Y,q,Y.path,[H,"key"])),value:J._parse(new S0(Y,L,Y.path,[H,"value"]))}});if(Y.common.async){let q=new Map;return Promise.resolve().then(async()=>{for(let L of W){let H=await L.key,E=await L.value;if(H.status==="aborted"||E.status==="aborted")return i;if(H.status==="dirty"||E.status==="dirty")Q.dirty();q.set(H.value,E.value)}return{status:Q.value,value:q}})}else{let q=new Map;for(let L of W){let{key:H,value:E}=L;if(H.status==="aborted"||E.status==="aborted")return i;if(H.status==="dirty"||E.status==="dirty")Q.dirty();q.set(H.value,E.value)}return{status:Q.value,value:q}}}}f$.create=($,Q,Y)=>{return new f$({valueType:Q,keyType:$,typeName:O.ZodMap,...r(Y)})};class Q$ extends a{_parse($){let{status:Q,ctx:Y}=this._processInputParams($);if(Y.parsedType!==_.set)return f(Y,{code:S.invalid_type,expected:_.set,received:Y.parsedType}),i;let G=this._def;if(G.minSize!==null){if(Y.data.size<G.minSize.value)f(Y,{code:S.too_small,minimum:G.minSize.value,type:"set",inclusive:!0,exact:!1,message:G.minSize.message}),Q.dirty()}if(G.maxSize!==null){if(Y.data.size>G.maxSize.value)f(Y,{code:S.too_big,maximum:G.maxSize.value,type:"set",inclusive:!0,exact:!1,message:G.maxSize.message}),Q.dirty()}let J=this._def.valueType;function W(L){let H=new Set;for(let E of L){if(E.status==="aborted")return i;if(E.status==="dirty")Q.dirty();H.add(E.value)}return{status:Q.value,value:H}}let q=[...Y.data.values()].map((L,H)=>J._parse(new S0(Y,L,Y.path,H)));if(Y.common.async)return Promise.all(q).then((L)=>W(L));else return W(q)}min($,Q){return new Q$({...this._def,minSize:{value:$,message:u.toString(Q)}})}max($,Q){return new Q$({...this._def,maxSize:{value:$,message:u.toString(Q)}})}size($,Q){return this.min($,Q).max($,Q)}nonempty($){return this.min(1,$)}}Q$.create=($,Q)=>{return new Q$({valueType:$,minSize:null,maxSize:null,typeName:O.ZodSet,...r(Q)})};class j$ extends a{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:Q}=this._processInputParams($);if(Q.parsedType!==_.function)return f(Q,{code:S.invalid_type,expected:_.function,received:Q.parsedType}),i;function Y(q,L){return _$({data:q,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,E$(),d0].filter((H)=>!!H),issueData:{code:S.invalid_arguments,argumentsError:L}})}function G(q,L){return _$({data:q,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,E$(),d0].filter((H)=>!!H),issueData:{code:S.invalid_return_type,returnTypeError:L}})}let J={errorMap:Q.common.contextualErrorMap},W=Q.data;if(this._def.returns instanceof Y$){let q=this;return w0(async function(...L){let H=new F0([]),E=await q._def.args.parseAsync(L,J).catch((w)=>{throw H.addIssue(Y(L,w)),H}),U=await Reflect.apply(W,this,E);return await q._def.returns._def.type.parseAsync(U,J).catch((w)=>{throw H.addIssue(G(U,w)),H})})}else{let q=this;return w0(function(...L){let H=q._def.args.safeParse(L,J);if(!H.success)throw new F0([Y(L,H.error)]);let E=Reflect.apply(W,this,H.data),U=q._def.returns.safeParse(E,J);if(!U.success)throw new F0([G(E,U.error)]);return U.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new j$({...this._def,args:h0.create($).rest(s0.create())})}returns($){return new j$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,Q,Y){return new j$({args:$?$:h0.create([]).rest(s0.create()),returns:Q||s0.create(),typeName:O.ZodFunction,...r(Y)})}}class w$ extends a{get schema(){return this._def.getter()}_parse($){let{ctx:Q}=this._processInputParams($);return this._def.getter()._parse({data:Q.data,path:Q.path,parent:Q})}}w$.create=($,Q)=>{return new w$({getter:$,typeName:O.ZodLazy,...r(Q)})};class D$ extends a{_parse($){if($.data!==this._def.value){let Q=this._getOrReturnCtx($);return f(Q,{received:Q.data,code:S.invalid_literal,expected:this._def.value}),i}return{status:"valid",value:$.data}}get value(){return this._def.value}}D$.create=($,Q)=>{return new D$({value:$,typeName:O.ZodLiteral,...r(Q)})};function V4($,Q){return new t0({values:$,typeName:O.ZodEnum,...r(Q)})}class t0 extends a{_parse($){if(typeof $.data!=="string"){let Q=this._getOrReturnCtx($),Y=this._def.values;return f(Q,{expected:t.joinValues(Y),received:Q.parsedType,code:S.invalid_type}),i}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let Q=this._getOrReturnCtx($),Y=this._def.values;return f(Q,{received:Q.data,code:S.invalid_enum_value,options:Y}),i}return w0($.data)}get options(){return this._def.values}get enum(){let $={};for(let Q of this._def.values)$[Q]=Q;return $}get Values(){let $={};for(let Q of this._def.values)$[Q]=Q;return $}get Enum(){let $={};for(let Q of this._def.values)$[Q]=Q;return $}extract($,Q=this._def){return t0.create($,{...this._def,...Q})}exclude($,Q=this._def){return t0.create(this.options.filter((Y)=>!$.includes(Y)),{...this._def,...Q})}}t0.create=V4;class V$ extends a{_parse($){let Q=t.getValidEnumValues(this._def.values),Y=this._getOrReturnCtx($);if(Y.parsedType!==_.string&&Y.parsedType!==_.number){let G=t.objectValues(Q);return f(Y,{expected:t.joinValues(G),received:Y.parsedType,code:S.invalid_type}),i}if(!this._cache)this._cache=new Set(t.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let G=t.objectValues(Q);return f(Y,{received:Y.data,code:S.invalid_enum_value,options:G}),i}return w0($.data)}get enum(){return this._def.values}}V$.create=($,Q)=>{return new V$({values:$,typeName:O.ZodNativeEnum,...r(Q)})};class Y$ extends a{unwrap(){return this._def.type}_parse($){let{ctx:Q}=this._processInputParams($);if(Q.parsedType!==_.promise&&Q.common.async===!1)return f(Q,{code:S.invalid_type,expected:_.promise,received:Q.parsedType}),i;let Y=Q.parsedType===_.promise?Q.data:Promise.resolve(Q.data);return w0(Y.then((G)=>{return this._def.type.parseAsync(G,{path:Q.path,errorMap:Q.common.contextualErrorMap})}))}}Y$.create=($,Q)=>{return new Y$({type:$,typeName:O.ZodPromise,...r(Q)})};class k0 extends a{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:Q,ctx:Y}=this._processInputParams($),G=this._def.effect||null,J={addIssue:(W)=>{if(f(Y,W),W.fatal)Q.abort();else Q.dirty()},get path(){return Y.path}};if(J.addIssue=J.addIssue.bind(J),G.type==="preprocess"){let W=G.transform(Y.data,J);if(Y.common.async)return Promise.resolve(W).then(async(q)=>{if(Q.value==="aborted")return i;let L=await this._def.schema._parseAsync({data:q,path:Y.path,parent:Y});if(L.status==="aborted")return i;if(L.status==="dirty")return o0(L.value);if(Q.value==="dirty")return o0(L.value);return L});else{if(Q.value==="aborted")return i;let q=this._def.schema._parseSync({data:W,path:Y.path,parent:Y});if(q.status==="aborted")return i;if(q.status==="dirty")return o0(q.value);if(Q.value==="dirty")return o0(q.value);return q}}if(G.type==="refinement"){let W=(q)=>{let L=G.refinement(q,J);if(Y.common.async)return Promise.resolve(L);if(L instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return q};if(Y.common.async===!1){let q=this._def.schema._parseSync({data:Y.data,path:Y.path,parent:Y});if(q.status==="aborted")return i;if(q.status==="dirty")Q.dirty();return W(q.value),{status:Q.value,value:q.value}}else return this._def.schema._parseAsync({data:Y.data,path:Y.path,parent:Y}).then((q)=>{if(q.status==="aborted")return i;if(q.status==="dirty")Q.dirty();return W(q.value).then(()=>{return{status:Q.value,value:q.value}})})}if(G.type==="transform")if(Y.common.async===!1){let W=this._def.schema._parseSync({data:Y.data,path:Y.path,parent:Y});if(!a0(W))return i;let q=G.transform(W.value,J);if(q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:Q.value,value:q}}else return this._def.schema._parseAsync({data:Y.data,path:Y.path,parent:Y}).then((W)=>{if(!a0(W))return i;return Promise.resolve(G.transform(W.value,J)).then((q)=>({status:Q.value,value:q}))});t.assertNever(G)}}k0.create=($,Q,Y)=>{return new k0({schema:$,typeName:O.ZodEffects,effect:Q,...r(Y)})};k0.createWithPreprocess=($,Q,Y)=>{return new k0({schema:Q,effect:{type:"preprocess",transform:$},typeName:O.ZodEffects,...r(Y)})};class _0 extends a{_parse($){if(this._getType($)===_.undefined)return w0(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}_0.create=($,Q)=>{return new _0({innerType:$,typeName:O.ZodOptional,...r(Q)})};class i0 extends a{_parse($){if(this._getType($)===_.null)return w0(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}i0.create=($,Q)=>{return new i0({innerType:$,typeName:O.ZodNullable,...r(Q)})};class K$ extends a{_parse($){let{ctx:Q}=this._processInputParams($),Y=Q.data;if(Q.parsedType===_.undefined)Y=this._def.defaultValue();return this._def.innerType._parse({data:Y,path:Q.path,parent:Q})}removeDefault(){return this._def.innerType}}K$.create=($,Q)=>{return new K$({innerType:$,typeName:O.ZodDefault,defaultValue:typeof Q.default==="function"?Q.default:()=>Q.default,...r(Q)})};class F$ extends a{_parse($){let{ctx:Q}=this._processInputParams($),Y={...Q,common:{...Q.common,issues:[]}},G=this._def.innerType._parse({data:Y.data,path:Y.path,parent:{...Y}});if(U$(G))return G.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new F0(Y.common.issues)},input:Y.data})}});else return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new F0(Y.common.issues)},input:Y.data})}}removeCatch(){return this._def.innerType}}F$.create=($,Q)=>{return new F$({innerType:$,typeName:O.ZodCatch,catchValue:typeof Q.catch==="function"?Q.catch:()=>Q.catch,...r(Q)})};class y$ extends a{_parse($){if(this._getType($)!==_.nan){let Y=this._getOrReturnCtx($);return f(Y,{code:S.invalid_type,expected:_.nan,received:Y.parsedType}),i}return{status:"valid",value:$.data}}}y$.create=($)=>{return new y$({typeName:O.ZodNaN,...r($)})};var Y6=Symbol("zod_brand");class J1 extends a{_parse($){let{ctx:Q}=this._processInputParams($),Y=Q.data;return this._def.type._parse({data:Y,path:Q.path,parent:Q})}unwrap(){return this._def.type}}class g$ extends a{_parse($){let{status:Q,ctx:Y}=this._processInputParams($);if(Y.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:Y.data,path:Y.path,parent:Y});if(J.status==="aborted")return i;if(J.status==="dirty")return Q.dirty(),o0(J.value);else return this._def.out._parseAsync({data:J.value,path:Y.path,parent:Y})})();else{let G=this._def.in._parseSync({data:Y.data,path:Y.path,parent:Y});if(G.status==="aborted")return i;if(G.status==="dirty")return Q.dirty(),{status:"dirty",value:G.value};else return this._def.out._parseSync({data:G.value,path:Y.path,parent:Y})}}static create($,Q){return new g$({in:$,out:Q,typeName:O.ZodPipeline})}}class R$ extends a{_parse($){let Q=this._def.innerType._parse($),Y=(G)=>{if(a0(G))G.value=Object.freeze(G.value);return G};return U$(Q)?Q.then((G)=>Y(G)):Y(Q)}unwrap(){return this._def.innerType}}R$.create=($,Q)=>{return new R$({innerType:$,typeName:O.ZodReadonly,...r(Q)})};var G6={object:W0.lazycreate},O;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(O||(O={}));var J6=y0.create,W6=$$.create,q6=y$.create,L6=X$.create,H6=k$.create,E6=B$.create,U6=T$.create,j6=z$.create,B6=N$.create,z6=Z$.create,N6=s0.create,M6=g0.create,A6=x$.create,w6=I0.create,D6=W0.create,V6=W0.strictCreate,K6=M$.create,F6=G1.create,R6=A$.create,S6=h0.create,O6=v$.create,P6=f$.create,b6=Q$.create,C6=j$.create,I6=w$.create,_6=D$.create,k6=t0.create,T6=V$.create,Z6=Y$.create,x6=k0.create,v6=_0.create,f6=i0.create,y6=k0.createWithPreprocess,g6=g$.create;function Q0(...$){return $.reduce((Q,Y)=>({...Q,...Y!=null?Y:{}}),{})}async function u6($,Q){if($==null)return Promise.resolve();let Y=Q==null?void 0:Q.abortSignal;return new Promise((G,J)=>{if(Y==null?void 0:Y.aborted){J(K4());return}let W=setTimeout(()=>{q(),G()},$),q=()=>{clearTimeout(W),Y==null||Y.removeEventListener("abort",L)},L=()=>{q(),J(K4())};Y==null||Y.addEventListener("abort",L)})}function K4(){return new DOMException("Delay was aborted","AbortError")}function G$($){return Object.fromEntries([...$.headers])}var LX=({prefix:$,size:Q=16,alphabet:Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:G="-"}={})=>{let J=()=>{let W=Y.length,q=Array(Q);for(let L=0;L<Q;L++)q[L]=Y[Math.random()*W|0];return q.join("")};if($==null)return J;if(Y.includes(G))throw new b$({argument:"separator",message:`The separator "${G}" must not be part of the alphabet "${Y}".`});return()=>`${$}${G}${J()}`},j0=LX();function d6($){if($==null)return"unknown error";if(typeof $==="string")return $;if($ instanceof Error)return $.message;return JSON.stringify($)}function S$($){return($ instanceof Error||$ instanceof DOMException)&&($.name==="AbortError"||$.name==="ResponseAborted"||$.name==="TimeoutError")}var HX=["fetch failed","failed to fetch"];function P4({error:$,url:Q,requestBodyValues:Y}){if(S$($))return $;if($ instanceof TypeError&&HX.includes($.message.toLowerCase())){let G=$.cause;if(G!=null)return new E0({message:`Cannot connect to API: ${G.message}`,cause:G,url:Q,requestBodyValues:Y,isRetryable:!0})}return $}function b4($=globalThis){var Q,Y,G;if($.window)return"runtime/browser";if((Q=$.navigator)==null?void 0:Q.userAgent)return`runtime/${$.navigator.userAgent.toLowerCase()}`;if((G=(Y=$.process)==null?void 0:Y.versions)==null?void 0:G.node)return`runtime/node.js/${$.process.version.substring(0)}`;if($.EdgeRuntime)return"runtime/vercel-edge";return"runtime/unknown"}function EX($){if($==null)return{};let Q={};if($ instanceof Headers)$.forEach((Y,G)=>{Q[G.toLowerCase()]=Y});else{if(!Array.isArray($))$=Object.entries($);for(let[Y,G]of $)if(G!=null)Q[Y.toLowerCase()]=G}return Q}function p0($,...Q){let Y=new Headers(EX($)),G=Y.get("user-agent")||"";return Y.set("user-agent",[G,...Q].filter(Boolean).join(" ")),Object.fromEntries(Y.entries())}var C4="3.0.15",UX=()=>globalThis.fetch,l6=async({url:$,headers:Q={},successfulResponseHandler:Y,failedResponseHandler:G,abortSignal:J,fetch:W=UX()})=>{try{let q=await W($,{method:"GET",headers:p0(Q,`ai-sdk/provider-utils/${C4}`,b4()),signal:J}),L=G$(q);if(!q.ok){let H;try{H=await G({response:q,url:$,requestBodyValues:{}})}catch(E){if(S$(E)||E0.isInstance(E))throw E;throw new E0({message:"Failed to process error response",cause:E,statusCode:q.status,url:$,responseHeaders:L,requestBodyValues:{}})}throw H.value}try{return await Y({response:q,url:$,requestBodyValues:{}})}catch(H){if(H instanceof Error){if(S$(H)||E0.isInstance(H))throw H}throw new E0({message:"Failed to process successful response",cause:H,statusCode:q.status,url:$,responseHeaders:L,requestBodyValues:{}})}}catch(q){throw P4({error:q,url:$,requestBodyValues:{}})}};function n6({mediaType:$,url:Q,supportedUrls:Y}){return Q=Q.toLowerCase(),$=$.toLowerCase(),Object.entries(Y).map(([G,J])=>{let W=G.toLowerCase();return W==="*"||W==="*/*"?{mediaTypePrefix:"",regexes:J}:{mediaTypePrefix:W.replace(/\*/,""),regexes:J}}).filter(({mediaTypePrefix:G})=>$.startsWith(G)).flatMap(({regexes:G})=>G).some((G)=>G.test(Q))}function J$({apiKey:$,environmentVariableName:Q,apiKeyParameterName:Y="apiKey",description:G}){if(typeof $==="string")return $;if($!=null)throw new H$({message:`${G} API key must be a string.`});if(typeof process>"u")throw new H$({message:`${G} API key is missing. Pass it using the '${Y}' parameter. Environment variables is not supported in this environment.`});if($=process.env[Q],$==null)throw new H$({message:`${G} API key is missing. Pass it using the '${Y}' parameter or the ${Q} environment variable.`});if(typeof $!=="string")throw new H$({message:`${G} API key must be a string. The value of the ${Q} environment variable is not a string.`});return $}function m$({settingValue:$,environmentVariableName:Q}){if(typeof $==="string")return $;if($!=null||typeof process>"u")return;if($=process.env[Q],$==null||typeof $!=="string")return;return $}function I4($){var Q;let[Y,G=""]=$.toLowerCase().split("/");return(Q={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[G])!=null?Q:G}var jX=/"__proto__"\s*:/,BX=/"constructor"\s*:/;function zX($){let Q=JSON.parse($);if(Q===null||typeof Q!=="object")return Q;if(jX.test($)===!1&&BX.test($)===!1)return Q;return NX(Q)}function NX($){let Q=[$];while(Q.length){let Y=Q;Q=[];for(let G of Y){if(Object.prototype.hasOwnProperty.call(G,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(G,"constructor")&&Object.prototype.hasOwnProperty.call(G.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let J in G){let W=G[J];if(W&&typeof W==="object")Q.push(W)}}}return $}function E1($){let{stackTraceLimit:Q}=Error;Error.stackTraceLimit=0;try{return zX($)}finally{Error.stackTraceLimit=Q}}var h$=Symbol.for("vercel.ai.validator");function MX($){return{[h$]:!0,validate:$}}function AX($){return typeof $==="object"&&$!==null&&h$ in $&&$[h$]===!0&&"validate"in $}function $0($){let Q;return()=>{if(Q==null)Q=$();return Q}}function wX($){return AX($)?$:typeof $==="function"?$():DX($)}function DX($){return MX(async(Q)=>{let Y=await $["~standard"].validate(Q);return Y.issues==null?{success:!0,value:Y.value}:{success:!1,error:new c0({value:Q,cause:Y.issues})}})}async function B0({value:$,schema:Q}){let Y=await U1({value:$,schema:Q});if(!Y.success)throw c0.wrap({value:$,cause:Y.error});return Y.value}async function U1({value:$,schema:Q}){let Y=wX(Q);try{if(Y.validate==null)return{success:!0,value:$,rawValue:$};let G=await Y.validate($);if(G.success)return{success:!0,value:G.value,rawValue:$};return{success:!1,error:c0.wrap({value:$,cause:G.error}),rawValue:$}}catch(G){return{success:!1,error:c0.wrap({value:$,cause:G}),rawValue:$}}}async function VX({text:$,schema:Q}){try{let Y=E1($);if(Q==null)return Y;return B0({value:Y,schema:Q})}catch(Y){if(L$.isInstance(Y)||c0.isInstance(Y))throw Y;throw new L$({text:$,cause:Y})}}async function _4({text:$,schema:Q}){try{let Y=E1($);if(Q==null)return{success:!0,value:Y,rawValue:Y};return await U1({value:Y,schema:Q})}catch(Y){return{success:!1,error:L$.isInstance(Y)?Y:new L$({text:$,cause:Y}),rawValue:void 0}}}function j1($){try{return E1($),!0}catch(Q){return!1}}function KX({stream:$,schema:Q}){return $.pipeThrough(new TextDecoderStream).pipeThrough(new e$).pipeThrough(new TransformStream({async transform({data:Y},G){if(Y==="[DONE]")return;G.enqueue(await _4({text:Y,schema:Q}))}}))}async function X0({provider:$,providerOptions:Q,schema:Y}){if((Q==null?void 0:Q[$])==null)return;let G=await U1({value:Q[$],schema:Y});if(!G.success)throw new b$({argument:"providerOptions",message:`invalid ${$} provider options`,cause:G.error});return G.value}var FX=()=>globalThis.fetch,Y0=async({url:$,headers:Q,body:Y,failedResponseHandler:G,successfulResponseHandler:J,abortSignal:W,fetch:q})=>T4({url:$,headers:{"Content-Type":"application/json",...Q},body:{content:JSON.stringify(Y),values:Y},failedResponseHandler:G,successfulResponseHandler:J,abortSignal:W,fetch:q}),k4=async({url:$,headers:Q,formData:Y,failedResponseHandler:G,successfulResponseHandler:J,abortSignal:W,fetch:q})=>T4({url:$,headers:Q,body:{content:Y,values:Object.fromEntries(Y.entries())},failedResponseHandler:G,successfulResponseHandler:J,abortSignal:W,fetch:q}),T4=async({url:$,headers:Q={},body:Y,successfulResponseHandler:G,failedResponseHandler:J,abortSignal:W,fetch:q=FX()})=>{try{let L=await q($,{method:"POST",headers:p0(Q,`ai-sdk/provider-utils/${C4}`,b4()),body:Y.content,signal:W}),H=G$(L);if(!L.ok){let E;try{E=await J({response:L,url:$,requestBodyValues:Y.values})}catch(U){if(S$(U)||E0.isInstance(U))throw U;throw new E0({message:"Failed to process error response",cause:U,statusCode:L.status,url:$,responseHeaders:H,requestBodyValues:Y.values})}throw E.value}try{return await G({response:L,url:$,requestBodyValues:Y.values})}catch(E){if(E instanceof Error){if(S$(E)||E0.isInstance(E))throw E}throw new E0({message:"Failed to process successful response",cause:E,statusCode:L.status,url:$,responseHeaders:H,requestBodyValues:Y.values})}}catch(L){throw P4({error:L,url:$,requestBodyValues:Y.values})}};function Z4($){return $}function q0({id:$,name:Q,inputSchema:Y}){return({execute:G,outputSchema:J,toModelOutput:W,onInputStart:q,onInputDelta:L,onInputAvailable:H,...E})=>Z4({type:"provider-defined",id:$,name:Q,args:E,inputSchema:Y,outputSchema:J,execute:G,toModelOutput:W,onInputStart:q,onInputDelta:L,onInputAvailable:H})}function L0({id:$,name:Q,inputSchema:Y,outputSchema:G}){return({execute:J,toModelOutput:W,onInputStart:q,onInputDelta:L,onInputAvailable:H,...E})=>Z4({type:"provider-defined",id:$,name:Q,args:E,inputSchema:Y,outputSchema:G,execute:J,toModelOutput:W,onInputStart:q,onInputDelta:L,onInputAvailable:H})}async function m0($){if(typeof $==="function")$=$();return Promise.resolve($)}var W$=({errorSchema:$,errorToMessage:Q,isRetryable:Y})=>async({response:G,url:J,requestBodyValues:W})=>{let q=await G.text(),L=G$(G);if(q.trim()==="")return{responseHeaders:L,value:new E0({message:G.statusText,url:J,requestBodyValues:W,statusCode:G.status,responseHeaders:L,responseBody:q,isRetryable:Y==null?void 0:Y(G)})};try{let H=await VX({text:q,schema:$});return{responseHeaders:L,value:new E0({message:Q(H),url:J,requestBodyValues:W,statusCode:G.status,responseHeaders:L,responseBody:q,data:H,isRetryable:Y==null?void 0:Y(G,H)})}}catch(H){return{responseHeaders:L,value:new E0({message:G.statusText,url:J,requestBodyValues:W,statusCode:G.status,responseHeaders:L,responseBody:q,isRetryable:Y==null?void 0:Y(G)})}}},T0=($)=>async({response:Q})=>{let Y=G$(Q);if(Q.body==null)throw new h1({});return{responseHeaders:Y,value:KX({stream:Q.body,schema:$})}};var U0=($)=>async({response:Q,url:Y,requestBodyValues:G})=>{let J=await Q.text(),W=await _4({text:J,schema:$}),q=G$(Q);if(!W.success)throw new E0({message:"Invalid JSON response",cause:W.error,statusCode:Q.status,responseHeaders:q,responseBody:J,url:Y,requestBodyValues:G});return{responseHeaders:q,value:W.value,rawValue:W.rawValue}},x4=()=>async({response:$,url:Q,requestBodyValues:Y})=>{let G=G$($);if(!$.body)throw new E0({message:"Response body is empty",url:Q,requestBodyValues:Y,statusCode:$.status,responseHeaders:G,responseBody:void 0});try{let J=await $.arrayBuffer();return{responseHeaders:G,value:new Uint8Array(J)}}catch(J){throw new E0({message:"Failed to read response as array buffer",url:Q,requestBodyValues:Y,statusCode:$.status,responseHeaders:G,responseBody:void 0,cause:J})}};var RX=($,Q)=>{let Y=0;for(;Y<$.length&&Y<Q.length;Y++)if($[Y]!==Q[Y])break;return[($.length-Y).toString(),...Q.slice(Y)].join("/")},SX=Symbol("Let zodToJsonSchema decide on which parser to use"),F4={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"},OX=($)=>typeof $==="string"?{...F4,name:$}:{...F4,...$};function R0(){return{}}function PX($,Q){var Y,G,J;let W={type:"array"};if(((Y=$.type)==null?void 0:Y._def)&&((J=(G=$.type)==null?void 0:G._def)==null?void 0:J.typeName)!==O.ZodAny)W.items=e($.type._def,{...Q,currentPath:[...Q.currentPath,"items"]});if($.minLength)W.minItems=$.minLength.value;if($.maxLength)W.maxItems=$.maxLength.value;if($.exactLength)W.minItems=$.exactLength.value,W.maxItems=$.exactLength.value;return W}function bX($){let Q={type:"integer",format:"int64"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"min":if(Y.inclusive)Q.minimum=Y.value;else Q.exclusiveMinimum=Y.value;break;case"max":if(Y.inclusive)Q.maximum=Y.value;else Q.exclusiveMaximum=Y.value;break;case"multipleOf":Q.multipleOf=Y.value;break}return Q}function CX(){return{type:"boolean"}}function v4($,Q){return e($.type._def,Q)}var IX=($,Q)=>{return e($.innerType._def,Q)};function f4($,Q,Y){let G=Y!=null?Y:Q.dateStrategy;if(Array.isArray(G))return{anyOf:G.map((J,W)=>f4($,Q,J))};switch(G){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return _X($)}}var _X=($)=>{let Q={type:"integer",format:"unix-time"};for(let Y of $.checks)switch(Y.kind){case"min":Q.minimum=Y.value;break;case"max":Q.maximum=Y.value;break}return Q};function kX($,Q){return{...e($.innerType._def,Q),default:$.defaultValue()}}function TX($,Q){return Q.effectStrategy==="input"?e($.schema._def,Q):R0()}function ZX($){return{type:"string",enum:Array.from($.values)}}var xX=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function vX($,Q){let Y=[e($.left._def,{...Q,currentPath:[...Q.currentPath,"allOf","0"]}),e($.right._def,{...Q,currentPath:[...Q.currentPath,"allOf","1"]})].filter((J)=>!!J),G=[];return Y.forEach((J)=>{if(xX(J))G.push(...J.allOf);else{let W=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:q,...L}=J;W=L}G.push(W)}}),G.length?{allOf:G}:void 0}function fX($){let Q=typeof $.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray($.value)?"array":"object"};return{type:Q==="bigint"?"integer":Q,const:$.value}}var W1=void 0,O0={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:()=>{if(W1===void 0)W1=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return W1},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 y4($,Q){let Y={type:"string"};if($.checks)for(let G of $.checks)switch(G.kind){case"min":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,G.value):G.value;break;case"max":Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,G.value):G.value;break;case"email":switch(Q.emailStrategy){case"format:email":P0(Y,"email",G.message,Q);break;case"format:idn-email":P0(Y,"idn-email",G.message,Q);break;case"pattern:zod":D0(Y,O0.email,G.message,Q);break}break;case"url":P0(Y,"uri",G.message,Q);break;case"uuid":P0(Y,"uuid",G.message,Q);break;case"regex":D0(Y,G.regex,G.message,Q);break;case"cuid":D0(Y,O0.cuid,G.message,Q);break;case"cuid2":D0(Y,O0.cuid2,G.message,Q);break;case"startsWith":D0(Y,RegExp(`^${q1(G.value,Q)}`),G.message,Q);break;case"endsWith":D0(Y,RegExp(`${q1(G.value,Q)}$`),G.message,Q);break;case"datetime":P0(Y,"date-time",G.message,Q);break;case"date":P0(Y,"date",G.message,Q);break;case"time":P0(Y,"time",G.message,Q);break;case"duration":P0(Y,"duration",G.message,Q);break;case"length":Y.minLength=typeof Y.minLength==="number"?Math.max(Y.minLength,G.value):G.value,Y.maxLength=typeof Y.maxLength==="number"?Math.min(Y.maxLength,G.value):G.value;break;case"includes":{D0(Y,RegExp(q1(G.value,Q)),G.message,Q);break}case"ip":{if(G.version!=="v6")P0(Y,"ipv4",G.message,Q);if(G.version!=="v4")P0(Y,"ipv6",G.message,Q);break}case"base64url":D0(Y,O0.base64url,G.message,Q);break;case"jwt":D0(Y,O0.jwt,G.message,Q);break;case"cidr":{if(G.version!=="v6")D0(Y,O0.ipv4Cidr,G.message,Q);if(G.version!=="v4")D0(Y,O0.ipv6Cidr,G.message,Q);break}case"emoji":D0(Y,O0.emoji(),G.message,Q);break;case"ulid":{D0(Y,O0.ulid,G.message,Q);break}case"base64":{switch(Q.base64Strategy){case"format:binary":{P0(Y,"binary",G.message,Q);break}case"contentEncoding:base64":{Y.contentEncoding="base64";break}case"pattern:zod":{D0(Y,O0.base64,G.message,Q);break}}break}case"nanoid":D0(Y,O0.nanoid,G.message,Q);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return Y}function q1($,Q){return Q.patternStrategy==="escape"?gX($):$}var yX=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function gX($){let Q="";for(let Y=0;Y<$.length;Y++){if(!yX.has($[Y]))Q+="\\";Q+=$[Y]}return Q}function P0($,Q,Y,G){var J;if($.format||((J=$.anyOf)==null?void 0:J.some((W)=>W.format))){if(!$.anyOf)$.anyOf=[];if($.format)$.anyOf.push({format:$.format}),delete $.format;$.anyOf.push({format:Q,...Y&&G.errorMessages&&{errorMessage:{format:Y}}})}else $.format=Q}function D0($,Q,Y,G){var J;if($.pattern||((J=$.allOf)==null?void 0:J.some((W)=>W.pattern))){if(!$.allOf)$.allOf=[];if($.pattern)$.allOf.push({pattern:$.pattern}),delete $.pattern;$.allOf.push({pattern:R4(Q,G),...Y&&G.errorMessages&&{errorMessage:{pattern:Y}}})}else $.pattern=R4(Q,G)}function R4($,Q){var Y;if(!Q.applyRegexFlags||!$.flags)return $.source;let G={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},J=G.i?$.source.toLowerCase():$.source,W="",q=!1,L=!1,H=!1;for(let E=0;E<J.length;E++){if(q){W+=J[E],q=!1;continue}if(G.i){if(L){if(J[E].match(/[a-z]/)){if(H)W+=J[E],W+=`${J[E-2]}-${J[E]}`.toUpperCase(),H=!1;else if(J[E+1]==="-"&&((Y=J[E+2])==null?void 0:Y.match(/[a-z]/)))W+=J[E],H=!0;else W+=`${J[E]}${J[E].toUpperCase()}`;continue}}else if(J[E].match(/[a-z]/)){W+=`[${J[E]}${J[E].toUpperCase()}]`;continue}}if(G.m){if(J[E]==="^"){W+=`(^|(?<=[\r
8
+ ]))`;continue}else if(J[E]==="$"){W+=`($|(?=[\r
9
+ ]))`;continue}}if(G.s&&J[E]==="."){W+=L?`${J[E]}\r
10
+ `:`[${J[E]}\r
11
+ ]`;continue}if(W+=J[E],J[E]==="\\")q=!0;else if(L&&J[E]==="]")L=!1;else if(!L&&J[E]==="[")L=!0}try{new RegExp(W)}catch(E){return console.warn(`Could not convert regex pattern at ${Q.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return W}function g4($,Q){var Y,G,J,W,q,L;let H={type:"object",additionalProperties:(Y=e($.valueType._def,{...Q,currentPath:[...Q.currentPath,"additionalProperties"]}))!=null?Y:Q.allowedAdditionalProperties};if(((G=$.keyType)==null?void 0:G._def.typeName)===O.ZodString&&((J=$.keyType._def.checks)==null?void 0:J.length)){let{type:E,...U}=y4($.keyType._def,Q);return{...H,propertyNames:U}}else if(((W=$.keyType)==null?void 0:W._def.typeName)===O.ZodEnum)return{...H,propertyNames:{enum:$.keyType._def.values}};else if(((q=$.keyType)==null?void 0:q._def.typeName)===O.ZodBranded&&$.keyType._def.type._def.typeName===O.ZodString&&((L=$.keyType._def.type._def.checks)==null?void 0:L.length)){let{type:E,...U}=v4($.keyType._def,Q);return{...H,propertyNames:U}}return H}function hX($,Q){if(Q.mapStrategy==="record")return g4($,Q);let Y=e($.keyType._def,{...Q,currentPath:[...Q.currentPath,"items","items","0"]})||R0(),G=e($.valueType._def,{...Q,currentPath:[...Q.currentPath,"items","items","1"]})||R0();return{type:"array",maxItems:125,items:{type:"array",items:[Y,G],minItems:2,maxItems:2}}}function mX($){let Q=$.values,G=Object.keys($.values).filter((W)=>{return typeof Q[Q[W]]!=="number"}).map((W)=>Q[W]),J=Array.from(new Set(G.map((W)=>typeof W)));return{type:J.length===1?J[0]==="string"?"string":"number":["string","number"],enum:G}}function uX(){return{not:R0()}}function cX(){return{type:"null"}}var L1={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function dX($,Q){let Y=$.options instanceof Map?Array.from($.options.values()):$.options;if(Y.every((G)=>(G._def.typeName in L1)&&(!G._def.checks||!G._def.checks.length))){let G=Y.reduce((J,W)=>{let q=L1[W._def.typeName];return q&&!J.includes(q)?[...J,q]:J},[]);return{type:G.length>1?G:G[0]}}else if(Y.every((G)=>G._def.typeName==="ZodLiteral"&&!G.description)){let G=Y.reduce((J,W)=>{let q=typeof W._def.value;switch(q){case"string":case"number":case"boolean":return[...J,q];case"bigint":return[...J,"integer"];case"object":if(W._def.value===null)return[...J,"null"];case"symbol":case"undefined":case"function":default:return J}},[]);if(G.length===Y.length){let J=G.filter((W,q,L)=>L.indexOf(W)===q);return{type:J.length>1?J:J[0],enum:Y.reduce((W,q)=>{return W.includes(q._def.value)?W:[...W,q._def.value]},[])}}}else if(Y.every((G)=>G._def.typeName==="ZodEnum"))return{type:"string",enum:Y.reduce((G,J)=>[...G,...J._def.values.filter((W)=>!G.includes(W))],[])};return iX($,Q)}var iX=($,Q)=>{let Y=($.options instanceof Map?Array.from($.options.values()):$.options).map((G,J)=>e(G._def,{...Q,currentPath:[...Q.currentPath,"anyOf",`${J}`]})).filter((G)=>!!G&&(!Q.strictUnions||typeof G==="object"&&Object.keys(G).length>0));return Y.length?{anyOf:Y}:void 0};function pX($,Q){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length))return{type:[L1[$.innerType._def.typeName],"null"]};let Y=e($.innerType._def,{...Q,currentPath:[...Q.currentPath,"anyOf","0"]});return Y&&{anyOf:[Y,{type:"null"}]}}function lX($){let Q={type:"number"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"int":Q.type="integer";break;case"min":if(Y.inclusive)Q.minimum=Y.value;else Q.exclusiveMinimum=Y.value;break;case"max":if(Y.inclusive)Q.maximum=Y.value;else Q.exclusiveMaximum=Y.value;break;case"multipleOf":Q.multipleOf=Y.value;break}return Q}function nX($,Q){let Y={type:"object",properties:{}},G=[],J=$.shape();for(let q in J){let L=J[q];if(L===void 0||L._def===void 0)continue;let H=aX(L),E=e(L._def,{...Q,currentPath:[...Q.currentPath,"properties",q],propertyPath:[...Q.currentPath,"properties",q]});if(E===void 0)continue;if(Y.properties[q]=E,!H)G.push(q)}if(G.length)Y.required=G;let W=rX($,Q);if(W!==void 0)Y.additionalProperties=W;return Y}function rX($,Q){if($.catchall._def.typeName!=="ZodNever")return e($.catchall._def,{...Q,currentPath:[...Q.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return Q.allowedAdditionalProperties;case"strict":return Q.rejectedAdditionalProperties;case"strip":return Q.removeAdditionalStrategy==="strict"?Q.allowedAdditionalProperties:Q.rejectedAdditionalProperties}}function aX($){try{return $.isOptional()}catch(Q){return!0}}var sX=($,Q)=>{var Y;if(Q.currentPath.toString()===((Y=Q.propertyPath)==null?void 0:Y.toString()))return e($.innerType._def,Q);let G=e($.innerType._def,{...Q,currentPath:[...Q.currentPath,"anyOf","1"]});return G?{anyOf:[{not:R0()},G]}:R0()},tX=($,Q)=>{if(Q.pipeStrategy==="input")return e($.in._def,Q);else if(Q.pipeStrategy==="output")return e($.out._def,Q);let Y=e($.in._def,{...Q,currentPath:[...Q.currentPath,"allOf","0"]}),G=e($.out._def,{...Q,currentPath:[...Q.currentPath,"allOf",Y?"1":"0"]});return{allOf:[Y,G].filter((J)=>J!==void 0)}};function oX($,Q){return e($.type._def,Q)}function eX($,Q){let G={type:"array",uniqueItems:!0,items:e($.valueType._def,{...Q,currentPath:[...Q.currentPath,"items"]})};if($.minSize)G.minItems=$.minSize.value;if($.maxSize)G.maxItems=$.maxSize.value;return G}function $Q($,Q){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Y,G)=>e(Y._def,{...Q,currentPath:[...Q.currentPath,"items",`${G}`]})).reduce((Y,G)=>G===void 0?Y:[...Y,G],[]),additionalItems:e($.rest._def,{...Q,currentPath:[...Q.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Y,G)=>e(Y._def,{...Q,currentPath:[...Q.currentPath,"items",`${G}`]})).reduce((Y,G)=>G===void 0?Y:[...Y,G],[])}}function XQ(){return{not:R0()}}function QQ(){return R0()}var YQ=($,Q)=>{return e($.innerType._def,Q)},GQ=($,Q,Y)=>{switch(Q){case O.ZodString:return y4($,Y);case O.ZodNumber:return lX($);case O.ZodObject:return nX($,Y);case O.ZodBigInt:return bX($);case O.ZodBoolean:return CX();case O.ZodDate:return f4($,Y);case O.ZodUndefined:return XQ();case O.ZodNull:return cX();case O.ZodArray:return PX($,Y);case O.ZodUnion:case O.ZodDiscriminatedUnion:return dX($,Y);case O.ZodIntersection:return vX($,Y);case O.ZodTuple:return $Q($,Y);case O.ZodRecord:return g4($,Y);case O.ZodLiteral:return fX($);case O.ZodEnum:return ZX($);case O.ZodNativeEnum:return mX($);case O.ZodNullable:return pX($,Y);case O.ZodOptional:return sX($,Y);case O.ZodMap:return hX($,Y);case O.ZodSet:return eX($,Y);case O.ZodLazy:return()=>$.getter()._def;case O.ZodPromise:return oX($,Y);case O.ZodNaN:case O.ZodNever:return uX();case O.ZodEffects:return TX($,Y);case O.ZodAny:return R0();case O.ZodUnknown:return QQ();case O.ZodDefault:return kX($,Y);case O.ZodBranded:return v4($,Y);case O.ZodReadonly:return YQ($,Y);case O.ZodCatch:return IX($,Y);case O.ZodPipeline:return tX($,Y);case O.ZodFunction:case O.ZodVoid:case O.ZodSymbol:return;default:return((G)=>{return})(Q)}};function e($,Q,Y=!1){var G;let J=Q.seen.get($);if(Q.override){let H=(G=Q.override)==null?void 0:G.call(Q,$,Q,J,Y);if(H!==SX)return H}if(J&&!Y){let H=JQ(J,Q);if(H!==void 0)return H}let W={def:$,path:Q.currentPath,jsonSchema:void 0};Q.seen.set($,W);let q=GQ($,$.typeName,Q),L=typeof q==="function"?e(q(),Q):q;if(L)WQ($,Q,L);if(Q.postProcess){let H=Q.postProcess(L,$,Q);return W.jsonSchema=L,H}return W.jsonSchema=L,L}var JQ=($,Q)=>{switch(Q.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:RX(Q.currentPath,$.path)};case"none":case"seen":{if($.path.length<Q.currentPath.length&&$.path.every((Y,G)=>Q.currentPath[G]===Y))return console.warn(`Recursive reference detected at ${Q.currentPath.join("/")}! Defaulting to any`),R0();return Q.$refStrategy==="seen"?R0():void 0}}},WQ=($,Q,Y)=>{if($.description)Y.description=$.description;return Y},qQ=($)=>{let Q=OX($),Y=Q.name!==void 0?[...Q.basePath,Q.definitionPath,Q.name]:Q.basePath;return{...Q,currentPath:Y,propertyPath:void 0,seen:new Map(Object.entries(Q.definitions).map(([G,J])=>[J._def,{def:J._def,path:[...Q.basePath,Q.definitionPath,G],jsonSchema:void 0}]))}},LQ=($,Q)=>{var Y;let G=qQ(Q),J=typeof Q==="object"&&Q.definitions?Object.entries(Q.definitions).reduce((E,[U,V])=>{var w;return{...E,[U]:(w=e(V._def,{...G,currentPath:[...G.basePath,G.definitionPath,U]},!0))!=null?w:R0()}},{}):void 0,W=typeof Q==="string"?Q:(Q==null?void 0:Q.nameStrategy)==="title"?void 0:Q==null?void 0:Q.name,q=(Y=e($._def,W===void 0?G:{...G,currentPath:[...G.basePath,G.definitionPath,W]},!1))!=null?Y:R0(),L=typeof Q==="object"&&Q.name!==void 0&&Q.nameStrategy==="title"?Q.name:void 0;if(L!==void 0)q.title=L;let H=W===void 0?J?{...q,[G.definitionPath]:J}:q:{$ref:[...G.$refStrategy==="relative"?[]:G.basePath,G.definitionPath,W].join("/"),[G.definitionPath]:{...J,[W]:q}};return H.$schema="http://json-schema.org/draft-07/schema#",H},HQ=LQ;function EQ($,Q){var Y;let G=(Y=Q==null?void 0:Q.useReferences)!=null?Y:!1;return B1(()=>HQ($,{$refStrategy:G?"root":"none"}),{validate:async(J)=>{let W=await $.safeParseAsync(J);return W.success?{success:!0,value:W.data}:{success:!1,error:W.error}}})}function UQ($,Q){var Y;let G=(Y=Q==null?void 0:Q.useReferences)!=null?Y:!1;return B1(()=>S4($,{target:"draft-7",io:"output",reused:G?"ref":"inline"}),{validate:async(J)=>{let W=await O4($,J);return W.success?{success:!0,value:W.data}:{success:!1,error:W.error}}})}function jQ($){return"_zod"in $}function R($,Q){if(jQ($))return UQ($,Q);else return EQ($,Q)}var H1=Symbol.for("vercel.ai.schema");function Z($){let Q;return()=>{if(Q==null)Q=$();return Q}}function B1($,{validate:Q}={}){return{[H1]:!0,_type:void 0,[h$]:!0,get jsonSchema(){if(typeof $==="function")$=$();return $},validate:Q}}function BQ($){return typeof $==="object"&&$!==null&&H1 in $&&$[H1]===!0&&"jsonSchema"in $&&"validate"in $}function JJ($){return $==null?B1({properties:{},additionalProperties:!1}):BQ($)?$:typeof $==="function"?$():R($)}var{btoa:zQ,atob:NQ}=globalThis;function h4($){let Q=$.replace(/-/g,"+").replace(/_/g,"/"),Y=NQ(Q);return Uint8Array.from(Y,(G)=>G.codePointAt(0))}function MQ($){let Q="";for(let Y=0;Y<$.length;Y++)Q+=String.fromCodePoint($[Y]);return zQ(Q)}function K0($){return $ instanceof Uint8Array?MQ($):$}function q$($){return $==null?void 0:$.replace(/\/$/,"")}function AQ($){return $!=null&&typeof $[Symbol.asyncIterator]==="function"}async function*WJ({execute:$,input:Q,options:Y}){let G=$(Q,Y);if(AQ(G)){let J;for await(let W of G)J=W,yield{type:"preliminary",output:W};yield{type:"final",output:J}}else yield{type:"final",output:await G}}var wQ="2.0.40",DQ=Z(()=>R(X.object({type:X.literal("error"),error:X.object({type:X.string(),message:X.string()})}))),m4=W$({errorSchema:DQ,errorToMessage:($)=>$.error.message}),VQ=Z(()=>R(X.object({type:X.literal("message"),id:X.string().nullish(),model:X.string().nullish(),content:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("text"),text:X.string(),citations:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("web_search_result_location"),cited_text:X.string(),url:X.string(),title:X.string(),encrypted_index:X.string()}),X.object({type:X.literal("page_location"),cited_text:X.string(),document_index:X.number(),document_title:X.string().nullable(),start_page_number:X.number(),end_page_number:X.number()}),X.object({type:X.literal("char_location"),cited_text:X.string(),document_index:X.number(),document_title:X.string().nullable(),start_char_index:X.number(),end_char_index:X.number()})])).optional()}),X.object({type:X.literal("thinking"),thinking:X.string(),signature:X.string()}),X.object({type:X.literal("redacted_thinking"),data:X.string()}),X.object({type:X.literal("tool_use"),id:X.string(),name:X.string(),input:X.unknown()}),X.object({type:X.literal("server_tool_use"),id:X.string(),name:X.string(),input:X.record(X.string(),X.unknown()).nullish()}),X.object({type:X.literal("web_fetch_tool_result"),tool_use_id:X.string(),content:X.union([X.object({type:X.literal("web_fetch_result"),url:X.string(),retrieved_at:X.string(),content:X.object({type:X.literal("document"),title:X.string().nullable(),citations:X.object({enabled:X.boolean()}).optional(),source:X.object({type:X.literal("text"),media_type:X.string(),data:X.string()})})}),X.object({type:X.literal("web_fetch_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("web_search_tool_result"),tool_use_id:X.string(),content:X.union([X.array(X.object({type:X.literal("web_search_result"),url:X.string(),title:X.string(),encrypted_content:X.string(),page_age:X.string().nullish()})),X.object({type:X.literal("web_search_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("code_execution_tool_result"),tool_use_id:X.string(),content:X.union([X.object({type:X.literal("code_execution_result"),stdout:X.string(),stderr:X.string(),return_code:X.number()}),X.object({type:X.literal("code_execution_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("bash_code_execution_tool_result"),tool_use_id:X.string(),content:X.discriminatedUnion("type",[X.object({type:X.literal("bash_code_execution_result"),content:X.array(X.object({type:X.literal("bash_code_execution_output"),file_id:X.string()})),stdout:X.string(),stderr:X.string(),return_code:X.number()}),X.object({type:X.literal("bash_code_execution_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("text_editor_code_execution_tool_result"),tool_use_id:X.string(),content:X.discriminatedUnion("type",[X.object({type:X.literal("text_editor_code_execution_tool_result_error"),error_code:X.string()}),X.object({type:X.literal("text_editor_code_execution_view_result"),content:X.string(),file_type:X.string(),num_lines:X.number().nullable(),start_line:X.number().nullable(),total_lines:X.number().nullable()}),X.object({type:X.literal("text_editor_code_execution_create_result"),is_file_update:X.boolean()}),X.object({type:X.literal("text_editor_code_execution_str_replace_result"),lines:X.array(X.string()).nullable(),new_lines:X.number().nullable(),new_start:X.number().nullable(),old_lines:X.number().nullable(),old_start:X.number().nullable()})])})])),stop_reason:X.string().nullish(),stop_sequence:X.string().nullish(),usage:X.looseObject({input_tokens:X.number(),output_tokens:X.number(),cache_creation_input_tokens:X.number().nullish(),cache_read_input_tokens:X.number().nullish()}),container:X.object({expires_at:X.string(),id:X.string(),skills:X.array(X.object({type:X.union([X.literal("anthropic"),X.literal("custom")]),skill_id:X.string(),version:X.string()})).nullish()}).nullish()}))),KQ=Z(()=>R(X.discriminatedUnion("type",[X.object({type:X.literal("message_start"),message:X.object({id:X.string().nullish(),model:X.string().nullish(),usage:X.looseObject({input_tokens:X.number(),cache_creation_input_tokens:X.number().nullish(),cache_read_input_tokens:X.number().nullish()})})}),X.object({type:X.literal("content_block_start"),index:X.number(),content_block:X.discriminatedUnion("type",[X.object({type:X.literal("text"),text:X.string()}),X.object({type:X.literal("thinking"),thinking:X.string()}),X.object({type:X.literal("tool_use"),id:X.string(),name:X.string()}),X.object({type:X.literal("redacted_thinking"),data:X.string()}),X.object({type:X.literal("server_tool_use"),id:X.string(),name:X.string(),input:X.record(X.string(),X.unknown()).nullish()}),X.object({type:X.literal("web_fetch_tool_result"),tool_use_id:X.string(),content:X.union([X.object({type:X.literal("web_fetch_result"),url:X.string(),retrieved_at:X.string(),content:X.object({type:X.literal("document"),title:X.string().nullable(),citations:X.object({enabled:X.boolean()}).optional(),source:X.object({type:X.literal("text"),media_type:X.string(),data:X.string()})})}),X.object({type:X.literal("web_fetch_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("web_search_tool_result"),tool_use_id:X.string(),content:X.union([X.array(X.object({type:X.literal("web_search_result"),url:X.string(),title:X.string(),encrypted_content:X.string(),page_age:X.string().nullish()})),X.object({type:X.literal("web_search_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("code_execution_tool_result"),tool_use_id:X.string(),content:X.union([X.object({type:X.literal("code_execution_result"),stdout:X.string(),stderr:X.string(),return_code:X.number()}),X.object({type:X.literal("code_execution_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("bash_code_execution_tool_result"),tool_use_id:X.string(),content:X.discriminatedUnion("type",[X.object({type:X.literal("bash_code_execution_result"),content:X.array(X.object({type:X.literal("bash_code_execution_output"),file_id:X.string()})),stdout:X.string(),stderr:X.string(),return_code:X.number()}),X.object({type:X.literal("bash_code_execution_tool_result_error"),error_code:X.string()})])}),X.object({type:X.literal("text_editor_code_execution_tool_result"),tool_use_id:X.string(),content:X.discriminatedUnion("type",[X.object({type:X.literal("text_editor_code_execution_tool_result_error"),error_code:X.string()}),X.object({type:X.literal("text_editor_code_execution_view_result"),content:X.string(),file_type:X.string(),num_lines:X.number().nullable(),start_line:X.number().nullable(),total_lines:X.number().nullable()}),X.object({type:X.literal("text_editor_code_execution_create_result"),is_file_update:X.boolean()}),X.object({type:X.literal("text_editor_code_execution_str_replace_result"),lines:X.array(X.string()).nullable(),new_lines:X.number().nullable(),new_start:X.number().nullable(),old_lines:X.number().nullable(),old_start:X.number().nullable()})])})])}),X.object({type:X.literal("content_block_delta"),index:X.number(),delta:X.discriminatedUnion("type",[X.object({type:X.literal("input_json_delta"),partial_json:X.string()}),X.object({type:X.literal("text_delta"),text:X.string()}),X.object({type:X.literal("thinking_delta"),thinking:X.string()}),X.object({type:X.literal("signature_delta"),signature:X.string()}),X.object({type:X.literal("citations_delta"),citation:X.discriminatedUnion("type",[X.object({type:X.literal("web_search_result_location"),cited_text:X.string(),url:X.string(),title:X.string(),encrypted_index:X.string()}),X.object({type:X.literal("page_location"),cited_text:X.string(),document_index:X.number(),document_title:X.string().nullable(),start_page_number:X.number(),end_page_number:X.number()}),X.object({type:X.literal("char_location"),cited_text:X.string(),document_index:X.number(),document_title:X.string().nullable(),start_char_index:X.number(),end_char_index:X.number()})])})])}),X.object({type:X.literal("content_block_stop"),index:X.number()}),X.object({type:X.literal("error"),error:X.object({type:X.string(),message:X.string()})}),X.object({type:X.literal("message_delta"),delta:X.object({stop_reason:X.string().nullish(),stop_sequence:X.string().nullish(),container:X.object({expires_at:X.string(),id:X.string(),skills:X.array(X.object({type:X.union([X.literal("anthropic"),X.literal("custom")]),skill_id:X.string(),version:X.string()})).nullish()}).nullish()}),usage:X.looseObject({output_tokens:X.number(),cache_creation_input_tokens:X.number().nullish()})}),X.object({type:X.literal("message_stop")}),X.object({type:X.literal("ping")})]))),FQ=Z(()=>R(X.object({signature:X.string().optional(),redactedData:X.string().optional()}))),u4=X.object({citations:X.object({enabled:X.boolean()}).optional(),title:X.string().optional(),context:X.string().optional()}),RQ=X.object({sendReasoning:X.boolean().optional(),thinking:X.object({type:X.union([X.literal("enabled"),X.literal("disabled")]),budgetTokens:X.number().optional()}).optional(),disableParallelToolUse:X.boolean().optional(),cacheControl:X.object({type:X.literal("ephemeral"),ttl:X.union([X.literal("5m"),X.literal("1h")]).optional()}).optional(),container:X.object({id:X.string().optional(),skills:X.array(X.object({type:X.union([X.literal("anthropic"),X.literal("custom")]),skillId:X.string(),version:X.string().optional()})).optional()}).optional()}),c4=4;function SQ($){var Q;let Y=$==null?void 0:$.anthropic;return(Q=Y==null?void 0:Y.cacheControl)!=null?Q:Y==null?void 0:Y.cache_control}var z1=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl($,Q){let Y=SQ($);if(!Y)return;if(!Q.canCache){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`cache_control cannot be set on ${Q.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>c4){this.warnings.push({type:"unsupported-setting",setting:"cacheControl",details:`Maximum ${c4} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return Y}getWarnings(){return this.warnings}},OQ=Z(()=>R(X.object({maxCharacters:X.number().optional()}))),PQ=Z(()=>R(X.object({command:X.enum(["view","create","str_replace","insert"]),path:X.string(),file_text:X.string().optional(),insert_line:X.number().int().optional(),new_str:X.string().optional(),old_str:X.string().optional(),view_range:X.array(X.number().int()).optional()}))),bQ=q0({id:"anthropic.text_editor_20250728",name:"str_replace_based_edit_tool",inputSchema:PQ}),CQ=($={})=>{return bQ($)},IQ=Z(()=>R(X.object({maxUses:X.number().optional(),allowedDomains:X.array(X.string()).optional(),blockedDomains:X.array(X.string()).optional(),userLocation:X.object({type:X.literal("approximate"),city:X.string().optional(),region:X.string().optional(),country:X.string().optional(),timezone:X.string().optional()}).optional()}))),p4=Z(()=>R(X.array(X.object({url:X.string(),title:X.string(),pageAge:X.string().nullable(),encryptedContent:X.string(),type:X.literal("web_search_result")})))),_Q=Z(()=>R(X.object({query:X.string()}))),kQ=L0({id:"anthropic.web_search_20250305",name:"web_search",inputSchema:_Q,outputSchema:p4}),TQ=($={})=>{return kQ($)},ZQ=Z(()=>R(X.object({maxUses:X.number().optional(),allowedDomains:X.array(X.string()).optional(),blockedDomains:X.array(X.string()).optional(),citations:X.object({enabled:X.boolean()}).optional(),maxContentTokens:X.number().optional()}))),l4=Z(()=>R(X.object({type:X.literal("web_fetch_result"),url:X.string(),content:X.object({type:X.literal("document"),title:X.string(),citations:X.object({enabled:X.boolean()}).optional(),source:X.union([X.object({type:X.literal("base64"),mediaType:X.literal("application/pdf"),data:X.string()}),X.object({type:X.literal("text"),mediaType:X.literal("text/plain"),data:X.string()})])}),retrievedAt:X.string().nullable()}))),xQ=Z(()=>R(X.object({url:X.string()}))),vQ=L0({id:"anthropic.web_fetch_20250910",name:"web_fetch",inputSchema:xQ,outputSchema:l4}),fQ=($={})=>{return vQ($)};async function yQ({tools:$,toolChoice:Q,disableParallelToolUse:Y,cacheControlValidator:G}){$=($==null?void 0:$.length)?$:void 0;let J=[],W=new Set,q=G||new z1;if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:J,betas:W};let L=[];for(let E of $)switch(E.type){case"function":{let U=q.getCacheControl(E.providerOptions,{type:"tool definition",canCache:!0});L.push({name:E.name,description:E.description,input_schema:E.inputSchema,cache_control:U});break}case"provider-defined":{switch(E.id){case"anthropic.code_execution_20250522":{W.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":{W.add("code-execution-2025-08-25"),L.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.computer_20250124":{W.add("computer-use-2025-01-24"),L.push({name:"computer",type:"computer_20250124",display_width_px:E.args.displayWidthPx,display_height_px:E.args.displayHeightPx,display_number:E.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20241022":{W.add("computer-use-2024-10-22"),L.push({name:"computer",type:"computer_20241022",display_width_px:E.args.displayWidthPx,display_height_px:E.args.displayHeightPx,display_number:E.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{W.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":{W.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":{W.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":{let U=await B0({value:E.args,schema:OQ});L.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:U.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{W.add("computer-use-2025-01-24"),L.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{W.add("computer-use-2024-10-22"),L.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{W.add("context-management-2025-06-27"),L.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{W.add("web-fetch-2025-09-10");let U=await B0({value:E.args,schema:ZQ});L.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:U.maxUses,allowed_domains:U.allowedDomains,blocked_domains:U.blockedDomains,citations:U.citations,max_content_tokens:U.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let U=await B0({value:E.args,schema:IQ});L.push({type:"web_search_20250305",name:"web_search",max_uses:U.maxUses,allowed_domains:U.allowedDomains,blocked_domains:U.blockedDomains,user_location:U.userLocation,cache_control:void 0});break}default:{J.push({type:"unsupported-tool",tool:E});break}}break}default:{J.push({type:"unsupported-tool",tool:E});break}}if(Q==null)return{tools:L,toolChoice:Y?{type:"auto",disable_parallel_tool_use:Y}:void 0,toolWarnings:J,betas:W};let H=Q.type;switch(H){case"auto":return{tools:L,toolChoice:{type:"auto",disable_parallel_tool_use:Y},toolWarnings:J,betas:W};case"required":return{tools:L,toolChoice:{type:"any",disable_parallel_tool_use:Y},toolWarnings:J,betas:W};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:J,betas:W};case"tool":return{tools:L,toolChoice:{type:"tool",name:Q.toolName,disable_parallel_tool_use:Y},toolWarnings:J,betas:W};default:throw new o({functionality:`tool choice type: ${H}`})}}var n4=Z(()=>R(X.object({type:X.literal("code_execution_result"),stdout:X.string(),stderr:X.string(),return_code:X.number()}))),gQ=Z(()=>R(X.object({code:X.string()}))),hQ=L0({id:"anthropic.code_execution_20250522",name:"code_execution",inputSchema:gQ,outputSchema:n4}),mQ=($={})=>{return hQ($)},r4=Z(()=>R(X.discriminatedUnion("type",[X.object({type:X.literal("bash_code_execution_result"),content:X.array(X.object({type:X.literal("bash_code_execution_output"),file_id:X.string()})),stdout:X.string(),stderr:X.string(),return_code:X.number()}),X.object({type:X.literal("bash_code_execution_tool_result_error"),error_code:X.string()}),X.object({type:X.literal("text_editor_code_execution_tool_result_error"),error_code:X.string()}),X.object({type:X.literal("text_editor_code_execution_view_result"),content:X.string(),file_type:X.string(),num_lines:X.number().nullable(),start_line:X.number().nullable(),total_lines:X.number().nullable()}),X.object({type:X.literal("text_editor_code_execution_create_result"),is_file_update:X.boolean()}),X.object({type:X.literal("text_editor_code_execution_str_replace_result"),lines:X.array(X.string()).nullable(),new_lines:X.number().nullable(),new_start:X.number().nullable(),old_lines:X.number().nullable(),old_start:X.number().nullable()})]))),uQ=Z(()=>R(X.discriminatedUnion("type",[X.object({type:X.literal("bash_code_execution"),command:X.string()}),X.discriminatedUnion("command",[X.object({type:X.literal("text_editor_code_execution"),command:X.literal("view"),path:X.string()}),X.object({type:X.literal("text_editor_code_execution"),command:X.literal("create"),path:X.string(),file_text:X.string().nullish()}),X.object({type:X.literal("text_editor_code_execution"),command:X.literal("str_replace"),path:X.string(),old_str:X.string(),new_str:X.string()})])]))),cQ=L0({id:"anthropic.code_execution_20250825",name:"code_execution",inputSchema:uQ,outputSchema:r4}),dQ=($={})=>{return cQ($)};function iQ($){if(typeof $==="string")return Buffer.from($,"base64").toString("utf-8");if($ instanceof Uint8Array)return new TextDecoder().decode($);if($ instanceof URL)throw new o({functionality:"URL-based text documents are not supported for citations"});throw new o({functionality:`unsupported data type for text documents: ${typeof $}`})}async function pQ({prompt:$,sendReasoning:Q,warnings:Y,cacheControlValidator:G}){var J,W,q,L,H;let E=new Set,U=lQ($),V=G||new z1,w=void 0,B=[];async function K(A){var j,N;let M=await X0({provider:"anthropic",providerOptions:A,schema:u4});return(N=(j=M==null?void 0:M.citations)==null?void 0:j.enabled)!=null?N:!1}async function z(A){let j=await X0({provider:"anthropic",providerOptions:A,schema:u4});return{title:j==null?void 0:j.title,context:j==null?void 0:j.context}}for(let A=0;A<U.length;A++){let j=U[A],N=A===U.length-1,M=j.type;switch(M){case"system":{if(w!=null)throw new o({functionality:"Multiple system messages that are separated by user/assistant messages"});w=j.messages.map(({content:T,providerOptions:c})=>({type:"text",text:T,cache_control:V.getCacheControl(c,{type:"system message",canCache:!0})}));break}case"user":{let T=[];for(let c of j.messages){let{role:d,content:v}=c;switch(d){case"user":{for(let m=0;m<v.length;m++){let b=v[m],C=m===v.length-1,x=(J=V.getCacheControl(b.providerOptions,{type:"user message part",canCache:!0}))!=null?J:C?V.getCacheControl(c.providerOptions,{type:"user message",canCache:!0}):void 0;switch(b.type){case"text":{T.push({type:"text",text:b.text,cache_control:x});break}case"file":{if(b.mediaType.startsWith("image/"))T.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:K0(b.data)},cache_control:x});else if(b.mediaType==="application/pdf"){E.add("pdfs-2024-09-25");let y=await K(b.providerOptions),g=await z(b.providerOptions);T.push({type:"document",source:b.data instanceof URL?{type:"url",url:b.data.toString()}:{type:"base64",media_type:"application/pdf",data:K0(b.data)},title:(W=g.title)!=null?W:b.filename,...g.context&&{context:g.context},...y&&{citations:{enabled:!0}},cache_control:x})}else if(b.mediaType==="text/plain"){let y=await K(b.providerOptions),g=await z(b.providerOptions);T.push({type:"document",source:b.data instanceof URL?{type:"url",url:b.data.toString()}:{type:"text",media_type:"text/plain",data:iQ(b.data)},title:(q=g.title)!=null?q:b.filename,...g.context&&{context:g.context},...y&&{citations:{enabled:!0}},cache_control:x})}else throw new o({functionality:`media type: ${b.mediaType}`});break}}}break}case"tool":{for(let m=0;m<v.length;m++){let b=v[m],C=m===v.length-1,x=(L=V.getCacheControl(b.providerOptions,{type:"tool result part",canCache:!0}))!=null?L:C?V.getCacheControl(c.providerOptions,{type:"tool result message",canCache:!0}):void 0,y=b.output,g;switch(y.type){case"content":g=y.value.map((F)=>{switch(F.type){case"text":return{type:"text",text:F.text};case"media":{if(F.mediaType.startsWith("image/"))return{type:"image",source:{type:"base64",media_type:F.mediaType,data:F.data}};if(F.mediaType==="application/pdf")return E.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:F.mediaType,data:F.data}};throw new o({functionality:`media type: ${F.mediaType}`})}}});break;case"text":case"error-text":g=y.value;break;case"json":case"error-json":default:g=JSON.stringify(y.value);break}T.push({type:"tool_result",tool_use_id:b.toolCallId,content:g,is_error:y.type==="error-text"||y.type==="error-json"?!0:void 0,cache_control:x})}break}default:throw Error(`Unsupported role: ${d}`)}}B.push({role:"user",content:T});break}case"assistant":{let T=[];for(let c=0;c<j.messages.length;c++){let d=j.messages[c],v=c===j.messages.length-1,{content:m}=d;for(let b=0;b<m.length;b++){let C=m[b],x=b===m.length-1,y=(H=V.getCacheControl(C.providerOptions,{type:"assistant message part",canCache:!0}))!=null?H:x?V.getCacheControl(d.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(C.type){case"text":{T.push({type:"text",text:N&&v&&x?C.text.trim():C.text,cache_control:y});break}case"reasoning":{if(Q){let g=await X0({provider:"anthropic",providerOptions:C.providerOptions,schema:FQ});if(g!=null)if(g.signature!=null)V.getCacheControl(C.providerOptions,{type:"thinking block",canCache:!1}),T.push({type:"thinking",thinking:C.text,signature:g.signature});else if(g.redactedData!=null)V.getCacheControl(C.providerOptions,{type:"redacted thinking block",canCache:!1}),T.push({type:"redacted_thinking",data:g.redactedData});else Y.push({type:"other",message:"unsupported reasoning metadata"});else Y.push({type:"other",message:"unsupported reasoning metadata"})}else Y.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(C.providerExecuted){if(C.toolName==="code_execution"&&C.input!=null&&typeof C.input==="object"&&"type"in C.input&&typeof C.input.type==="string"&&(C.input.type==="bash_code_execution"||C.input.type==="text_editor_code_execution"))T.push({type:"server_tool_use",id:C.toolCallId,name:C.input.type,input:C.input,cache_control:y});else if(C.toolName==="code_execution"||C.toolName==="web_fetch"||C.toolName==="web_search")T.push({type:"server_tool_use",id:C.toolCallId,name:C.toolName,input:C.input,cache_control:y});else Y.push({type:"other",message:`provider executed tool call for tool ${C.toolName} is not supported`});break}T.push({type:"tool_use",id:C.toolCallId,name:C.toolName,input:C.input,cache_control:y});break}case"tool-result":{if(C.toolName==="code_execution"){let g=C.output;if(g.type!=="json"){Y.push({type:"other",message:`provider executed tool result output type ${g.type} for tool ${C.toolName} is not supported`});break}if(g.value==null||typeof g.value!=="object"||!("type"in g.value)||typeof g.value.type!=="string"){Y.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${C.toolName}`});break}if(g.value.type==="code_execution_result"){let F=await B0({value:g.value,schema:n4});T.push({type:"code_execution_tool_result",tool_use_id:C.toolCallId,content:{type:F.type,stdout:F.stdout,stderr:F.stderr,return_code:F.return_code},cache_control:y})}else{let F=await B0({value:g.value,schema:r4});T.push(F.type==="bash_code_execution_result"||F.type==="bash_code_execution_tool_result_error"?{type:"bash_code_execution_tool_result",tool_use_id:C.toolCallId,cache_control:y,content:F}:{type:"text_editor_code_execution_tool_result",tool_use_id:C.toolCallId,cache_control:y,content:F})}break}if(C.toolName==="web_fetch"){let g=C.output;if(g.type!=="json"){Y.push({type:"other",message:`provider executed tool result output type ${g.type} for tool ${C.toolName} is not supported`});break}let F=await B0({value:g.value,schema:l4});T.push({type:"web_fetch_tool_result",tool_use_id:C.toolCallId,content:{type:"web_fetch_result",url:F.url,retrieved_at:F.retrievedAt,content:{type:"document",title:F.content.title,citations:F.content.citations,source:{type:F.content.source.type,media_type:F.content.source.mediaType,data:F.content.source.data}}},cache_control:y});break}if(C.toolName==="web_search"){let g=C.output;if(g.type!=="json"){Y.push({type:"other",message:`provider executed tool result output type ${g.type} for tool ${C.toolName} is not supported`});break}let F=await B0({value:g.value,schema:p4});T.push({type:"web_search_tool_result",tool_use_id:C.toolCallId,content:F.map((k)=>({url:k.url,title:k.title,page_age:k.pageAge,encrypted_content:k.encryptedContent,type:k.type})),cache_control:y});break}Y.push({type:"other",message:`provider executed tool result for tool ${C.toolName} is not supported`});break}}}}B.push({role:"assistant",content:T});break}default:throw Error(`content type: ${M}`)}}return{prompt:{system:w,messages:B},betas:E}}function lQ($){let Q=[],Y=void 0;for(let G of $){let{role:J}=G;switch(J){case"system":{if((Y==null?void 0:Y.type)!=="system")Y={type:"system",messages:[]},Q.push(Y);Y.messages.push(G);break}case"assistant":{if((Y==null?void 0:Y.type)!=="assistant")Y={type:"assistant",messages:[]},Q.push(Y);Y.messages.push(G);break}case"user":{if((Y==null?void 0:Y.type)!=="user")Y={type:"user",messages:[]},Q.push(Y);Y.messages.push(G);break}case"tool":{if((Y==null?void 0:Y.type)!=="user")Y={type:"user",messages:[]},Q.push(Y);Y.messages.push(G);break}default:throw Error(`Unsupported role: ${J}`)}}return Q}function d4({finishReason:$,isJsonResponseFromTool:Q}){switch($){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return Q?"stop":"tool-calls";case"max_tokens":return"length";default:return"unknown"}}function i4($,Q,Y){var G;if($.type!=="page_location"&&$.type!=="char_location")return;let J=Q[$.document_index];if(!J)return;return{type:"source",sourceType:"document",id:Y(),mediaType:J.mediaType,title:(G=$.document_title)!=null?G:J.title,filename:J.filename,providerMetadata:{anthropic:$.type==="page_location"?{citedText:$.cited_text,startPageNumber:$.start_page_number,endPageNumber:$.end_page_number}:{citedText:$.cited_text,startCharIndex:$.start_char_index,endCharIndex:$.end_char_index}}}}var nQ=class{constructor($,Q){this.specificationVersion="v2";var Y;this.modelId=$,this.config=Q,this.generateId=(Y=Q.generateId)!=null?Y:j0}supportsUrl($){return $.protocol==="https:"}get provider(){return this.config.provider}get supportedUrls(){var $,Q,Y;return(Y=(Q=($=this.config).supportedUrls)==null?void 0:Q.call($))!=null?Y:{}}async getArgs({prompt:$,maxOutputTokens:Q,temperature:Y,topP:G,topK:J,frequencyPenalty:W,presencePenalty:q,stopSequences:L,responseFormat:H,seed:E,tools:U,toolChoice:V,providerOptions:w}){var B,K,z,A;let j=[];if(W!=null)j.push({type:"unsupported-setting",setting:"frequencyPenalty"});if(q!=null)j.push({type:"unsupported-setting",setting:"presencePenalty"});if(E!=null)j.push({type:"unsupported-setting",setting:"seed"});if((H==null?void 0:H.type)==="json"){if(H.schema==null)j.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});else if(U!=null)j.push({type:"unsupported-setting",setting:"tools",details:"JSON response format does not support tools. The provided tools are ignored."})}let N=(H==null?void 0:H.type)==="json"&&H.schema!=null?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:H.schema}:void 0,M=await X0({provider:"anthropic",providerOptions:w,schema:RQ}),T=new z1,{prompt:c,betas:d}=await pQ({prompt:$,sendReasoning:(B=M==null?void 0:M.sendReasoning)!=null?B:!0,warnings:j,cacheControlValidator:T}),v=((K=M==null?void 0:M.thinking)==null?void 0:K.type)==="enabled",m=(z=M==null?void 0:M.thinking)==null?void 0:z.budgetTokens,{maxOutputTokens:b,knownModel:C}=rQ(this.modelId),x=Q!=null?Q:b,y={model:this.modelId,max_tokens:x,temperature:Y,top_k:J,top_p:G,stop_sequences:L,...v&&{thinking:{type:"enabled",budget_tokens:m}},...(M==null?void 0:M.container)&&{container:{id:M.container.id,skills:(A=M.container.skills)==null?void 0:A.map((s)=>({type:s.type,skill_id:s.skillId,version:s.version}))}},system:c.system,messages:c.messages};if(v){if(m==null)throw new o({functionality:"thinking requires a budget"});if(y.temperature!=null)y.temperature=void 0,j.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"});if(J!=null)y.top_k=void 0,j.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"});if(G!=null)y.top_p=void 0,j.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"});y.max_tokens=x+m}if(C&&y.max_tokens>b){if(Q!=null)j.push({type:"unsupported-setting",setting:"maxOutputTokens",details:`${y.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${b} max output tokens. The max output tokens have been limited to ${b}.`});y.max_tokens=b}if((M==null?void 0:M.container)&&M.container.skills&&M.container.skills.length>0){if(d.add("code-execution-2025-08-25"),d.add("skills-2025-10-02"),d.add("files-api-2025-04-14"),!(U==null?void 0:U.some((s)=>s.type==="provider-defined"&&s.id==="anthropic.code_execution_20250825")))j.push({type:"other",message:"code execution tool is required when using skills"})}let{tools:g,toolChoice:F,toolWarnings:k,betas:P}=await yQ(N!=null?{tools:[N],toolChoice:{type:"tool",toolName:N.name},disableParallelToolUse:!0,cacheControlValidator:T}:{tools:U!=null?U:[],toolChoice:V,disableParallelToolUse:M==null?void 0:M.disableParallelToolUse,cacheControlValidator:T}),I=T.getWarnings();return{args:{...y,tools:g,tool_choice:F},warnings:[...j,...k,...I],betas:new Set([...d,...P]),usesJsonResponseTool:N!=null}}async getHeaders({betas:$,headers:Q}){return Q0(await m0(this.config.headers),$.size>0?{"anthropic-beta":Array.from($).join(",")}:{},Q)}buildRequestUrl($){var Q,Y,G;return(G=(Y=(Q=this.config).buildRequestUrl)==null?void 0:Y.call(Q,this.config.baseURL,$))!=null?G:`${this.config.baseURL}/messages`}transformRequestBody($){var Q,Y,G;return(G=(Y=(Q=this.config).transformRequestBody)==null?void 0:Y.call(Q,$))!=null?G:$}extractCitationDocuments($){let Q=(Y)=>{var G,J;if(Y.type!=="file")return!1;if(Y.mediaType!=="application/pdf"&&Y.mediaType!=="text/plain")return!1;let W=(G=Y.providerOptions)==null?void 0:G.anthropic,q=W==null?void 0:W.citations;return(J=q==null?void 0:q.enabled)!=null?J:!1};return $.filter((Y)=>Y.role==="user").flatMap((Y)=>Y.content).filter(Q).map((Y)=>{var G;let J=Y;return{title:(G=J.filename)!=null?G:"Untitled Document",filename:J.filename,mediaType:J.mediaType}})}async doGenerate($){var Q,Y,G,J,W,q,L,H;let{args:E,warnings:U,betas:V,usesJsonResponseTool:w}=await this.getArgs($),B=this.extractCitationDocuments($.prompt),{responseHeaders:K,value:z,rawValue:A}=await Y0({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:V,headers:$.headers}),body:this.transformRequestBody(E),failedResponseHandler:m4,successfulResponseHandler:U0(VQ),abortSignal:$.abortSignal,fetch:this.config.fetch}),j=[];for(let N of z.content)switch(N.type){case"text":{if(!w){if(j.push({type:"text",text:N.text}),N.citations)for(let M of N.citations){let T=i4(M,B,this.generateId);if(T)j.push(T)}}break}case"thinking":{j.push({type:"reasoning",text:N.thinking,providerMetadata:{anthropic:{signature:N.signature}}});break}case"redacted_thinking":{j.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:N.data}}});break}case"tool_use":{j.push(w?{type:"text",text:JSON.stringify(N.input)}:{type:"tool-call",toolCallId:N.id,toolName:N.name,input:JSON.stringify(N.input)});break}case"server_tool_use":{if(N.name==="text_editor_code_execution"||N.name==="bash_code_execution")j.push({type:"tool-call",toolCallId:N.id,toolName:"code_execution",input:JSON.stringify({type:N.name,...N.input}),providerExecuted:!0});else if(N.name==="web_search"||N.name==="code_execution"||N.name==="web_fetch")j.push({type:"tool-call",toolCallId:N.id,toolName:N.name,input:JSON.stringify(N.input),providerExecuted:!0});break}case"web_fetch_tool_result":{if(N.content.type==="web_fetch_result")j.push({type:"tool-result",toolCallId:N.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:N.content.url,retrievedAt:N.content.retrieved_at,content:{type:N.content.content.type,title:N.content.content.title,citations:N.content.content.citations,source:{type:N.content.content.source.type,mediaType:N.content.content.source.media_type,data:N.content.content.source.data}}},providerExecuted:!0});else if(N.content.type==="web_fetch_tool_result_error")j.push({type:"tool-result",toolCallId:N.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:N.content.error_code},providerExecuted:!0});break}case"web_search_tool_result":{if(Array.isArray(N.content)){j.push({type:"tool-result",toolCallId:N.tool_use_id,toolName:"web_search",result:N.content.map((M)=>{var T;return{url:M.url,title:M.title,pageAge:(T=M.page_age)!=null?T:null,encryptedContent:M.encrypted_content,type:M.type}}),providerExecuted:!0});for(let M of N.content)j.push({type:"source",sourceType:"url",id:this.generateId(),url:M.url,title:M.title,providerMetadata:{anthropic:{pageAge:(Q=M.page_age)!=null?Q:null}}})}else j.push({type:"tool-result",toolCallId:N.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:N.content.error_code},providerExecuted:!0});break}case"code_execution_tool_result":{if(N.content.type==="code_execution_result")j.push({type:"tool-result",toolCallId:N.tool_use_id,toolName:"code_execution",result:{type:N.content.type,stdout:N.content.stdout,stderr:N.content.stderr,return_code:N.content.return_code},providerExecuted:!0});else if(N.content.type==="code_execution_tool_result_error")j.push({type:"tool-result",toolCallId:N.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:N.content.error_code},providerExecuted:!0});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{j.push({type:"tool-result",toolCallId:N.tool_use_id,toolName:"code_execution",result:N.content,providerExecuted:!0});break}}return{content:j,finishReason:d4({finishReason:z.stop_reason,isJsonResponseFromTool:w}),usage:{inputTokens:z.usage.input_tokens,outputTokens:z.usage.output_tokens,totalTokens:z.usage.input_tokens+z.usage.output_tokens,cachedInputTokens:(Y=z.usage.cache_read_input_tokens)!=null?Y:void 0},request:{body:E},response:{id:(G=z.id)!=null?G:void 0,modelId:(J=z.model)!=null?J:void 0,headers:K,body:A},warnings:U,providerMetadata:{anthropic:{usage:z.usage,cacheCreationInputTokens:(W=z.usage.cache_creation_input_tokens)!=null?W:null,stopSequence:(q=z.stop_sequence)!=null?q:null,container:z.container?{expiresAt:z.container.expires_at,id:z.container.id,skills:(H=(L=z.container.skills)==null?void 0:L.map((N)=>({type:N.type,skillId:N.skill_id,version:N.version})))!=null?H:null}:null}}}}async doStream($){let{args:Q,warnings:Y,betas:G,usesJsonResponseTool:J}=await this.getArgs($),W=this.extractCitationDocuments($.prompt),q={...Q,stream:!0},{responseHeaders:L,value:H}=await Y0({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:G,headers:$.headers}),body:this.transformRequestBody(q),failedResponseHandler:m4,successfulResponseHandler:T0(KQ),abortSignal:$.abortSignal,fetch:this.config.fetch}),E="unknown",U={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},V={},w=void 0,B=null,K=null,z=null,A=void 0,j=this.generateId;return{stream:H.pipeThrough(new TransformStream({start(N){N.enqueue({type:"stream-start",warnings:Y})},transform(N,M){var T,c,d,v,m,b,C,x,y,g;if($.includeRawChunks)M.enqueue({type:"raw",rawValue:N.rawValue});if(!N.success){M.enqueue({type:"error",error:N.error});return}let F=N.value;switch(F.type){case"ping":return;case"content_block_start":{let k=F.content_block.type;switch(A=k,k){case"text":{V[F.index]={type:"text"},M.enqueue({type:"text-start",id:String(F.index)});return}case"thinking":{V[F.index]={type:"reasoning"},M.enqueue({type:"reasoning-start",id:String(F.index)});return}case"redacted_thinking":{V[F.index]={type:"reasoning"},M.enqueue({type:"reasoning-start",id:String(F.index),providerMetadata:{anthropic:{redactedData:F.content_block.data}}});return}case"tool_use":{V[F.index]=J?{type:"text"}:{type:"tool-call",toolCallId:F.content_block.id,toolName:F.content_block.name,input:"",firstDelta:!0},M.enqueue(J?{type:"text-start",id:String(F.index)}:{type:"tool-input-start",id:F.content_block.id,toolName:F.content_block.name});return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(F.content_block.name)){V[F.index]={type:"tool-call",toolCallId:F.content_block.id,toolName:F.content_block.name,input:"",providerExecuted:!0,firstDelta:!0};let P=F.content_block.name==="text_editor_code_execution"||F.content_block.name==="bash_code_execution"?"code_execution":F.content_block.name;M.enqueue({type:"tool-input-start",id:F.content_block.id,toolName:P,providerExecuted:!0})}return}case"web_fetch_tool_result":{let P=F.content_block;if(P.content.type==="web_fetch_result")M.enqueue({type:"tool-result",toolCallId:P.tool_use_id,toolName:"web_fetch",result:{type:"web_fetch_result",url:P.content.url,retrievedAt:P.content.retrieved_at,content:{type:P.content.content.type,title:P.content.content.title,citations:P.content.content.citations,source:{type:P.content.content.source.type,mediaType:P.content.content.source.media_type,data:P.content.content.source.data}}}});else if(P.content.type==="web_fetch_tool_result_error")M.enqueue({type:"tool-result",toolCallId:P.tool_use_id,toolName:"web_fetch",isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:P.content.error_code},providerExecuted:!0});return}case"web_search_tool_result":{let P=F.content_block;if(Array.isArray(P.content)){M.enqueue({type:"tool-result",toolCallId:P.tool_use_id,toolName:"web_search",result:P.content.map((I)=>{var s;return{url:I.url,title:I.title,pageAge:(s=I.page_age)!=null?s:null,encryptedContent:I.encrypted_content,type:I.type}}),providerExecuted:!0});for(let I of P.content)M.enqueue({type:"source",sourceType:"url",id:j(),url:I.url,title:I.title,providerMetadata:{anthropic:{pageAge:(T=I.page_age)!=null?T:null}}})}else M.enqueue({type:"tool-result",toolCallId:P.tool_use_id,toolName:"web_search",isError:!0,result:{type:"web_search_tool_result_error",errorCode:P.content.error_code},providerExecuted:!0});return}case"code_execution_tool_result":{let P=F.content_block;if(P.content.type==="code_execution_result")M.enqueue({type:"tool-result",toolCallId:P.tool_use_id,toolName:"code_execution",result:{type:P.content.type,stdout:P.content.stdout,stderr:P.content.stderr,return_code:P.content.return_code},providerExecuted:!0});else if(P.content.type==="code_execution_tool_result_error")M.enqueue({type:"tool-result",toolCallId:P.tool_use_id,toolName:"code_execution",isError:!0,result:{type:"code_execution_tool_result_error",errorCode:P.content.error_code},providerExecuted:!0});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{let P=F.content_block;M.enqueue({type:"tool-result",toolCallId:P.tool_use_id,toolName:"code_execution",result:P.content,providerExecuted:!0});return}default:throw Error(`Unsupported content block type: ${k}`)}}case"content_block_stop":{if(V[F.index]!=null){let k=V[F.index];switch(k.type){case"text":{M.enqueue({type:"text-end",id:String(F.index)});break}case"reasoning":{M.enqueue({type:"reasoning-end",id:String(F.index)});break}case"tool-call":if(!J){M.enqueue({type:"tool-input-end",id:k.toolCallId});let P=k.toolName==="text_editor_code_execution"||k.toolName==="bash_code_execution"?"code_execution":k.toolName;M.enqueue({type:"tool-call",toolCallId:k.toolCallId,toolName:P,input:k.input,providerExecuted:k.providerExecuted})}break}delete V[F.index]}A=void 0;return}case"content_block_delta":{let k=F.delta.type;switch(k){case"text_delta":{if(J)return;M.enqueue({type:"text-delta",id:String(F.index),delta:F.delta.text});return}case"thinking_delta":{M.enqueue({type:"reasoning-delta",id:String(F.index),delta:F.delta.thinking});return}case"signature_delta":{if(A==="thinking")M.enqueue({type:"reasoning-delta",id:String(F.index),delta:"",providerMetadata:{anthropic:{signature:F.delta.signature}}});return}case"input_json_delta":{let P=V[F.index],I=F.delta.partial_json;if(I.length===0)return;if(J){if((P==null?void 0:P.type)!=="text")return;M.enqueue({type:"text-delta",id:String(F.index),delta:I})}else{if((P==null?void 0:P.type)!=="tool-call")return;if(P.firstDelta&&(P.toolName==="bash_code_execution"||P.toolName==="text_editor_code_execution"))I=`{"type": "${P.toolName}",${I.substring(1)}`;M.enqueue({type:"tool-input-delta",id:P.toolCallId,delta:I}),P.input+=I,P.firstDelta=!1}return}case"citations_delta":{let P=F.delta.citation,I=i4(P,W,j);if(I)M.enqueue(I);return}default:throw Error(`Unsupported delta type: ${k}`)}}case"message_start":{U.inputTokens=F.message.usage.input_tokens,U.cachedInputTokens=(c=F.message.usage.cache_read_input_tokens)!=null?c:void 0,w={...F.message.usage},B=(d=F.message.usage.cache_creation_input_tokens)!=null?d:null,M.enqueue({type:"response-metadata",id:(v=F.message.id)!=null?v:void 0,modelId:(m=F.message.model)!=null?m:void 0});return}case"message_delta":{U.outputTokens=F.usage.output_tokens,U.totalTokens=((b=U.inputTokens)!=null?b:0)+((C=F.usage.output_tokens)!=null?C:0),E=d4({finishReason:F.delta.stop_reason,isJsonResponseFromTool:J}),K=(x=F.delta.stop_sequence)!=null?x:null,z=F.delta.container!=null?{expiresAt:F.delta.container.expires_at,id:F.delta.container.id,skills:(g=(y=F.delta.container.skills)==null?void 0:y.map((k)=>({type:k.type,skillId:k.skill_id,version:k.version})))!=null?g:null}:null,w={...w,...F.usage};return}case"message_stop":{M.enqueue({type:"finish",finishReason:E,usage:U,providerMetadata:{anthropic:{usage:w!=null?w:null,cacheCreationInputTokens:B,stopSequence:K,container:z}}});return}case"error":{M.enqueue({type:"error",error:F.error});return}default:throw Error(`Unsupported chunk type: ${F}`)}}})),request:{body:q},response:{headers:L}}}};function rQ($){if($.includes("claude-sonnet-4-")||$.includes("claude-3-7-sonnet")||$.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,knownModel:!0};else if($.includes("claude-opus-4-"))return{maxOutputTokens:32000,knownModel:!0};else if($.includes("claude-3-5-haiku"))return{maxOutputTokens:8192,knownModel:!0};else if($.includes("claude-3-haiku"))return{maxOutputTokens:4096,knownModel:!0};else return{maxOutputTokens:4096,knownModel:!1}}var aQ=Z(()=>R(X.object({command:X.string(),restart:X.boolean().optional()}))),sQ=q0({id:"anthropic.bash_20241022",name:"bash",inputSchema:aQ}),tQ=Z(()=>R(X.object({command:X.string(),restart:X.boolean().optional()}))),oQ=q0({id:"anthropic.bash_20250124",name:"bash",inputSchema:tQ}),eQ=Z(()=>R(X.object({action:X.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:X.array(X.number().int()).optional(),text:X.string().optional()}))),$Y=q0({id:"anthropic.computer_20241022",name:"computer",inputSchema:eQ}),XY=Z(()=>R(X.object({action:X.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:X.tuple([X.number().int(),X.number().int()]).optional(),duration:X.number().optional(),scroll_amount:X.number().optional(),scroll_direction:X.enum(["up","down","left","right"]).optional(),start_coordinate:X.tuple([X.number().int(),X.number().int()]).optional(),text:X.string().optional()}))),QY=q0({id:"anthropic.computer_20250124",name:"computer",inputSchema:XY}),YY=Z(()=>R(X.discriminatedUnion("command",[X.object({command:X.literal("view"),path:X.string(),view_range:X.tuple([X.number(),X.number()]).optional()}),X.object({command:X.literal("create"),path:X.string(),file_text:X.string()}),X.object({command:X.literal("str_replace"),path:X.string(),old_str:X.string(),new_str:X.string()}),X.object({command:X.literal("insert"),path:X.string(),insert_line:X.number(),insert_text:X.string()}),X.object({command:X.literal("delete"),path:X.string()}),X.object({command:X.literal("rename"),old_path:X.string(),new_path:X.string()})]))),GY=q0({id:"anthropic.memory_20250818",name:"memory",inputSchema:YY}),JY=Z(()=>R(X.object({command:X.enum(["view","create","str_replace","insert","undo_edit"]),path:X.string(),file_text:X.string().optional(),insert_line:X.number().int().optional(),new_str:X.string().optional(),old_str:X.string().optional(),view_range:X.array(X.number().int()).optional()}))),WY=q0({id:"anthropic.text_editor_20241022",name:"str_replace_editor",inputSchema:JY}),qY=Z(()=>R(X.object({command:X.enum(["view","create","str_replace","insert","undo_edit"]),path:X.string(),file_text:X.string().optional(),insert_line:X.number().int().optional(),new_str:X.string().optional(),old_str:X.string().optional(),view_range:X.array(X.number().int()).optional()}))),LY=q0({id:"anthropic.text_editor_20250124",name:"str_replace_editor",inputSchema:qY}),HY=Z(()=>R(X.object({command:X.enum(["view","create","str_replace","insert"]),path:X.string(),file_text:X.string().optional(),insert_line:X.number().int().optional(),new_str:X.string().optional(),old_str:X.string().optional(),view_range:X.array(X.number().int()).optional()}))),EY=q0({id:"anthropic.text_editor_20250429",name:"str_replace_based_edit_tool",inputSchema:HY}),UY={bash_20241022:sQ,bash_20250124:oQ,codeExecution_20250522:mQ,codeExecution_20250825:dQ,computer_20241022:$Y,computer_20250124:QY,memory_20250818:GY,textEditor_20241022:WY,textEditor_20250124:LY,textEditor_20250429:EY,textEditor_20250728:CQ,webFetch_20250910:fQ,webSearch_20250305:TQ};function jY($={}){var Q;let Y=(Q=q$(m$({settingValue:$.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?Q:"https://api.anthropic.com/v1",G=()=>p0({"anthropic-version":"2023-06-01","x-api-key":J$({apiKey:$.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...$.headers},`ai-sdk/anthropic/${wQ}`),J=(q)=>{var L;return new nQ(q,{provider:"anthropic.messages",baseURL:Y,headers:G,fetch:$.fetch,generateId:(L=$.generateId)!=null?L:j0,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},W=function(q){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return J(q)};return W.languageModel=J,W.chat=J,W.messages=J,W.textEmbeddingModel=(q)=>{throw new s$({modelId:q,modelType:"textEmbeddingModel"})},W.imageModel=(q)=>{throw new s$({modelId:q,modelType:"imageModel"})},W.tools=UY,W}var a4=jY();var N1=null;async function BY(){if(N1)return N1;try{let $=await fetch("https://models.dev/api.json",{headers:{"User-Agent":"sylphx-flow/1.0"}});if(!$.ok)throw Error(`Failed to fetch models.dev: ${$.status}`);let Q=await $.json(),Y=new Map;for(let G of Q.models)Y.set(G.id,{id:G.id,name:G.name,contextLength:G.context_length,maxOutput:G.max_output,inputPrice:G.pricing?.input,outputPrice:G.pricing?.output,provider:G.provider,description:G.description});return N1=Y,Y}catch($){return console.error("Failed to fetch models.dev:",$),new Map}}async function l0($){return(await BY()).get($)||null}var zY=[{id:"claude-3-5-sonnet-20241022",name:"Claude 3.5 Sonnet (Latest)"},{id:"claude-3-5-haiku-20241022",name:"Claude 3.5 Haiku"},{id:"claude-3-opus-20240229",name:"Claude 3 Opus"},{id:"claude-3-sonnet-20240229",name:"Claude 3 Sonnet"},{id:"claude-3-haiku-20240307",name:"Claude 3 Haiku"}],s4={"claude-3-5-sonnet-20241022":{contextLength:200000,maxOutput:8192},"claude-3-5-haiku-20241022":{contextLength:200000,maxOutput:8192},"claude-3-opus-20240229":{contextLength:200000,maxOutput:4096},"claude-3-sonnet-20240229":{contextLength:200000,maxOutput:4096},"claude-3-haiku-20240307":{contextLength:200000,maxOutput:4096}};class M1{id="anthropic";name="Anthropic";keyName="ANTHROPIC_API_KEY";async fetchModels(){return zY}async getModelDetails($){if(s4[$])return s4[$];let Q=await l0($);if(Q)return{contextLength:Q.contextLength,maxOutput:Q.maxOutput,inputPrice:Q.inputPrice,outputPrice:Q.outputPrice};return null}createClient($,Q){return a4(Q,{apiKey:$})}}var A1=X.object({error:X.object({message:X.string(),type:X.string().nullish(),param:X.any().nullish(),code:X.union([X.string(),X.number()]).nullish()})}),Z0=W$({errorSchema:A1,errorToMessage:($)=>$.error.message});function NY({prompt:$,systemMessageMode:Q="system"}){let Y=[],G=[];for(let{role:J,content:W}of $)switch(J){case"system":{switch(Q){case"system":{Y.push({role:"system",content:W});break}case"developer":{Y.push({role:"developer",content:W});break}case"remove":{G.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${Q}`)}break}case"user":{if(W.length===1&&W[0].type==="text"){Y.push({role:"user",content:W[0].text});break}Y.push({role:"user",content:W.map((q,L)=>{var H,E,U;switch(q.type){case"text":return{type:"text",text:q.text};case"file":if(q.mediaType.startsWith("image/")){let V=q.mediaType==="image/*"?"image/jpeg":q.mediaType;return{type:"image_url",image_url:{url:q.data instanceof URL?q.data.toString():`data:${V};base64,${K0(q.data)}`,detail:(E=(H=q.providerOptions)==null?void 0:H.openai)==null?void 0:E.imageDetail}}}else if(q.mediaType.startsWith("audio/")){if(q.data instanceof URL)throw new o({functionality:"audio file parts with URLs"});switch(q.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:K0(q.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:K0(q.data),format:"mp3"}};default:throw new o({functionality:`audio content parts with media type ${q.mediaType}`})}}else if(q.mediaType==="application/pdf"){if(q.data instanceof URL)throw new o({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof q.data==="string"&&q.data.startsWith("file-")?{file_id:q.data}:{filename:(U=q.filename)!=null?U:`part-${L}.pdf`,file_data:`data:application/pdf;base64,${K0(q.data)}`}}}else throw new o({functionality:`file part media type ${q.mediaType}`})}})});break}case"assistant":{let q="",L=[];for(let H of W)switch(H.type){case"text":{q+=H.text;break}case"tool-call":{L.push({id:H.toolCallId,type:"function",function:{name:H.toolName,arguments:JSON.stringify(H.input)}});break}}Y.push({role:"assistant",content:q,tool_calls:L.length>0?L:void 0});break}case"tool":{for(let q of W){let L=q.output,H;switch(L.type){case"text":case"error-text":H=L.value;break;case"content":case"json":case"error-json":H=JSON.stringify(L.value);break}Y.push({role:"tool",tool_call_id:q.toolCallId,content:H})}break}default:throw Error(`Unsupported role: ${J}`)}return{messages:Y,warnings:G}}function t4({id:$,model:Q,created:Y}){return{id:$!=null?$:void 0,modelId:Q!=null?Q:void 0,timestamp:Y!=null?new Date(Y*1000):void 0}}function o4($){switch($){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 MY=$0(()=>R(X.object({id:X.string().nullish(),created:X.number().nullish(),model:X.string().nullish(),choices:X.array(X.object({message:X.object({role:X.literal("assistant").nullish(),content:X.string().nullish(),tool_calls:X.array(X.object({id:X.string().nullish(),type:X.literal("function"),function:X.object({name:X.string(),arguments:X.string()})})).nullish(),annotations:X.array(X.object({type:X.literal("url_citation"),start_index:X.number(),end_index:X.number(),url:X.string(),title:X.string()})).nullish()}),index:X.number(),logprobs:X.object({content:X.array(X.object({token:X.string(),logprob:X.number(),top_logprobs:X.array(X.object({token:X.string(),logprob:X.number()}))})).nullish()}).nullish(),finish_reason:X.string().nullish()})),usage:X.object({prompt_tokens:X.number().nullish(),completion_tokens:X.number().nullish(),total_tokens:X.number().nullish(),prompt_tokens_details:X.object({cached_tokens:X.number().nullish()}).nullish(),completion_tokens_details:X.object({reasoning_tokens:X.number().nullish(),accepted_prediction_tokens:X.number().nullish(),rejected_prediction_tokens:X.number().nullish()}).nullish()}).nullish()}))),AY=$0(()=>R(X.union([X.object({id:X.string().nullish(),created:X.number().nullish(),model:X.string().nullish(),choices:X.array(X.object({delta:X.object({role:X.enum(["assistant"]).nullish(),content:X.string().nullish(),tool_calls:X.array(X.object({index:X.number(),id:X.string().nullish(),type:X.literal("function").nullish(),function:X.object({name:X.string().nullish(),arguments:X.string().nullish()})})).nullish(),annotations:X.array(X.object({type:X.literal("url_citation"),start_index:X.number(),end_index:X.number(),url:X.string(),title:X.string()})).nullish()}).nullish(),logprobs:X.object({content:X.array(X.object({token:X.string(),logprob:X.number(),top_logprobs:X.array(X.object({token:X.string(),logprob:X.number()}))})).nullish()}).nullish(),finish_reason:X.string().nullish(),index:X.number()})),usage:X.object({prompt_tokens:X.number().nullish(),completion_tokens:X.number().nullish(),total_tokens:X.number().nullish(),prompt_tokens_details:X.object({cached_tokens:X.number().nullish()}).nullish(),completion_tokens_details:X.object({reasoning_tokens:X.number().nullish(),accepted_prediction_tokens:X.number().nullish(),rejected_prediction_tokens:X.number().nullish()}).nullish()}).nullish()}),A1]))),wY=$0(()=>R(X.object({logitBias:X.record(X.coerce.number(),X.number()).optional(),logprobs:X.union([X.boolean(),X.number()]).optional(),parallelToolCalls:X.boolean().optional(),user:X.string().optional(),reasoningEffort:X.enum(["minimal","low","medium","high"]).optional(),maxCompletionTokens:X.number().optional(),store:X.boolean().optional(),metadata:X.record(X.string().max(64),X.string().max(512)).optional(),prediction:X.record(X.string(),X.any()).optional(),structuredOutputs:X.boolean().optional(),serviceTier:X.enum(["auto","flex","priority","default"]).optional(),strictJsonSchema:X.boolean().optional(),textVerbosity:X.enum(["low","medium","high"]).optional(),promptCacheKey:X.string().optional(),safetyIdentifier:X.string().optional()})));function DY({tools:$,toolChoice:Q,structuredOutputs:Y,strictJsonSchema:G}){$=($==null?void 0:$.length)?$:void 0;let J=[];if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:J};let W=[];for(let L of $)switch(L.type){case"function":W.push({type:"function",function:{name:L.name,description:L.description,parameters:L.inputSchema,strict:Y?G:void 0}});break;default:J.push({type:"unsupported-tool",tool:L});break}if(Q==null)return{tools:W,toolChoice:void 0,toolWarnings:J};let q=Q.type;switch(q){case"auto":case"none":case"required":return{tools:W,toolChoice:q,toolWarnings:J};case"tool":return{tools:W,toolChoice:{type:"function",function:{name:Q.toolName}},toolWarnings:J};default:throw new o({functionality:`tool choice type: ${q}`})}}var VY=class{constructor($,Q){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=$,this.config=Q}get provider(){return this.config.provider}async getArgs({prompt:$,maxOutputTokens:Q,temperature:Y,topP:G,topK:J,frequencyPenalty:W,presencePenalty:q,stopSequences:L,responseFormat:H,seed:E,tools:U,toolChoice:V,providerOptions:w}){var B,K,z,A;let j=[],N=(B=await X0({provider:"openai",providerOptions:w,schema:wY}))!=null?B:{},M=(K=N.structuredOutputs)!=null?K:!0;if(J!=null)j.push({type:"unsupported-setting",setting:"topK"});if((H==null?void 0:H.type)==="json"&&H.schema!=null&&!M)j.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let{messages:T,warnings:c}=NY({prompt:$,systemMessageMode:RY(this.modelId)});j.push(...c);let d=(z=N.strictJsonSchema)!=null?z:!1,v={model:this.modelId,logit_bias:N.logitBias,logprobs:N.logprobs===!0||typeof N.logprobs==="number"?!0:void 0,top_logprobs:typeof N.logprobs==="number"?N.logprobs:typeof N.logprobs==="boolean"?N.logprobs?0:void 0:void 0,user:N.user,parallel_tool_calls:N.parallelToolCalls,max_tokens:Q,temperature:Y,top_p:G,frequency_penalty:W,presence_penalty:q,response_format:(H==null?void 0:H.type)==="json"?M&&H.schema!=null?{type:"json_schema",json_schema:{schema:H.schema,strict:d,name:(A=H.name)!=null?A:"response",description:H.description}}:{type:"json_object"}:void 0,stop:L,seed:E,verbosity:N.textVerbosity,max_completion_tokens:N.maxCompletionTokens,store:N.store,metadata:N.metadata,prediction:N.prediction,reasoning_effort:N.reasoningEffort,service_tier:N.serviceTier,prompt_cache_key:N.promptCacheKey,safety_identifier:N.safetyIdentifier,messages:T};if(q8(this.modelId)){if(v.temperature!=null)v.temperature=void 0,j.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"});if(v.top_p!=null)v.top_p=void 0,j.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"});if(v.frequency_penalty!=null)v.frequency_penalty=void 0,j.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"});if(v.presence_penalty!=null)v.presence_penalty=void 0,j.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"});if(v.logit_bias!=null)v.logit_bias=void 0,j.push({type:"other",message:"logitBias is not supported for reasoning models"});if(v.logprobs!=null)v.logprobs=void 0,j.push({type:"other",message:"logprobs is not supported for reasoning models"});if(v.top_logprobs!=null)v.top_logprobs=void 0,j.push({type:"other",message:"topLogprobs is not supported for reasoning models"});if(v.max_tokens!=null){if(v.max_completion_tokens==null)v.max_completion_tokens=v.max_tokens;v.max_tokens=void 0}}else if(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview")){if(v.temperature!=null)v.temperature=void 0,j.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})}if(N.serviceTier==="flex"&&!KY(this.modelId))j.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),v.service_tier=void 0;if(N.serviceTier==="priority"&&!FY(this.modelId))j.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"}),v.service_tier=void 0;let{tools:m,toolChoice:b,toolWarnings:C}=DY({tools:U,toolChoice:V,structuredOutputs:M,strictJsonSchema:d});return{args:{...v,tools:m,tool_choice:b},warnings:[...j,...C]}}async doGenerate($){var Q,Y,G,J,W,q,L,H,E,U,V,w,B,K;let{args:z,warnings:A}=await this.getArgs($),{responseHeaders:j,value:N,rawValue:M}=await Y0({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Q0(this.config.headers(),$.headers),body:z,failedResponseHandler:Z0,successfulResponseHandler:U0(MY),abortSignal:$.abortSignal,fetch:this.config.fetch}),T=N.choices[0],c=[],d=T.message.content;if(d!=null&&d.length>0)c.push({type:"text",text:d});for(let C of(Q=T.message.tool_calls)!=null?Q:[])c.push({type:"tool-call",toolCallId:(Y=C.id)!=null?Y:j0(),toolName:C.function.name,input:C.function.arguments});for(let C of(G=T.message.annotations)!=null?G:[])c.push({type:"source",sourceType:"url",id:j0(),url:C.url,title:C.title});let v=(J=N.usage)==null?void 0:J.completion_tokens_details,m=(W=N.usage)==null?void 0:W.prompt_tokens_details,b={openai:{}};if((v==null?void 0:v.accepted_prediction_tokens)!=null)b.openai.acceptedPredictionTokens=v==null?void 0:v.accepted_prediction_tokens;if((v==null?void 0:v.rejected_prediction_tokens)!=null)b.openai.rejectedPredictionTokens=v==null?void 0:v.rejected_prediction_tokens;if(((q=T.logprobs)==null?void 0:q.content)!=null)b.openai.logprobs=T.logprobs.content;return{content:c,finishReason:o4(T.finish_reason),usage:{inputTokens:(H=(L=N.usage)==null?void 0:L.prompt_tokens)!=null?H:void 0,outputTokens:(U=(E=N.usage)==null?void 0:E.completion_tokens)!=null?U:void 0,totalTokens:(w=(V=N.usage)==null?void 0:V.total_tokens)!=null?w:void 0,reasoningTokens:(B=v==null?void 0:v.reasoning_tokens)!=null?B:void 0,cachedInputTokens:(K=m==null?void 0:m.cached_tokens)!=null?K:void 0},request:{body:z},response:{...t4(N),headers:j,body:M},warnings:A,providerMetadata:b}}async doStream($){let{args:Q,warnings:Y}=await this.getArgs($),G={...Q,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:J,value:W}=await Y0({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Q0(this.config.headers(),$.headers),body:G,failedResponseHandler:Z0,successfulResponseHandler:T0(AY),abortSignal:$.abortSignal,fetch:this.config.fetch}),q=[],L="unknown",H={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},E=!0,U=!1,V={openai:{}};return{stream:W.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:Y})},transform(w,B){var K,z,A,j,N,M,T,c,d,v,m,b,C,x,y,g,F,k,P,I,s,l,N0,p;if($.includeRawChunks)B.enqueue({type:"raw",rawValue:w.rawValue});if(!w.success){L="error",B.enqueue({type:"error",error:w.error});return}let G0=w.value;if("error"in G0){L="error",B.enqueue({type:"error",error:G0.error});return}if(E)E=!1,B.enqueue({type:"response-metadata",...t4(G0)});if(G0.usage!=null){if(H.inputTokens=(K=G0.usage.prompt_tokens)!=null?K:void 0,H.outputTokens=(z=G0.usage.completion_tokens)!=null?z:void 0,H.totalTokens=(A=G0.usage.total_tokens)!=null?A:void 0,H.reasoningTokens=(N=(j=G0.usage.completion_tokens_details)==null?void 0:j.reasoning_tokens)!=null?N:void 0,H.cachedInputTokens=(T=(M=G0.usage.prompt_tokens_details)==null?void 0:M.cached_tokens)!=null?T:void 0,((c=G0.usage.completion_tokens_details)==null?void 0:c.accepted_prediction_tokens)!=null)V.openai.acceptedPredictionTokens=(d=G0.usage.completion_tokens_details)==null?void 0:d.accepted_prediction_tokens;if(((v=G0.usage.completion_tokens_details)==null?void 0:v.rejected_prediction_tokens)!=null)V.openai.rejectedPredictionTokens=(m=G0.usage.completion_tokens_details)==null?void 0:m.rejected_prediction_tokens}let h=G0.choices[0];if((h==null?void 0:h.finish_reason)!=null)L=o4(h.finish_reason);if(((b=h==null?void 0:h.logprobs)==null?void 0:b.content)!=null)V.openai.logprobs=h.logprobs.content;if((h==null?void 0:h.delta)==null)return;let D=h.delta;if(D.content!=null){if(!U)B.enqueue({type:"text-start",id:"0"}),U=!0;B.enqueue({type:"text-delta",id:"0",delta:D.content})}if(D.tool_calls!=null)for(let n of D.tool_calls){let C0=n.index;if(q[C0]==null){if(n.type!=="function")throw new C$({data:n,message:"Expected 'function' type."});if(n.id==null)throw new C$({data:n,message:"Expected 'id' to be a string."});if(((C=n.function)==null?void 0:C.name)==null)throw new C$({data:n,message:"Expected 'function.name' to be a string."});B.enqueue({type:"tool-input-start",id:n.id,toolName:n.function.name}),q[C0]={id:n.id,type:"function",function:{name:n.function.name,arguments:(x=n.function.arguments)!=null?x:""},hasFinished:!1};let V0=q[C0];if(((y=V0.function)==null?void 0:y.name)!=null&&((g=V0.function)==null?void 0:g.arguments)!=null){if(V0.function.arguments.length>0)B.enqueue({type:"tool-input-delta",id:V0.id,delta:V0.function.arguments});if(j1(V0.function.arguments))B.enqueue({type:"tool-input-end",id:V0.id}),B.enqueue({type:"tool-call",toolCallId:(F=V0.id)!=null?F:j0(),toolName:V0.function.name,input:V0.function.arguments}),V0.hasFinished=!0}continue}let M0=q[C0];if(M0.hasFinished)continue;if(((k=n.function)==null?void 0:k.arguments)!=null)M0.function.arguments+=(I=(P=n.function)==null?void 0:P.arguments)!=null?I:"";if(B.enqueue({type:"tool-input-delta",id:M0.id,delta:(s=n.function.arguments)!=null?s:""}),((l=M0.function)==null?void 0:l.name)!=null&&((N0=M0.function)==null?void 0:N0.arguments)!=null&&j1(M0.function.arguments))B.enqueue({type:"tool-input-end",id:M0.id}),B.enqueue({type:"tool-call",toolCallId:(p=M0.id)!=null?p:j0(),toolName:M0.function.name,input:M0.function.arguments}),M0.hasFinished=!0}if(D.annotations!=null)for(let n of D.annotations)B.enqueue({type:"source",sourceType:"url",id:j0(),url:n.url,title:n.title})},flush(w){if(U)w.enqueue({type:"text-end",id:"0"});w.enqueue({type:"finish",finishReason:L,usage:H,...V!=null?{providerMetadata:V}:{}})}})),request:{body:G},response:{headers:J}}}};function q8($){return($.startsWith("o")||$.startsWith("gpt-5"))&&!$.startsWith("gpt-5-chat")}function KY($){return $.startsWith("o3")||$.startsWith("o4-mini")||$.startsWith("gpt-5")&&!$.startsWith("gpt-5-chat")}function FY($){return $.startsWith("gpt-4")||$.startsWith("gpt-5-mini")||$.startsWith("gpt-5")&&!$.startsWith("gpt-5-nano")&&!$.startsWith("gpt-5-chat")||$.startsWith("o3")||$.startsWith("o4-mini")}function RY($){var Q,Y;if(!q8($))return"system";return(Y=(Q=SY[$])==null?void 0:Q.systemMessageMode)!=null?Y:"developer"}var SY={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function OY({prompt:$,user:Q="user",assistant:Y="assistant"}){let G="";if($[0].role==="system")G+=`${$[0].content}
12
+
13
+ `,$=$.slice(1);for(let{role:J,content:W}of $)switch(J){case"system":throw new n1({message:"Unexpected system message in prompt: ${content}",prompt:$});case"user":{let q=W.map((L)=>{switch(L.type){case"text":return L.text}}).filter(Boolean).join("");G+=`${Q}:
14
+ ${q}
15
+
16
+ `;break}case"assistant":{let q=W.map((L)=>{switch(L.type){case"text":return L.text;case"tool-call":throw new o({functionality:"tool-call messages"})}}).join("");G+=`${Y}:
17
+ ${q}
18
+
19
+ `;break}case"tool":throw new o({functionality:"tool messages"});default:throw Error(`Unsupported role: ${J}`)}return G+=`${Y}:
20
+ `,{prompt:G,stopSequences:[`
21
+ ${Q}:`]}}function e4({id:$,model:Q,created:Y}){return{id:$!=null?$:void 0,modelId:Q!=null?Q:void 0,timestamp:Y!=null?new Date(Y*1000):void 0}}function $8($){switch($){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 PY=$0(()=>R(X.object({id:X.string().nullish(),created:X.number().nullish(),model:X.string().nullish(),choices:X.array(X.object({text:X.string(),finish_reason:X.string(),logprobs:X.object({tokens:X.array(X.string()),token_logprobs:X.array(X.number()),top_logprobs:X.array(X.record(X.string(),X.number())).nullish()}).nullish()})),usage:X.object({prompt_tokens:X.number(),completion_tokens:X.number(),total_tokens:X.number()}).nullish()}))),bY=$0(()=>R(X.union([X.object({id:X.string().nullish(),created:X.number().nullish(),model:X.string().nullish(),choices:X.array(X.object({text:X.string(),finish_reason:X.string().nullish(),index:X.number(),logprobs:X.object({tokens:X.array(X.string()),token_logprobs:X.array(X.number()),top_logprobs:X.array(X.record(X.string(),X.number())).nullish()}).nullish()})),usage:X.object({prompt_tokens:X.number(),completion_tokens:X.number(),total_tokens:X.number()}).nullish()}),A1]))),X8=$0(()=>R(X.object({echo:X.boolean().optional(),logitBias:X.record(X.string(),X.number()).optional(),suffix:X.string().optional(),user:X.string().optional(),logprobs:X.union([X.boolean(),X.number()]).optional()}))),CY=class{constructor($,Q){this.specificationVersion="v2",this.supportedUrls={},this.modelId=$,this.config=Q}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:$,maxOutputTokens:Q,temperature:Y,topP:G,topK:J,frequencyPenalty:W,presencePenalty:q,stopSequences:L,responseFormat:H,tools:E,toolChoice:U,seed:V,providerOptions:w}){let B=[],K={...await X0({provider:"openai",providerOptions:w,schema:X8}),...await X0({provider:this.providerOptionsName,providerOptions:w,schema:X8})};if(J!=null)B.push({type:"unsupported-setting",setting:"topK"});if(E==null?void 0:E.length)B.push({type:"unsupported-setting",setting:"tools"});if(U!=null)B.push({type:"unsupported-setting",setting:"toolChoice"});if(H!=null&&H.type!=="text")B.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:z,stopSequences:A}=OY({prompt:$}),j=[...A!=null?A:[],...L!=null?L:[]];return{args:{model:this.modelId,echo:K.echo,logit_bias:K.logitBias,logprobs:(K==null?void 0:K.logprobs)===!0?0:(K==null?void 0:K.logprobs)===!1?void 0:K==null?void 0:K.logprobs,suffix:K.suffix,user:K.user,max_tokens:Q,temperature:Y,top_p:G,frequency_penalty:W,presence_penalty:q,seed:V,prompt:z,stop:j.length>0?j:void 0},warnings:B}}async doGenerate($){var Q,Y,G;let{args:J,warnings:W}=await this.getArgs($),{responseHeaders:q,value:L,rawValue:H}=await Y0({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Q0(this.config.headers(),$.headers),body:J,failedResponseHandler:Z0,successfulResponseHandler:U0(PY),abortSignal:$.abortSignal,fetch:this.config.fetch}),E=L.choices[0],U={openai:{}};if(E.logprobs!=null)U.openai.logprobs=E.logprobs;return{content:[{type:"text",text:E.text}],usage:{inputTokens:(Q=L.usage)==null?void 0:Q.prompt_tokens,outputTokens:(Y=L.usage)==null?void 0:Y.completion_tokens,totalTokens:(G=L.usage)==null?void 0:G.total_tokens},finishReason:$8(E.finish_reason),request:{body:J},response:{...e4(L),headers:q,body:H},providerMetadata:U,warnings:W}}async doStream($){let{args:Q,warnings:Y}=await this.getArgs($),G={...Q,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:J,value:W}=await Y0({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Q0(this.config.headers(),$.headers),body:G,failedResponseHandler:Z0,successfulResponseHandler:T0(bY),abortSignal:$.abortSignal,fetch:this.config.fetch}),q="unknown",L={openai:{}},H={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},E=!0;return{stream:W.pipeThrough(new TransformStream({start(U){U.enqueue({type:"stream-start",warnings:Y})},transform(U,V){if($.includeRawChunks)V.enqueue({type:"raw",rawValue:U.rawValue});if(!U.success){q="error",V.enqueue({type:"error",error:U.error});return}let w=U.value;if("error"in w){q="error",V.enqueue({type:"error",error:w.error});return}if(E)E=!1,V.enqueue({type:"response-metadata",...e4(w)}),V.enqueue({type:"text-start",id:"0"});if(w.usage!=null)H.inputTokens=w.usage.prompt_tokens,H.outputTokens=w.usage.completion_tokens,H.totalTokens=w.usage.total_tokens;let B=w.choices[0];if((B==null?void 0:B.finish_reason)!=null)q=$8(B.finish_reason);if((B==null?void 0:B.logprobs)!=null)L.openai.logprobs=B.logprobs;if((B==null?void 0:B.text)!=null&&B.text.length>0)V.enqueue({type:"text-delta",id:"0",delta:B.text})},flush(U){if(!E)U.enqueue({type:"text-end",id:"0"});U.enqueue({type:"finish",finishReason:q,providerMetadata:L,usage:H})}})),request:{body:G},response:{headers:J}}}},IY=$0(()=>R(X.object({dimensions:X.number().optional(),user:X.string().optional()}))),_Y=$0(()=>R(X.object({data:X.array(X.object({embedding:X.array(X.number())})),usage:X.object({prompt_tokens:X.number()}).nullish()}))),kY=class{constructor($,Q){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=$,this.config=Q}get provider(){return this.config.provider}async doEmbed({values:$,headers:Q,abortSignal:Y,providerOptions:G}){var J;if($.length>this.maxEmbeddingsPerCall)throw new I$({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:$});let W=(J=await X0({provider:"openai",providerOptions:G,schema:IY}))!=null?J:{},{responseHeaders:q,value:L,rawValue:H}=await Y0({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Q0(this.config.headers(),Q),body:{model:this.modelId,input:$,encoding_format:"float",dimensions:W.dimensions,user:W.user},failedResponseHandler:Z0,successfulResponseHandler:U0(_Y),abortSignal:Y,fetch:this.config.fetch});return{embeddings:L.data.map((E)=>E.embedding),usage:L.usage?{tokens:L.usage.prompt_tokens}:void 0,response:{headers:q,body:H}}}},TY=$0(()=>R(X.object({data:X.array(X.object({b64_json:X.string(),revised_prompt:X.string().nullish()}))}))),ZY={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},xY=new Set(["gpt-image-1","gpt-image-1-mini"]),vY=class{constructor($,Q){this.modelId=$,this.config=Q,this.specificationVersion="v2"}get maxImagesPerCall(){var $;return($=ZY[this.modelId])!=null?$:1}get provider(){return this.config.provider}async doGenerate({prompt:$,n:Q,size:Y,aspectRatio:G,seed:J,providerOptions:W,headers:q,abortSignal:L}){var H,E,U,V;let w=[];if(G!=null)w.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."});if(J!=null)w.push({type:"unsupported-setting",setting:"seed"});let B=(U=(E=(H=this.config._internal)==null?void 0:H.currentDate)==null?void 0:E.call(H))!=null?U:new Date,{value:K,responseHeaders:z}=await Y0({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Q0(this.config.headers(),q),body:{model:this.modelId,prompt:$,n:Q,size:Y,...(V=W.openai)!=null?V:{},...!xY.has(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:Z0,successfulResponseHandler:U0(TY),abortSignal:L,fetch:this.config.fetch});return{images:K.data.map((A)=>A.b64_json),warnings:w,response:{timestamp:B,modelId:this.modelId,headers:z},providerMetadata:{openai:{images:K.data.map((A)=>A.revised_prompt?{revisedPrompt:A.revised_prompt}:null)}}}}},fY=Z(()=>R(X.object({code:X.string().nullish(),containerId:X.string()}))),yY=Z(()=>R(X.object({outputs:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("logs"),logs:X.string()}),X.object({type:X.literal("image"),url:X.string()})])).nullish()}))),gY=Z(()=>R(X.object({container:X.union([X.string(),X.object({fileIds:X.array(X.string()).optional()})]).optional()}))),hY=L0({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:fY,outputSchema:yY}),mY=($={})=>{return hY($)},L8=X.object({key:X.string(),type:X.enum(["eq","ne","gt","gte","lt","lte"]),value:X.union([X.string(),X.number(),X.boolean()])}),H8=X.object({type:X.enum(["and","or"]),filters:X.array(X.union([L8,X.lazy(()=>H8)]))}),uY=Z(()=>R(X.object({vectorStoreIds:X.array(X.string()),maxNumResults:X.number().optional(),ranking:X.object({ranker:X.string().optional(),scoreThreshold:X.number().optional()}).optional(),filters:X.union([L8,H8]).optional()}))),cY=Z(()=>R(X.object({queries:X.array(X.string()),results:X.array(X.object({attributes:X.record(X.string(),X.unknown()),fileId:X.string(),filename:X.string(),score:X.number(),text:X.string()})).nullable()}))),dY=L0({id:"openai.file_search",name:"file_search",inputSchema:X.object({}),outputSchema:cY}),iY=Z(()=>R(X.object({background:X.enum(["auto","opaque","transparent"]).optional(),inputFidelity:X.enum(["low","high"]).optional(),inputImageMask:X.object({fileId:X.string().optional(),imageUrl:X.string().optional()}).optional(),model:X.string().optional(),moderation:X.enum(["auto"]).optional(),outputCompression:X.number().int().min(0).max(100).optional(),outputFormat:X.enum(["png","jpeg","webp"]).optional(),partialImages:X.number().int().min(0).max(3).optional(),quality:X.enum(["auto","low","medium","high"]).optional(),size:X.enum(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),pY=Z(()=>R(X.object({}))),lY=Z(()=>R(X.object({result:X.string()}))),nY=L0({id:"openai.image_generation",name:"image_generation",inputSchema:pY,outputSchema:lY}),rY=($={})=>{return nY($)},E8=Z(()=>R(X.object({action:X.object({type:X.literal("exec"),command:X.array(X.string()),timeoutMs:X.number().optional(),user:X.string().optional(),workingDirectory:X.string().optional(),env:X.record(X.string(),X.string()).optional()})}))),U8=Z(()=>R(X.object({output:X.string()}))),aY=L0({id:"openai.local_shell",name:"local_shell",inputSchema:E8,outputSchema:U8}),sY=Z(()=>R(X.object({filters:X.object({allowedDomains:X.array(X.string()).optional()}).optional(),searchContextSize:X.enum(["low","medium","high"]).optional(),userLocation:X.object({type:X.literal("approximate"),country:X.string().optional(),city:X.string().optional(),region:X.string().optional(),timezone:X.string().optional()}).optional()}))),tY=Z(()=>R(X.object({}))),oY=Z(()=>R(X.object({action:X.discriminatedUnion("type",[X.object({type:X.literal("search"),query:X.string().optional()}),X.object({type:X.literal("openPage"),url:X.string()}),X.object({type:X.literal("find"),url:X.string(),pattern:X.string()})]),sources:X.array(X.object({type:X.literal("url"),url:X.string()})).optional()}))),eY=L0({id:"openai.web_search",name:"web_search",inputSchema:tY,outputSchema:oY}),$G=($={})=>eY($),XG=Z(()=>R(X.object({searchContextSize:X.enum(["low","medium","high"]).optional(),userLocation:X.object({type:X.literal("approximate"),country:X.string().optional(),city:X.string().optional(),region:X.string().optional(),timezone:X.string().optional()}).optional()}))),QG=Z(()=>R(X.object({}))),YG=Z(()=>R(X.object({action:X.discriminatedUnion("type",[X.object({type:X.literal("search"),query:X.string().optional()}),X.object({type:X.literal("openPage"),url:X.string()}),X.object({type:X.literal("find"),url:X.string(),pattern:X.string()})])}))),GG=L0({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:QG,outputSchema:YG}),JG={codeInterpreter:mY,fileSearch:dY,imageGeneration:rY,localShell:aY,webSearchPreview:GG,webSearch:$G};function Q8($,Q){if(!Q)return!1;return Q.some((Y)=>$.startsWith(Y))}async function WG({prompt:$,systemMessageMode:Q,fileIdPrefixes:Y,store:G,hasLocalShellTool:J=!1}){var W,q,L,H;let E=[],U=[];for(let{role:V,content:w}of $)switch(V){case"system":{switch(Q){case"system":{E.push({role:"system",content:w});break}case"developer":{E.push({role:"developer",content:w});break}case"remove":{U.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${Q}`)}break}case"user":{E.push({role:"user",content:w.map((B,K)=>{var z,A,j;switch(B.type){case"text":return{type:"input_text",text:B.text};case"file":if(B.mediaType.startsWith("image/")){let N=B.mediaType==="image/*"?"image/jpeg":B.mediaType;return{type:"input_image",...B.data instanceof URL?{image_url:B.data.toString()}:typeof B.data==="string"&&Q8(B.data,Y)?{file_id:B.data}:{image_url:`data:${N};base64,${K0(B.data)}`},detail:(A=(z=B.providerOptions)==null?void 0:z.openai)==null?void 0:A.imageDetail}}else if(B.mediaType==="application/pdf"){if(B.data instanceof URL)return{type:"input_file",file_url:B.data.toString()};return{type:"input_file",...typeof B.data==="string"&&Q8(B.data,Y)?{file_id:B.data}:{filename:(j=B.filename)!=null?j:`part-${K}.pdf`,file_data:`data:application/pdf;base64,${K0(B.data)}`}}}else throw new o({functionality:`file part media type ${B.mediaType}`})}})});break}case"assistant":{let B={},K={};for(let z of w)switch(z.type){case"text":{let A=(q=(W=z.providerOptions)==null?void 0:W.openai)==null?void 0:q.itemId;if(G&&A!=null){E.push({type:"item_reference",id:A});break}E.push({role:"assistant",content:[{type:"output_text",text:z.text}],id:A});break}case"tool-call":{if(K[z.toolCallId]=z,z.providerExecuted)break;let A=(H=(L=z.providerOptions)==null?void 0:L.openai)==null?void 0:H.itemId;if(G&&A!=null){E.push({type:"item_reference",id:A});break}if(J&&z.toolName==="local_shell"){let j=await B0({value:z.input,schema:E8});E.push({type:"local_shell_call",call_id:z.toolCallId,id:A,action:{type:"exec",command:j.action.command,timeout_ms:j.action.timeoutMs,user:j.action.user,working_directory:j.action.workingDirectory,env:j.action.env}});break}E.push({type:"function_call",call_id:z.toolCallId,name:z.toolName,arguments:JSON.stringify(z.input),id:A});break}case"tool-result":{if(G)E.push({type:"item_reference",id:z.toolCallId});else U.push({type:"other",message:`Results for OpenAI tool ${z.toolName} are not sent to the API when store is false`});break}case"reasoning":{let A=await X0({provider:"openai",providerOptions:z.providerOptions,schema:qG}),j=A==null?void 0:A.itemId;if(j!=null){let N=B[j];if(G){if(N===void 0)E.push({type:"item_reference",id:j}),B[j]={type:"reasoning",id:j,summary:[]}}else{let M=[];if(z.text.length>0)M.push({type:"summary_text",text:z.text});else if(N!==void 0)U.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(z)}.`});if(N===void 0)B[j]={type:"reasoning",id:j,encrypted_content:A==null?void 0:A.reasoningEncryptedContent,summary:M},E.push(B[j]);else if(N.summary.push(...M),(A==null?void 0:A.reasoningEncryptedContent)!=null)N.encrypted_content=A.reasoningEncryptedContent}}else U.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(z)}.`});break}}break}case"tool":{for(let B of w){let K=B.output;if(J&&B.toolName==="local_shell"&&K.type==="json"){let A=await B0({value:K.value,schema:U8});E.push({type:"local_shell_call_output",call_id:B.toolCallId,output:A.output});break}let z;switch(K.type){case"text":case"error-text":z=K.value;break;case"json":case"error-json":z=JSON.stringify(K.value);break;case"content":z=K.value.map((A)=>{switch(A.type){case"text":return{type:"input_text",text:A.text};case"media":return A.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${A.mediaType};base64,${A.data}`}:{type:"input_file",filename:"data",file_data:`data:${A.mediaType};base64,${A.data}`}}});break}E.push({type:"function_call_output",call_id:B.toolCallId,output:z})}break}default:throw Error(`Unsupported role: ${V}`)}return{input:E,warnings:U}}var qG=X.object({itemId:X.string().nullish(),reasoningEncryptedContent:X.string().nullish()});function Y8({finishReason:$,hasFunctionCall:Q}){switch($){case void 0:case null:return Q?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return Q?"tool-calls":"unknown"}}var LG=$0(()=>R(X.union([X.object({type:X.literal("response.output_text.delta"),item_id:X.string(),delta:X.string(),logprobs:X.array(X.object({token:X.string(),logprob:X.number(),top_logprobs:X.array(X.object({token:X.string(),logprob:X.number()}))})).nullish()}),X.object({type:X.enum(["response.completed","response.incomplete"]),response:X.object({incomplete_details:X.object({reason:X.string()}).nullish(),usage:X.object({input_tokens:X.number(),input_tokens_details:X.object({cached_tokens:X.number().nullish()}).nullish(),output_tokens:X.number(),output_tokens_details:X.object({reasoning_tokens:X.number().nullish()}).nullish()}),service_tier:X.string().nullish()})}),X.object({type:X.literal("response.created"),response:X.object({id:X.string(),created_at:X.number(),model:X.string(),service_tier:X.string().nullish()})}),X.object({type:X.literal("response.output_item.added"),output_index:X.number(),item:X.discriminatedUnion("type",[X.object({type:X.literal("message"),id:X.string()}),X.object({type:X.literal("reasoning"),id:X.string(),encrypted_content:X.string().nullish()}),X.object({type:X.literal("function_call"),id:X.string(),call_id:X.string(),name:X.string(),arguments:X.string()}),X.object({type:X.literal("web_search_call"),id:X.string(),status:X.string()}),X.object({type:X.literal("computer_call"),id:X.string(),status:X.string()}),X.object({type:X.literal("file_search_call"),id:X.string()}),X.object({type:X.literal("image_generation_call"),id:X.string()}),X.object({type:X.literal("code_interpreter_call"),id:X.string(),container_id:X.string(),code:X.string().nullable(),outputs:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("logs"),logs:X.string()}),X.object({type:X.literal("image"),url:X.string()})])).nullable(),status:X.string()})])}),X.object({type:X.literal("response.output_item.done"),output_index:X.number(),item:X.discriminatedUnion("type",[X.object({type:X.literal("message"),id:X.string()}),X.object({type:X.literal("reasoning"),id:X.string(),encrypted_content:X.string().nullish()}),X.object({type:X.literal("function_call"),id:X.string(),call_id:X.string(),name:X.string(),arguments:X.string(),status:X.literal("completed")}),X.object({type:X.literal("code_interpreter_call"),id:X.string(),code:X.string().nullable(),container_id:X.string(),outputs:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("logs"),logs:X.string()}),X.object({type:X.literal("image"),url:X.string()})])).nullable()}),X.object({type:X.literal("image_generation_call"),id:X.string(),result:X.string()}),X.object({type:X.literal("web_search_call"),id:X.string(),status:X.string(),action:X.discriminatedUnion("type",[X.object({type:X.literal("search"),query:X.string().nullish(),sources:X.array(X.object({type:X.literal("url"),url:X.string()})).nullish()}),X.object({type:X.literal("open_page"),url:X.string()}),X.object({type:X.literal("find"),url:X.string(),pattern:X.string()})])}),X.object({type:X.literal("file_search_call"),id:X.string(),queries:X.array(X.string()),results:X.array(X.object({attributes:X.record(X.string(),X.unknown()),file_id:X.string(),filename:X.string(),score:X.number(),text:X.string()})).nullish()}),X.object({type:X.literal("local_shell_call"),id:X.string(),call_id:X.string(),action:X.object({type:X.literal("exec"),command:X.array(X.string()),timeout_ms:X.number().optional(),user:X.string().optional(),working_directory:X.string().optional(),env:X.record(X.string(),X.string()).optional()})}),X.object({type:X.literal("computer_call"),id:X.string(),status:X.literal("completed")})])}),X.object({type:X.literal("response.function_call_arguments.delta"),item_id:X.string(),output_index:X.number(),delta:X.string()}),X.object({type:X.literal("response.image_generation_call.partial_image"),item_id:X.string(),output_index:X.number(),partial_image_b64:X.string()}),X.object({type:X.literal("response.code_interpreter_call_code.delta"),item_id:X.string(),output_index:X.number(),delta:X.string()}),X.object({type:X.literal("response.code_interpreter_call_code.done"),item_id:X.string(),output_index:X.number(),code:X.string()}),X.object({type:X.literal("response.output_text.annotation.added"),annotation:X.discriminatedUnion("type",[X.object({type:X.literal("url_citation"),url:X.string(),title:X.string()}),X.object({type:X.literal("file_citation"),file_id:X.string(),filename:X.string().nullish(),index:X.number().nullish(),start_index:X.number().nullish(),end_index:X.number().nullish(),quote:X.string().nullish()})])}),X.object({type:X.literal("response.reasoning_summary_part.added"),item_id:X.string(),summary_index:X.number()}),X.object({type:X.literal("response.reasoning_summary_text.delta"),item_id:X.string(),summary_index:X.number(),delta:X.string()}),X.object({type:X.literal("response.reasoning_summary_part.done"),item_id:X.string(),summary_index:X.number()}),X.object({type:X.literal("error"),code:X.string(),message:X.string(),param:X.string().nullish(),sequence_number:X.number()}),X.object({type:X.string()}).loose().transform(($)=>({type:"unknown_chunk",message:$.type}))]))),HG=$0(()=>R(X.object({id:X.string(),created_at:X.number(),error:X.object({code:X.string(),message:X.string()}).nullish(),model:X.string(),output:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("message"),role:X.literal("assistant"),id:X.string(),content:X.array(X.object({type:X.literal("output_text"),text:X.string(),logprobs:X.array(X.object({token:X.string(),logprob:X.number(),top_logprobs:X.array(X.object({token:X.string(),logprob:X.number()}))})).nullish(),annotations:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("url_citation"),start_index:X.number(),end_index:X.number(),url:X.string(),title:X.string()}),X.object({type:X.literal("file_citation"),file_id:X.string(),filename:X.string().nullish(),index:X.number().nullish(),start_index:X.number().nullish(),end_index:X.number().nullish(),quote:X.string().nullish()}),X.object({type:X.literal("container_file_citation")})]))}))}),X.object({type:X.literal("web_search_call"),id:X.string(),status:X.string(),action:X.discriminatedUnion("type",[X.object({type:X.literal("search"),query:X.string().nullish(),sources:X.array(X.object({type:X.literal("url"),url:X.string()})).nullish()}),X.object({type:X.literal("open_page"),url:X.string()}),X.object({type:X.literal("find"),url:X.string(),pattern:X.string()})])}),X.object({type:X.literal("file_search_call"),id:X.string(),queries:X.array(X.string()),results:X.array(X.object({attributes:X.record(X.string(),X.unknown()),file_id:X.string(),filename:X.string(),score:X.number(),text:X.string()})).nullish()}),X.object({type:X.literal("code_interpreter_call"),id:X.string(),code:X.string().nullable(),container_id:X.string(),outputs:X.array(X.discriminatedUnion("type",[X.object({type:X.literal("logs"),logs:X.string()}),X.object({type:X.literal("image"),url:X.string()})])).nullable()}),X.object({type:X.literal("image_generation_call"),id:X.string(),result:X.string()}),X.object({type:X.literal("local_shell_call"),id:X.string(),call_id:X.string(),action:X.object({type:X.literal("exec"),command:X.array(X.string()),timeout_ms:X.number().optional(),user:X.string().optional(),working_directory:X.string().optional(),env:X.record(X.string(),X.string()).optional()})}),X.object({type:X.literal("function_call"),call_id:X.string(),name:X.string(),arguments:X.string(),id:X.string()}),X.object({type:X.literal("computer_call"),id:X.string(),status:X.string().optional()}),X.object({type:X.literal("reasoning"),id:X.string(),encrypted_content:X.string().nullish(),summary:X.array(X.object({type:X.literal("summary_text"),text:X.string()}))})])),service_tier:X.string().nullish(),incomplete_details:X.object({reason:X.string()}).nullish(),usage:X.object({input_tokens:X.number(),input_tokens_details:X.object({cached_tokens:X.number().nullish()}).nullish(),output_tokens:X.number(),output_tokens_details:X.object({reasoning_tokens:X.number().nullish()}).nullish()})}))),j8=20,EG=["o1","o1-2024-12-17","o3-mini","o3-mini-2025-01-31","o3","o3-2025-04-16","o4-mini","o4-mini-2025-04-16","codex-mini-latest","computer-use-preview","gpt-5","gpt-5-2025-08-07","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06"],sW=["gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","gpt-4-0125-preview","gpt-4-1106-preview","gpt-4","gpt-4-0613","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","chatgpt-4o-latest","gpt-5-chat-latest",...EG],UG=$0(()=>R(X.object({include:X.array(X.enum(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:X.string().nullish(),logprobs:X.union([X.boolean(),X.number().min(1).max(j8)]).optional(),maxToolCalls:X.number().nullish(),metadata:X.any().nullish(),parallelToolCalls:X.boolean().nullish(),previousResponseId:X.string().nullish(),promptCacheKey:X.string().nullish(),reasoningEffort:X.string().nullish(),reasoningSummary:X.string().nullish(),safetyIdentifier:X.string().nullish(),serviceTier:X.enum(["auto","flex","priority","default"]).nullish(),store:X.boolean().nullish(),strictJsonSchema:X.boolean().nullish(),textVerbosity:X.enum(["low","medium","high"]).nullish(),truncation:X.enum(["auto","disabled"]).nullish(),user:X.string().nullish()})));async function jG({tools:$,toolChoice:Q,strictJsonSchema:Y}){$=($==null?void 0:$.length)?$:void 0;let G=[];if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:G};let J=[];for(let q of $)switch(q.type){case"function":J.push({type:"function",name:q.name,description:q.description,parameters:q.inputSchema,strict:Y});break;case"provider-defined":{switch(q.id){case"openai.file_search":{let L=await B0({value:q.args,schema:uY});J.push({type:"file_search",vector_store_ids:L.vectorStoreIds,max_num_results:L.maxNumResults,ranking_options:L.ranking?{ranker:L.ranking.ranker,score_threshold:L.ranking.scoreThreshold}:void 0,filters:L.filters});break}case"openai.local_shell":{J.push({type:"local_shell"});break}case"openai.web_search_preview":{let L=await B0({value:q.args,schema:XG});J.push({type:"web_search_preview",search_context_size:L.searchContextSize,user_location:L.userLocation});break}case"openai.web_search":{let L=await B0({value:q.args,schema:sY});J.push({type:"web_search",filters:L.filters!=null?{allowed_domains:L.filters.allowedDomains}:void 0,search_context_size:L.searchContextSize,user_location:L.userLocation});break}case"openai.code_interpreter":{let L=await B0({value:q.args,schema:gY});J.push({type:"code_interpreter",container:L.container==null?{type:"auto",file_ids:void 0}:typeof L.container==="string"?L.container:{type:"auto",file_ids:L.container.fileIds}});break}case"openai.image_generation":{let L=await B0({value:q.args,schema:iY});J.push({type:"image_generation",background:L.background,input_fidelity:L.inputFidelity,input_image_mask:L.inputImageMask?{file_id:L.inputImageMask.fileId,image_url:L.inputImageMask.imageUrl}:void 0,model:L.model,size:L.size,quality:L.quality,moderation:L.moderation,output_format:L.outputFormat,output_compression:L.outputCompression});break}}break}default:G.push({type:"unsupported-tool",tool:q});break}if(Q==null)return{tools:J,toolChoice:void 0,toolWarnings:G};let W=Q.type;switch(W){case"auto":case"none":case"required":return{tools:J,toolChoice:W,toolWarnings:G};case"tool":return{tools:J,toolChoice:Q.toolName==="code_interpreter"||Q.toolName==="file_search"||Q.toolName==="image_generation"||Q.toolName==="web_search_preview"||Q.toolName==="web_search"?{type:Q.toolName}:{type:"function",name:Q.toolName},toolWarnings:G};default:throw new o({functionality:`tool choice type: ${W}`})}}var BG=class{constructor($,Q){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=$,this.config=Q}get provider(){return this.config.provider}async getArgs({maxOutputTokens:$,temperature:Q,stopSequences:Y,topP:G,topK:J,presencePenalty:W,frequencyPenalty:q,seed:L,prompt:H,providerOptions:E,tools:U,toolChoice:V,responseFormat:w}){var B,K,z,A;let j=[],N=RG(this.modelId);if(J!=null)j.push({type:"unsupported-setting",setting:"topK"});if(L!=null)j.push({type:"unsupported-setting",setting:"seed"});if(W!=null)j.push({type:"unsupported-setting",setting:"presencePenalty"});if(q!=null)j.push({type:"unsupported-setting",setting:"frequencyPenalty"});if(Y!=null)j.push({type:"unsupported-setting",setting:"stopSequences"});let M=await X0({provider:"openai",providerOptions:E,schema:UG}),{input:T,warnings:c}=await WG({prompt:H,systemMessageMode:N.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(B=M==null?void 0:M.store)!=null?B:!0,hasLocalShellTool:b("openai.local_shell")});j.push(...c);let d=(K=M==null?void 0:M.strictJsonSchema)!=null?K:!1,v=M==null?void 0:M.include;function m(I){if(v==null)v=[I];else if(!v.includes(I))v=[...v,I]}function b(I){return(U==null?void 0:U.find((s)=>s.type==="provider-defined"&&s.id===I))!=null}let C=typeof(M==null?void 0:M.logprobs)==="number"?M==null?void 0:M.logprobs:(M==null?void 0:M.logprobs)===!0?j8:void 0;if(C)m("message.output_text.logprobs");let x=(z=U==null?void 0:U.find((I)=>I.type==="provider-defined"&&(I.id==="openai.web_search"||I.id==="openai.web_search_preview")))==null?void 0:z.name;if(x)m("web_search_call.action.sources");if(b("openai.code_interpreter"))m("code_interpreter_call.outputs");let y=M==null?void 0:M.store;if(y===!1&&N.isReasoningModel)m("reasoning.encrypted_content");let g={model:this.modelId,input:T,temperature:Q,top_p:G,max_output_tokens:$,...((w==null?void 0:w.type)==="json"||(M==null?void 0:M.textVerbosity))&&{text:{...(w==null?void 0:w.type)==="json"&&{format:w.schema!=null?{type:"json_schema",strict:d,name:(A=w.name)!=null?A:"response",description:w.description,schema:w.schema}:{type:"json_object"}},...(M==null?void 0:M.textVerbosity)&&{verbosity:M.textVerbosity}}},max_tool_calls:M==null?void 0:M.maxToolCalls,metadata:M==null?void 0:M.metadata,parallel_tool_calls:M==null?void 0:M.parallelToolCalls,previous_response_id:M==null?void 0:M.previousResponseId,store:y,user:M==null?void 0:M.user,instructions:M==null?void 0:M.instructions,service_tier:M==null?void 0:M.serviceTier,include:v,prompt_cache_key:M==null?void 0:M.promptCacheKey,safety_identifier:M==null?void 0:M.safetyIdentifier,top_logprobs:C,truncation:M==null?void 0:M.truncation,...N.isReasoningModel&&((M==null?void 0:M.reasoningEffort)!=null||(M==null?void 0:M.reasoningSummary)!=null)&&{reasoning:{...(M==null?void 0:M.reasoningEffort)!=null&&{effort:M.reasoningEffort},...(M==null?void 0:M.reasoningSummary)!=null&&{summary:M.reasoningSummary}}}};if(N.isReasoningModel){if(g.temperature!=null)g.temperature=void 0,j.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"});if(g.top_p!=null)g.top_p=void 0,j.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})}else{if((M==null?void 0:M.reasoningEffort)!=null)j.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"});if((M==null?void 0:M.reasoningSummary)!=null)j.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})}if((M==null?void 0:M.serviceTier)==="flex"&&!N.supportsFlexProcessing)j.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete g.service_tier;if((M==null?void 0:M.serviceTier)==="priority"&&!N.supportsPriorityProcessing)j.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 g.service_tier;let{tools:F,toolChoice:k,toolWarnings:P}=await jG({tools:U,toolChoice:V,strictJsonSchema:d});return{webSearchToolName:x,args:{...g,tools:F,tool_choice:k},warnings:[...j,...P],store:y}}async doGenerate($){var Q,Y,G,J,W,q,L,H,E,U,V,w,B,K,z,A,j,N,M;let{args:T,warnings:c,webSearchToolName:d}=await this.getArgs($),v=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:m,value:b,rawValue:C}=await Y0({url:v,headers:Q0(this.config.headers(),$.headers),body:T,failedResponseHandler:Z0,successfulResponseHandler:U0(HG),abortSignal:$.abortSignal,fetch:this.config.fetch});if(b.error)throw new E0({message:b.error.message,url:v,requestBodyValues:T,statusCode:400,responseHeaders:m,responseBody:C,isRetryable:!1});let x=[],y=[],g=!1;for(let k of b.output)switch(k.type){case"reasoning":{if(k.summary.length===0)k.summary.push({type:"summary_text",text:""});for(let P of k.summary)x.push({type:"reasoning",text:P.text,providerMetadata:{openai:{itemId:k.id,reasoningEncryptedContent:(Q=k.encrypted_content)!=null?Q:null}}});break}case"image_generation_call":{x.push({type:"tool-call",toolCallId:k.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:k.id,toolName:"image_generation",result:{result:k.result},providerExecuted:!0});break}case"local_shell_call":{x.push({type:"tool-call",toolCallId:k.call_id,toolName:"local_shell",input:JSON.stringify({action:k.action}),providerMetadata:{openai:{itemId:k.id}}});break}case"message":{for(let P of k.content){if(((G=(Y=$.providerOptions)==null?void 0:Y.openai)==null?void 0:G.logprobs)&&P.logprobs)y.push(P.logprobs);x.push({type:"text",text:P.text,providerMetadata:{openai:{itemId:k.id}}});for(let I of P.annotations)if(I.type==="url_citation")x.push({type:"source",sourceType:"url",id:(q=(W=(J=this.config).generateId)==null?void 0:W.call(J))!=null?q:j0(),url:I.url,title:I.title});else if(I.type==="file_citation")x.push({type:"source",sourceType:"document",id:(E=(H=(L=this.config).generateId)==null?void 0:H.call(L))!=null?E:j0(),mediaType:"text/plain",title:(V=(U=I.quote)!=null?U:I.filename)!=null?V:"Document",filename:(w=I.filename)!=null?w:I.file_id,...I.file_id?{providerMetadata:{openai:{fileId:I.file_id}}}:{}})}break}case"function_call":{g=!0,x.push({type:"tool-call",toolCallId:k.call_id,toolName:k.name,input:k.arguments,providerMetadata:{openai:{itemId:k.id}}});break}case"web_search_call":{x.push({type:"tool-call",toolCallId:k.id,toolName:d!=null?d:"web_search",input:JSON.stringify({}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:k.id,toolName:d!=null?d:"web_search",result:J8(k.action),providerExecuted:!0});break}case"computer_call":{x.push({type:"tool-call",toolCallId:k.id,toolName:"computer_use",input:"",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:k.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:k.status||"completed"},providerExecuted:!0});break}case"file_search_call":{x.push({type:"tool-call",toolCallId:k.id,toolName:"file_search",input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:k.id,toolName:"file_search",result:{queries:k.queries,results:(K=(B=k.results)==null?void 0:B.map((P)=>({attributes:P.attributes,fileId:P.file_id,filename:P.filename,score:P.score,text:P.text})))!=null?K:null},providerExecuted:!0});break}case"code_interpreter_call":{x.push({type:"tool-call",toolCallId:k.id,toolName:"code_interpreter",input:JSON.stringify({code:k.code,containerId:k.container_id}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:k.id,toolName:"code_interpreter",result:{outputs:k.outputs},providerExecuted:!0});break}}let F={openai:{responseId:b.id}};if(y.length>0)F.openai.logprobs=y;if(typeof b.service_tier==="string")F.openai.serviceTier=b.service_tier;return{content:x,finishReason:Y8({finishReason:(z=b.incomplete_details)==null?void 0:z.reason,hasFunctionCall:g}),usage:{inputTokens:b.usage.input_tokens,outputTokens:b.usage.output_tokens,totalTokens:b.usage.input_tokens+b.usage.output_tokens,reasoningTokens:(j=(A=b.usage.output_tokens_details)==null?void 0:A.reasoning_tokens)!=null?j:void 0,cachedInputTokens:(M=(N=b.usage.input_tokens_details)==null?void 0:N.cached_tokens)!=null?M:void 0},request:{body:T},response:{id:b.id,timestamp:new Date(b.created_at*1000),modelId:b.model,headers:m,body:C},providerMetadata:F,warnings:c}}async doStream($){let{args:Q,warnings:Y,webSearchToolName:G,store:J}=await this.getArgs($),{responseHeaders:W,value:q}=await Y0({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Q0(this.config.headers(),$.headers),body:{...Q,stream:!0},failedResponseHandler:Z0,successfulResponseHandler:T0(LG),abortSignal:$.abortSignal,fetch:this.config.fetch}),L=this,H="unknown",E={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},U=[],V=null,w={},B=!1,K={},z;return{stream:q.pipeThrough(new TransformStream({start(A){A.enqueue({type:"stream-start",warnings:Y})},transform(A,j){var N,M,T,c,d,v,m,b,C,x,y,g,F,k,P,I,s,l,N0,p,G0,h;if($.includeRawChunks)j.enqueue({type:"raw",rawValue:A.rawValue});if(!A.success){H="error",j.enqueue({type:"error",error:A.error});return}let D=A.value;if(G8(D)){if(D.item.type==="function_call")w[D.output_index]={toolName:D.item.name,toolCallId:D.item.call_id},j.enqueue({type:"tool-input-start",id:D.item.call_id,toolName:D.item.name});else if(D.item.type==="web_search_call")w[D.output_index]={toolName:G!=null?G:"web_search",toolCallId:D.item.id},j.enqueue({type:"tool-input-start",id:D.item.id,toolName:G!=null?G:"web_search",providerExecuted:!0}),j.enqueue({type:"tool-input-end",id:D.item.id}),j.enqueue({type:"tool-call",toolCallId:D.item.id,toolName:"web_search",input:JSON.stringify({}),providerExecuted:!0});else if(D.item.type==="computer_call")w[D.output_index]={toolName:"computer_use",toolCallId:D.item.id},j.enqueue({type:"tool-input-start",id:D.item.id,toolName:"computer_use",providerExecuted:!0});else if(D.item.type==="code_interpreter_call")w[D.output_index]={toolName:"code_interpreter",toolCallId:D.item.id,codeInterpreter:{containerId:D.item.container_id}},j.enqueue({type:"tool-input-start",id:D.item.id,toolName:"code_interpreter",providerExecuted:!0}),j.enqueue({type:"tool-input-delta",id:D.item.id,delta:`{"containerId":"${D.item.container_id}","code":"`});else if(D.item.type==="file_search_call")j.enqueue({type:"tool-call",toolCallId:D.item.id,toolName:"file_search",input:"{}",providerExecuted:!0});else if(D.item.type==="image_generation_call")j.enqueue({type:"tool-call",toolCallId:D.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0});else if(D.item.type==="message")j.enqueue({type:"text-start",id:D.item.id,providerMetadata:{openai:{itemId:D.item.id}}});else if(G8(D)&&D.item.type==="reasoning")K[D.item.id]={encryptedContent:D.item.encrypted_content,summaryParts:{0:"active"}},j.enqueue({type:"reasoning-start",id:`${D.item.id}:0`,providerMetadata:{openai:{itemId:D.item.id,reasoningEncryptedContent:(N=D.item.encrypted_content)!=null?N:null}}})}else if(NG(D)){if(D.item.type==="function_call")w[D.output_index]=void 0,B=!0,j.enqueue({type:"tool-input-end",id:D.item.call_id}),j.enqueue({type:"tool-call",toolCallId:D.item.call_id,toolName:D.item.name,input:D.item.arguments,providerMetadata:{openai:{itemId:D.item.id}}});else if(D.item.type==="web_search_call")w[D.output_index]=void 0,j.enqueue({type:"tool-result",toolCallId:D.item.id,toolName:"web_search",result:J8(D.item.action),providerExecuted:!0});else if(D.item.type==="computer_call")w[D.output_index]=void 0,j.enqueue({type:"tool-input-end",id:D.item.id}),j.enqueue({type:"tool-call",toolCallId:D.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),j.enqueue({type:"tool-result",toolCallId:D.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:D.item.status||"completed"},providerExecuted:!0});else if(D.item.type==="file_search_call")w[D.output_index]=void 0,j.enqueue({type:"tool-result",toolCallId:D.item.id,toolName:"file_search",result:{queries:D.item.queries,results:(T=(M=D.item.results)==null?void 0:M.map((n)=>({attributes:n.attributes,fileId:n.file_id,filename:n.filename,score:n.score,text:n.text})))!=null?T:null},providerExecuted:!0});else if(D.item.type==="code_interpreter_call")w[D.output_index]=void 0,j.enqueue({type:"tool-result",toolCallId:D.item.id,toolName:"code_interpreter",result:{outputs:D.item.outputs},providerExecuted:!0});else if(D.item.type==="image_generation_call")j.enqueue({type:"tool-result",toolCallId:D.item.id,toolName:"image_generation",result:{result:D.item.result},providerExecuted:!0});else if(D.item.type==="local_shell_call")w[D.output_index]=void 0,j.enqueue({type:"tool-call",toolCallId:D.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:D.item.action.command,timeoutMs:D.item.action.timeout_ms,user:D.item.action.user,workingDirectory:D.item.action.working_directory,env:D.item.action.env}}),providerMetadata:{openai:{itemId:D.item.id}}});else if(D.item.type==="message")j.enqueue({type:"text-end",id:D.item.id});else if(D.item.type==="reasoning"){let n=K[D.item.id],C0=Object.entries(n.summaryParts).filter(([M0,V0])=>V0==="active"||V0==="can-conclude").map(([M0])=>M0);for(let M0 of C0)j.enqueue({type:"reasoning-end",id:`${D.item.id}:${M0}`,providerMetadata:{openai:{itemId:D.item.id,reasoningEncryptedContent:(c=D.item.encrypted_content)!=null?c:null}}});delete K[D.item.id]}}else if(wG(D)){let n=w[D.output_index];if(n!=null)j.enqueue({type:"tool-input-delta",id:n.toolCallId,delta:D.delta})}else if(DG(D)){let n=w[D.output_index];if(n!=null)j.enqueue({type:"tool-input-delta",id:n.toolCallId,delta:JSON.stringify(D.delta).slice(1,-1)})}else if(VG(D)){let n=w[D.output_index];if(n!=null)j.enqueue({type:"tool-input-delta",id:n.toolCallId,delta:'"}'}),j.enqueue({type:"tool-input-end",id:n.toolCallId}),j.enqueue({type:"tool-call",toolCallId:n.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:D.code,containerId:n.codeInterpreter.containerId}),providerExecuted:!0})}else if(AG(D))V=D.response.id,j.enqueue({type:"response-metadata",id:D.response.id,timestamp:new Date(D.response.created_at*1000),modelId:D.response.model});else if(zG(D)){if(j.enqueue({type:"text-delta",id:D.item_id,delta:D.delta}),((v=(d=$.providerOptions)==null?void 0:d.openai)==null?void 0:v.logprobs)&&D.logprobs)U.push(D.logprobs)}else if(D.type==="response.reasoning_summary_part.added"){if(D.summary_index>0){let n=K[D.item_id];n.summaryParts[D.summary_index]="active";for(let C0 of Object.keys(n.summaryParts))if(n.summaryParts[C0]==="can-conclude")j.enqueue({type:"reasoning-end",id:`${D.item_id}:${C0}`,providerMetadata:{openai:{itemId:D.item_id}}}),n.summaryParts[C0]="concluded";j.enqueue({type:"reasoning-start",id:`${D.item_id}:${D.summary_index}`,providerMetadata:{openai:{itemId:D.item_id,reasoningEncryptedContent:(b=(m=K[D.item_id])==null?void 0:m.encryptedContent)!=null?b:null}}})}}else if(D.type==="response.reasoning_summary_text.delta")j.enqueue({type:"reasoning-delta",id:`${D.item_id}:${D.summary_index}`,delta:D.delta,providerMetadata:{openai:{itemId:D.item_id}}});else if(D.type==="response.reasoning_summary_part.done")if(J)j.enqueue({type:"reasoning-end",id:`${D.item_id}:${D.summary_index}`,providerMetadata:{openai:{itemId:D.item_id}}}),K[D.item_id].summaryParts[D.summary_index]="concluded";else K[D.item_id].summaryParts[D.summary_index]="can-conclude";else if(MG(D)){if(H=Y8({finishReason:(C=D.response.incomplete_details)==null?void 0:C.reason,hasFunctionCall:B}),E.inputTokens=D.response.usage.input_tokens,E.outputTokens=D.response.usage.output_tokens,E.totalTokens=D.response.usage.input_tokens+D.response.usage.output_tokens,E.reasoningTokens=(y=(x=D.response.usage.output_tokens_details)==null?void 0:x.reasoning_tokens)!=null?y:void 0,E.cachedInputTokens=(F=(g=D.response.usage.input_tokens_details)==null?void 0:g.cached_tokens)!=null?F:void 0,typeof D.response.service_tier==="string")z=D.response.service_tier}else if(KG(D)){if(D.annotation.type==="url_citation")j.enqueue({type:"source",sourceType:"url",id:(I=(P=(k=L.config).generateId)==null?void 0:P.call(k))!=null?I:j0(),url:D.annotation.url,title:D.annotation.title});else if(D.annotation.type==="file_citation")j.enqueue({type:"source",sourceType:"document",id:(N0=(l=(s=L.config).generateId)==null?void 0:l.call(s))!=null?N0:j0(),mediaType:"text/plain",title:(G0=(p=D.annotation.quote)!=null?p:D.annotation.filename)!=null?G0:"Document",filename:(h=D.annotation.filename)!=null?h:D.annotation.file_id,...D.annotation.file_id?{providerMetadata:{openai:{fileId:D.annotation.file_id}}}:{}})}else if(FG(D))j.enqueue({type:"error",error:D})},flush(A){let j={openai:{responseId:V}};if(U.length>0)j.openai.logprobs=U;if(z!==void 0)j.openai.serviceTier=z;A.enqueue({type:"finish",finishReason:H,usage:E,providerMetadata:j})}})),request:{body:Q},response:{headers:W}}}};function zG($){return $.type==="response.output_text.delta"}function NG($){return $.type==="response.output_item.done"}function MG($){return $.type==="response.completed"||$.type==="response.incomplete"}function AG($){return $.type==="response.created"}function wG($){return $.type==="response.function_call_arguments.delta"}function DG($){return $.type==="response.code_interpreter_call_code.delta"}function VG($){return $.type==="response.code_interpreter_call_code.done"}function G8($){return $.type==="response.output_item.added"}function KG($){return $.type==="response.output_text.annotation.added"}function FG($){return $.type==="error"}function RG($){let Q=$.startsWith("o3")||$.startsWith("o4-mini")||$.startsWith("gpt-5")&&!$.startsWith("gpt-5-chat"),Y=$.startsWith("gpt-4")||$.startsWith("gpt-5-mini")||$.startsWith("gpt-5")&&!$.startsWith("gpt-5-nano")&&!$.startsWith("gpt-5-chat")||$.startsWith("o3")||$.startsWith("o4-mini"),G={systemMessageMode:"system",supportsFlexProcessing:Q,supportsPriorityProcessing:Y};if($.startsWith("gpt-5-chat"))return{...G,isReasoningModel:!1};if($.startsWith("o")||$.startsWith("gpt-5")||$.startsWith("codex-")||$.startsWith("computer-use")){if($.startsWith("o1-mini")||$.startsWith("o1-preview"))return{...G,isReasoningModel:!0,systemMessageMode:"remove"};return{...G,isReasoningModel:!0,systemMessageMode:"developer"}}return{...G,isReasoningModel:!1}}function J8($){var Q;switch($.type){case"search":return{action:{type:"search",query:(Q=$.query)!=null?Q:void 0},...$.sources!=null&&{sources:$.sources}};case"open_page":return{action:{type:"openPage",url:$.url}};case"find":return{action:{type:"find",url:$.url,pattern:$.pattern}}}}var SG=$0(()=>R(X.object({instructions:X.string().nullish(),speed:X.number().min(0.25).max(4).default(1).nullish()}))),OG=class{constructor($,Q){this.modelId=$,this.config=Q,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:$,voice:Q="alloy",outputFormat:Y="mp3",speed:G,instructions:J,language:W,providerOptions:q}){let L=[],H=await X0({provider:"openai",providerOptions:q,schema:SG}),E={model:this.modelId,input:$,voice:Q,response_format:"mp3",speed:G,instructions:J};if(Y)if(["mp3","opus","aac","flac","wav","pcm"].includes(Y))E.response_format=Y;else L.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${Y}. Using mp3 instead.`});if(H){let U={};for(let V in U){let w=U[V];if(w!==void 0)E[V]=w}}if(W)L.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${W}" was ignored.`});return{requestBody:E,warnings:L}}async doGenerate($){var Q,Y,G;let J=(G=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?G:new Date,{requestBody:W,warnings:q}=await this.getArgs($),{value:L,responseHeaders:H,rawValue:E}=await Y0({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Q0(this.config.headers(),$.headers),body:W,failedResponseHandler:Z0,successfulResponseHandler:x4(),abortSignal:$.abortSignal,fetch:this.config.fetch});return{audio:L,warnings:q,request:{body:JSON.stringify(W)},response:{timestamp:J,modelId:this.modelId,headers:H,body:E}}}},PG=$0(()=>R(X.object({text:X.string(),language:X.string().nullish(),duration:X.number().nullish(),words:X.array(X.object({word:X.string(),start:X.number(),end:X.number()})).nullish(),segments:X.array(X.object({id:X.number(),seek:X.number(),start:X.number(),end:X.number(),text:X.string(),tokens:X.array(X.number()),temperature:X.number(),avg_logprob:X.number(),compression_ratio:X.number(),no_speech_prob:X.number()})).nullish()}))),bG=$0(()=>R(X.object({include:X.array(X.string()).optional(),language:X.string().optional(),prompt:X.string().optional(),temperature:X.number().min(0).max(1).default(0).optional(),timestampGranularities:X.array(X.enum(["word","segment"])).default(["segment"]).optional()}))),W8={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"},CG=class{constructor($,Q){this.modelId=$,this.config=Q,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:$,mediaType:Q,providerOptions:Y}){let G=[],J=await X0({provider:"openai",providerOptions:Y,schema:bG}),W=new FormData,q=$ instanceof Uint8Array?new Blob([$]):new Blob([h4($)]);W.append("model",this.modelId);let L=I4(Q);if(W.append("file",new File([q],"audio",{type:Q}),`audio.${L}`),J){let H={include:J.include,language:J.language,prompt:J.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:J.temperature,timestamp_granularities:J.timestampGranularities};for(let[E,U]of Object.entries(H))if(U!=null)if(Array.isArray(U))for(let V of U)W.append(`${E}[]`,String(V));else W.append(E,String(U))}return{formData:W,warnings:G}}async doGenerate($){var Q,Y,G,J,W,q,L,H;let E=(G=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?G:new Date,{formData:U,warnings:V}=await this.getArgs($),{value:w,responseHeaders:B,rawValue:K}=await k4({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Q0(this.config.headers(),$.headers),formData:U,failedResponseHandler:Z0,successfulResponseHandler:U0(PG),abortSignal:$.abortSignal,fetch:this.config.fetch}),z=w.language!=null&&w.language in W8?W8[w.language]:void 0;return{text:w.text,segments:(L=(q=(J=w.segments)==null?void 0:J.map((A)=>({text:A.text,startSecond:A.start,endSecond:A.end})))!=null?q:(W=w.words)==null?void 0:W.map((A)=>({text:A.word,startSecond:A.start,endSecond:A.end})))!=null?L:[],language:z,durationInSeconds:(H=w.duration)!=null?H:void 0,warnings:V,response:{timestamp:E,modelId:this.modelId,headers:B,body:K}}}},IG="2.0.59";function _G($={}){var Q,Y;let G=(Q=q$(m$({settingValue:$.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?Q:"https://api.openai.com/v1",J=(Y=$.name)!=null?Y:"openai",W=()=>p0({Authorization:`Bearer ${J$({apiKey:$.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":$.organization,"OpenAI-Project":$.project,...$.headers},`ai-sdk/openai/${IG}`),q=(z)=>new VY(z,{provider:`${J}.chat`,url:({path:A})=>`${G}${A}`,headers:W,fetch:$.fetch}),L=(z)=>new CY(z,{provider:`${J}.completion`,url:({path:A})=>`${G}${A}`,headers:W,fetch:$.fetch}),H=(z)=>new kY(z,{provider:`${J}.embedding`,url:({path:A})=>`${G}${A}`,headers:W,fetch:$.fetch}),E=(z)=>new vY(z,{provider:`${J}.image`,url:({path:A})=>`${G}${A}`,headers:W,fetch:$.fetch}),U=(z)=>new CG(z,{provider:`${J}.transcription`,url:({path:A})=>`${G}${A}`,headers:W,fetch:$.fetch}),V=(z)=>new OG(z,{provider:`${J}.speech`,url:({path:A})=>`${G}${A}`,headers:W,fetch:$.fetch}),w=(z)=>{if(new.target)throw Error("The OpenAI model function cannot be called with the new keyword.");return B(z)},B=(z)=>{return new BG(z,{provider:`${J}.responses`,url:({path:A})=>`${G}${A}`,headers:W,fetch:$.fetch,fileIdPrefixes:["file-"]})},K=function(z){return w(z)};return K.languageModel=w,K.chat=q,K.completion=L,K.responses=B,K.embedding=H,K.textEmbedding=H,K.textEmbeddingModel=H,K.image=E,K.imageModel=E,K.transcription=U,K.transcriptionModel=U,K.speech=V,K.speechModel=V,K.tools=JG,K}var B8=_G();var w1=[{id:"gpt-4o",name:"GPT-4o"},{id:"gpt-4o-mini",name:"GPT-4o Mini"},{id:"gpt-4-turbo",name:"GPT-4 Turbo"},{id:"gpt-4",name:"GPT-4"},{id:"gpt-3.5-turbo",name:"GPT-3.5 Turbo"}],z8={"gpt-4o":{contextLength:128000,maxOutput:16384},"gpt-4o-mini":{contextLength:128000,maxOutput:16384},"gpt-4-turbo":{contextLength:128000,maxOutput:4096},"gpt-4":{contextLength:8192,maxOutput:8192},"gpt-3.5-turbo":{contextLength:16384,maxOutput:4096}};class D1{id="openai";name="OpenAI";keyName="OPENAI_API_KEY";async fetchModels($){if(!$)return w1;try{let Q=await fetch("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${$}`}});if(!Q.ok)return w1;return(await Q.json()).data.filter((G)=>G.id.startsWith("gpt-")).map((G)=>({id:G.id,name:G.id}))}catch{return w1}}async getModelDetails($){if(z8[$])return z8[$];let Q=await l0($);if(Q)return{contextLength:Q.contextLength,maxOutput:Q.maxOutput,inputPrice:Q.inputPrice,outputPrice:Q.outputPrice};return null}createClient($,Q){return B8(Q,{apiKey:$})}}var kG="2.0.26",TG=Z(()=>R(X.object({error:X.object({code:X.number().nullable(),message:X.string(),status:X.string()})}))),O$=W$({errorSchema:TG,errorToMessage:($)=>$.error.message}),ZG=Z(()=>R(X.object({outputDimensionality:X.number().optional(),taskType:X.enum(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional()}))),xG=class{constructor($,Q){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=$,this.config=Q}get provider(){return this.config.provider}async doEmbed({values:$,headers:Q,abortSignal:Y,providerOptions:G}){let J=await X0({provider:"google",providerOptions:G,schema:ZG});if($.length>this.maxEmbeddingsPerCall)throw new I$({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:$});let W=Q0(await m0(this.config.headers),Q);if($.length===1){let{responseHeaders:E,value:U,rawValue:V}=await Y0({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:W,body:{model:`models/${this.modelId}`,content:{parts:[{text:$[0]}]},outputDimensionality:J==null?void 0:J.outputDimensionality,taskType:J==null?void 0:J.taskType},failedResponseHandler:O$,successfulResponseHandler:U0(fG),abortSignal:Y,fetch:this.config.fetch});return{embeddings:[U.embedding.values],usage:void 0,response:{headers:E,body:V}}}let{responseHeaders:q,value:L,rawValue:H}=await Y0({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:W,body:{requests:$.map((E)=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:E}]},outputDimensionality:J==null?void 0:J.outputDimensionality,taskType:J==null?void 0:J.taskType}))},failedResponseHandler:O$,successfulResponseHandler:U0(vG),abortSignal:Y,fetch:this.config.fetch});return{embeddings:L.embeddings.map((E)=>E.values),usage:void 0,response:{headers:q,body:H}}}},vG=Z(()=>R(X.object({embeddings:X.array(X.object({values:X.array(X.number())}))}))),fG=Z(()=>R(X.object({embedding:X.object({values:X.array(X.number())})})));function x0($){if($==null||yG($))return;if(typeof $==="boolean")return{type:"boolean",properties:{}};let{type:Q,description:Y,required:G,properties:J,items:W,allOf:q,anyOf:L,oneOf:H,format:E,const:U,minLength:V,enum:w}=$,B={};if(Y)B.description=Y;if(G)B.required=G;if(E)B.format=E;if(U!==void 0)B.enum=[U];if(Q)if(Array.isArray(Q))if(Q.includes("null"))B.type=Q.filter((K)=>K!=="null")[0],B.nullable=!0;else B.type=Q;else if(Q==="null")B.type="null";else B.type=Q;if(w!==void 0)B.enum=w;if(J!=null)B.properties=Object.entries(J).reduce((K,[z,A])=>{return K[z]=x0(A),K},{});if(W)B.items=Array.isArray(W)?W.map(x0):x0(W);if(q)B.allOf=q.map(x0);if(L)if(L.some((K)=>typeof K==="object"&&(K==null?void 0:K.type)==="null")){let K=L.filter((z)=>!(typeof z==="object"&&(z==null?void 0:z.type)==="null"));if(K.length===1){let z=x0(K[0]);if(typeof z==="object")B.nullable=!0,Object.assign(B,z)}else B.anyOf=K.map(x0),B.nullable=!0}else B.anyOf=L.map(x0);if(H)B.oneOf=H.map(x0);if(V!==void 0)B.minLength=V;return B}function yG($){return $!=null&&typeof $==="object"&&$.type==="object"&&($.properties==null||Object.keys($.properties).length===0)&&!$.additionalProperties}function gG($,Q){var Y;let G=[],J=[],W=!0,q=(Y=Q==null?void 0:Q.isGemmaModel)!=null?Y:!1;for(let{role:L,content:H}of $)switch(L){case"system":{if(!W)throw new o({functionality:"system messages are only supported at the beginning of the conversation"});G.push({text:H});break}case"user":{W=!1;let E=[];for(let U of H)switch(U.type){case"text":{E.push({text:U.text});break}case"file":{let V=U.mediaType==="image/*"?"image/jpeg":U.mediaType;E.push(U.data instanceof URL?{fileData:{mimeType:V,fileUri:U.data.toString()}}:{inlineData:{mimeType:V,data:K0(U.data)}});break}}J.push({role:"user",parts:E});break}case"assistant":{W=!1,J.push({role:"model",parts:H.map((E)=>{var U,V,w,B,K,z;switch(E.type){case"text":return E.text.length===0?void 0:{text:E.text,thoughtSignature:(V=(U=E.providerOptions)==null?void 0:U.google)==null?void 0:V.thoughtSignature};case"reasoning":return E.text.length===0?void 0:{text:E.text,thought:!0,thoughtSignature:(B=(w=E.providerOptions)==null?void 0:w.google)==null?void 0:B.thoughtSignature};case"file":{if(E.mediaType!=="image/png")throw new o({functionality:"Only PNG images are supported in assistant messages"});if(E.data instanceof URL)throw new o({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:E.mediaType,data:K0(E.data)}}}case"tool-call":return{functionCall:{name:E.toolName,args:E.input},thoughtSignature:(z=(K=E.providerOptions)==null?void 0:K.google)==null?void 0:z.thoughtSignature}}}).filter((E)=>E!==void 0)});break}case"tool":{W=!1;let E=[];for(let U of H){let V=U.output;if(V.type==="content")for(let w of V.value)switch(w.type){case"text":E.push({functionResponse:{name:U.toolName,response:{name:U.toolName,content:w.text}}});break;case"media":E.push({inlineData:{mimeType:w.mediaType,data:w.data}},{text:"Tool executed successfully and returned this image as a response"});break;default:E.push({text:JSON.stringify(w)});break}else E.push({functionResponse:{name:U.toolName,response:{name:U.toolName,content:V.value}}})}J.push({role:"user",parts:E});break}}if(q&&G.length>0&&J.length>0&&J[0].role==="user"){let L=G.map((H)=>H.text).join(`
22
+
23
+ `);J[0].parts.unshift({text:L+`
24
+
25
+ `})}return{systemInstruction:G.length>0&&!q?{parts:G}:void 0,contents:J}}function N8($){return $.includes("/")?$:`models/${$}`}var hG=Z(()=>R(X.object({responseModalities:X.array(X.enum(["TEXT","IMAGE"])).optional(),thinkingConfig:X.object({thinkingBudget:X.number().optional(),includeThoughts:X.boolean().optional()}).optional(),cachedContent:X.string().optional(),structuredOutputs:X.boolean().optional(),safetySettings:X.array(X.object({category:X.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:X.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:X.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:X.boolean().optional(),labels:X.record(X.string(),X.string()).optional(),mediaResolution:X.enum(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:X.object({aspectRatio:X.enum(["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]).optional()}).optional()})));function mG({tools:$,toolChoice:Q,modelId:Y}){var G;$=($==null?void 0:$.length)?$:void 0;let J=[],W=Y.includes("gemini-2"),q=Y.includes("gemini-1.5-flash")&&!Y.includes("-8b");if($==null)return{tools:void 0,toolConfig:void 0,toolWarnings:J};let L=$.some((V)=>V.type==="function"),H=$.some((V)=>V.type==="provider-defined");if(L&&H)J.push({type:"unsupported-tool",tool:$.find((V)=>V.type==="function"),details:"Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both."});if(H){let V=[];return $.filter((B)=>B.type==="provider-defined").forEach((B)=>{switch(B.id){case"google.google_search":if(W)V.push({googleSearch:{}});else if(q)V.push({googleSearchRetrieval:{dynamicRetrievalConfig:{mode:B.args.mode,dynamicThreshold:B.args.dynamicThreshold}}});else V.push({googleSearchRetrieval:{}});break;case"google.url_context":if(W)V.push({urlContext:{}});else J.push({type:"unsupported-tool",tool:B,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(W)V.push({codeExecution:{}});else J.push({type:"unsupported-tool",tool:B,details:"The code execution tools is not supported with other Gemini models than Gemini 2."});break;default:J.push({type:"unsupported-tool",tool:B});break}}),{tools:V.length>0?V:void 0,toolConfig:void 0,toolWarnings:J}}let E=[];for(let V of $)switch(V.type){case"function":E.push({name:V.name,description:(G=V.description)!=null?G:"",parameters:x0(V.inputSchema)});break;default:J.push({type:"unsupported-tool",tool:V});break}if(Q==null)return{tools:{functionDeclarations:E},toolConfig:void 0,toolWarnings:J};let U=Q.type;switch(U){case"auto":return{tools:{functionDeclarations:E},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:J};case"none":return{tools:{functionDeclarations:E},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:J};case"required":return{tools:{functionDeclarations:E},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:J};case"tool":return{tools:{functionDeclarations:E},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[Q.toolName]}},toolWarnings:J};default:throw new o({functionality:`tool choice type: ${U}`})}}function M8({finishReason:$,hasToolCalls:Q}){switch($){case"STOP":return Q?"tool-calls":"stop";case"MAX_TOKENS":return"length";case"IMAGE_SAFETY":case"RECITATION":case"SAFETY":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":return"content-filter";case"FINISH_REASON_UNSPECIFIED":case"OTHER":return"other";case"MALFORMED_FUNCTION_CALL":return"error";default:return"unknown"}}var uG=class{constructor($,Q){this.specificationVersion="v2";var Y;this.modelId=$,this.config=Q,this.generateId=(Y=Q.generateId)!=null?Y:j0}get provider(){return this.config.provider}get supportedUrls(){var $,Q,Y;return(Y=(Q=($=this.config).supportedUrls)==null?void 0:Q.call($))!=null?Y:{}}async getArgs({prompt:$,maxOutputTokens:Q,temperature:Y,topP:G,topK:J,frequencyPenalty:W,presencePenalty:q,stopSequences:L,responseFormat:H,seed:E,tools:U,toolChoice:V,providerOptions:w}){var B,K;let z=[],A=await X0({provider:"google",providerOptions:w,schema:hG});if(((B=A==null?void 0:A.thinkingConfig)==null?void 0:B.includeThoughts)===!0&&!this.config.provider.startsWith("google.vertex."))z.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let j=this.modelId.toLowerCase().startsWith("gemma-"),{contents:N,systemInstruction:M}=gG($,{isGemmaModel:j}),{tools:T,toolConfig:c,toolWarnings:d}=mG({tools:U,toolChoice:V,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:Q,temperature:Y,topK:J,topP:G,frequencyPenalty:W,presencePenalty:q,stopSequences:L,seed:E,responseMimeType:(H==null?void 0:H.type)==="json"?"application/json":void 0,responseSchema:(H==null?void 0:H.type)==="json"&&H.schema!=null&&((K=A==null?void 0:A.structuredOutputs)!=null?K:!0)?x0(H.schema):void 0,...(A==null?void 0:A.audioTimestamp)&&{audioTimestamp:A.audioTimestamp},responseModalities:A==null?void 0:A.responseModalities,thinkingConfig:A==null?void 0:A.thinkingConfig,...(A==null?void 0:A.imageConfig)&&{imageConfig:A.imageConfig},...(A==null?void 0:A.mediaResolution)&&{mediaResolution:A.mediaResolution}},contents:N,systemInstruction:j?void 0:M,safetySettings:A==null?void 0:A.safetySettings,tools:T,toolConfig:c,cachedContent:A==null?void 0:A.cachedContent,labels:A==null?void 0:A.labels},warnings:[...z,...d]}}async doGenerate($){var Q,Y,G,J,W,q,L,H,E,U,V,w,B;let{args:K,warnings:z}=await this.getArgs($),A=JSON.stringify(K),j=Q0(await m0(this.config.headers),$.headers),{responseHeaders:N,value:M,rawValue:T}=await Y0({url:`${this.config.baseURL}/${N8(this.modelId)}:generateContent`,headers:j,body:K,failedResponseHandler:O$,successfulResponseHandler:U0(iG),abortSignal:$.abortSignal,fetch:this.config.fetch}),c=M.candidates[0],d=[],v=(Y=(Q=c.content)==null?void 0:Q.parts)!=null?Y:[],m=M.usageMetadata,b;for(let x of v)if("executableCode"in x&&((G=x.executableCode)==null?void 0:G.code)){let y=this.config.generateId();b=y,d.push({type:"tool-call",toolCallId:y,toolName:"code_execution",input:JSON.stringify(x.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in x&&x.codeExecutionResult)d.push({type:"tool-result",toolCallId:b,toolName:"code_execution",result:{outcome:x.codeExecutionResult.outcome,output:x.codeExecutionResult.output},providerExecuted:!0}),b=void 0;else if("text"in x&&x.text!=null&&x.text.length>0)d.push({type:x.thought===!0?"reasoning":"text",text:x.text,providerMetadata:x.thoughtSignature?{google:{thoughtSignature:x.thoughtSignature}}:void 0});else if("functionCall"in x)d.push({type:"tool-call",toolCallId:this.config.generateId(),toolName:x.functionCall.name,input:JSON.stringify(x.functionCall.args),providerMetadata:x.thoughtSignature?{google:{thoughtSignature:x.thoughtSignature}}:void 0});else if("inlineData"in x)d.push({type:"file",data:x.inlineData.data,mediaType:x.inlineData.mimeType});let C=(J=A8({groundingMetadata:c.groundingMetadata,generateId:this.config.generateId}))!=null?J:[];for(let x of C)d.push(x);return{content:d,finishReason:M8({finishReason:c.finishReason,hasToolCalls:d.some((x)=>x.type==="tool-call")}),usage:{inputTokens:(W=m==null?void 0:m.promptTokenCount)!=null?W:void 0,outputTokens:(q=m==null?void 0:m.candidatesTokenCount)!=null?q:void 0,totalTokens:(L=m==null?void 0:m.totalTokenCount)!=null?L:void 0,reasoningTokens:(H=m==null?void 0:m.thoughtsTokenCount)!=null?H:void 0,cachedInputTokens:(E=m==null?void 0:m.cachedContentTokenCount)!=null?E:void 0},warnings:z,providerMetadata:{google:{promptFeedback:(U=M.promptFeedback)!=null?U:null,groundingMetadata:(V=c.groundingMetadata)!=null?V:null,urlContextMetadata:(w=c.urlContextMetadata)!=null?w:null,safetyRatings:(B=c.safetyRatings)!=null?B:null,usageMetadata:m!=null?m:null}},request:{body:A},response:{headers:N,body:T}}}async doStream($){let{args:Q,warnings:Y}=await this.getArgs($),G=JSON.stringify(Q),J=Q0(await m0(this.config.headers),$.headers),{responseHeaders:W,value:q}=await Y0({url:`${this.config.baseURL}/${N8(this.modelId)}:streamGenerateContent?alt=sse`,headers:J,body:Q,failedResponseHandler:O$,successfulResponseHandler:T0(pG),abortSignal:$.abortSignal,fetch:this.config.fetch}),L="unknown",H={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},E=void 0,U=this.config.generateId,V=!1,w=null,B=null,K=0,z=new Set,A;return{stream:q.pipeThrough(new TransformStream({start(j){j.enqueue({type:"stream-start",warnings:Y})},transform(j,N){var M,T,c,d,v,m,b,C,x,y,g,F;if($.includeRawChunks)N.enqueue({type:"raw",rawValue:j.rawValue});if(!j.success){N.enqueue({type:"error",error:j.error});return}let k=j.value,P=k.usageMetadata;if(P!=null)H.inputTokens=(M=P.promptTokenCount)!=null?M:void 0,H.outputTokens=(T=P.candidatesTokenCount)!=null?T:void 0,H.totalTokens=(c=P.totalTokenCount)!=null?c:void 0,H.reasoningTokens=(d=P.thoughtsTokenCount)!=null?d:void 0,H.cachedInputTokens=(v=P.cachedContentTokenCount)!=null?v:void 0;let I=(m=k.candidates)==null?void 0:m[0];if(I==null)return;let s=I.content,l=A8({groundingMetadata:I.groundingMetadata,generateId:U});if(l!=null){for(let N0 of l)if(N0.sourceType==="url"&&!z.has(N0.url))z.add(N0.url),N.enqueue(N0)}if(s!=null){let N0=(b=s.parts)!=null?b:[];for(let h of N0)if("executableCode"in h&&((C=h.executableCode)==null?void 0:C.code)){let D=U();A=D,N.enqueue({type:"tool-call",toolCallId:D,toolName:"code_execution",input:JSON.stringify(h.executableCode),providerExecuted:!0}),V=!0}else if("codeExecutionResult"in h&&h.codeExecutionResult){let D=A;if(D)N.enqueue({type:"tool-result",toolCallId:D,toolName:"code_execution",result:{outcome:h.codeExecutionResult.outcome,output:h.codeExecutionResult.output},providerExecuted:!0}),A=void 0}else if("text"in h&&h.text!=null&&h.text.length>0)if(h.thought===!0){if(w!==null)N.enqueue({type:"text-end",id:w}),w=null;if(B===null)B=String(K++),N.enqueue({type:"reasoning-start",id:B,providerMetadata:h.thoughtSignature?{google:{thoughtSignature:h.thoughtSignature}}:void 0});N.enqueue({type:"reasoning-delta",id:B,delta:h.text,providerMetadata:h.thoughtSignature?{google:{thoughtSignature:h.thoughtSignature}}:void 0})}else{if(B!==null)N.enqueue({type:"reasoning-end",id:B}),B=null;if(w===null)w=String(K++),N.enqueue({type:"text-start",id:w,providerMetadata:h.thoughtSignature?{google:{thoughtSignature:h.thoughtSignature}}:void 0});N.enqueue({type:"text-delta",id:w,delta:h.text,providerMetadata:h.thoughtSignature?{google:{thoughtSignature:h.thoughtSignature}}:void 0})}let p=dG(s.parts);if(p!=null)for(let h of p)N.enqueue({type:"file",mediaType:h.inlineData.mimeType,data:h.inlineData.data});let G0=cG({parts:s.parts,generateId:U});if(G0!=null)for(let h of G0)N.enqueue({type:"tool-input-start",id:h.toolCallId,toolName:h.toolName,providerMetadata:h.providerMetadata}),N.enqueue({type:"tool-input-delta",id:h.toolCallId,delta:h.args,providerMetadata:h.providerMetadata}),N.enqueue({type:"tool-input-end",id:h.toolCallId,providerMetadata:h.providerMetadata}),N.enqueue({type:"tool-call",toolCallId:h.toolCallId,toolName:h.toolName,input:h.args,providerMetadata:h.providerMetadata}),V=!0}if(I.finishReason!=null){if(L=M8({finishReason:I.finishReason,hasToolCalls:V}),E={google:{promptFeedback:(x=k.promptFeedback)!=null?x:null,groundingMetadata:(y=I.groundingMetadata)!=null?y:null,urlContextMetadata:(g=I.urlContextMetadata)!=null?g:null,safetyRatings:(F=I.safetyRatings)!=null?F:null}},P!=null)E.google.usageMetadata=P}},flush(j){if(w!==null)j.enqueue({type:"text-end",id:w});if(B!==null)j.enqueue({type:"reasoning-end",id:B});j.enqueue({type:"finish",finishReason:L,usage:H,providerMetadata:E})}})),response:{headers:W},request:{body:G}}}};function cG({parts:$,generateId:Q}){let Y=$==null?void 0:$.filter((G)=>("functionCall"in G));return Y==null||Y.length===0?void 0:Y.map((G)=>({type:"tool-call",toolCallId:Q(),toolName:G.functionCall.name,args:JSON.stringify(G.functionCall.args),providerMetadata:G.thoughtSignature?{google:{thoughtSignature:G.thoughtSignature}}:void 0}))}function dG($){return $==null?void 0:$.filter((Q)=>("inlineData"in Q))}function A8({groundingMetadata:$,generateId:Q}){var Y;return(Y=$==null?void 0:$.groundingChunks)==null?void 0:Y.filter((G)=>G.web!=null).map((G)=>({type:"source",sourceType:"url",id:Q(),url:G.web.uri,title:G.web.title}))}var w8=()=>X.object({webSearchQueries:X.array(X.string()).nullish(),retrievalQueries:X.array(X.string()).nullish(),searchEntryPoint:X.object({renderedContent:X.string()}).nullish(),groundingChunks:X.array(X.object({web:X.object({uri:X.string(),title:X.string()}).nullish(),retrievedContext:X.object({uri:X.string(),title:X.string()}).nullish()})).nullish(),groundingSupports:X.array(X.object({segment:X.object({startIndex:X.number().nullish(),endIndex:X.number().nullish(),text:X.string().nullish()}),segment_text:X.string().nullish(),groundingChunkIndices:X.array(X.number()).nullish(),supportChunkIndices:X.array(X.number()).nullish(),confidenceScores:X.array(X.number()).nullish(),confidenceScore:X.array(X.number()).nullish()})).nullish(),retrievalMetadata:X.union([X.object({webDynamicRetrievalScore:X.number()}),X.object({})]).nullish()}),D8=()=>X.object({parts:X.array(X.union([X.object({functionCall:X.object({name:X.string(),args:X.unknown()}),thoughtSignature:X.string().nullish()}),X.object({inlineData:X.object({mimeType:X.string(),data:X.string()})}),X.object({executableCode:X.object({language:X.string(),code:X.string()}).nullish(),codeExecutionResult:X.object({outcome:X.string(),output:X.string()}).nullish(),text:X.string().nullish(),thought:X.boolean().nullish(),thoughtSignature:X.string().nullish()})])).nullish()}),u$=()=>X.object({category:X.string().nullish(),probability:X.string().nullish(),probabilityScore:X.number().nullish(),severity:X.string().nullish(),severityScore:X.number().nullish(),blocked:X.boolean().nullish()}),V8=X.object({cachedContentTokenCount:X.number().nullish(),thoughtsTokenCount:X.number().nullish(),promptTokenCount:X.number().nullish(),candidatesTokenCount:X.number().nullish(),totalTokenCount:X.number().nullish()}),K8=()=>X.object({urlMetadata:X.array(X.object({retrievedUrl:X.string(),urlRetrievalStatus:X.string()}))}),iG=Z(()=>R(X.object({candidates:X.array(X.object({content:D8().nullish().or(X.object({}).strict()),finishReason:X.string().nullish(),safetyRatings:X.array(u$()).nullish(),groundingMetadata:w8().nullish(),urlContextMetadata:K8().nullish()})),usageMetadata:V8.nullish(),promptFeedback:X.object({blockReason:X.string().nullish(),safetyRatings:X.array(u$()).nullish()}).nullish()}))),pG=Z(()=>R(X.object({candidates:X.array(X.object({content:D8().nullish(),finishReason:X.string().nullish(),safetyRatings:X.array(u$()).nullish(),groundingMetadata:w8().nullish(),urlContextMetadata:K8().nullish()})).nullish(),usageMetadata:V8.nullish(),promptFeedback:X.object({blockReason:X.string().nullish(),safetyRatings:X.array(u$()).nullish()}).nullish()}))),lG=L0({id:"google.code_execution",name:"code_execution",inputSchema:X.object({language:X.string().describe("The programming language of the code."),code:X.string().describe("The code to be executed.")}),outputSchema:X.object({outcome:X.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:X.string().describe("The output from the code execution.")})}),nG=q0({id:"google.google_search",name:"google_search",inputSchema:Z(()=>R(X.object({mode:X.enum(["MODE_DYNAMIC","MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),dynamicThreshold:X.number().default(1)})))}),rG=q0({id:"google.url_context",name:"url_context",inputSchema:Z(()=>R(X.object({})))}),aG={googleSearch:nG,urlContext:rG,codeExecution:lG},sG=class{constructor($,Q,Y){this.modelId=$,this.settings=Q,this.config=Y,this.specificationVersion="v2"}get maxImagesPerCall(){var $;return($=this.settings.maxImagesPerCall)!=null?$:4}get provider(){return this.config.provider}async doGenerate($){var Q,Y,G;let{prompt:J,n:W=1,size:q="1024x1024",aspectRatio:L="1:1",seed:H,providerOptions:E,headers:U,abortSignal:V}=$,w=[];if(q!=null)w.push({type:"unsupported-setting",setting:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});if(H!=null)w.push({type:"unsupported-setting",setting:"seed",details:"This model does not support the `seed` option through this provider."});let B=await X0({provider:"google",providerOptions:E,schema:oG}),K=(G=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?G:new Date,z={sampleCount:W};if(L!=null)z.aspectRatio=L;if(B)Object.assign(z,B);let A={instances:[{prompt:J}],parameters:z},{responseHeaders:j,value:N}=await Y0({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:Q0(await m0(this.config.headers),U),body:A,failedResponseHandler:O$,successfulResponseHandler:U0(tG),abortSignal:V,fetch:this.config.fetch});return{images:N.predictions.map((M)=>M.bytesBase64Encoded),warnings:w!=null?w:[],providerMetadata:{google:{images:N.predictions.map((M)=>({}))}},response:{timestamp:K,modelId:this.modelId,headers:j}}}},tG=Z(()=>R(X.object({predictions:X.array(X.object({bytesBase64Encoded:X.string()})).default([])}))),oG=Z(()=>R(X.object({personGeneration:X.enum(["dont_allow","allow_adult","allow_all"]).nullish(),aspectRatio:X.enum(["1:1","3:4","4:3","9:16","16:9"]).nullish()})));function eG($={}){var Q;let Y=(Q=q$($.baseURL))!=null?Q:"https://generativelanguage.googleapis.com/v1beta",G=()=>p0({"x-goog-api-key":J$({apiKey:$.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...$.headers},`ai-sdk/google/${kG}`),J=(H)=>{var E;return new uG(H,{provider:"google.generative-ai",baseURL:Y,headers:G,generateId:(E=$.generateId)!=null?E:j0,supportedUrls:()=>({"*":[new RegExp(`^${Y}/files/.*$`),new RegExp("^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$"),new RegExp("^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$")]}),fetch:$.fetch})},W=(H)=>new xG(H,{provider:"google.generative-ai",baseURL:Y,headers:G,fetch:$.fetch}),q=(H,E={})=>new sG(H,E,{provider:"google.generative-ai",baseURL:Y,headers:G,fetch:$.fetch}),L=function(H){if(new.target)throw Error("The Google Generative AI model function cannot be called with the new keyword.");return J(H)};return L.languageModel=J,L.chat=J,L.generativeAI=J,L.embedding=W,L.textEmbedding=W,L.textEmbeddingModel=W,L.image=q,L.imageModel=q,L.tools=aG,L}var F8=eG();var $2=[{id:"gemini-2.0-flash-exp",name:"Gemini 2.0 Flash (Experimental)"},{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro"},{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash"}],R8={"gemini-2.0-flash-exp":{contextLength:1e6,maxOutput:8192},"gemini-1.5-pro":{contextLength:2000000,maxOutput:8192},"gemini-1.5-flash":{contextLength:1e6,maxOutput:8192}};class V1{id="google";name="Google";keyName="GOOGLE_API_KEY";async fetchModels(){return $2}async getModelDetails($){if(R8[$])return R8[$];let Q=await l0($);if(Q)return{contextLength:Q.contextLength,maxOutput:Q.maxOutput,inputPrice:Q.inputPrice,outputPrice:Q.outputPrice};return null}createClient($,Q){return F8(Q,{apiKey:$})}}var{defineProperty:X2,defineProperties:Q2,getOwnPropertyDescriptors:Y2,getOwnPropertySymbols:S8}=Object,G2=Object.prototype.hasOwnProperty,J2=Object.prototype.propertyIsEnumerable,O8=($,Q,Y)=>(Q in $)?X2($,Q,{enumerable:!0,configurable:!0,writable:!0,value:Y}):$[Q]=Y,H0=($,Q)=>{for(var Y in Q||(Q={}))if(G2.call(Q,Y))O8($,Y,Q[Y]);if(S8){for(var Y of S8(Q))if(J2.call(Q,Y))O8($,Y,Q[Y])}return $},d$=($,Q)=>Q2($,Y2(Q)),k8="vercel.ai.error",W2=Symbol.for(k8),T8,q2=class $ extends Error{constructor({name:Q,message:Y,cause:G}){super(Y);this[T8]=!0,this.name=Q,this.cause=G}static isInstance(Q){return $.hasMarker(Q,k8)}static hasMarker(Q,Y){let G=Symbol.for(Y);return Q!=null&&typeof Q==="object"&&G in Q&&typeof Q[G]==="boolean"&&Q[G]===!0}};T8=W2;var z0=q2,Z8="AI_APICallError",x8=`vercel.ai.error.${Z8}`,L2=Symbol.for(x8),v8,u0=class extends z0{constructor({message:$,url:Q,requestBodyValues:Y,statusCode:G,responseHeaders:J,responseBody:W,cause:q,isRetryable:L=G!=null&&(G===408||G===409||G===429||G>=500),data:H}){super({name:Z8,message:$,cause:q});this[v8]=!0,this.url=Q,this.requestBodyValues=Y,this.statusCode=G,this.responseHeaders=J,this.responseBody=W,this.isRetryable=L,this.data=H}static isInstance($){return z0.hasMarker($,x8)}};v8=L2;var f8="AI_EmptyResponseBodyError",y8=`vercel.ai.error.${f8}`,H2=Symbol.for(y8),g8,E2=class extends z0{constructor({message:$="Empty response body"}={}){super({name:f8,message:$});this[g8]=!0}static isInstance($){return z0.hasMarker($,y8)}};g8=H2;function h8($){if($==null)return"unknown error";if(typeof $==="string")return $;if($ instanceof Error)return $.message;return JSON.stringify($)}var m8="AI_InvalidArgumentError",u8=`vercel.ai.error.${m8}`,U2=Symbol.for(u8),c8,j2=class extends z0{constructor({message:$,cause:Q,argument:Y}){super({name:m8,message:$,cause:Q});this[c8]=!0,this.argument=Y}static isInstance($){return z0.hasMarker($,u8)}};c8=U2;var d8="AI_InvalidPromptError",i8=`vercel.ai.error.${d8}`,B2=Symbol.for(i8),p8,z2=class extends z0{constructor({prompt:$,message:Q,cause:Y}){super({name:d8,message:`Invalid prompt: ${Q}`,cause:Y});this[p8]=!0,this.prompt=$}static isInstance($){return z0.hasMarker($,i8)}};p8=B2;var l8="AI_InvalidResponseDataError",n8=`vercel.ai.error.${l8}`,N2=Symbol.for(n8),r8,K1=class extends z0{constructor({data:$,message:Q=`Invalid response data: ${JSON.stringify($)}.`}){super({name:l8,message:Q});this[r8]=!0,this.data=$}static isInstance($){return z0.hasMarker($,n8)}};r8=N2;var a8="AI_JSONParseError",s8=`vercel.ai.error.${a8}`,M2=Symbol.for(s8),t8,i$=class extends z0{constructor({text:$,cause:Q}){super({name:a8,message:`JSON parsing failed: Text: ${$}.
26
+ Error message: ${h8(Q)}`,cause:Q});this[t8]=!0,this.text=$}static isInstance($){return z0.hasMarker($,s8)}};t8=M2;var o8="AI_LoadAPIKeyError",e8=`vercel.ai.error.${o8}`,A2=Symbol.for(e8),$9,c$=class extends z0{constructor({message:$}){super({name:o8,message:$});this[$9]=!0}static isInstance($){return z0.hasMarker($,e8)}};$9=A2;var w2="AI_LoadSettingError",D2=`vercel.ai.error.${w2}`,V2=Symbol.for(D2),K2;K2=V2;var F2="AI_NoContentGeneratedError",R2=`vercel.ai.error.${F2}`,S2=Symbol.for(R2),O2;O2=S2;var P2="AI_NoSuchModelError",b2=`vercel.ai.error.${P2}`,C2=Symbol.for(b2),I2;I2=C2;var _2="AI_TooManyEmbeddingValuesForCallError",k2=`vercel.ai.error.${_2}`,T2=Symbol.for(k2),Z2;Z2=T2;var X9="AI_TypeValidationError",Q9=`vercel.ai.error.${X9}`,x2=Symbol.for(Q9),Y9,v2=class $ extends z0{constructor({value:Q,cause:Y}){super({name:X9,message:`Type validation failed: Value: ${JSON.stringify(Q)}.
27
+ Error message: ${h8(Y)}`,cause:Y});this[Y9]=!0,this.value=Q}static isInstance(Q){return z0.hasMarker(Q,Q9)}static wrap({value:Q,cause:Y}){return $.isInstance(Y)&&Y.value===Q?Y:new $({value:Q,cause:Y})}};Y9=x2;var P$=v2,G9="AI_UnsupportedFunctionalityError",J9=`vercel.ai.error.${G9}`,f2=Symbol.for(J9),W9,r0=class extends z0{constructor({functionality:$,message:Q=`'${$}' functionality not supported.`}){super({name:G9,message:Q});this[W9]=!0,this.functionality=$}static isInstance($){return z0.hasMarker($,J9)}};W9=f2;var P8=class extends Error{constructor($,Q){super($),this.name="ParseError",this.type=Q.type,this.field=Q.field,this.value=Q.value,this.line=Q.line}};function F1($){}function y2($){if(typeof $=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:Q=F1,onError:Y=F1,onRetry:G=F1,onComment:J}=$,W="",q=!0,L,H="",E="";function U(z){let A=q?z.replace(/^\xEF\xBB\xBF/,""):z,[j,N]=g2(`${W}${A}`);for(let M of j)V(M);W=N,q=!1}function V(z){if(z===""){B();return}if(z.startsWith(":")){J&&J(z.slice(z.startsWith(": ")?2:1));return}let A=z.indexOf(":");if(A!==-1){let j=z.slice(0,A),N=z[A+1]===" "?2:1,M=z.slice(A+N);w(j,M,z);return}w(z,"",z)}function w(z,A,j){switch(z){case"event":E=A;break;case"data":H=`${H}${A}
28
+ `;break;case"id":L=A.includes("\x00")?void 0:A;break;case"retry":/^\d+$/.test(A)?G(parseInt(A,10)):Y(new P8(`Invalid \`retry\` value: "${A}"`,{type:"invalid-retry",value:A,line:j}));break;default:Y(new P8(`Unknown field "${z.length>20?`${z.slice(0,20)}…`:z}"`,{type:"unknown-field",field:z,value:A,line:j}));break}}function B(){H.length>0&&Q({id:L,event:E||void 0,data:H.endsWith(`
29
+ `)?H.slice(0,-1):H}),L=void 0,H="",E=""}function K(z={}){W&&z.consume&&V(W),q=!0,L=void 0,H="",E="",W=""}return{feed:U,reset:K}}function g2($){let Q=[],Y="",G=0;for(;G<$.length;){let J=$.indexOf("\r",G),W=$.indexOf(`
30
+ `,G),q=-1;if(J!==-1&&W!==-1?q=Math.min(J,W):J!==-1?q=J:W!==-1&&(q=W),q===-1){Y=$.slice(G);break}else{let L=$.slice(G,q);Q.push(L),G=q+1,$[G-1]==="\r"&&$[G]===`
31
+ `&&G++}}return[Q,Y]}var h2=class extends TransformStream{constructor({onError:$,onRetry:Q,onComment:Y}={}){let G;super({start(J){G=y2({onEvent:(W)=>{J.enqueue(W)},onError(W){$==="terminate"?J.error(W):typeof $=="function"&&$(W)},onRetry:Q,onComment:Y})},transform(J){G.feed(J)}})}},rq=Symbol("Let zodToJsonSchema decide on which parser to use"),aq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function p$(...$){return $.reduce((Q,Y)=>H0(H0({},Q),Y!=null?Y:{}),{})}function a$($){return Object.fromEntries([...$.headers])}var m2=({prefix:$,size:Q=16,alphabet:Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:G="-"}={})=>{let J=()=>{let W=Y.length,q=Array(Q);for(let L=0;L<Q;L++)q[L]=Y[Math.random()*W|0];return q.join("")};if($==null)return J;if(Y.includes(G))throw new j2({argument:"separator",message:`The separator "${G}" must not be part of the alphabet "${Y}".`});return()=>`${$}${G}${J()}`},b0=m2();function S1($){return($ instanceof Error||$ instanceof DOMException)&&($.name==="AbortError"||$.name==="ResponseAborted"||$.name==="TimeoutError")}var u2=["fetch failed","failed to fetch"];function c2({error:$,url:Q,requestBodyValues:Y}){if(S1($))return $;if($ instanceof TypeError&&u2.includes($.message.toLowerCase())){let G=$.cause;if(G!=null)return new u0({message:`Cannot connect to API: ${G.message}`,cause:G,url:Q,requestBodyValues:Y,isRetryable:!0})}return $}function d2($){return Object.fromEntries(Object.entries($).filter(([Q,Y])=>Y!=null))}function i2({apiKey:$,environmentVariableName:Q,apiKeyParameterName:Y="apiKey",description:G}){if(typeof $==="string")return $;if($!=null)throw new c$({message:`${G} API key must be a string.`});if(typeof process>"u")throw new c$({message:`${G} API key is missing. Pass it using the '${Y}' parameter. Environment variables is not supported in this environment.`});if($=process.env[Q],$==null)throw new c$({message:`${G} API key is missing. Pass it using the '${Y}' parameter or the ${Q} environment variable.`});if(typeof $!=="string")throw new c$({message:`${G} API key must be a string. The value of the ${Q} environment variable is not a string.`});return $}var p2=/"__proto__"\s*:/,l2=/"constructor"\s*:/;function n2($){let Q=JSON.parse($);if(Q===null||typeof Q!=="object")return Q;if(p2.test($)===!1&&l2.test($)===!1)return Q;return r2(Q)}function r2($){let Q=[$];while(Q.length){let Y=Q;Q=[];for(let G of Y){if(Object.prototype.hasOwnProperty.call(G,"__proto__"))throw SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(G,"constructor")&&Object.prototype.hasOwnProperty.call(G.constructor,"prototype"))throw SyntaxError("Object contains forbidden prototype property");for(let J in G){let W=G[J];if(W&&typeof W==="object")Q.push(W)}}}return $}function P1($){let{stackTraceLimit:Q}=Error;Error.stackTraceLimit=0;try{return n2($)}finally{Error.stackTraceLimit=Q}}var O1=Symbol.for("vercel.ai.validator");function a2($){return{[O1]:!0,validate:$}}function s2($){return typeof $==="object"&&$!==null&&O1 in $&&$[O1]===!0&&"validate"in $}function t2($){return s2($)?$:o2($)}function o2($){return a2(async(Q)=>{let Y=await $["~standard"].validate(Q);return Y.issues==null?{success:!0,value:Y.value}:{success:!1,error:new P$({value:Q,cause:Y.issues})}})}async function e2({value:$,schema:Q}){let Y=await q9({value:$,schema:Q});if(!Y.success)throw P$.wrap({value:$,cause:Y.error});return Y.value}async function q9({value:$,schema:Q}){let Y=t2(Q);try{if(Y.validate==null)return{success:!0,value:$,rawValue:$};let G=await Y.validate($);if(G.success)return{success:!0,value:G.value,rawValue:$};return{success:!1,error:P$.wrap({value:$,cause:G.error}),rawValue:$}}catch(G){return{success:!1,error:P$.wrap({value:$,cause:G}),rawValue:$}}}async function $5({text:$,schema:Q}){try{let Y=P1($);if(Q==null)return Y;return e2({value:Y,schema:Q})}catch(Y){if(i$.isInstance(Y)||P$.isInstance(Y))throw Y;throw new i$({text:$,cause:Y})}}async function L9({text:$,schema:Q}){try{let Y=P1($);if(Q==null)return{success:!0,value:Y,rawValue:Y};return await q9({value:Y,schema:Q})}catch(Y){return{success:!1,error:i$.isInstance(Y)?Y:new i$({text:$,cause:Y}),rawValue:void 0}}}function R1($){try{return P1($),!0}catch(Q){return!1}}function X5({stream:$,schema:Q}){return $.pipeThrough(new TextDecoderStream).pipeThrough(new h2).pipeThrough(new TransformStream({async transform({data:Y},G){if(Y==="[DONE]")return;G.enqueue(await L9({text:Y,schema:Q}))}}))}var Q5=()=>globalThis.fetch,l$=async({url:$,headers:Q,body:Y,failedResponseHandler:G,successfulResponseHandler:J,abortSignal:W,fetch:q})=>Y5({url:$,headers:H0({"Content-Type":"application/json"},Q),body:{content:JSON.stringify(Y),values:Y},failedResponseHandler:G,successfulResponseHandler:J,abortSignal:W,fetch:q}),Y5=async({url:$,headers:Q={},body:Y,successfulResponseHandler:G,failedResponseHandler:J,abortSignal:W,fetch:q=Q5()})=>{try{let L=await q($,{method:"POST",headers:d2(Q),body:Y.content,signal:W}),H=a$(L);if(!L.ok){let E;try{E=await J({response:L,url:$,requestBodyValues:Y.values})}catch(U){if(S1(U)||u0.isInstance(U))throw U;throw new u0({message:"Failed to process error response",cause:U,statusCode:L.status,url:$,responseHeaders:H,requestBodyValues:Y.values})}throw E.value}try{return await G({response:L,url:$,requestBodyValues:Y.values})}catch(E){if(E instanceof Error){if(S1(E)||u0.isInstance(E))throw E}throw new u0({message:"Failed to process successful response",cause:E,statusCode:L.status,url:$,responseHeaders:H,requestBodyValues:Y.values})}}catch(L){throw c2({error:L,url:$,requestBodyValues:Y.values})}},G5=({errorSchema:$,errorToMessage:Q,isRetryable:Y})=>async({response:G,url:J,requestBodyValues:W})=>{let q=await G.text(),L=a$(G);if(q.trim()==="")return{responseHeaders:L,value:new u0({message:G.statusText,url:J,requestBodyValues:W,statusCode:G.status,responseHeaders:L,responseBody:q,isRetryable:Y==null?void 0:Y(G)})};try{let H=await $5({text:q,schema:$});return{responseHeaders:L,value:new u0({message:Q(H),url:J,requestBodyValues:W,statusCode:G.status,responseHeaders:L,responseBody:q,data:H,isRetryable:Y==null?void 0:Y(G,H)})}}catch(H){return{responseHeaders:L,value:new u0({message:G.statusText,url:J,requestBodyValues:W,statusCode:G.status,responseHeaders:L,responseBody:q,isRetryable:Y==null?void 0:Y(G)})}}},H9=($)=>async({response:Q})=>{let Y=a$(Q);if(Q.body==null)throw new E2({});return{responseHeaders:Y,value:X5({stream:Q.body,schema:$})}},E9=($)=>async({response:Q,url:Y,requestBodyValues:G})=>{let J=await Q.text(),W=await L9({text:J,schema:$}),q=a$(Q);if(!W.success)throw new u0({message:"Invalid JSON response",cause:W.error,statusCode:Q.status,responseHeaders:q,responseBody:J,url:Y,requestBodyValues:G});return{responseHeaders:q,value:W.value,rawValue:W.rawValue}};var{btoa:J5,atob:sq}=globalThis;function W5($){let Q="";for(let Y=0;Y<$.length;Y++)Q+=String.fromCodePoint($[Y]);return J5(Q)}function q5($){return $==null?void 0:$.replace(/\/$/,"")}var L5=X.object({type:X.literal("reasoning.summary"),summary:X.string()}),H5=X.object({type:X.literal("reasoning.encrypted"),data:X.string()}),E5=X.object({type:X.literal("reasoning.text"),text:X.string().nullish(),signature:X.string().nullish()}),U5=X.union([L5,H5,E5]),j5=X.union([U5,X.unknown().transform(()=>null)]),b1=X.array(j5).transform(($)=>$.filter((Q)=>!!Q)),C1=X.object({error:X.object({code:X.union([X.string(),X.number()]).nullable().optional().default(null),message:X.string(),type:X.string().nullable().optional().default(null),param:X.any().nullable().optional().default(null)})}),n$=G5({errorSchema:C1,errorToMessage:($)=>$.error.message});function r$($){switch($){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"}}function U9({url:$,protocols:Q}){try{let Y=new URL($);return Q.has(Y.protocol)}catch(Y){return!1}}function b8({part:$,defaultMediaType:Q}){var Y,G;if($.data instanceof Uint8Array){let W=W5($.data);return`data:${(Y=$.mediaType)!=null?Y:Q};base64,${W}`}let J=$.data.toString();if(U9({url:J,protocols:new Set(["http:","https:"])}))return J;return J.startsWith("data:")?J:`data:${(G=$.mediaType)!=null?G:Q};base64,${J}`}function C8($,Q){var Y;let G=$.match(/^data:([^;]+)/);return G?(Y=G[1])!=null?Y:Q:Q}function I8($){let Q=$.match(/^data:[^;]*;base64,(.+)$/);return Q?Q[1]:$}function n0($){var Q,Y,G;let J=$==null?void 0:$.anthropic,W=$==null?void 0:$.openrouter;return(G=(Y=(Q=W==null?void 0:W.cacheControl)!=null?Q:W==null?void 0:W.cache_control)!=null?Y:J==null?void 0:J.cacheControl)!=null?G:J==null?void 0:J.cache_control}function B5($){var Q,Y,G;let J=[];for(let{role:W,content:q,providerOptions:L}of $)switch(W){case"system":{J.push({role:"system",content:q,cache_control:n0(L)});break}case"user":{if(q.length===1&&((Q=q[0])==null?void 0:Q.type)==="text"){let U=(Y=n0(L))!=null?Y:n0(q[0].providerOptions),V=U?[{type:"text",text:q[0].text,cache_control:U}]:q[0].text;J.push({role:"user",content:V});break}let H=n0(L),E=q.map((U)=>{var V,w,B,K,z,A;let j=(V=n0(U.providerOptions))!=null?V:H;switch(U.type){case"text":return{type:"text",text:U.text,cache_control:j};case"file":{if((w=U.mediaType)==null?void 0:w.startsWith("image/"))return{type:"image_url",image_url:{url:b8({part:U,defaultMediaType:"image/jpeg"})},cache_control:j};let N=String((A=(z=(K=(B=U.providerOptions)==null?void 0:B.openrouter)==null?void 0:K.filename)!=null?z:U.filename)!=null?A:""),M=b8({part:U,defaultMediaType:"application/pdf"});if(U9({url:M,protocols:new Set(["http:","https:"])}))return{type:"file",file:{filename:N,file_data:M}};return{type:"file",file:{filename:N,file_data:M},cache_control:j}}default:return{type:"text",text:"",cache_control:j}}});J.push({role:"user",content:E});break}case"assistant":{let H="",E="",U=[],V=[];for(let w of q)switch(w.type){case"text":{H+=w.text;break}case"tool-call":{V.push({id:w.toolCallId,type:"function",function:{name:w.toolName,arguments:JSON.stringify(w.input)}});break}case"reasoning":{E+=w.text,U.push({type:"reasoning.text",text:w.text});break}case"file":break;default:break}J.push({role:"assistant",content:H,tool_calls:V.length>0?V:void 0,reasoning:E||void 0,reasoning_details:U.length>0?U:void 0,cache_control:n0(L)});break}case"tool":{for(let H of q){let E=z5(H);J.push({role:"tool",tool_call_id:H.toolCallId,content:E,cache_control:(G=n0(L))!=null?G:n0(H.providerOptions)})}break}default:break}return J}function z5($){return $.output.type==="text"?$.output.value:JSON.stringify($.output.value)}var $7=X.union([X.literal("auto"),X.literal("none"),X.literal("required"),X.object({type:X.literal("function"),function:X.object({name:X.string()})})]);function N5($){switch($.type){case"auto":case"none":case"required":return $.type;case"tool":return{type:"function",function:{name:$.toolName}};default:throw Error(`Invalid tool choice type: ${$}`)}}var M5=X.object({type:X.literal("image_url"),image_url:X.object({url:X.string()})}),A5=X.union([M5,X.unknown().transform(()=>null)]),j9=X.array(A5).transform(($)=>$.filter((Q)=>!!Q)),B9=X.object({id:X.string().optional(),model:X.string().optional(),provider:X.string().optional(),usage:X.object({prompt_tokens:X.number(),prompt_tokens_details:X.object({cached_tokens:X.number()}).nullish(),completion_tokens:X.number(),completion_tokens_details:X.object({reasoning_tokens:X.number()}).nullish(),total_tokens:X.number(),cost:X.number().optional(),cost_details:X.object({upstream_inference_cost:X.number().nullish()}).nullish()}).nullish()}),w5=B9.extend({choices:X.array(X.object({message:X.object({role:X.literal("assistant"),content:X.string().nullable().optional(),reasoning:X.string().nullable().optional(),reasoning_details:b1.nullish(),images:j9.nullish(),tool_calls:X.array(X.object({id:X.string().optional().nullable(),type:X.literal("function"),function:X.object({name:X.string(),arguments:X.string()})})).optional(),annotations:X.array(X.object({type:X.enum(["url_citation"]),url_citation:X.object({end_index:X.number(),start_index:X.number(),title:X.string(),url:X.string(),content:X.string().optional()})})).nullish()}),index:X.number().nullish(),logprobs:X.object({content:X.array(X.object({token:X.string(),logprob:X.number(),top_logprobs:X.array(X.object({token:X.string(),logprob:X.number()}))})).nullable()}).nullable().optional(),finish_reason:X.string().optional().nullable()}))}),D5=X.union([B9.extend({choices:X.array(X.object({delta:X.object({role:X.enum(["assistant"]).optional(),content:X.string().nullish(),reasoning:X.string().nullish().optional(),reasoning_details:b1.nullish(),images:j9.nullish(),tool_calls:X.array(X.object({index:X.number().nullish(),id:X.string().nullish(),type:X.literal("function").optional(),function:X.object({name:X.string().nullish(),arguments:X.string().nullish()})})).nullish(),annotations:X.array(X.object({type:X.enum(["url_citation"]),url_citation:X.object({end_index:X.number(),start_index:X.number(),title:X.string(),url:X.string(),content:X.string().optional()})})).nullish()}).nullish(),logprobs:X.object({content:X.array(X.object({token:X.string(),logprob:X.number(),top_logprobs:X.array(X.object({token:X.string(),logprob:X.number()}))})).nullable()}).nullish(),finish_reason:X.string().nullable().optional(),index:X.number().nullish()}))}),C1]),V5=class{constructor($,Q,Y){this.specificationVersion="v2",this.provider="openrouter",this.defaultObjectGenerationMode="tool",this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.modelId=$,this.settings=Q,this.config=Y}getArgs({prompt:$,maxOutputTokens:Q,temperature:Y,topP:G,frequencyPenalty:J,presencePenalty:W,seed:q,stopSequences:L,responseFormat:H,topK:E,tools:U,toolChoice:V}){var w;let B=H0(H0({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===!0||typeof this.settings.logprobs==="number"?!0:void 0,top_logprobs:typeof this.settings.logprobs==="number"?this.settings.logprobs:typeof this.settings.logprobs==="boolean"?this.settings.logprobs?0:void 0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:Q,temperature:Y,top_p:G,frequency_penalty:J,presence_penalty:W,seed:q,stop:L,response_format:H,top_k:E,messages:B5($),include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning,usage:this.settings.usage,plugins:this.settings.plugins,web_search_options:this.settings.web_search_options,provider:this.settings.provider},this.config.extraBody),this.settings.extraBody);if((H==null?void 0:H.type)==="json"&&H.schema!=null)return d$(H0({},B),{response_format:{type:"json_schema",json_schema:H0({schema:H.schema,strict:!0,name:(w=H.name)!=null?w:"response"},H.description&&{description:H.description})}});if(U&&U.length>0){let K=U.filter((z)=>z.type==="function").map((z)=>({type:"function",function:{name:z.name,description:z.description,parameters:z.inputSchema}}));return d$(H0({},B),{tools:K,tool_choice:V?N5(V):void 0})}return B}async doGenerate($){var Q,Y,G,J,W,q,L,H,E,U,V,w,B,K,z,A,j,N,M,T,c,d,v,m;let C=($.providerOptions||{}).openrouter||{},x=H0(H0({},this.getArgs($)),C),{value:y,responseHeaders:g}=await l$({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:p$(this.config.headers(),$.headers),body:x,failedResponseHandler:n$,successfulResponseHandler:E9(w5),abortSignal:$.abortSignal,fetch:this.config.fetch}),F=y.choices[0];if(!F)throw Error("No choice in response");let k=y.usage?{inputTokens:(Q=y.usage.prompt_tokens)!=null?Q:0,outputTokens:(Y=y.usage.completion_tokens)!=null?Y:0,totalTokens:((G=y.usage.prompt_tokens)!=null?G:0)+((J=y.usage.completion_tokens)!=null?J:0),reasoningTokens:(q=(W=y.usage.completion_tokens_details)==null?void 0:W.reasoning_tokens)!=null?q:0,cachedInputTokens:(H=(L=y.usage.prompt_tokens_details)==null?void 0:L.cached_tokens)!=null?H:0}:{inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0},P=(E=F.message.reasoning_details)!=null?E:[],I=P.length>0?P.map((l)=>{switch(l.type){case"reasoning.text":{if(l.text)return{type:"reasoning",text:l.text};break}case"reasoning.summary":{if(l.summary)return{type:"reasoning",text:l.summary};break}case"reasoning.encrypted":{if(l.data)return{type:"reasoning",text:"[REDACTED]"};break}default:}return null}).filter((l)=>l!==null):F.message.reasoning?[{type:"reasoning",text:F.message.reasoning}]:[],s=[];if(s.push(...I),F.message.content)s.push({type:"text",text:F.message.content});if(F.message.tool_calls)for(let l of F.message.tool_calls)s.push({type:"tool-call",toolCallId:(U=l.id)!=null?U:b0(),toolName:l.function.name,input:l.function.arguments});if(F.message.images)for(let l of F.message.images)s.push({type:"file",mediaType:C8(l.image_url.url,"image/jpeg"),data:I8(l.image_url.url)});if(F.message.annotations){for(let l of F.message.annotations)if(l.type==="url_citation")s.push({type:"source",sourceType:"url",id:l.url_citation.url,url:l.url_citation.url,title:l.url_citation.title,providerMetadata:{openrouter:{content:l.url_citation.content||""}}})}return{content:s,finishReason:r$(F.finish_reason),usage:k,warnings:[],providerMetadata:{openrouter:{provider:(V=y.provider)!=null?V:"",usage:{promptTokens:(w=k.inputTokens)!=null?w:0,completionTokens:(B=k.outputTokens)!=null?B:0,totalTokens:(K=k.totalTokens)!=null?K:0,cost:(z=y.usage)==null?void 0:z.cost,promptTokensDetails:{cachedTokens:(N=(j=(A=y.usage)==null?void 0:A.prompt_tokens_details)==null?void 0:j.cached_tokens)!=null?N:0},completionTokensDetails:{reasoningTokens:(c=(T=(M=y.usage)==null?void 0:M.completion_tokens_details)==null?void 0:T.reasoning_tokens)!=null?c:0},costDetails:{upstreamInferenceCost:(m=(v=(d=y.usage)==null?void 0:d.cost_details)==null?void 0:v.upstream_inference_cost)!=null?m:0}}}},request:{body:x},response:{id:y.id,modelId:y.model,headers:g}}}async doStream($){var Q;let G=($.providerOptions||{}).openrouter||{},J=H0(H0({},this.getArgs($)),G),{value:W,responseHeaders:q}=await l$({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:p$(this.config.headers(),$.headers),body:d$(H0({},J),{stream:!0,stream_options:this.config.compatibility==="strict"?H0({include_usage:!0},((Q=this.settings.usage)==null?void 0:Q.include)?{include_usage:!0}:{}):void 0}),failedResponseHandler:n$,successfulResponseHandler:H9(D5),abortSignal:$.abortSignal,fetch:this.config.fetch}),L=[],H="other",E={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},U={},V=!1,w=!1,B,K,z,A;return{stream:W.pipeThrough(new TransformStream({transform(j,N){var M,T,c,d,v,m,b,C,x,y,g,F,k,P;if(!j.success){H="error",N.enqueue({type:"error",error:j.error});return}let I=j.value;if("error"in I){H="error",N.enqueue({type:"error",error:I.error});return}if(I.provider)A=I.provider;if(I.id)z=I.id,N.enqueue({type:"response-metadata",id:I.id});if(I.model)N.enqueue({type:"response-metadata",modelId:I.model});if(I.usage!=null){if(E.inputTokens=I.usage.prompt_tokens,E.outputTokens=I.usage.completion_tokens,E.totalTokens=I.usage.prompt_tokens+I.usage.completion_tokens,U.promptTokens=I.usage.prompt_tokens,I.usage.prompt_tokens_details){let p=(M=I.usage.prompt_tokens_details.cached_tokens)!=null?M:0;E.cachedInputTokens=p,U.promptTokensDetails={cachedTokens:p}}if(U.completionTokens=I.usage.completion_tokens,I.usage.completion_tokens_details){let p=(T=I.usage.completion_tokens_details.reasoning_tokens)!=null?T:0;E.reasoningTokens=p,U.completionTokensDetails={reasoningTokens:p}}U.cost=I.usage.cost,U.totalTokens=I.usage.total_tokens}let s=I.choices[0];if((s==null?void 0:s.finish_reason)!=null)H=r$(s.finish_reason);if((s==null?void 0:s.delta)==null)return;let l=s.delta,N0=(p)=>{if(!w)K=z||b0(),N.enqueue({type:"reasoning-start",id:K}),w=!0;N.enqueue({type:"reasoning-delta",delta:p,id:K||b0()})};if(l.reasoning_details&&l.reasoning_details.length>0)for(let p of l.reasoning_details)switch(p.type){case"reasoning.text":{if(p.text)N0(p.text);break}case"reasoning.encrypted":{if(p.data)N0("[REDACTED]");break}case"reasoning.summary":{if(p.summary)N0(p.summary);break}default:break}else if(l.reasoning)N0(l.reasoning);if(l.content){if(w&&!V)N.enqueue({type:"reasoning-end",id:K||b0()}),w=!1;if(!V)B=z||b0(),N.enqueue({type:"text-start",id:B}),V=!0;N.enqueue({type:"text-delta",delta:l.content,id:B||b0()})}if(l.annotations){for(let p of l.annotations)if(p.type==="url_citation")N.enqueue({type:"source",sourceType:"url",id:p.url_citation.url,url:p.url_citation.url,title:p.url_citation.title,providerMetadata:{openrouter:{content:p.url_citation.content||""}}})}if(l.tool_calls!=null)for(let p of l.tool_calls){let G0=(c=p.index)!=null?c:L.length-1;if(L[G0]==null){if(p.type!=="function")throw new K1({data:p,message:"Expected 'function' type."});if(p.id==null)throw new K1({data:p,message:"Expected 'id' to be a string."});if(((d=p.function)==null?void 0:d.name)==null)throw new K1({data:p,message:"Expected 'function.name' to be a string."});L[G0]={id:p.id,type:"function",function:{name:p.function.name,arguments:(v=p.function.arguments)!=null?v:""},inputStarted:!1,sent:!1};let D=L[G0];if(D==null)throw Error("Tool call is missing");if(((m=D.function)==null?void 0:m.name)!=null&&((b=D.function)==null?void 0:b.arguments)!=null&&R1(D.function.arguments))D.inputStarted=!0,N.enqueue({type:"tool-input-start",id:D.id,toolName:D.function.name}),N.enqueue({type:"tool-input-delta",id:D.id,delta:D.function.arguments}),N.enqueue({type:"tool-input-end",id:D.id}),N.enqueue({type:"tool-call",toolCallId:D.id,toolName:D.function.name,input:D.function.arguments}),D.sent=!0;continue}let h=L[G0];if(h==null)throw Error("Tool call is missing");if(!h.inputStarted)h.inputStarted=!0,N.enqueue({type:"tool-input-start",id:h.id,toolName:h.function.name});if(((C=p.function)==null?void 0:C.arguments)!=null)h.function.arguments+=(y=(x=p.function)==null?void 0:x.arguments)!=null?y:"";if(N.enqueue({type:"tool-input-delta",id:h.id,delta:(g=p.function.arguments)!=null?g:""}),((F=h.function)==null?void 0:F.name)!=null&&((k=h.function)==null?void 0:k.arguments)!=null&&R1(h.function.arguments))N.enqueue({type:"tool-call",toolCallId:(P=h.id)!=null?P:b0(),toolName:h.function.name,input:h.function.arguments}),h.sent=!0}if(l.images!=null)for(let p of l.images)N.enqueue({type:"file",mediaType:C8(p.image_url.url,"image/jpeg"),data:I8(p.image_url.url)})},flush(j){var N;if(H==="tool-calls"){for(let T of L)if(T&&!T.sent)j.enqueue({type:"tool-call",toolCallId:(N=T.id)!=null?N:b0(),toolName:T.function.name,input:R1(T.function.arguments)?T.function.arguments:"{}"}),T.sent=!0}if(w)j.enqueue({type:"reasoning-end",id:K||b0()});if(V)j.enqueue({type:"text-end",id:B||b0()});let M={usage:U};if(A!==void 0)M.provider=A;j.enqueue({type:"finish",finishReason:H,usage:E,providerMetadata:{openrouter:M}})}})),warnings:[],request:{body:J},response:{headers:q}}}};function K5({prompt:$,inputFormat:Q,user:Y="user",assistant:G="assistant"}){if(Q==="prompt"&&$.length===1&&$[0]&&$[0].role==="user"&&$[0].content.length===1&&$[0].content[0]&&$[0].content[0].type==="text")return{prompt:$[0].content[0].text};let J="";if($[0]&&$[0].role==="system")J+=`${$[0].content}
32
+
33
+ `,$=$.slice(1);for(let{role:W,content:q}of $)switch(W){case"system":throw new z2({message:`Unexpected system message in prompt: ${q}`,prompt:$});case"user":{let L=q.map((H)=>{switch(H.type){case"text":return H.text;case"file":throw new r0({functionality:"file attachments"});default:return""}}).join("");J+=`${Y}:
34
+ ${L}
35
+
36
+ `;break}case"assistant":{let L=q.map((H)=>{switch(H.type){case"text":return H.text;case"tool-call":throw new r0({functionality:"tool-call messages"});case"tool-result":throw new r0({functionality:"tool-result messages"});case"reasoning":throw new r0({functionality:"reasoning messages"});case"file":throw new r0({functionality:"file attachments"});default:return""}}).join("");J+=`${G}:
37
+ ${L}
38
+
39
+ `;break}case"tool":throw new r0({functionality:"tool messages"});default:break}return J+=`${G}:
40
+ `,{prompt:J}}var _8=X.union([X.object({id:X.string().optional(),model:X.string().optional(),choices:X.array(X.object({text:X.string(),reasoning:X.string().nullish().optional(),reasoning_details:b1.nullish(),finish_reason:X.string().nullish(),index:X.number().nullish(),logprobs:X.object({tokens:X.array(X.string()),token_logprobs:X.array(X.number()),top_logprobs:X.array(X.record(X.string(),X.number())).nullable()}).nullable().optional()})),usage:X.object({prompt_tokens:X.number(),prompt_tokens_details:X.object({cached_tokens:X.number()}).nullish(),completion_tokens:X.number(),completion_tokens_details:X.object({reasoning_tokens:X.number()}).nullish(),total_tokens:X.number(),cost:X.number().optional()}).nullish()}),C1]),F5=class{constructor($,Q,Y){this.specificationVersion="v2",this.provider="openrouter",this.supportedUrls={"image/*":[/^data:image\/[a-zA-Z]+;base64,/,/^https?:\/\/.+\.(jpg|jpeg|png|gif|webp)$/i],"text/*":[/^data:text\//,/^https?:\/\/.+$/],"application/*":[/^data:application\//,/^https?:\/\/.+$/]},this.defaultObjectGenerationMode=void 0,this.modelId=$,this.settings=Q,this.config=Y}getArgs({prompt:$,maxOutputTokens:Q,temperature:Y,topP:G,frequencyPenalty:J,presencePenalty:W,seed:q,responseFormat:L,topK:H,stopSequences:E,tools:U,toolChoice:V}){let{prompt:w}=K5({prompt:$,inputFormat:"prompt"});if(U==null?void 0:U.length)throw new r0({functionality:"tools"});if(V)throw new r0({functionality:"toolChoice"});return H0(H0({model:this.modelId,models:this.settings.models,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs==="number"?this.settings.logprobs:typeof this.settings.logprobs==="boolean"?this.settings.logprobs?0:void 0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:Q,temperature:Y,top_p:G,frequency_penalty:J,presence_penalty:W,seed:q,stop:E,response_format:L,top_k:H,prompt:w,include_reasoning:this.settings.includeReasoning,reasoning:this.settings.reasoning},this.config.extraBody),this.settings.extraBody)}async doGenerate($){var Q,Y,G,J,W,q,L,H,E,U,V,w,B,K,z;let j=($.providerOptions||{}).openrouter||{},N=H0(H0({},this.getArgs($)),j),{value:M,responseHeaders:T}=await l$({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:p$(this.config.headers(),$.headers),body:N,failedResponseHandler:n$,successfulResponseHandler:E9(_8),abortSignal:$.abortSignal,fetch:this.config.fetch});if("error"in M)throw Error(`${M.error.message}`);let c=M.choices[0];if(!c)throw Error("No choice in OpenRouter completion response");return{content:[{type:"text",text:(Q=c.text)!=null?Q:""}],finishReason:r$(c.finish_reason),usage:{inputTokens:(G=(Y=M.usage)==null?void 0:Y.prompt_tokens)!=null?G:0,outputTokens:(W=(J=M.usage)==null?void 0:J.completion_tokens)!=null?W:0,totalTokens:((L=(q=M.usage)==null?void 0:q.prompt_tokens)!=null?L:0)+((E=(H=M.usage)==null?void 0:H.completion_tokens)!=null?E:0),reasoningTokens:(w=(V=(U=M.usage)==null?void 0:U.completion_tokens_details)==null?void 0:V.reasoning_tokens)!=null?w:0,cachedInputTokens:(z=(K=(B=M.usage)==null?void 0:B.prompt_tokens_details)==null?void 0:K.cached_tokens)!=null?z:0},warnings:[],response:{headers:T}}}async doStream($){let Y=($.providerOptions||{}).openrouter||{},G=H0(H0({},this.getArgs($)),Y),{value:J,responseHeaders:W}=await l$({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:p$(this.config.headers(),$.headers),body:d$(H0({},G),{stream:!0,stream_options:this.config.compatibility==="strict"?{include_usage:!0}:void 0}),failedResponseHandler:n$,successfulResponseHandler:H9(_8),abortSignal:$.abortSignal,fetch:this.config.fetch}),q="other",L={inputTokens:Number.NaN,outputTokens:Number.NaN,totalTokens:Number.NaN,reasoningTokens:Number.NaN,cachedInputTokens:Number.NaN},H={};return{stream:J.pipeThrough(new TransformStream({transform(E,U){var V,w;if(!E.success){q="error",U.enqueue({type:"error",error:E.error});return}let B=E.value;if("error"in B){q="error",U.enqueue({type:"error",error:B.error});return}if(B.usage!=null){if(L.inputTokens=B.usage.prompt_tokens,L.outputTokens=B.usage.completion_tokens,L.totalTokens=B.usage.prompt_tokens+B.usage.completion_tokens,H.promptTokens=B.usage.prompt_tokens,B.usage.prompt_tokens_details){let z=(V=B.usage.prompt_tokens_details.cached_tokens)!=null?V:0;L.cachedInputTokens=z,H.promptTokensDetails={cachedTokens:z}}if(H.completionTokens=B.usage.completion_tokens,B.usage.completion_tokens_details){let z=(w=B.usage.completion_tokens_details.reasoning_tokens)!=null?w:0;L.reasoningTokens=z,H.completionTokensDetails={reasoningTokens:z}}H.cost=B.usage.cost,H.totalTokens=B.usage.total_tokens}let K=B.choices[0];if((K==null?void 0:K.finish_reason)!=null)q=r$(K.finish_reason);if((K==null?void 0:K.text)!=null)U.enqueue({type:"text-delta",delta:K.text,id:b0()})},flush(E){E.enqueue({type:"finish",finishReason:q,usage:L,providerMetadata:{openrouter:{usage:H}}})}})),response:{headers:W}}}};function I1($={}){var Q,Y,G;let J=(Y=q5((Q=$.baseURL)!=null?Q:$.baseUrl))!=null?Y:"https://openrouter.ai/api/v1",W=(G=$.compatibility)!=null?G:"compatible",q=()=>H0({Authorization:`Bearer ${i2({apiKey:$.apiKey,environmentVariableName:"OPENROUTER_API_KEY",description:"OpenRouter"})}`},$.headers),L=(V,w={})=>new V5(V,w,{provider:"openrouter.chat",url:({path:B})=>`${J}${B}`,headers:q,compatibility:W,fetch:$.fetch,extraBody:$.extraBody}),H=(V,w={})=>new F5(V,w,{provider:"openrouter.completion",url:({path:B})=>`${J}${B}`,headers:q,compatibility:W,fetch:$.fetch,extraBody:$.extraBody}),E=(V,w)=>{if(new.target)throw Error("The OpenRouter model function cannot be called with the new keyword.");if(V==="openai/gpt-3.5-turbo-instruct")return H(V,w);return L(V,w)},U=(V,w)=>E(V,w);return U.languageModel=E,U.chat=L,U.completion=H,U}var G7=I1({compatibility:"strict"});class _1{id="openrouter";name="OpenRouter";keyName="OPENROUTER_API_KEY";async fetchModels($){let Y;for(let J=0;J<=2;J++)try{let W=await fetch("https://openrouter.ai/api/v1/models",{headers:$?{Authorization:`Bearer ${$}`}:{},signal:AbortSignal.timeout(1e4)});if(!W.ok)throw Error(`API returned ${W.status}: ${W.statusText}`);return(await W.json()).data.map((L)=>({id:L.id,name:L.name||L.id}))}catch(W){if(Y=W,J<2)await new Promise((q)=>setTimeout(q,100*Math.pow(2,J)))}let G=Y instanceof Error?Y.message:String(Y);throw Error(`Failed to fetch models after 3 attempts: ${G}`)}async getModelDetails($,Q){try{let G=await fetch("https://openrouter.ai/api/v1/models",{headers:Q?{Authorization:`Bearer ${Q}`}:{}});if(G.ok){let W=(await G.json()).data.find((q)=>q.id===$);if(W)return{contextLength:W.context_length,maxOutput:W.top_provider?.max_completion_tokens,inputPrice:parseFloat(W.pricing?.prompt||"0"),outputPrice:parseFloat(W.pricing?.completion||"0")}}}catch{}let Y=await l0($);if(Y)return{contextLength:Y.contextLength,maxOutput:Y.maxOutput,inputPrice:Y.inputPrice,outputPrice:Y.outputPrice};return null}createClient($,Q){return I1({apiKey:$})(Q)}}var R5={anthropic:new M1,openai:new D1,google:new V1,openrouter:new _1};function z9($){let Q=R5[$];if(!Q)throw Error(`Unknown provider: ${$}`);return Q}async function b7($,Q){return z9($).fetchModels(Q)}export{b7 as fetchModels};
41
+ export{J0 as s,E0 as t,m1 as u,n1 as v,s$ as w,Q0 as x,u6 as y,LX as z,j0 as A,d6 as B,S$ as C,b4 as D,p0 as E,l6 as F,n6 as G,m$ as H,$0 as I,B0 as J,U1 as K,_4 as L,Y0 as M,Z4 as N,m0 as O,W$ as P,T0 as Q,U0 as R,R as S,JJ as T,h4 as U,MQ as V,q$ as W,WJ as X,z9 as Y,b7 as Z};
42
+
43
+ //# debugId=E12E565D3DD26B8E64756E2164756E21