@agiflowai/agent-cli 0.0.6 → 0.0.8

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.
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- "use strict";const Ss=require("node:fs"),cs=require("node:os"),Os=require("node:path"),ye=require("path"),ce=require("fs-extra"),Et=require("os");require("node:crypto");require("@inquirer/prompts");function zt(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const ie=zt(Ss),As=zt(cs),Ae=zt(Os);var T;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(T||(T={}));var It;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(It||(It={}));const h=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=r=>{switch(typeof r){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(r)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(r)?h.array:r===null?h.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?h.promise:typeof Map<"u"&&r instanceof Map?h.map:typeof Set<"u"&&r instanceof Set?h.set:typeof Date<"u"&&r instanceof Date?h.date:h.object;default:return h.unknown}},l=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"]),Is=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class U extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,d=0;for(;d<i.path.length;){const u=i.path[d];d===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],d++}}};return n(this),s}static assert(e){if(!(e instanceof U))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const n of this.issues)if(n.path.length>0){const a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}U.create=r=>new U(r);const Ne=(r,e)=>{let t;switch(r.code){case l.invalid_type:r.received===h.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,T.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${T.joinValues(r.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${T.joinValues(r.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${T.joinValues(r.options)}, received '${r.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:T.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case l.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case l.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,T.assertNever(r)}return{message:t}};let ls=Ne;function Ns(r){ls=r}function dt(){return ls}const ft=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const d=s.filter(u=>!!u).slice().reverse();for(const u of d)o=u(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Rs=[];function f(r,e){const t=dt(),s=ft({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ne?void 0:Ne].filter(n=>!!n)});r.common.issues.push(s)}class Z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return v;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return Z.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return v;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const v=Object.freeze({status:"aborted"}),Oe=r=>({status:"dirty",value:r}),B=r=>({status:"valid",value:r}),Nt=r=>r.status==="aborted",Rt=r=>r.status==="dirty",be=r=>r.status==="valid",Fe=r=>typeof Promise<"u"&&r instanceof Promise;var m;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));class te{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const qt=(r,e)=>{if(be(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new U(r.common.issues);return this._error=t,this._error}}};function w(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{const{message:d}=r;return i.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:d??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:d??t??o.defaultError}},description:n}}class k{get description(){return this._def.description}_getType(e){return ae(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Z,ctx:{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Fe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},n=this._parseSync({data:e,path:s.path,parent:s});return qt(s,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return be(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>be(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(Fe(n)?n:Promise.resolve(n));return qt(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:l.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new Y({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return Q.create(this,this._def)}nullable(){return he.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return Ce.create(this,this._def)}or(e){return Ve.create([this,e],this._def)}and(e){return Be.create(this,e,this._def)}transform(e){return new Y({...w(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Je({...w(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new Lt({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ke({...w(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Xe.create(this,e)}readonly(){return We.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Cs=/^c[^\s-]{8,}$/i,js=/^[0-9a-z]+$/,$s=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ms=/^[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,zs=/^[a-z0-9_-]{21}$/i,Ls=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fs=/^[-+]?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)?)??$/,Ds=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ps="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let St;const Zs=/^(?:(?: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])$/,Vs=/^(?:(?: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])$/,Bs=/^(([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]))$/,Gs=/^(([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])$/,Us=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,us="((\\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])))",Hs=new RegExp(`^${us}$`);function ds(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Js(r){return new RegExp(`^${ds(r)}$`)}function fs(r){let e=`${us}T${ds(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ks(r,e){return!!((e==="v4"||!e)&&Zs.test(r)||(e==="v6"||!e)&&Bs.test(r))}function Ws(r,e){if(!Ls.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Ys(r,e){return!!((e==="v4"||!e)&&Vs.test(r)||(e==="v6"||!e)&&Gs.test(r))}class K extends k{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.string,received:a.parsedType}),v}const s=new Z;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?f(n,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(n,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")Ds.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")St||(St=new RegExp(Ps,"u")),St.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"emoji",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")Ms.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")zs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"nanoid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")Cs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")js.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid2",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")$s.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ulid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:l.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:l.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?fs(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?Hs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?Js(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?Fs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Ks(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ip",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?Ws(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"jwt",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?Ys(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cidr",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?Us.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?qs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:l.invalid_string,message:a.message}),s.dirty()):T.assertNever(a);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:l.invalid_string,...m.errToObj(s)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}K.create=r=>new K({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...w(r)});function Xs(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=Number.parseInt(r.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}class ue extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.number,received:a.parsedType}),v}let s;const n=new Z;for(const a of this._def.checks)a.kind==="int"?T.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?Xs(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_finite,message:a.message}),n.dirty()):T.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new ue({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ue.create=r=>new ue({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...w(r)});class de extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let s;const n=new Z;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):T.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:h.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new de({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}de.create=r=>new de({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...w(r)});class De extends k{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.boolean,received:s.parsedType}),v}return B(e.data)}}De.create=r=>new De({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...w(r)});class we extends k{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.date,received:a.parsedType}),v}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_date}),v}const s=new Z;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):T.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new we({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}we.create=r=>new we({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...w(r)});class ht extends k{_parse(e){if(this._getType(e)!==h.symbol){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.symbol,received:s.parsedType}),v}return B(e.data)}}ht.create=r=>new ht({typeName:_.ZodSymbol,...w(r)});class Pe extends k{_parse(e){if(this._getType(e)!==h.undefined){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.undefined,received:s.parsedType}),v}return B(e.data)}}Pe.create=r=>new Pe({typeName:_.ZodUndefined,...w(r)});class Ze extends k{_parse(e){if(this._getType(e)!==h.null){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.null,received:s.parsedType}),v}return B(e.data)}}Ze.create=r=>new Ze({typeName:_.ZodNull,...w(r)});class Re extends k{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}}Re.create=r=>new Re({typeName:_.ZodAny,...w(r)});class _e extends k{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}}_e.create=r=>new _e({typeName:_.ZodUnknown,...w(r)});class oe extends k{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:h.never,received:t.parsedType}),v}}oe.create=r=>new oe({typeName:_.ZodNever,...w(r)});class pt extends k{_parse(e){if(this._getType(e)!==h.undefined){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.void,received:s.parsedType}),v}return B(e.data)}}pt.create=r=>new pt({typeName:_.ZodVoid,...w(r)});class W extends k{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==h.array)return f(t,{code:l.invalid_type,expected:h.array,received:t.parsedType}),v;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(f(t,{code:i?l.too_big:l.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(f(t,{code:l.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(f(t,{code:l.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new te(t,i,t.path,o)))).then(i=>Z.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new te(t,i,t.path,o)));return Z.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new W({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new W({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new W({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}W.create=(r,e)=>new W({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...w(e)});function Se(r){if(r instanceof $){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=Q.create(Se(s))}return new $({...r._def,shape:()=>e})}else return r instanceof W?new W({...r._def,type:Se(r.element)}):r instanceof Q?Q.create(Se(r.unwrap())):r instanceof he?he.create(Se(r.unwrap())):r instanceof se?se.create(r.items.map(e=>Se(e))):r}class $ extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=T.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const u=this._getOrReturnCtx(e);return f(u,{code:l.invalid_type,expected:h.object,received:u.parsedType}),v}const{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof oe&&this._def.unknownKeys==="strip"))for(const u in n.data)i.includes(u)||o.push(u);const d=[];for(const u of i){const g=a[u],x=n.data[u];d.push({key:{status:"valid",value:u},value:g._parse(new te(n,x,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof oe){const u=this._def.unknownKeys;if(u==="passthrough")for(const g of o)d.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(u==="strict")o.length>0&&(f(n,{code:l.unrecognized_keys,keys:o}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const g of o){const x=n.data[g];d.push({key:{status:"valid",value:g},value:u._parse(new te(n,x,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const g of d){const x=await g.key,j=await g.value;u.push({key:x,value:j,alwaysSet:g.alwaysSet})}return u}).then(u=>Z.mergeObjectSync(s,u)):Z.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new $({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new $({...this._def,unknownKeys:"strip"})}passthrough(){return new $({...this._def,unknownKeys:"passthrough"})}extend(e){return new $({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new $({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new $({...this._def,catchall:e})}pick(e){const t={};for(const s of T.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new $({...this._def,shape:()=>t})}omit(e){const t={};for(const s of T.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new $({...this._def,shape:()=>t})}deepPartial(){return Se(this)}partial(e){const t={};for(const s of T.objectKeys(this.shape)){const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new $({...this._def,shape:()=>t})}required(e){const t={};for(const s of T.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof Q;)a=a._def.innerType;t[s]=a}return new $({...this._def,shape:()=>t})}keyof(){return hs(T.objectKeys(this.shape))}}$.create=(r,e)=>new $({shape:()=>r,unknownKeys:"strip",catchall:oe.create(),typeName:_.ZodObject,...w(e)});$.strictCreate=(r,e)=>new $({shape:()=>r,unknownKeys:"strict",catchall:oe.create(),typeName:_.ZodObject,...w(e)});$.lazycreate=(r,e)=>new $({shape:r,unknownKeys:"strip",catchall:oe.create(),typeName:_.ZodObject,...w(e)});class Ve extends k{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new U(o.ctx.common.issues));return f(t,{code:l.invalid_union,unionErrors:i}),v}if(t.common.async)return Promise.all(s.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const d of s){const u={...t,common:{...t.common,issues:[]},parent:null},g=d._parseSync({data:t.data,path:t.path,parent:u});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(d=>new U(d));return f(t,{code:l.invalid_union,unionErrors:o}),v}}get options(){return this._def.options}}Ve.create=(r,e)=>new Ve({options:r,typeName:_.ZodUnion,...w(e)});const ne=r=>r instanceof Ue?ne(r.schema):r instanceof Y?ne(r.innerType()):r instanceof qe?[r.value]:r instanceof fe?r.options:r instanceof He?T.objectValues(r.enum):r instanceof Je?ne(r._def.innerType):r instanceof Pe?[void 0]:r instanceof Ze?[null]:r instanceof Q?[void 0,...ne(r.unwrap())]:r instanceof he?[null,...ne(r.unwrap())]:r instanceof Lt||r instanceof We?ne(r.unwrap()):r instanceof Ke?ne(r._def.innerType):[];class _t extends k{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return f(t,{code:l.invalid_type,expected:h.object,received:t.parsedType}),v;const s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const a of t){const i=ne(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new _t({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...w(s)})}}function Ct(r,e){const t=ae(r),s=ae(e);if(r===e)return{valid:!0,data:r};if(t===h.object&&s===h.object){const n=T.objectKeys(e),a=T.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(const o of a){const d=Ct(r[o],e[o]);if(!d.valid)return{valid:!1};i[o]=d.data}return{valid:!0,data:i}}else if(t===h.array&&s===h.array){if(r.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<r.length;a++){const i=r[a],o=e[a],d=Ct(i,o);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return t===h.date&&s===h.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class Be extends k{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(Nt(a)||Nt(i))return v;const o=Ct(a.value,i.value);return o.valid?((Rt(a)||Rt(i))&&t.dirty(),{status:t.value,value:o.data}):(f(s,{code:l.invalid_intersection_types}),v)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Be.create=(r,e,t)=>new Be({left:r,right:e,typeName:_.ZodIntersection,...w(t)});class se extends k{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.array)return f(s,{code:l.invalid_type,expected:h.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return f(s,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&s.data.length>this._def.items.length&&(f(s,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((i,o)=>{const d=this._def.items[o]||this._def.rest;return d?d._parse(new te(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>Z.mergeArray(t,i)):Z.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new se({...this._def,rest:e})}}se.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new se({items:r,typeName:_.ZodTuple,rest:null,...w(e)})};class Ge extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.object)return f(s,{code:l.invalid_type,expected:h.object,received:s.parsedType}),v;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in s.data)n.push({key:a._parse(new te(s,o,s.path,o)),value:i._parse(new te(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?Z.mergeObjectAsync(t,n):Z.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof k?new Ge({keyType:e,valueType:t,typeName:_.ZodRecord,...w(s)}):new Ge({keyType:K.create(),valueType:e,typeName:_.ZodRecord,...w(t)})}}class mt extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.map)return f(s,{code:l.invalid_type,expected:h.map,received:s.parsedType}),v;const n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,d],u)=>({key:n._parse(new te(s,o,s.path,[u,"key"])),value:a._parse(new te(s,d,s.path,[u,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const d of i){const u=await d.key,g=await d.value;if(u.status==="aborted"||g.status==="aborted")return v;(u.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(u.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const d of i){const u=d.key,g=d.value;if(u.status==="aborted"||g.status==="aborted")return v;(u.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(u.value,g.value)}return{status:t.value,value:o}}}}mt.create=(r,e,t)=>new mt({valueType:e,keyType:r,typeName:_.ZodMap,...w(t)});class ke extends k{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.set)return f(s,{code:l.invalid_type,expected:h.set,received:s.parsedType}),v;const n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(f(s,{code:l.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(f(s,{code:l.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(d){const u=new Set;for(const g of d){if(g.status==="aborted")return v;g.status==="dirty"&&t.dirty(),u.add(g.value)}return{status:t.value,value:u}}const o=[...s.data.values()].map((d,u)=>a._parse(new te(s,d,s.path,u)));return s.common.async?Promise.all(o).then(d=>i(d)):i(o)}min(e,t){return new ke({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new ke({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ke.create=(r,e)=>new ke({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});class Ie extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return f(t,{code:l.invalid_type,expected:h.function,received:t.parsedType}),v;function s(o,d){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dt(),Ne].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:d}})}function n(o,d){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dt(),Ne].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:d}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Ce){const o=this;return B(async function(...d){const u=new U([]),g=await o._def.args.parseAsync(d,a).catch(S=>{throw u.addIssue(s(d,S)),u}),x=await Reflect.apply(i,this,g);return await o._def.returns._def.type.parseAsync(x,a).catch(S=>{throw u.addIssue(n(x,S)),u})})}else{const o=this;return B(function(...d){const u=o._def.args.safeParse(d,a);if(!u.success)throw new U([s(d,u.error)]);const g=Reflect.apply(i,this,u.data),x=o._def.returns.safeParse(g,a);if(!x.success)throw new U([n(g,x.error)]);return x.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ie({...this._def,args:se.create(e).rest(_e.create())})}returns(e){return new Ie({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new Ie({args:e||se.create([]).rest(_e.create()),returns:t||_e.create(),typeName:_.ZodFunction,...w(s)})}}class Ue extends k{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ue.create=(r,e)=>new Ue({getter:r,typeName:_.ZodLazy,...w(e)});class qe extends k{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}}qe.create=(r,e)=>new qe({value:r,typeName:_.ZodLiteral,...w(e)});function hs(r,e){return new fe({values:r,typeName:_.ZodEnum,...w(e)})}class fe extends k{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return f(t,{expected:T.joinValues(s),received:t.parsedType,code:l.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return f(t,{received:t.data,code:l.invalid_enum_value,options:s}),v}return B(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return fe.create(e,{...this._def,...t})}exclude(e,t=this._def){return fe.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}fe.create=hs;class He extends k{_parse(e){const t=T.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==h.string&&s.parsedType!==h.number){const n=T.objectValues(t);return f(s,{expected:T.joinValues(n),received:s.parsedType,code:l.invalid_type}),v}if(this._cache||(this._cache=new Set(T.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=T.objectValues(t);return f(s,{received:s.data,code:l.invalid_enum_value,options:n}),v}return B(e.data)}get enum(){return this._def.values}}He.create=(r,e)=>new He({values:r,typeName:_.ZodNativeEnum,...w(e)});class Ce extends k{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return f(t,{code:l.invalid_type,expected:h.promise,received:t.parsedType}),v;const s=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return B(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ce.create=(r,e)=>new Ce({type:r,typeName:_.ZodPromise,...w(e)});class Y extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{f(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return v;const d=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return d.status==="aborted"?v:d.status==="dirty"||t.value==="dirty"?Oe(d.value):d});{if(t.value==="aborted")return v;const o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?v:o.status==="dirty"||t.value==="dirty"?Oe(o.value):o}}if(n.type==="refinement"){const i=o=>{const d=n.refinement(o,a);if(s.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!be(i))return v;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>be(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):v);T.assertNever(n)}}Y.create=(r,e,t)=>new Y({schema:r,typeName:_.ZodEffects,effect:e,...w(t)});Y.createWithPreprocess=(r,e,t)=>new Y({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...w(t)});class Q extends k{_parse(e){return this._getType(e)===h.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Q.create=(r,e)=>new Q({innerType:r,typeName:_.ZodOptional,...w(e)});class he extends k{_parse(e){return this._getType(e)===h.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}he.create=(r,e)=>new he({innerType:r,typeName:_.ZodNullable,...w(e)});class Je extends k{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===h.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Je.create=(r,e)=>new Je({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class Ke extends k{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Fe(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new U(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new U(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ke.create=(r,e)=>new Ke({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class gt extends k{_parse(e){if(this._getType(e)!==h.nan){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.nan,received:s.parsedType}),v}return{status:"valid",value:e.data}}}gt.create=r=>new gt({typeName:_.ZodNaN,...w(r)});const Qs=Symbol("zod_brand");class Lt extends k{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Xe extends k{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?v:a.status==="dirty"?(t.dirty(),Oe(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?v:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new Xe({in:e,out:t,typeName:_.ZodPipeline})}}class We extends k{_parse(e){const t=this._def.innerType._parse(e),s=n=>(be(n)&&(n.value=Object.freeze(n.value)),n);return Fe(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}We.create=(r,e)=>new We({innerType:r,typeName:_.ZodReadonly,...w(e)});function Ht(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function ps(r,e={},t){return r?Re.create().superRefine((s,n)=>{const a=r(s);if(a instanceof Promise)return a.then(i=>{if(!i){const o=Ht(e,s),d=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:d})}});if(!a){const i=Ht(e,s),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):Re.create()}const er={object:$.lazycreate};var _;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));const tr=(r,e={message:`Input not instance of ${r.name}`})=>ps(t=>t instanceof r,e),I=K.create,ee=ue.create,sr=gt.create,rr=de.create,Qe=De.create,nr=we.create,ar=ht.create,ir=Pe.create,ms=Ze.create,pe=Re.create,bt=_e.create,or=oe.create,cr=pt.create,xe=W.create,N=$.create,lr=$.strictCreate,Te=Ve.create,ur=_t.create,dr=Be.create,fr=se.create,et=Ge.create,hr=mt.create,pr=ke.create,mr=Ie.create,gs=Ue.create,V=qe.create,wt=fe.create,gr=He.create,yr=Ce.create,Jt=Y.create,vr=Q.create,_r=he.create,br=Y.createWithPreprocess,wr=Xe.create,kr=()=>I().optional(),xr=()=>ee().optional(),Tr=()=>Qe().optional(),ut={string:r=>K.create({...r,coerce:!0}),number:r=>ue.create({...r,coerce:!0}),boolean:r=>De.create({...r,coerce:!0}),bigint:r=>de.create({...r,coerce:!0}),date:r=>we.create({...r,coerce:!0})},Er=v,D=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Qs,DIRTY:Oe,EMPTY_PATH:Rs,INVALID:v,NEVER:Er,OK:B,ParseStatus:Z,Schema:k,ZodAny:Re,ZodArray:W,ZodBigInt:de,ZodBoolean:De,ZodBranded:Lt,ZodCatch:Ke,ZodDate:we,ZodDefault:Je,ZodDiscriminatedUnion:_t,ZodEffects:Y,ZodEnum:fe,ZodError:U,get ZodFirstPartyTypeKind(){return _},ZodFunction:Ie,ZodIntersection:Be,ZodIssueCode:l,ZodLazy:Ue,ZodLiteral:qe,ZodMap:mt,ZodNaN:gt,ZodNativeEnum:He,ZodNever:oe,ZodNull:Ze,ZodNullable:he,ZodNumber:ue,ZodObject:$,ZodOptional:Q,ZodParsedType:h,ZodPipeline:Xe,ZodPromise:Ce,ZodReadonly:We,ZodRecord:Ge,ZodSchema:k,ZodSet:ke,ZodString:K,ZodSymbol:ht,ZodTransformer:Y,ZodTuple:se,ZodType:k,ZodUndefined:Pe,ZodUnion:Ve,ZodUnknown:_e,ZodVoid:pt,addIssueToContext:f,any:pe,array:xe,bigint:rr,boolean:Qe,coerce:ut,custom:ps,date:nr,datetimeRegex:fs,defaultErrorMap:Ne,discriminatedUnion:ur,effect:Jt,enum:wt,function:mr,getErrorMap:dt,getParsedType:ae,instanceof:tr,intersection:dr,isAborted:Nt,isAsync:Fe,isDirty:Rt,isValid:be,late:er,lazy:gs,literal:V,makeIssue:ft,map:hr,nan:sr,nativeEnum:gr,never:or,null:ms,nullable:_r,number:ee,object:N,get objectUtil(){return It},oboolean:Tr,onumber:xr,optional:vr,ostring:kr,pipeline:wr,preprocess:br,promise:yr,quotelessJson:Is,record:et,set:pr,setErrorMap:Ns,strictObject:lr,string:I,symbol:ar,transformer:Jt,tuple:fr,undefined:ir,union:Te,unknown:bt,get util(){return T},void:cr},Symbol.toStringTag,{value:"Module"})),ge=()=>D.preprocess(r=>{if(typeof r=="boolean")return r;if(typeof r=="number")return r===1;if(typeof r=="string"){const e=r.trim().toLowerCase();if(["1","true","yes","y","on"].includes(e))return!0;if(["0","false","no","n","off"].includes(e))return!1}},D.boolean()),Sr=()=>D.preprocess(r=>{if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){const e=Number(r);if(Number.isFinite(e))return e}},D.number()),ys=D.object({NODE_ENV:D.enum(["development","production","test"]).default("production"),AGENT_CONTAINER_MODE:ge().default(!1),AGENT_API_KEY:D.string().optional(),AGENT_ORGANIZATION_ID:D.string().optional(),AGENT_SESSION_ID:D.string().optional(),AGENT_SERVER_URL:D.string().optional(),AGENT_TYPE:D.string().optional(),AGENT_DEVICE_GUID:D.string().optional(),CONTEXT_DATA:D.string().optional(),AGI_NETLOG_ENABLE:ge().default(!0),AGI_NETLOG_DEBUG:ge().optional(),AGI_NETLOG_FILE:D.string().optional(),AGI_NETLOG_MAX_BODY:Sr().optional(),AGI_NETLOG_REMOTE_ENABLE:ge().default(!0),AGI_NETLOG_REMOTE_FILE:D.string().optional(),DEBUG:ge().default(!1),VERBOSE:ge().default(!1),LOG_LEVEL:D.string().optional(),HOSTNAME:D.string().optional(),VITE_SAVE_RAW:ge().default(!1)});function ct(r=!1){return r?"https://agiflow.io":"https://agiflow.io"}let R=ys.parse(process.env);class ve{static refresh(){R=ys.parse(process.env)}static get isContainerMode(){return!!R.AGENT_CONTAINER_MODE}static get apiKey(){return R.AGENT_API_KEY||process.env.AGENT_API_KEY}static get organizationId(){return R.AGENT_ORGANIZATION_ID||process.env.AGENT_ORGANIZATION_ID}static get sessionId(){return R.AGENT_SESSION_ID||process.env.AGENT_SESSION_ID}static get serverUrl(){return R.AGENT_SERVER_URL||process.env.AGENT_SERVER_URL||ct(this.isContainerMode)}static get isNetlogEnabled(){return!!R.AGI_NETLOG_ENABLE}static get isNetlogDebug(){return!!R.AGI_NETLOG_DEBUG}static get isNetlogRemoteEnabled(){return!!R.AGI_NETLOG_REMOTE_ENABLE}static get isDebugMode(){return R.DEBUG}static get isVerbose(){return R.VERBOSE}static get logLevel(){return R.LOG_LEVEL??(R.DEBUG?"debug":"info")}static get nodeEnv(){return R.NODE_ENV}static get homeDir(){return process.env.HOME||process.env.USERPROFILE}static get isMacOS(){return process.platform==="darwin"}static get hostname(){return R.HOSTNAME}static get netlogMaxBody(){return R.AGI_NETLOG_MAX_BODY}static get netlogFile(){return R.AGI_NETLOG_FILE}static get netlogRemoteFile(){return R.AGI_NETLOG_REMOTE_FILE}static get agentType(){return R.AGENT_TYPE||process.env.AGENT_TYPE}static get deviceGuid(){return R.AGENT_DEVICE_GUID}static get isSaveRawEnabled(){return!!R.VITE_SAVE_RAW}static get contextData(){return R.CONTEXT_DATA||process.env.CONTEXT_DATA}static serializeEnv(){const e={...process.env};for(const[t,s]of Object.entries(R))s!==void 0&&(typeof s=="string"?e[t]=s:typeof s=="number"?e[t]=String(s):typeof s=="boolean"?e[t]=s?"true":"false":e[t]=String(s));return e}static toChildProcess(){const e=this.serializeEnv();return e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=ct(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static toDocker(){const e=this.serializeEnv();return e.AGENT_CONTAINER_MODE="true",e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=ct(!0)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static toPty(){const e=this.serializeEnv();return e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=ct(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static getEnvs(){return R}}const Kt=gs(()=>Te([ms(),I(),ee(),Qe(),xe(Kt),et(Kt)])),Wt=N({toolCallId:I(),toolName:I(),args:pe()}),Or=N({toolCallId:I(),toolName:I(),args:pe(),result:pe()}),Ar=Te([Wt.extend({state:V("partial-call"),step:ee().optional()}),Wt.extend({state:V("call"),step:ee().optional()}),Or.extend({state:V("result"),step:ee().optional()})]),Ir=N({type:I(),content:I()}),Nr=N({type:V("text"),text:I()}),Rr=N({type:V("reasoning"),reasoning:I(),details:xe(Te([N({type:V("text"),text:I(),signature:I().optional()}),N({type:V("redacted"),data:I()})])).optional()}),Cr=N({name:V("select"),props:N({options:xe(N({label:I(),value:Te([I(),ee()]),selected:Qe().optional()}))})}),jr=N({name:V("placeholder"),props:N({})}),$r=Te([Cr,jr]),Mr=N({completed:Qe(),component:$r}),zr=N({type:V("tool-invocation"),toolInvocation:Ar,input:Mr.optional(),jsx:I({description:"UI rendering"}).optional()}),Lr=N({type:V("source"),source:Ir}),Fr=N({type:V("file"),mimeType:I(),data:I()}),Dr=N({type:V("error"),text:I(),error:pe().optional()}),Pr=N({type:V("step-start")}),vs=Te([Nr,Rr,zr,Lr,Fr,Dr,Pr]),Ft=wt(["input","output","error","system"]),_s=N({messageType:Ft,parts:xe(vs),metadata:et(I(),bt()).optional(),raw:pe().optional()});N({id:I(),sessionId:I(),agentTypeId:I(),messageType:Ft,contentSize:ee().nullable(),timestamp:ut.date(),metadata:I().nullable(),raw:pe().nullable().optional(),createdAt:ut.date(),updatedAt:ut.date()});const Zr=N({messageType:wt(["output"]).default("output"),metadata:et(I(),bt()).optional()});N({id:I(),messageId:I()});const Vr=N({parts:xe(vs).optional(),metadata:et(I(),bt()).optional(),raw:pe().optional()});N({messages:xe(_s)});function Br(r){return[Gr(r)]}function Yt(r){let e=r.parts;if(!e&&r.content&&(e=Br(r.content)),!e)throw new Error("Either content or parts is required for message creation");return{messageType:r.messageType,parts:e,metadata:r.metadata,raw:r.raw}}function Gr(r){return{type:"text",text:r}}const Ot=10,Xt=(r=0)=>e=>`\x1B[${e+r}m`,Qt=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,es=(r=0)=>(e,t,s)=>`\x1B[${38+r};2;${e};${t};${s}m`,C={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(C.modifier);const Ur=Object.keys(C.color),qr=Object.keys(C.bgColor);[...Ur,...qr];function Hr(){const r=new Map;for(const[e,t]of Object.entries(C)){for(const[s,n]of Object.entries(t))C[s]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[s]=C[s],r.set(n[0],n[1]);Object.defineProperty(C,e,{value:t,enumerable:!1})}return Object.defineProperty(C,"codes",{value:r,enumerable:!1}),C.color.close="\x1B[39m",C.bgColor.close="\x1B[49m",C.color.ansi=Xt(),C.color.ansi256=Qt(),C.color.ansi16m=es(),C.bgColor.ansi=Xt(Ot),C.bgColor.ansi256=Qt(Ot),C.bgColor.ansi16m=es(Ot),Object.defineProperties(C,{rgbToAnsi256:{value(e,t,s){return e===t&&t===s?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[s]=t;s.length===3&&(s=[...s].map(a=>a+a).join(""));const n=Number.parseInt(s,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:e=>C.rgbToAnsi256(...C.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,s,n;if(e>=232)t=((e-232)*10+8)/255,s=t,n=t;else{e-=16;const o=e%36;t=Math.floor(e/36)/5,s=Math.floor(o/6)/5,n=o%6/5}const a=Math.max(t,s,n)*2;if(a===0)return 30;let i=30+(Math.round(n)<<2|Math.round(s)<<1|Math.round(t));return a===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,s)=>C.ansi256ToAnsi(C.rgbToAnsi256(e,t,s)),enumerable:!1},hexToAnsi:{value:e=>C.ansi256ToAnsi(C.hexToAnsi256(e)),enumerable:!1}}),C}const X=Hr(),ts=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),ss=ts!==0&&{level:ts},Jr={stdout:ss,stderr:ss};function Kr(r,e,t){let s=r.indexOf(e);if(s===-1)return r;const n=e.length;let a=0,i="";do i+=r.slice(a,s)+e+t,a=s+n,s=r.indexOf(e,a);while(s!==-1);return i+=r.slice(a),i}function Wr(r,e,t,s){let n=0,a="";do{const i=r[s-1]==="\r";a+=r.slice(n,i?s-1:s)+e+(i?`\r
2
+ "use strict";const Ss=require("node:fs"),cs=require("node:os"),Is=require("node:path"),ue=require("path"),le=require("fs-extra"),Et=require("os");require("node:crypto");require("@inquirer/prompts");function zt(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const oe=zt(Ss),Os=zt(cs),Oe=zt(Is);var T;(function(r){r.assertEqual=n=>{};function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(T||(T={}));var At;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(At||(At={}));const h=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=r=>{switch(typeof r){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(r)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(r)?h.array:r===null?h.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?h.promise:typeof Map<"u"&&r instanceof Map?h.map:typeof Set<"u"&&r instanceof Set?h.set:typeof Date<"u"&&r instanceof Date?h.date:h.object;default:return h.unknown}},l=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"]),As=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class q extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,d=0;for(;d<i.path.length;){const u=i.path[d];d===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],d++}}};return n(this),s}static assert(e){if(!(e instanceof q))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const n of this.issues)if(n.path.length>0){const a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}q.create=r=>new q(r);const Ne=(r,e)=>{let t;switch(r.code){case l.invalid_type:r.received===h.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,T.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${T.joinValues(r.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${T.joinValues(r.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${T.joinValues(r.options)}, received '${r.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:T.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case l.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case l.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,T.assertNever(r)}return{message:t}};let ls=Ne;function Ns(r){ls=r}function dt(){return ls}const ft=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const d=s.filter(u=>!!u).slice().reverse();for(const u of d)o=u(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Rs=[];function f(r,e){const t=dt(),s=ft({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Ne?void 0:Ne].filter(n=>!!n)});r.common.issues.push(s)}class V{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return v;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return V.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return v;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const v=Object.freeze({status:"aborted"}),Ie=r=>({status:"dirty",value:r}),G=r=>({status:"valid",value:r}),Nt=r=>r.status==="aborted",Rt=r=>r.status==="dirty",be=r=>r.status==="valid",Fe=r=>typeof Promise<"u"&&r instanceof Promise;var m;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));class se{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const qt=(r,e)=>{if(be(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new q(r.common.issues);return this._error=t,this._error}}};function w(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{const{message:d}=r;return i.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:d??s??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:d??t??o.defaultError}},description:n}}class x{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new V,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Fe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},n=this._parseSync({data:e,path:s.path,parent:s});return qt(s,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return be(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>be(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(Fe(n)?n:Promise.resolve(n));return qt(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:l.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new X({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return ee.create(this,this._def)}nullable(){return pe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Y.create(this)}promise(){return Ce.create(this,this._def)}or(e){return Ve.create([this,e],this._def)}and(e){return Be.create(this,e,this._def)}transform(e){return new X({...w(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new He({...w(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new Lt({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new We({...w(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Xe.create(this,e)}readonly(){return Ke.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Cs=/^c[^\s-]{8,}$/i,js=/^[0-9a-z]+$/,$s=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ms=/^[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,zs=/^[a-z0-9_-]{21}$/i,Ls=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fs=/^[-+]?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)?)??$/,Ds=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ps="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let St;const Zs=/^(?:(?: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])$/,Vs=/^(?:(?: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])$/,Bs=/^(([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]))$/,Gs=/^(([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])$/,Us=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,us="((\\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])))",Js=new RegExp(`^${us}$`);function ds(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Hs(r){return new RegExp(`^${ds(r)}$`)}function fs(r){let e=`${us}T${ds(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ws(r,e){return!!((e==="v4"||!e)&&Zs.test(r)||(e==="v6"||!e)&&Bs.test(r))}function Ks(r,e){if(!Ls.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Ys(r,e){return!!((e==="v4"||!e)&&Vs.test(r)||(e==="v6"||!e)&&Gs.test(r))}class K extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.string,received:a.parsedType}),v}const s=new V;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?f(n,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(n,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")Ds.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")St||(St=new RegExp(Ps,"u")),St.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"emoji",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")Ms.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")zs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"nanoid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")Cs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")js.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid2",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")$s.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ulid",code:l.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:l.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:l.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?fs(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?Js.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?Hs(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?Fs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Ws(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ip",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?Ks(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"jwt",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?Ys(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cidr",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?Us.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?qs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:l.invalid_string,message:a.message}),s.dirty()):T.assertNever(a);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(n=>e.test(n),{validation:t,code:l.invalid_string,...m.errToObj(s)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}K.create=r=>new K({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...w(r)});function Xs(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=Number.parseInt(r.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}class de extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.number,received:a.parsedType}),v}let s;const n=new V;for(const a of this._def.checks)a.kind==="int"?T.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?Xs(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_finite,message:a.message}),n.dirty()):T.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new de({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}de.create=r=>new de({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...w(r)});class fe extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let s;const n=new V;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):T.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:h.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,s,n){return new fe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new fe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}fe.create=r=>new fe({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...w(r)});class De extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.boolean,received:s.parsedType}),v}return G(e.data)}}De.create=r=>new De({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...w(r)});class we extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:h.date,received:a.parsedType}),v}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_date}),v}const s=new V;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):T.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new we({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}we.create=r=>new we({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...w(r)});class ht extends x{_parse(e){if(this._getType(e)!==h.symbol){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.symbol,received:s.parsedType}),v}return G(e.data)}}ht.create=r=>new ht({typeName:_.ZodSymbol,...w(r)});class Pe extends x{_parse(e){if(this._getType(e)!==h.undefined){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.undefined,received:s.parsedType}),v}return G(e.data)}}Pe.create=r=>new Pe({typeName:_.ZodUndefined,...w(r)});class Ze extends x{_parse(e){if(this._getType(e)!==h.null){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.null,received:s.parsedType}),v}return G(e.data)}}Ze.create=r=>new Ze({typeName:_.ZodNull,...w(r)});class Re extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return G(e.data)}}Re.create=r=>new Re({typeName:_.ZodAny,...w(r)});class _e extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return G(e.data)}}_e.create=r=>new _e({typeName:_.ZodUnknown,...w(r)});class ce extends x{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:l.invalid_type,expected:h.never,received:t.parsedType}),v}}ce.create=r=>new ce({typeName:_.ZodNever,...w(r)});class pt extends x{_parse(e){if(this._getType(e)!==h.undefined){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.void,received:s.parsedType}),v}return G(e.data)}}pt.create=r=>new pt({typeName:_.ZodVoid,...w(r)});class Y extends x{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==h.array)return f(t,{code:l.invalid_type,expected:h.array,received:t.parsedType}),v;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(f(t,{code:i?l.too_big:l.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),s.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(f(t,{code:l.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),s.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(f(t,{code:l.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new se(t,i,t.path,o)))).then(i=>V.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new se(t,i,t.path,o)));return V.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new Y({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new Y({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new Y({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}Y.create=(r,e)=>new Y({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...w(e)});function Se(r){if(r instanceof $){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=ee.create(Se(s))}return new $({...r._def,shape:()=>e})}else return r instanceof Y?new Y({...r._def,type:Se(r.element)}):r instanceof ee?ee.create(Se(r.unwrap())):r instanceof pe?pe.create(Se(r.unwrap())):r instanceof re?re.create(r.items.map(e=>Se(e))):r}class $ extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=T.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const u=this._getOrReturnCtx(e);return f(u,{code:l.invalid_type,expected:h.object,received:u.parsedType}),v}const{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ce&&this._def.unknownKeys==="strip"))for(const u in n.data)i.includes(u)||o.push(u);const d=[];for(const u of i){const g=a[u],k=n.data[u];d.push({key:{status:"valid",value:u},value:g._parse(new se(n,k,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof ce){const u=this._def.unknownKeys;if(u==="passthrough")for(const g of o)d.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(u==="strict")o.length>0&&(f(n,{code:l.unrecognized_keys,keys:o}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const g of o){const k=n.data[g];d.push({key:{status:"valid",value:g},value:u._parse(new se(n,k,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const g of d){const k=await g.key,j=await g.value;u.push({key:k,value:j,alwaysSet:g.alwaysSet})}return u}).then(u=>V.mergeObjectSync(s,u)):V.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new $({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const n=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new $({...this._def,unknownKeys:"strip"})}passthrough(){return new $({...this._def,unknownKeys:"passthrough"})}extend(e){return new $({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new $({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new $({...this._def,catchall:e})}pick(e){const t={};for(const s of T.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new $({...this._def,shape:()=>t})}omit(e){const t={};for(const s of T.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new $({...this._def,shape:()=>t})}deepPartial(){return Se(this)}partial(e){const t={};for(const s of T.objectKeys(this.shape)){const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new $({...this._def,shape:()=>t})}required(e){const t={};for(const s of T.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof ee;)a=a._def.innerType;t[s]=a}return new $({...this._def,shape:()=>t})}keyof(){return hs(T.objectKeys(this.shape))}}$.create=(r,e)=>new $({shape:()=>r,unknownKeys:"strip",catchall:ce.create(),typeName:_.ZodObject,...w(e)});$.strictCreate=(r,e)=>new $({shape:()=>r,unknownKeys:"strict",catchall:ce.create(),typeName:_.ZodObject,...w(e)});$.lazycreate=(r,e)=>new $({shape:r,unknownKeys:"strip",catchall:ce.create(),typeName:_.ZodObject,...w(e)});class Ve extends x{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new q(o.ctx.common.issues));return f(t,{code:l.invalid_union,unionErrors:i}),v}if(t.common.async)return Promise.all(s.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const d of s){const u={...t,common:{...t.common,issues:[]},parent:null},g=d._parseSync({data:t.data,path:t.path,parent:u});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(d=>new q(d));return f(t,{code:l.invalid_union,unionErrors:o}),v}}get options(){return this._def.options}}Ve.create=(r,e)=>new Ve({options:r,typeName:_.ZodUnion,...w(e)});const ae=r=>r instanceof Ue?ae(r.schema):r instanceof X?ae(r.innerType()):r instanceof qe?[r.value]:r instanceof he?r.options:r instanceof Je?T.objectValues(r.enum):r instanceof He?ae(r._def.innerType):r instanceof Pe?[void 0]:r instanceof Ze?[null]:r instanceof ee?[void 0,...ae(r.unwrap())]:r instanceof pe?[null,...ae(r.unwrap())]:r instanceof Lt||r instanceof Ke?ae(r.unwrap()):r instanceof We?ae(r._def.innerType):[];class _t extends x{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return f(t,{code:l.invalid_type,expected:h.object,received:t.parsedType}),v;const s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(f(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const a of t){const i=ae(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new _t({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...w(s)})}}function Ct(r,e){const t=ie(r),s=ie(e);if(r===e)return{valid:!0,data:r};if(t===h.object&&s===h.object){const n=T.objectKeys(e),a=T.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(const o of a){const d=Ct(r[o],e[o]);if(!d.valid)return{valid:!1};i[o]=d.data}return{valid:!0,data:i}}else if(t===h.array&&s===h.array){if(r.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<r.length;a++){const i=r[a],o=e[a],d=Ct(i,o);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return t===h.date&&s===h.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class Be extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(Nt(a)||Nt(i))return v;const o=Ct(a.value,i.value);return o.valid?((Rt(a)||Rt(i))&&t.dirty(),{status:t.value,value:o.data}):(f(s,{code:l.invalid_intersection_types}),v)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Be.create=(r,e,t)=>new Be({left:r,right:e,typeName:_.ZodIntersection,...w(t)});class re extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.array)return f(s,{code:l.invalid_type,expected:h.array,received:s.parsedType}),v;if(s.data.length<this._def.items.length)return f(s,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&s.data.length>this._def.items.length&&(f(s,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((i,o)=>{const d=this._def.items[o]||this._def.rest;return d?d._parse(new se(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>V.mergeArray(t,i)):V.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new re({...this._def,rest:e})}}re.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:r,typeName:_.ZodTuple,rest:null,...w(e)})};class Ge extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.object)return f(s,{code:l.invalid_type,expected:h.object,received:s.parsedType}),v;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in s.data)n.push({key:a._parse(new se(s,o,s.path,o)),value:i._parse(new se(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?V.mergeObjectAsync(t,n):V.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof x?new Ge({keyType:e,valueType:t,typeName:_.ZodRecord,...w(s)}):new Ge({keyType:K.create(),valueType:e,typeName:_.ZodRecord,...w(t)})}}class mt extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.map)return f(s,{code:l.invalid_type,expected:h.map,received:s.parsedType}),v;const n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,d],u)=>({key:n._parse(new se(s,o,s.path,[u,"key"])),value:a._parse(new se(s,d,s.path,[u,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const d of i){const u=await d.key,g=await d.value;if(u.status==="aborted"||g.status==="aborted")return v;(u.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(u.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const d of i){const u=d.key,g=d.value;if(u.status==="aborted"||g.status==="aborted")return v;(u.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(u.value,g.value)}return{status:t.value,value:o}}}}mt.create=(r,e,t)=>new mt({valueType:e,keyType:r,typeName:_.ZodMap,...w(t)});class xe extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.set)return f(s,{code:l.invalid_type,expected:h.set,received:s.parsedType}),v;const n=this._def;n.minSize!==null&&s.data.size<n.minSize.value&&(f(s,{code:l.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&s.data.size>n.maxSize.value&&(f(s,{code:l.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(d){const u=new Set;for(const g of d){if(g.status==="aborted")return v;g.status==="dirty"&&t.dirty(),u.add(g.value)}return{status:t.value,value:u}}const o=[...s.data.values()].map((d,u)=>a._parse(new se(s,d,s.path,u)));return s.common.async?Promise.all(o).then(d=>i(d)):i(o)}min(e,t){return new xe({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new xe({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}xe.create=(r,e)=>new xe({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});class Ae extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return f(t,{code:l.invalid_type,expected:h.function,received:t.parsedType}),v;function s(o,d){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dt(),Ne].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:d}})}function n(o,d){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,dt(),Ne].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:d}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Ce){const o=this;return G(async function(...d){const u=new q([]),g=await o._def.args.parseAsync(d,a).catch(S=>{throw u.addIssue(s(d,S)),u}),k=await Reflect.apply(i,this,g);return await o._def.returns._def.type.parseAsync(k,a).catch(S=>{throw u.addIssue(n(k,S)),u})})}else{const o=this;return G(function(...d){const u=o._def.args.safeParse(d,a);if(!u.success)throw new q([s(d,u.error)]);const g=Reflect.apply(i,this,u.data),k=o._def.returns.safeParse(g,a);if(!k.success)throw new q([n(g,k.error)]);return k.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ae({...this._def,args:re.create(e).rest(_e.create())})}returns(e){return new Ae({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new Ae({args:e||re.create([]).rest(_e.create()),returns:t||_e.create(),typeName:_.ZodFunction,...w(s)})}}class Ue extends x{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ue.create=(r,e)=>new Ue({getter:r,typeName:_.ZodLazy,...w(e)});class qe extends x{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}}qe.create=(r,e)=>new qe({value:r,typeName:_.ZodLiteral,...w(e)});function hs(r,e){return new he({values:r,typeName:_.ZodEnum,...w(e)})}class he extends x{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return f(t,{expected:T.joinValues(s),received:t.parsedType,code:l.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return f(t,{received:t.data,code:l.invalid_enum_value,options:s}),v}return G(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return he.create(e,{...this._def,...t})}exclude(e,t=this._def){return he.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}he.create=hs;class Je extends x{_parse(e){const t=T.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==h.string&&s.parsedType!==h.number){const n=T.objectValues(t);return f(s,{expected:T.joinValues(n),received:s.parsedType,code:l.invalid_type}),v}if(this._cache||(this._cache=new Set(T.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=T.objectValues(t);return f(s,{received:s.data,code:l.invalid_enum_value,options:n}),v}return G(e.data)}get enum(){return this._def.values}}Je.create=(r,e)=>new Je({values:r,typeName:_.ZodNativeEnum,...w(e)});class Ce extends x{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return f(t,{code:l.invalid_type,expected:h.promise,received:t.parsedType}),v;const s=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return G(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ce.create=(r,e)=>new Ce({type:r,typeName:_.ZodPromise,...w(e)});class X extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{f(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return v;const d=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return d.status==="aborted"?v:d.status==="dirty"||t.value==="dirty"?Ie(d.value):d});{if(t.value==="aborted")return v;const o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?v:o.status==="dirty"||t.value==="dirty"?Ie(o.value):o}}if(n.type==="refinement"){const i=o=>{const d=n.refinement(o,a);if(s.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?v:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!be(i))return v;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>be(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):v);T.assertNever(n)}}X.create=(r,e,t)=>new X({schema:r,typeName:_.ZodEffects,effect:e,...w(t)});X.createWithPreprocess=(r,e,t)=>new X({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...w(t)});class ee extends x{_parse(e){return this._getType(e)===h.undefined?G(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ee.create=(r,e)=>new ee({innerType:r,typeName:_.ZodOptional,...w(e)});class pe extends x{_parse(e){return this._getType(e)===h.null?G(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pe.create=(r,e)=>new pe({innerType:r,typeName:_.ZodNullable,...w(e)});class He extends x{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===h.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}He.create=(r,e)=>new He({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class We extends x{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Fe(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new q(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}We.create=(r,e)=>new We({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class gt extends x{_parse(e){if(this._getType(e)!==h.nan){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:h.nan,received:s.parsedType}),v}return{status:"valid",value:e.data}}}gt.create=r=>new gt({typeName:_.ZodNaN,...w(r)});const Qs=Symbol("zod_brand");class Lt extends x{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Xe extends x{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?v:a.status==="dirty"?(t.dirty(),Ie(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?v:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new Xe({in:e,out:t,typeName:_.ZodPipeline})}}class Ke extends x{_parse(e){const t=this._def.innerType._parse(e),s=n=>(be(n)&&(n.value=Object.freeze(n.value)),n);return Fe(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}Ke.create=(r,e)=>new Ke({innerType:r,typeName:_.ZodReadonly,...w(e)});function Jt(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function ps(r,e={},t){return r?Re.create().superRefine((s,n)=>{const a=r(s);if(a instanceof Promise)return a.then(i=>{if(!i){const o=Jt(e,s),d=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:d})}});if(!a){const i=Jt(e,s),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):Re.create()}const er={object:$.lazycreate};var _;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));const tr=(r,e={message:`Input not instance of ${r.name}`})=>ps(t=>t instanceof r,e),A=K.create,te=de.create,sr=gt.create,rr=fe.create,Qe=De.create,nr=we.create,ar=ht.create,ir=Pe.create,ms=Ze.create,me=Re.create,bt=_e.create,or=ce.create,cr=pt.create,ke=Y.create,N=$.create,lr=$.strictCreate,Te=Ve.create,ur=_t.create,dr=Be.create,fr=re.create,et=Ge.create,hr=mt.create,pr=xe.create,mr=Ae.create,gs=Ue.create,B=qe.create,wt=he.create,gr=Je.create,yr=Ce.create,Ht=X.create,vr=ee.create,_r=pe.create,br=X.createWithPreprocess,wr=Xe.create,xr=()=>A().optional(),kr=()=>te().optional(),Tr=()=>Qe().optional(),ut={string:r=>K.create({...r,coerce:!0}),number:r=>de.create({...r,coerce:!0}),boolean:r=>De.create({...r,coerce:!0}),bigint:r=>fe.create({...r,coerce:!0}),date:r=>we.create({...r,coerce:!0})},Er=v,P=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Qs,DIRTY:Ie,EMPTY_PATH:Rs,INVALID:v,NEVER:Er,OK:G,ParseStatus:V,Schema:x,ZodAny:Re,ZodArray:Y,ZodBigInt:fe,ZodBoolean:De,ZodBranded:Lt,ZodCatch:We,ZodDate:we,ZodDefault:He,ZodDiscriminatedUnion:_t,ZodEffects:X,ZodEnum:he,ZodError:q,get ZodFirstPartyTypeKind(){return _},ZodFunction:Ae,ZodIntersection:Be,ZodIssueCode:l,ZodLazy:Ue,ZodLiteral:qe,ZodMap:mt,ZodNaN:gt,ZodNativeEnum:Je,ZodNever:ce,ZodNull:Ze,ZodNullable:pe,ZodNumber:de,ZodObject:$,ZodOptional:ee,ZodParsedType:h,ZodPipeline:Xe,ZodPromise:Ce,ZodReadonly:Ke,ZodRecord:Ge,ZodSchema:x,ZodSet:xe,ZodString:K,ZodSymbol:ht,ZodTransformer:X,ZodTuple:re,ZodType:x,ZodUndefined:Pe,ZodUnion:Ve,ZodUnknown:_e,ZodVoid:pt,addIssueToContext:f,any:me,array:ke,bigint:rr,boolean:Qe,coerce:ut,custom:ps,date:nr,datetimeRegex:fs,defaultErrorMap:Ne,discriminatedUnion:ur,effect:Ht,enum:wt,function:mr,getErrorMap:dt,getParsedType:ie,instanceof:tr,intersection:dr,isAborted:Nt,isAsync:Fe,isDirty:Rt,isValid:be,late:er,lazy:gs,literal:B,makeIssue:ft,map:hr,nan:sr,nativeEnum:gr,never:or,null:ms,nullable:_r,number:te,object:N,get objectUtil(){return At},oboolean:Tr,onumber:kr,optional:vr,ostring:xr,pipeline:wr,preprocess:br,promise:yr,quotelessJson:As,record:et,set:pr,setErrorMap:Ns,strictObject:lr,string:A,symbol:ar,transformer:Ht,tuple:fr,undefined:ir,union:Te,unknown:bt,get util(){return T},void:cr},Symbol.toStringTag,{value:"Module"})),ye=()=>P.preprocess(r=>{if(typeof r=="boolean")return r;if(typeof r=="number")return r===1;if(typeof r=="string"){const e=r.trim().toLowerCase();if(["1","true","yes","y","on"].includes(e))return!0;if(["0","false","no","n","off"].includes(e))return!1}},P.boolean()),Sr=()=>P.preprocess(r=>{if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){const e=Number(r);if(Number.isFinite(e))return e}},P.number()),ys=P.object({NODE_ENV:P.enum(["development","production","test"]).default("production"),AGENT_CONTAINER_MODE:ye().default(!1),AGENT_API_KEY:P.string().optional(),AGENT_ORGANIZATION_ID:P.string().optional(),AGENT_SESSION_ID:P.string().optional(),AGENT_SERVER_URL:P.string().optional(),AGENT_TYPE:P.string().optional(),AGENT_DEVICE_GUID:P.string().optional(),CONTEXT_DATA:P.string().optional(),AGI_NETLOG_ENABLE:ye().default(!0),AGI_NETLOG_DEBUG:ye().optional(),AGI_NETLOG_FILE:P.string().optional(),AGI_NETLOG_MAX_BODY:Sr().optional(),AGI_NETLOG_REMOTE_ENABLE:ye().default(!0),AGI_NETLOG_REMOTE_FILE:P.string().optional(),DEBUG:ye().default(!1),VERBOSE:ye().default(!1),LOG_LEVEL:P.string().optional(),HOSTNAME:P.string().optional(),VITE_SAVE_RAW:ye().default(!1)});function ct(r=!1){return r?"https://agiflow.io":"https://agiflow.io"}let R=ys.parse(process.env);class ve{static refresh(){R=ys.parse(process.env)}static get isContainerMode(){return!!R.AGENT_CONTAINER_MODE}static get apiKey(){return R.AGENT_API_KEY||process.env.AGENT_API_KEY}static get organizationId(){return R.AGENT_ORGANIZATION_ID||process.env.AGENT_ORGANIZATION_ID}static get sessionId(){return R.AGENT_SESSION_ID||process.env.AGENT_SESSION_ID}static get serverUrl(){return R.AGENT_SERVER_URL||process.env.AGENT_SERVER_URL||ct(this.isContainerMode)}static get isNetlogEnabled(){return!!R.AGI_NETLOG_ENABLE}static get isNetlogDebug(){return!!R.AGI_NETLOG_DEBUG}static get isNetlogRemoteEnabled(){return!!R.AGI_NETLOG_REMOTE_ENABLE}static get isDebugMode(){return R.DEBUG}static get isVerbose(){return R.VERBOSE}static get logLevel(){return R.LOG_LEVEL??(R.DEBUG?"debug":"info")}static get nodeEnv(){return R.NODE_ENV}static get homeDir(){return process.env.HOME||process.env.USERPROFILE}static get isMacOS(){return process.platform==="darwin"}static get hostname(){return R.HOSTNAME}static get netlogMaxBody(){return R.AGI_NETLOG_MAX_BODY}static get netlogFile(){return R.AGI_NETLOG_FILE}static get netlogRemoteFile(){return R.AGI_NETLOG_REMOTE_FILE}static get agentType(){return R.AGENT_TYPE||process.env.AGENT_TYPE}static get deviceGuid(){return R.AGENT_DEVICE_GUID}static get isSaveRawEnabled(){return!!R.VITE_SAVE_RAW}static get contextData(){return R.CONTEXT_DATA||process.env.CONTEXT_DATA}static serializeEnv(){const e={...process.env};for(const[t,s]of Object.entries(R))s!==void 0&&(typeof s=="string"?e[t]=s:typeof s=="number"?e[t]=String(s):typeof s=="boolean"?e[t]=s?"true":"false":e[t]=String(s));return e}static toChildProcess(){const e=this.serializeEnv();return e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=ct(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static toDocker(){const e=this.serializeEnv();return e.AGENT_CONTAINER_MODE="true",e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=ct(!0)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static toPty(){const e=this.serializeEnv();return e.AGENT_SERVER_URL||(e.AGENT_SERVER_URL=ct(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static getEnvs(){return R}}const Wt=gs(()=>Te([ms(),A(),te(),Qe(),ke(Wt),et(Wt)])),Kt=N({toolCallId:A(),toolName:A(),args:me()}),Ir=N({toolCallId:A(),toolName:A(),args:me(),result:me()}),Or=Te([Kt.extend({state:B("partial-call"),step:te().optional()}),Kt.extend({state:B("call"),step:te().optional()}),Ir.extend({state:B("result"),step:te().optional()})]),Ar=N({type:A(),content:A()}),Nr=N({type:B("text"),text:A()}),Rr=N({type:B("reasoning"),reasoning:A(),details:ke(Te([N({type:B("text"),text:A(),signature:A().optional()}),N({type:B("redacted"),data:A()})])).optional()}),Cr=N({name:B("select"),props:N({options:ke(N({label:A(),value:Te([A(),te()]),selected:Qe().optional()}))})}),jr=N({name:B("placeholder"),props:N({})}),$r=Te([Cr,jr]),Mr=N({completed:Qe(),component:$r}),zr=N({type:B("tool-invocation"),toolInvocation:Or,input:Mr.optional(),jsx:A({description:"UI rendering"}).optional()}),Lr=N({type:B("source"),source:Ar}),Fr=N({type:B("file"),mimeType:A(),data:A()}),Dr=N({type:B("error"),text:A(),error:me().optional()}),Pr=N({type:B("step-start")}),vs=Te([Nr,Rr,zr,Lr,Fr,Dr,Pr]),Ft=wt(["input","output","error","system"]),_s=N({messageType:Ft,parts:ke(vs),metadata:et(A(),bt()).optional(),raw:me().optional()});N({id:A(),sessionId:A(),agentTypeId:A(),messageType:Ft,contentSize:te().nullable(),timestamp:ut.date(),metadata:A().nullable(),raw:me().nullable().optional(),createdAt:ut.date(),updatedAt:ut.date()});const Zr=N({messageType:wt(["output"]).default("output"),metadata:et(A(),bt()).optional()});N({id:A(),messageId:A()});const Vr=N({parts:ke(vs).optional(),metadata:et(A(),bt()).optional(),raw:me().optional()});N({messages:ke(_s)});function Br(r){return[Gr(r)]}function Yt(r){let e=r.parts;if(!e&&r.content&&(e=Br(r.content)),!e)throw new Error("Either content or parts is required for message creation");return{messageType:r.messageType,parts:e,metadata:r.metadata,raw:r.raw}}function Gr(r){return{type:"text",text:r}}const It=10,Xt=(r=0)=>e=>`\x1B[${e+r}m`,Qt=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,es=(r=0)=>(e,t,s)=>`\x1B[${38+r};2;${e};${t};${s}m`,C={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(C.modifier);const Ur=Object.keys(C.color),qr=Object.keys(C.bgColor);[...Ur,...qr];function Jr(){const r=new Map;for(const[e,t]of Object.entries(C)){for(const[s,n]of Object.entries(t))C[s]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[s]=C[s],r.set(n[0],n[1]);Object.defineProperty(C,e,{value:t,enumerable:!1})}return Object.defineProperty(C,"codes",{value:r,enumerable:!1}),C.color.close="\x1B[39m",C.bgColor.close="\x1B[49m",C.color.ansi=Xt(),C.color.ansi256=Qt(),C.color.ansi16m=es(),C.bgColor.ansi=Xt(It),C.bgColor.ansi256=Qt(It),C.bgColor.ansi16m=es(It),Object.defineProperties(C,{rgbToAnsi256:{value(e,t,s){return e===t&&t===s?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(e){const t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[s]=t;s.length===3&&(s=[...s].map(a=>a+a).join(""));const n=Number.parseInt(s,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:e=>C.rgbToAnsi256(...C.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,s,n;if(e>=232)t=((e-232)*10+8)/255,s=t,n=t;else{e-=16;const o=e%36;t=Math.floor(e/36)/5,s=Math.floor(o/6)/5,n=o%6/5}const a=Math.max(t,s,n)*2;if(a===0)return 30;let i=30+(Math.round(n)<<2|Math.round(s)<<1|Math.round(t));return a===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:(e,t,s)=>C.ansi256ToAnsi(C.rgbToAnsi256(e,t,s)),enumerable:!1},hexToAnsi:{value:e=>C.ansi256ToAnsi(C.hexToAnsi256(e)),enumerable:!1}}),C}const Q=Jr(),ts=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const r=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(r&&r.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),ss=ts!==0&&{level:ts},Hr={stdout:ss,stderr:ss};function Wr(r,e,t){let s=r.indexOf(e);if(s===-1)return r;const n=e.length;let a=0,i="";do i+=r.slice(a,s)+e+t,a=s+n,s=r.indexOf(e,a);while(s!==-1);return i+=r.slice(a),i}function Kr(r,e,t,s){let n=0,a="";do{const i=r[s-1]==="\r";a+=r.slice(n,i?s-1:s)+e+(i?`\r
3
3
  `:`
4
4
  `)+t,n=s+1,s=r.indexOf(`
5
- `,n)}while(s!==-1);return a+=r.slice(n),a}const{stdout:rs,stderr:ns}=Jr,jt=Symbol("GENERATOR"),je=Symbol("STYLER"),Ye=Symbol("IS_EMPTY"),as=["ansi","ansi","ansi256","ansi16m"],$e=Object.create(null),Yr=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const t=rs?rs.level:0;r.level=e.level===void 0?t:e.level},Xr=r=>{const e=(...t)=>t.join(" ");return Yr(e,r),Object.setPrototypeOf(e,tt.prototype),e};function tt(r){return Xr(r)}Object.setPrototypeOf(tt.prototype,Function.prototype);for(const[r,e]of Object.entries(X))$e[r]={get(){const t=yt(this,Mt(e.open,e.close,this[je]),this[Ye]);return Object.defineProperty(this,r,{value:t}),t}};$e.visible={get(){const r=yt(this,this[je],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const $t=(r,e,t,...s)=>r==="rgb"?e==="ansi16m"?X[t].ansi16m(...s):e==="ansi256"?X[t].ansi256(X.rgbToAnsi256(...s)):X[t].ansi(X.rgbToAnsi(...s)):r==="hex"?$t("rgb",e,t,...X.hexToRgb(...s)):X[t][r](...s),Qr=["rgb","hex","ansi256"];for(const r of Qr){$e[r]={get(){const{level:t}=this;return function(...s){const n=Mt($t(r,as[t],"color",...s),X.color.close,this[je]);return yt(this,n,this[Ye])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);$e[e]={get(){const{level:t}=this;return function(...s){const n=Mt($t(r,as[t],"bgColor",...s),X.bgColor.close,this[je]);return yt(this,n,this[Ye])}}}}const en=Object.defineProperties(()=>{},{...$e,level:{enumerable:!0,get(){return this[jt].level},set(r){this[jt].level=r}}}),Mt=(r,e,t)=>{let s,n;return t===void 0?(s=r,n=e):(s=t.openAll+r,n=e+t.closeAll),{open:r,close:e,openAll:s,closeAll:n,parent:t}},yt=(r,e,t)=>{const s=(...n)=>tn(s,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(s,en),s[jt]=r,s[je]=e,s[Ye]=t,s},tn=(r,e)=>{if(r.level<=0||!e)return r[Ye]?"":e;let t=r[je];if(t===void 0)return e;const{openAll:s,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Kr(e,t.close,t.open),t=t.parent;const a=e.indexOf(`
6
- `);return a!==-1&&(e=Wr(e,n,s,a)),s+e+n};Object.defineProperties(tt.prototype,$e);const z=tt();tt({level:ns?ns.level:0});function sn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Le={exports:{}},At,is;function rn(){if(is)return At;is=1;function r(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}At=e;function e(t,s,n){var a=n&&n.stringify||r,i=1;if(typeof t=="object"&&t!==null){var o=s.length+i;if(o===1)return t;var d=new Array(o);d[0]=a(t);for(var u=1;u<o;u++)d[u]=a(s[u]);return d.join(" ")}if(typeof t!="string")return t;var g=s.length;if(g===0)return t;for(var x="",j=1-i,S=-1,H=t&&t.length||0,O=0;O<H;){if(t.charCodeAt(O)===37&&O+1<H){switch(S=S>-1?S:0,t.charCodeAt(O+1)){case 100:case 102:if(j>=g||s[j]==null)break;S<O&&(x+=t.slice(S,O)),x+=Number(s[j]),S=O+2,O++;break;case 105:if(j>=g||s[j]==null)break;S<O&&(x+=t.slice(S,O)),x+=Math.floor(Number(s[j])),S=O+2,O++;break;case 79:case 111:case 106:if(j>=g||s[j]===void 0)break;S<O&&(x+=t.slice(S,O));var st=typeof s[j];if(st==="string"){x+="'"+s[j]+"'",S=O+2,O++;break}if(st==="function"){x+=s[j].name||"<anonymous>",S=O+2,O++;break}x+=a(s[j]),S=O+2,O++;break;case 115:if(j>=g)break;S<O&&(x+=t.slice(S,O)),x+=String(s[j]),S=O+2,O++;break;case 37:S<O&&(x+=t.slice(S,O)),x+="%",S=O+2,O++,j--;break}++j}++O}return S===-1?t:(S<H&&(x+=t.slice(S)),x)}return At}var os;function nn(){if(os)return Le.exports;os=1;const r=rn();Le.exports=g;const e=Es().console||{},t={mapHttpRequest:rt,mapHttpResponse:rt,wrapRequestSerializer:Tt,wrapResponseSerializer:Tt,wrapErrorSerializer:Tt,req:rt,res:rt,err:Dt,errWithCause:Dt};function s(c,p){return c==="silent"?1/0:p.levels.values[c]}const n=Symbol("pino.logFuncs"),a=Symbol("pino.hierarchy"),i={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function o(c,p){const b={logger:p,parent:c[a]};p[a]=b}function d(c,p,b){const E={};p.forEach(A=>{E[A]=b[A]?b[A]:e[A]||e[i[A]||"log"]||Ee}),c[n]=E}function u(c,p){return Array.isArray(c)?c.filter(function(E){return E!=="!stdSerializers.err"}):c===!0?Object.keys(p):!1}function g(c){c=c||{},c.browser=c.browser||{};const p=c.browser.transmit;if(p&&typeof p.send!="function")throw Error("pino: transmit option must have a send function");const b=c.browser.write||e;c.browser.write&&(c.browser.asObject=!0);const E=c.serializers||{},A=u(c.browser.serialize,E);let P=c.browser.serialize;Array.isArray(c.browser.serialize)&&c.browser.serialize.indexOf("!stdSerializers.err")>-1&&(P=!1);const q=Object.keys(c.customLevels||{}),M=["error","fatal","warn","info","debug","trace"].concat(q);typeof b=="function"&&M.forEach(function(J){b[J]=b}),(c.enabled===!1||c.browser.disabled)&&(c.level="silent");const G=c.level||"info",y=Object.create(b);y.log||(y.log=Ee),d(y,M,b),o({},y),Object.defineProperty(y,"levelVal",{get:nt}),Object.defineProperty(y,"level",{get:me,set:at});const L={transmit:p,serialize:A,asObject:c.browser.asObject,formatters:c.browser.formatters,levels:M,timestamp:ks(c),messageKey:c.messageKey||"msg",onChild:c.onChild||Ee};y.levels=x(c),y.level=G,y.setMaxListeners=y.getMaxListeners=y.emit=y.addListener=y.on=y.prependListener=y.once=y.prependOnceListener=y.removeListener=y.removeAllListeners=y.listeners=y.listenerCount=y.eventNames=y.write=y.flush=Ee,y.serializers=E,y._serialize=A,y._stdErrSerialize=P,y.child=function(...J){return Vt.call(this,L,...J)},p&&(y._logEvent=xt());function nt(){return s(this.level,this)}function me(){return this._level}function at(J){if(J!=="silent"&&!this.levels.values[J])throw Error("unknown level "+J);this._level=J,H(this,L,y,"error"),H(this,L,y,"fatal"),H(this,L,y,"warn"),H(this,L,y,"info"),H(this,L,y,"debug"),H(this,L,y,"trace"),q.forEach(re=>{H(this,L,y,re)})}function Vt(J,re,Me){if(!re)throw new Error("missing bindings for child Pino");Me=Me||{},A&&re.serializers&&(Me.serializers=re.serializers);const Bt=Me.serializers;if(A&&Bt){var it=Object.assign({},E,Bt),Gt=c.browser.serialize===!0?Object.keys(it):A;delete re.serializers,kt([re],Gt,it,this._stdErrSerialize)}function Ut(ot){this._childLevel=(ot._childLevel|0)+1,this.bindings=re,it&&(this.serializers=it,this._serialize=Gt),p&&(this._logEvent=xt([].concat(ot._logEvent.bindings,re)))}Ut.prototype=this;const ze=new Ut(this);return o(this,ze),ze.child=function(...ot){return Vt.call(this,J,...ot)},ze.level=Me.level||this.level,J.onChild(ze),ze}return y}function x(c){const p=c.customLevels||{},b=Object.assign({},g.levels.values,p),E=Object.assign({},g.levels.labels,j(p));return{values:b,labels:E}}function j(c){const p={};return Object.keys(c).forEach(function(b){p[c[b]]=b}),p}g.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},g.stdSerializers=t,g.stdTimeFunctions=Object.assign({},{nullTime:Pt,epochTime:Zt,unixTime:xs,isoTime:Ts});function S(c){const p=[];c.bindings&&p.push(c.bindings);let b=c[a];for(;b.parent;)b=b.parent,b.logger.bindings&&p.push(b.logger.bindings);return p.reverse()}function H(c,p,b,E){if(Object.defineProperty(c,E,{value:s(c.level,b)>s(E,b)?Ee:b[n][E],writable:!0,enumerable:!0,configurable:!0}),c[E]===Ee){if(!p.transmit)return;const P=p.transmit.level||c.level,q=s(P,b);if(s(E,b)<q)return}c[E]=st(c,p,b,E);const A=S(c);A.length!==0&&(c[E]=O(A,c[E]))}function O(c,p){return function(){return p.apply(this,[...c,...arguments])}}function st(c,p,b,E){return function(A){return function(){const q=p.timestamp(),M=new Array(arguments.length),G=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var y=0;y<M.length;y++)M[y]=arguments[y];var L=!1;if(p.serialize&&(kt(M,this._serialize,this.serializers,this._stdErrSerialize),L=!0),p.asObject||p.formatters?A.call(G,bs(this,E,M,q,p)):A.apply(G,M),p.transmit){const nt=p.transmit.level||c._level,me=s(nt,b),at=s(E,b);if(at<me)return;ws(this,{ts:q,methodLevel:E,methodValue:at,transmitValue:b.levels.values[p.transmit.level||c._level],send:p.transmit.send,val:s(c._level,b)},M,L)}}}(c[n][E])}function bs(c,p,b,E,A){const{level:P,log:q=me=>me}=A.formatters||{},M=b.slice();let G=M[0];const y={};if(E&&(y.time=E),P){const me=P(p,c.levels.values[p]);Object.assign(y,me)}else y.level=c.levels.values[p];let L=(c._childLevel|0)+1;if(L<1&&(L=1),G!==null&&typeof G=="object"){for(;L--&&typeof M[0]=="object";)Object.assign(y,M.shift());G=M.length?r(M.shift(),M):void 0}else typeof G=="string"&&(G=r(M.shift(),M));return G!==void 0&&(y[A.messageKey]=G),q(y)}function kt(c,p,b,E){for(const A in c)if(E&&c[A]instanceof Error)c[A]=g.stdSerializers.err(c[A]);else if(typeof c[A]=="object"&&!Array.isArray(c[A])&&p)for(const P in c[A])p.indexOf(P)>-1&&P in b&&(c[A][P]=b[P](c[A][P]))}function ws(c,p,b,E=!1){const A=p.send,P=p.ts,q=p.methodLevel,M=p.methodValue,G=p.val,y=c._logEvent.bindings;E||kt(b,c._serialize||Object.keys(c.serializers),c.serializers,c._stdErrSerialize===void 0?!0:c._stdErrSerialize),c._logEvent.ts=P,c._logEvent.messages=b.filter(function(L){return y.indexOf(L)===-1}),c._logEvent.level.label=q,c._logEvent.level.value=M,A(q,c._logEvent,G),c._logEvent=xt(y)}function xt(c){return{ts:0,messages:[],bindings:c||[],level:{label:"",value:0}}}function Dt(c){const p={type:c.constructor.name,msg:c.message,stack:c.stack};for(const b in c)p[b]===void 0&&(p[b]=c[b]);return p}function ks(c){return typeof c.timestamp=="function"?c.timestamp:c.timestamp===!1?Pt:Zt}function rt(){return{}}function Tt(c){return c}function Ee(){}function Pt(){return!1}function Zt(){return Date.now()}function xs(){return Math.round(Date.now()/1e3)}function Ts(){return new Date(Date.now()).toISOString()}function Es(){function c(p){return typeof p<"u"&&p}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return c(self)||c(window)||c(this)||{}}}return Le.exports.default=g,Le.exports.pino=g,Le.exports}var an=nn();const lt=sn(an);class F{pino;useTerminalFormat;static instance;constructor(e={}){this.useTerminalFormat=e.useTerminalFormat??!0;const t=e.debug?"debug":e.verbose?"trace":"info";e.silent?this.pino=lt({level:"silent"}):e.logFile||e.logDir?this.pino=this.createMultiTransportLogger(t,e):this.useTerminalFormat&&process.stdout.isTTY?this.pino=lt({level:t,transport:{target:"pino-pretty",options:{colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}}):this.pino=lt({level:t})}createMultiTransportLogger(e,t){let s;if(t.logFile)s=t.logFile;else if(t.logDir){ie.existsSync(t.logDir)||ie.mkdirSync(t.logDir,{recursive:!0});const a=new Date().toISOString().split("T")[0];s=Ae.join(t.logDir,`app-${a}.log`)}else{const a=Ae.join(As.tmpdir(),"agiflow-agents","logs",`session-${process.pid}`);ie.existsSync(a)||ie.mkdirSync(a,{recursive:!0});const i=new Date().toISOString().split("T")[0];s=Ae.join(a,`app-${i}.log`)}const n=[];return this.useTerminalFormat&&process.stdout.isTTY?n.push({level:e,target:"pino-pretty",options:{destination:1,colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}):n.push({level:e,target:"pino/file",options:{destination:1}}),t.maxFileSize||t.maxFiles?n.push({level:e,target:"pino-roll",options:{file:s,frequency:"daily",size:t.maxFileSize||"10m",limit:{count:t.maxFiles||7},symlink:!0,mkdir:!0}}):n.push({level:e,target:"pino/file",options:{destination:s,mkdir:!0}}),lt({level:e,transport:{targets:n}})}static getInstance(){return F.instance||(F.instance=new F),F.instance}static configure(e){F.instance=new F(e)}getLogFilePath(){const e=this.pino.transports;if(e&&Array.isArray(e)){const t=e.find(s=>s.target==="pino/file"||s.target==="pino-roll");if(t&&t.options)return t.options.destination||t.options.file}}info(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.log(z.blue("ℹ"),e,...t):this.pino.info(e,...t)}static info(e,...t){F.getInstance().info(e,...t)}success(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.log(z.green("✓"),e,...t):this.pino.info({type:"success"},e,...t)}static success(e,...t){F.getInstance().success(e,...t)}warn(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.warn(z.yellow("⚠"),e,...t):this.pino.warn(e,...t)}static warn(e,...t){F.getInstance().warn(e,...t)}error(e,t,s){let n,a;t instanceof Error?(n=t,a=s):a=t,this.useTerminalFormat&&process.stdout.isTTY?console.error(z.red("✗"),e,n||""):n?this.pino.error(n,e):this.pino.error(e),a?.exit!==void 0&&process.exit(a.exit)}static error(e,t){F.getInstance().error(e,void 0,t)}debug(e,...t){this.useTerminalFormat&&process.stdout.isTTY?(ve.isDebugMode||this.pino.level==="debug"||this.pino.level==="trace")&&console.log(z.gray("🔍"),z.gray(e),...t):this.pino.debug(e,...t)}static debug(e,...t){F.getInstance().debug(e,...t)}trace(e,...t){this.useTerminalFormat&&process.stdout.isTTY?this.pino.level==="trace"&&console.log(z.gray("..."),z.gray(e),...t):this.pino.trace(e,...t)}title(e){this.useTerminalFormat&&process.stdout.isTTY?(console.log(),console.log(z.bold.cyan(e)),console.log(z.cyan("=".repeat(e.length)))):this.pino.info({type:"title"},e)}static title(e){F.getInstance().title(e)}code(e){this.useTerminalFormat&&process.stdout.isTTY?(console.log(),console.log(z.gray(" "+e)),console.log()):this.pino.info({type:"code",code:e},"Code example")}static code(e){F.getInstance().code(e)}newLine(){this.useTerminalFormat&&process.stdout.isTTY&&console.log()}static newLine(){F.getInstance().newLine()}terminal(e,t,...s){if(!process.stdout.isTTY){this.pino[e==="success"||e==="title"||e==="code"?"info":e](t,...s);return}switch(e){case"info":console.log(z.blue("ℹ"),t,...s);break;case"success":console.log(z.green("✓"),t,...s);break;case"warn":console.warn(z.yellow("⚠"),t,...s);break;case"error":console.error(z.red("✗"),t,...s);break;case"debug":console.log(z.gray("🔍"),z.gray(t),...s);break;case"title":console.log(),console.log(z.bold.cyan(t)),console.log(z.cyan("=".repeat(t.length)));break;case"code":console.log(),console.log(z.gray(" "+t)),console.log();break}}getPino(){return this.pino}child(e){const t=new F({useTerminalFormat:this.useTerminalFormat});return t.pino=this.pino.child(e),t}}class le{static AGIFLOW_DIR=ye.join(Et.homedir(),".agiflow");static async ensureDir(e){await ce.ensureDir(e)}static async exists(e){try{return await ce.access(e),!0}catch{return!1}}static async readJson(e){const t=await ce.readFile(e,"utf-8");return JSON.parse(t)}static async writeJson(e,t,s){await ce.ensureDir(ye.dirname(e));const n=JSON.stringify(t,null,s?.spaces??2);await ce.writeFile(e,n,"utf-8")}static async copy(e,t){await ce.copy(e,t)}static async remove(e){await ce.remove(e)}static getCurrentDirectory(){return process.cwd()}static resolvePath(...e){return ye.resolve(process.cwd(),...e)}static async getFiles(e,t){const s=await ce.readdir(e);return t?s.filter(n=>t.test(n)):s}static getAbsolutePath(e){return e?e.startsWith("~/")?ye.join(Et.homedir(),e.slice(2)):e==="~"?Et.homedir():ye.isAbsolute(e)?e:ye.resolve(process.cwd(),e):process.cwd()}}class on{filePath;cache=null;dirty=!1;constructor(e){this.filePath=e||ye.join(le.AGIFLOW_DIR,"credentials.json")}async load(){if(this.cache)return this.cache;try{if(!await le.exists(this.filePath))return null;const t=await le.readJson(this.filePath);return this.cache=t,t}catch{return null}}async flush(){!this.dirty||!this.cache||(await le.ensureDir(le.AGIFLOW_DIR),await le.writeJson(this.filePath,this.cache),this.dirty=!1)}async setApiKey(e){this.cache={apiKey:e.apiKey,organizationId:e.organizationId,deviceId:e.deviceId||this.cache?.deviceId,expiresAt:e.expiresAt},this.dirty=!0,await this.flush()}async setDeviceId(e){const t=await this.load()||{apiKey:"",organizationId:""};t.deviceId=e,this.cache=t,this.dirty=!0,await this.flush()}async getApiKey(){return(await this.load())?.apiKey||null}async getAgentCreds(){const e=await this.load();if(!e)throw new Error("Cred not set");return{apiKey:e.apiKey,organizationId:e.organizationId,deviceId:e.deviceId}}async getOrganizationId(){return(await this.load())?.organizationId||null}async getDeviceId(){return(await this.load())?.deviceId||null}async isExpired(e=300*1e3){const t=await this.load();return t?.expiresAt?Date.now()>=t.expiresAt-e:!1}async clear(){this.cache=null,this.dirty=!1;try{await le.exists(this.filePath)&&await le.remove(this.filePath)}catch{}}async buildAuthHeaders(){const e=await this.load();return e?.apiKey?{"x-api-key":e.apiKey}:{}}async buildDeviceAuthHeaders(e){const t=await this.load();if(!t?.apiKey)return{};const s={"x-api-key":t.apiKey};return e&&(s["x-device-guid"]=e),t.deviceId&&(s["x-device-id"]=t.deviceId),t.organizationId&&(s["x-organization-id"]=t.organizationId),s}async buildAgentAuthHeaders(e){let t=e;if(t||(t=await this.getApiKey()||void 0),t||(t=ve.apiKey),!t)return{};const s={"x-api-key":t,"Content-Type":"application/json"},n=await this.getOrganizationId();n&&(s["x-organization-id"]=n);const a=await this.getDeviceId();return a&&(s["x-device-id"]=a),s}}N({limit:ee().min(1).max(100).optional(),offset:ee().min(0).optional(),messageType:Ft.optional(),sort:I().optional(),order:wt(["asc","desc"]).optional()});class cn{options;authService;credentials;logger;constructor(e){this.options=e,this.authService=e.authService,this.credentials=e.credentials??new on,this.logger=e.logger??new F({verbose:!1})}async getAuthHeaders(){let e=await this.credentials.getApiKey(),t=await this.credentials.getOrganizationId();if((!e||!t)&&this.authService){const n=await this.authService.getValidApiKey();e=n.api_key,t=n.organization_id,await this.credentials.setApiKey({apiKey:e,organizationId:t,expiresAt:n.expires_at})}if(!e&&this.options.apiKey&&(e=this.options.apiKey),!t&&this.options.organizationId&&(t=this.options.organizationId),e&&t)return this.options.organizationId=t,{"Content-Type":"application/json","x-api-key":e};const s=this.options.authToken;if(!s)throw new Error("Authentication token is required for agent message operations");if(!this.options.organizationId)throw new Error("Organization ID is required for agent message operations");return{"Content-Type":"application/json",Authorization:`Bearer ${s}`}}async makeAuthenticatedRequest(e,t,s=!0){const n=await fetch(e,t);if(n.status===401&&s&&this.authService){const a=await n.text();if(a.includes("Invalid API key")){this.logger.info("= API key expired or invalid, clearing tokens and retrying authentication..."),await this.authService.clearTokens();try{await this.credentials.clear()}catch{}this.logger.info("= Retrying authentication...");const i=await this.getAuthHeaders(),o={...t,headers:{...t.headers,...i}};return await this.makeAuthenticatedRequest(e,o,!1)}if(a.includes("Invalid or expired session")){const i=ve.isContainerMode;if(this.logger.error("🚫 Session validation failed:",new Error(`Session validation failed for ${e}. Docker mode: ${i}, Method: ${t.method||"GET"}, Timestamp: ${new Date().toISOString()}`)),i)return this.logger.warn("🐳 Docker session timing issue detected, waiting and retrying..."),await new Promise(o=>setTimeout(o,2e3)),await this.makeAuthenticatedRequest(e,t,!1)}}return n.status===429&&this.logger.warn("= Rate limit exceeded, keeping credentials but not retrying"),n}async sendMessage(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for sending agent messages");const n=Yt(e);try{_s.parse(n)}catch(a){throw new Error(`Invalid message payload: ${a instanceof Error?a.message:a}`)}try{const a=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e.sessionId}/messages`,{method:"POST",headers:t,body:JSON.stringify(n)});if(!a.ok){const o=await a.text();throw new Error(`Failed to send agent message: ${a.status} ${o}`)}return await a.json()}catch(a){throw new Error(`Failed to send agent message: ${a instanceof Error?a.message:a}`)}}async sendMessageBatch(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for sending agent messages");const a=t.map(i=>Yt(i));try{const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages/batch`,{method:"POST",headers:s,body:JSON.stringify({messages:a})});if(!i.ok){const d=await i.text();throw new Error(`Failed to send agent message batch: ${i.status} ${d}`)}return await i.json()}catch(i){throw new Error(`Failed to send agent message batch: ${i instanceof Error?i.message:i}`)}}async getSessionMessages(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for fetching agent messages");const a=new URLSearchParams;t?.limit&&a.append("limit",t.limit.toString()),t?.offset&&a.append("offset",t.offset.toString()),t?.messageType&&a.append("messageType",t.messageType),t?.sort&&a.append("sort",t.sort),t?.order&&a.append("order",t.order);const i=`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages?${a.toString()}`;try{const o=await this.makeAuthenticatedRequest(i,{method:"GET",headers:s});if(!o.ok){const u=await o.text();throw new Error(`Failed to fetch session messages: ${o.status} ${u}`)}return await o.json()}catch(o){throw new Error(`Failed to fetch session messages: ${o instanceof Error?o.message:o}`)}}async uploadMessageContent(e,t,s,n){const a=await this.getAuthHeaders(),i=this.options.organizationId;if(!i)throw new Error("Organization ID is required for uploading message content");const o=typeof s=="string"?Buffer.from(s,"utf-8"):s,d=o.length;try{const u=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${i}/agent-sessions/${e}/messages/presign`,{method:"POST",headers:a,body:JSON.stringify({messageType:t,contentSize:d})});if(!u.ok){const S=await u.text();throw new Error(`Failed to get presigned URL: ${u.status} ${S}`)}const{uploadUrl:g}=await u.json(),x=await fetch(g,{method:"PUT",body:o,headers:{"Content-Type":"application/octet-stream","Content-Length":d.toString()}});if(!x.ok)throw new Error(`Failed to upload content to R2: ${x.status}`);const j={sessionId:e,messageType:t,contentSize:d,metadata:n};return await this.sendMessage(j)}catch(u){throw new Error(`Failed to upload message content: ${u instanceof Error?u.message:u}`)}}async startMessage(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for starting agent messages");try{Zr.parse(t)}catch(a){throw new Error(`Invalid start message payload: ${a instanceof Error?a.message:a}`)}try{const a=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages/start`,{method:"POST",headers:s,body:JSON.stringify(t)});if(!a.ok){const o=await a.text();throw new Error(`Failed to start agent message: ${a.status} ${o}`)}return await a.json()}catch(a){throw new Error(`Failed to start agent message: ${a instanceof Error?a.message:a}`)}}async updateMessage(e,t,s){const n=await this.getAuthHeaders(),a=this.options.organizationId;if(!a)throw new Error("Organization ID is required for updating agent messages");try{Vr.parse(s)}catch(o){throw this.logger.error("=❌ Update message validation failed",new Error(`Update message validation failed: ${o instanceof Error?o.message:o}`)),new Error(`Invalid update message payload: ${o instanceof Error?o.message:o}`)}const i=JSON.stringify(s);try{const o=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${a}/agent-sessions/${e}/messages/${t}`,{method:"PATCH",headers:n,body:i});if(!o.ok){const u=await o.text();throw new Error(`Failed to update agent message: ${o.status} ${u}`)}return await o.json()}catch(o){throw new Error(`Failed to update agent message: ${o instanceof Error?o.message:o}`)}}async deleteSessionMessages(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for deleting session messages");this.logger.info(`=� Deleting all messages for session ${e}...`);try{const n=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e}/messages`,{method:"DELETE",headers:t},!1);if(!n.ok){const i=await n.text().catch(()=>"Unknown error");return this.logger.warn(`� Failed to delete session messages: ${n.status} ${i}`),0}const{deletedCount:a}=await n.json();return this.logger.success(` Deleted ${a} messages for session ${e}`),a}catch(n){return this.logger.warn("� Failed to delete session messages:",n),0}}async getAgentSession(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for fetching agent session");try{const n=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e}`,{method:"GET",headers:t});if(!n.ok){const i=await n.text();throw new Error(`Failed to fetch agent session: ${n.status} ${i}`)}return await n.json()}catch(n){throw new Error(`Failed to fetch agent session: ${n instanceof Error?n.message:n}`)}}async createTaskComment(e,t,s,n){try{const a=await this.getAuthHeaders(),i=this.options.organizationId;if(!i)return this.logger.warn("Organization ID is required for creating task comment"),null;const o=t&&t.length>1e4?t.substring(0,1e4):t,d=await this.getAgentSession(e);if(!d)return this.logger.warn("Agent session not found for task comment creation"),null;if(!d.taskId)return this.logger.debug("Agent session has no associated task - skipping comment creation"),null;const u=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${i}/tasks/${d.taskId}/comments`,{method:"POST",headers:a,body:JSON.stringify({content:o,assigneeId:s,info:n})});if(!u.ok){const x=await u.text();return this.logger.warn(`Failed to create task comment: ${u.status} ${x}`),null}const g=await u.json();return this.logger.debug("Task comment created successfully"),g}catch(a){return this.logger.warn(`Failed to create task comment: ${a instanceof Error?a.message:a}`),null}}async updateTaskDevInfo(e,t){try{const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)return this.logger.warn("Organization ID is required for updating task devInfo"),null;const a=await this.getAgentSession(e);if(!a)return this.logger.warn("Agent session not found for task devInfo update"),null;if(!a.taskId)return this.logger.debug("Agent session has no associated task - skipping devInfo update"),null;const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/tasks/${a.taskId}`,{method:"PATCH",headers:s,body:JSON.stringify({devInfo:t})});if(!i.ok){const d=await i.text();return this.logger.warn(`Failed to update task devInfo: ${i.status} ${d}`),null}const o=await i.json();return this.logger.debug("Task devInfo updated successfully"),o}catch(s){return this.logger.warn(`Failed to update task devInfo: ${s instanceof Error?s.message:s}`),null}}}const vt=Ae.join(cs.tmpdir(),"claude-posttooluse-logs"),ln=Ae.join(vt,"posttooluse.jsonl");ie.existsSync(vt)||ie.mkdirSync(vt,{recursive:!0});class un{agentHttpService=null;sessionId;currentMessageId=null;enableRemote=!1;constructor(){this.sessionId=ve.sessionId||"",this.currentMessageId=null,this.setupRemoteService()}setupRemoteService(){let e=ve.serverUrl||"";e.startsWith("wss://")?e="https://"+e.slice(6):e.startsWith("ws://")&&(e="http://"+e.slice(5));const t=ve.apiKey||"",s=ve.organizationId||"";if(this.enableRemote=!!(this.sessionId&&e&&t&&s),this.enableRemote&&e)try{this.agentHttpService=new cn({apiUrl:e,organizationId:s,apiKey:t})}catch(n){this.enableRemote=!1,this.logToFile({type:"error",message:"Failed to initialize remote service",error:n instanceof Error?n.message:String(n)})}}logToFile(e){const t={timestamp:new Date().toISOString(),sessionId:this.sessionId,...e};ie.appendFileSync(ln,JSON.stringify(t)+`
7
- `)}findMessageIdFromTranscript(e){try{const s=ie.readFileSync(e,"utf-8").trim().split(`
8
- `);let n=null;for(let a=s.length-1;a>=0;a--)try{const i=JSON.parse(s[a]);if(i.type==="assistant"&&i.message?.id){n=i.message.id;break}}catch{}return n}catch{return null}}async processToolExecution(e){try{try{this.logToFile({type:"tool-execution",tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response,cwd:e.cwd})}catch{}if(e.transcript_path&&(this.currentMessageId=this.findMessageIdFromTranscript(e.transcript_path),this.currentMessageId))try{this.logToFile({type:"message-id-found",messageId:this.currentMessageId,source:"transcript"})}catch{}if(this.enableRemote&&this.agentHttpService&&this.currentMessageId)try{const t={parts:[{type:"tool-invocation",toolInvocation:{toolCallId:`tool_${e.tool_name}_${Date.now()}`,toolName:e.tool_name,state:"result",args:e.tool_input,result:e.tool_response}}],metadata:{tool_name:e.tool_name,tool_input:e.tool_input,has_error:this.hasError(e.tool_response),response_size:JSON.stringify(e.tool_response).length,execution_time:new Date().toISOString(),cwd:e.cwd}};await this.agentHttpService.updateMessage(this.sessionId,this.currentMessageId,t);try{this.logToFile({type:"message-updated",messageId:this.currentMessageId,tool_name:e.tool_name})}catch{}}catch(t){try{this.logToFile({type:"remote-update-error",error:t instanceof Error?t.message:String(t),tool_name:e.tool_name,messageId:this.currentMessageId})}catch{}}if(this.hasError(e.tool_response))try{this.logToFile({type:"tool-error",tool_name:e.tool_name,error:this.extractErrorMessage(e.tool_response)})}catch{}}catch{}return{decision:"approve"}}hasError(e){if(e.error||e.errorMessage||e.success===!1)return!0;const t=typeof e=="string"?e:JSON.stringify(e);return!!(t.includes("Error:")||t.includes("Failed")||t.includes("Exception"))}extractErrorMessage(e){return e.error?String(e.error):e.errorMessage?String(e.errorMessage):e.message?String(e.message):typeof e=="string"?e:"Unknown error occurred"}}async function dn(){try{let r;try{const n=[];for await(const i of process.stdin)n.push(i);const a=Buffer.concat(n).toString();r=JSON.parse(a);try{ie.appendFileSync(Ae.join(vt,"raw-input.jsonl"),JSON.stringify({timestamp:new Date().toISOString(),raw:a})+`
5
+ `,n)}while(s!==-1);return a+=r.slice(n),a}const{stdout:rs,stderr:ns}=Hr,jt=Symbol("GENERATOR"),je=Symbol("STYLER"),Ye=Symbol("IS_EMPTY"),as=["ansi","ansi","ansi256","ansi16m"],$e=Object.create(null),Yr=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const t=rs?rs.level:0;r.level=e.level===void 0?t:e.level},Xr=r=>{const e=(...t)=>t.join(" ");return Yr(e,r),Object.setPrototypeOf(e,tt.prototype),e};function tt(r){return Xr(r)}Object.setPrototypeOf(tt.prototype,Function.prototype);for(const[r,e]of Object.entries(Q))$e[r]={get(){const t=yt(this,Mt(e.open,e.close,this[je]),this[Ye]);return Object.defineProperty(this,r,{value:t}),t}};$e.visible={get(){const r=yt(this,this[je],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const $t=(r,e,t,...s)=>r==="rgb"?e==="ansi16m"?Q[t].ansi16m(...s):e==="ansi256"?Q[t].ansi256(Q.rgbToAnsi256(...s)):Q[t].ansi(Q.rgbToAnsi(...s)):r==="hex"?$t("rgb",e,t,...Q.hexToRgb(...s)):Q[t][r](...s),Qr=["rgb","hex","ansi256"];for(const r of Qr){$e[r]={get(){const{level:t}=this;return function(...s){const n=Mt($t(r,as[t],"color",...s),Q.color.close,this[je]);return yt(this,n,this[Ye])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);$e[e]={get(){const{level:t}=this;return function(...s){const n=Mt($t(r,as[t],"bgColor",...s),Q.bgColor.close,this[je]);return yt(this,n,this[Ye])}}}}const en=Object.defineProperties(()=>{},{...$e,level:{enumerable:!0,get(){return this[jt].level},set(r){this[jt].level=r}}}),Mt=(r,e,t)=>{let s,n;return t===void 0?(s=r,n=e):(s=t.openAll+r,n=e+t.closeAll),{open:r,close:e,openAll:s,closeAll:n,parent:t}},yt=(r,e,t)=>{const s=(...n)=>tn(s,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(s,en),s[jt]=r,s[je]=e,s[Ye]=t,s},tn=(r,e)=>{if(r.level<=0||!e)return r[Ye]?"":e;let t=r[je];if(t===void 0)return e;const{openAll:s,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Wr(e,t.close,t.open),t=t.parent;const a=e.indexOf(`
6
+ `);return a!==-1&&(e=Kr(e,n,s,a)),s+e+n};Object.defineProperties(tt.prototype,$e);const z=tt();tt({level:ns?ns.level:0});function sn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Le={exports:{}},Ot,is;function rn(){if(is)return Ot;is=1;function r(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}Ot=e;function e(t,s,n){var a=n&&n.stringify||r,i=1;if(typeof t=="object"&&t!==null){var o=s.length+i;if(o===1)return t;var d=new Array(o);d[0]=a(t);for(var u=1;u<o;u++)d[u]=a(s[u]);return d.join(" ")}if(typeof t!="string")return t;var g=s.length;if(g===0)return t;for(var k="",j=1-i,S=-1,H=t&&t.length||0,I=0;I<H;){if(t.charCodeAt(I)===37&&I+1<H){switch(S=S>-1?S:0,t.charCodeAt(I+1)){case 100:case 102:if(j>=g||s[j]==null)break;S<I&&(k+=t.slice(S,I)),k+=Number(s[j]),S=I+2,I++;break;case 105:if(j>=g||s[j]==null)break;S<I&&(k+=t.slice(S,I)),k+=Math.floor(Number(s[j])),S=I+2,I++;break;case 79:case 111:case 106:if(j>=g||s[j]===void 0)break;S<I&&(k+=t.slice(S,I));var st=typeof s[j];if(st==="string"){k+="'"+s[j]+"'",S=I+2,I++;break}if(st==="function"){k+=s[j].name||"<anonymous>",S=I+2,I++;break}k+=a(s[j]),S=I+2,I++;break;case 115:if(j>=g)break;S<I&&(k+=t.slice(S,I)),k+=String(s[j]),S=I+2,I++;break;case 37:S<I&&(k+=t.slice(S,I)),k+="%",S=I+2,I++,j--;break}++j}++I}return S===-1?t:(S<H&&(k+=t.slice(S)),k)}return Ot}var os;function nn(){if(os)return Le.exports;os=1;const r=rn();Le.exports=g;const e=Es().console||{},t={mapHttpRequest:rt,mapHttpResponse:rt,wrapRequestSerializer:Tt,wrapResponseSerializer:Tt,wrapErrorSerializer:Tt,req:rt,res:rt,err:Dt,errWithCause:Dt};function s(c,p){return c==="silent"?1/0:p.levels.values[c]}const n=Symbol("pino.logFuncs"),a=Symbol("pino.hierarchy"),i={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function o(c,p){const b={logger:p,parent:c[a]};p[a]=b}function d(c,p,b){const E={};p.forEach(O=>{E[O]=b[O]?b[O]:e[O]||e[i[O]||"log"]||Ee}),c[n]=E}function u(c,p){return Array.isArray(c)?c.filter(function(E){return E!=="!stdSerializers.err"}):c===!0?Object.keys(p):!1}function g(c){c=c||{},c.browser=c.browser||{};const p=c.browser.transmit;if(p&&typeof p.send!="function")throw Error("pino: transmit option must have a send function");const b=c.browser.write||e;c.browser.write&&(c.browser.asObject=!0);const E=c.serializers||{},O=u(c.browser.serialize,E);let Z=c.browser.serialize;Array.isArray(c.browser.serialize)&&c.browser.serialize.indexOf("!stdSerializers.err")>-1&&(Z=!1);const J=Object.keys(c.customLevels||{}),M=["error","fatal","warn","info","debug","trace"].concat(J);typeof b=="function"&&M.forEach(function(W){b[W]=b}),(c.enabled===!1||c.browser.disabled)&&(c.level="silent");const U=c.level||"info",y=Object.create(b);y.log||(y.log=Ee),d(y,M,b),o({},y),Object.defineProperty(y,"levelVal",{get:nt}),Object.defineProperty(y,"level",{get:ge,set:at});const F={transmit:p,serialize:O,asObject:c.browser.asObject,formatters:c.browser.formatters,levels:M,timestamp:xs(c),messageKey:c.messageKey||"msg",onChild:c.onChild||Ee};y.levels=k(c),y.level=U,y.setMaxListeners=y.getMaxListeners=y.emit=y.addListener=y.on=y.prependListener=y.once=y.prependOnceListener=y.removeListener=y.removeAllListeners=y.listeners=y.listenerCount=y.eventNames=y.write=y.flush=Ee,y.serializers=E,y._serialize=O,y._stdErrSerialize=Z,y.child=function(...W){return Vt.call(this,F,...W)},p&&(y._logEvent=kt());function nt(){return s(this.level,this)}function ge(){return this._level}function at(W){if(W!=="silent"&&!this.levels.values[W])throw Error("unknown level "+W);this._level=W,H(this,F,y,"error"),H(this,F,y,"fatal"),H(this,F,y,"warn"),H(this,F,y,"info"),H(this,F,y,"debug"),H(this,F,y,"trace"),J.forEach(ne=>{H(this,F,y,ne)})}function Vt(W,ne,Me){if(!ne)throw new Error("missing bindings for child Pino");Me=Me||{},O&&ne.serializers&&(Me.serializers=ne.serializers);const Bt=Me.serializers;if(O&&Bt){var it=Object.assign({},E,Bt),Gt=c.browser.serialize===!0?Object.keys(it):O;delete ne.serializers,xt([ne],Gt,it,this._stdErrSerialize)}function Ut(ot){this._childLevel=(ot._childLevel|0)+1,this.bindings=ne,it&&(this.serializers=it,this._serialize=Gt),p&&(this._logEvent=kt([].concat(ot._logEvent.bindings,ne)))}Ut.prototype=this;const ze=new Ut(this);return o(this,ze),ze.child=function(...ot){return Vt.call(this,W,...ot)},ze.level=Me.level||this.level,W.onChild(ze),ze}return y}function k(c){const p=c.customLevels||{},b=Object.assign({},g.levels.values,p),E=Object.assign({},g.levels.labels,j(p));return{values:b,labels:E}}function j(c){const p={};return Object.keys(c).forEach(function(b){p[c[b]]=b}),p}g.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},g.stdSerializers=t,g.stdTimeFunctions=Object.assign({},{nullTime:Pt,epochTime:Zt,unixTime:ks,isoTime:Ts});function S(c){const p=[];c.bindings&&p.push(c.bindings);let b=c[a];for(;b.parent;)b=b.parent,b.logger.bindings&&p.push(b.logger.bindings);return p.reverse()}function H(c,p,b,E){if(Object.defineProperty(c,E,{value:s(c.level,b)>s(E,b)?Ee:b[n][E],writable:!0,enumerable:!0,configurable:!0}),c[E]===Ee){if(!p.transmit)return;const Z=p.transmit.level||c.level,J=s(Z,b);if(s(E,b)<J)return}c[E]=st(c,p,b,E);const O=S(c);O.length!==0&&(c[E]=I(O,c[E]))}function I(c,p){return function(){return p.apply(this,[...c,...arguments])}}function st(c,p,b,E){return function(O){return function(){const J=p.timestamp(),M=new Array(arguments.length),U=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var y=0;y<M.length;y++)M[y]=arguments[y];var F=!1;if(p.serialize&&(xt(M,this._serialize,this.serializers,this._stdErrSerialize),F=!0),p.asObject||p.formatters?O.call(U,bs(this,E,M,J,p)):O.apply(U,M),p.transmit){const nt=p.transmit.level||c._level,ge=s(nt,b),at=s(E,b);if(at<ge)return;ws(this,{ts:J,methodLevel:E,methodValue:at,transmitValue:b.levels.values[p.transmit.level||c._level],send:p.transmit.send,val:s(c._level,b)},M,F)}}}(c[n][E])}function bs(c,p,b,E,O){const{level:Z,log:J=ge=>ge}=O.formatters||{},M=b.slice();let U=M[0];const y={};if(E&&(y.time=E),Z){const ge=Z(p,c.levels.values[p]);Object.assign(y,ge)}else y.level=c.levels.values[p];let F=(c._childLevel|0)+1;if(F<1&&(F=1),U!==null&&typeof U=="object"){for(;F--&&typeof M[0]=="object";)Object.assign(y,M.shift());U=M.length?r(M.shift(),M):void 0}else typeof U=="string"&&(U=r(M.shift(),M));return U!==void 0&&(y[O.messageKey]=U),J(y)}function xt(c,p,b,E){for(const O in c)if(E&&c[O]instanceof Error)c[O]=g.stdSerializers.err(c[O]);else if(typeof c[O]=="object"&&!Array.isArray(c[O])&&p)for(const Z in c[O])p.indexOf(Z)>-1&&Z in b&&(c[O][Z]=b[Z](c[O][Z]))}function ws(c,p,b,E=!1){const O=p.send,Z=p.ts,J=p.methodLevel,M=p.methodValue,U=p.val,y=c._logEvent.bindings;E||xt(b,c._serialize||Object.keys(c.serializers),c.serializers,c._stdErrSerialize===void 0?!0:c._stdErrSerialize),c._logEvent.ts=Z,c._logEvent.messages=b.filter(function(F){return y.indexOf(F)===-1}),c._logEvent.level.label=J,c._logEvent.level.value=M,O(J,c._logEvent,U),c._logEvent=kt(y)}function kt(c){return{ts:0,messages:[],bindings:c||[],level:{label:"",value:0}}}function Dt(c){const p={type:c.constructor.name,msg:c.message,stack:c.stack};for(const b in c)p[b]===void 0&&(p[b]=c[b]);return p}function xs(c){return typeof c.timestamp=="function"?c.timestamp:c.timestamp===!1?Pt:Zt}function rt(){return{}}function Tt(c){return c}function Ee(){}function Pt(){return!1}function Zt(){return Date.now()}function ks(){return Math.round(Date.now()/1e3)}function Ts(){return new Date(Date.now()).toISOString()}function Es(){function c(p){return typeof p<"u"&&p}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return c(self)||c(window)||c(this)||{}}}return Le.exports.default=g,Le.exports.pino=g,Le.exports}var an=nn();const lt=sn(an);class D{pino;useTerminalFormat;static instance;constructor(e={}){this.useTerminalFormat=e.useTerminalFormat??!0;const t=e.debug?"debug":e.verbose?"trace":"info";e.silent?this.pino=lt({level:"silent"}):e.logFile||e.logDir?this.pino=this.createMultiTransportLogger(t,e):this.useTerminalFormat&&process.stdout.isTTY?this.pino=lt({level:t,transport:{target:"pino-pretty",options:{colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}}):this.pino=lt({level:t})}createMultiTransportLogger(e,t){let s;if(t.logFile)s=t.logFile;else if(t.logDir){oe.existsSync(t.logDir)||oe.mkdirSync(t.logDir,{recursive:!0});const a=new Date().toISOString().split("T")[0];s=Oe.join(t.logDir,`app-${a}.log`)}else{const a=Oe.join(Os.tmpdir(),"agiflow-agents","logs",`session-${process.pid}`);oe.existsSync(a)||oe.mkdirSync(a,{recursive:!0});const i=new Date().toISOString().split("T")[0];s=Oe.join(a,`app-${i}.log`)}const n=[];return this.useTerminalFormat&&process.stdout.isTTY?n.push({level:e,target:"pino-pretty",options:{destination:1,colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}):n.push({level:e,target:"pino/file",options:{destination:1}}),t.maxFileSize||t.maxFiles?n.push({level:e,target:"pino-roll",options:{file:s,frequency:"daily",size:t.maxFileSize||"10m",limit:{count:t.maxFiles||7},symlink:!0,mkdir:!0}}):n.push({level:e,target:"pino/file",options:{destination:s,mkdir:!0}}),lt({level:e,transport:{targets:n}})}static getInstance(){return D.instance||(D.instance=new D),D.instance}static configure(e){D.instance=new D(e)}getLogFilePath(){const e=this.pino.transports;if(e&&Array.isArray(e)){const t=e.find(s=>s.target==="pino/file"||s.target==="pino-roll");if(t&&t.options)return t.options.destination||t.options.file}}info(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.log(z.blue("ℹ"),e,...t):this.pino.info(e,...t)}static info(e,...t){D.getInstance().info(e,...t)}success(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.log(z.green("✓"),e,...t):this.pino.info({type:"success"},e,...t)}static success(e,...t){D.getInstance().success(e,...t)}warn(e,...t){this.useTerminalFormat&&process.stdout.isTTY?console.warn(z.yellow("⚠"),e,...t):this.pino.warn(e,...t)}static warn(e,...t){D.getInstance().warn(e,...t)}error(e,t,s){let n,a;t instanceof Error?(n=t,a=s):a=t,this.useTerminalFormat&&process.stdout.isTTY?console.error(z.red("✗"),e,n||""):n?this.pino.error(n,e):this.pino.error(e),a?.exit!==void 0&&process.exit(a.exit)}static error(e,t){D.getInstance().error(e,void 0,t)}debug(e,...t){this.useTerminalFormat&&process.stdout.isTTY?(ve.isDebugMode||this.pino.level==="debug"||this.pino.level==="trace")&&console.log(z.gray("🔍"),z.gray(e),...t):this.pino.debug(e,...t)}static debug(e,...t){D.getInstance().debug(e,...t)}trace(e,...t){this.useTerminalFormat&&process.stdout.isTTY?this.pino.level==="trace"&&console.log(z.gray("..."),z.gray(e),...t):this.pino.trace(e,...t)}title(e){this.useTerminalFormat&&process.stdout.isTTY?(console.log(),console.log(z.bold.cyan(e)),console.log(z.cyan("=".repeat(e.length)))):this.pino.info({type:"title"},e)}static title(e){D.getInstance().title(e)}code(e){this.useTerminalFormat&&process.stdout.isTTY?(console.log(),console.log(z.gray(" "+e)),console.log()):this.pino.info({type:"code",code:e},"Code example")}static code(e){D.getInstance().code(e)}newLine(){this.useTerminalFormat&&process.stdout.isTTY&&console.log()}static newLine(){D.getInstance().newLine()}terminal(e,t,...s){if(!process.stdout.isTTY){this.pino[e==="success"||e==="title"||e==="code"?"info":e](t,...s);return}switch(e){case"info":console.log(z.blue("ℹ"),t,...s);break;case"success":console.log(z.green("✓"),t,...s);break;case"warn":console.warn(z.yellow("⚠"),t,...s);break;case"error":console.error(z.red("✗"),t,...s);break;case"debug":console.log(z.gray("🔍"),z.gray(t),...s);break;case"title":console.log(),console.log(z.bold.cyan(t)),console.log(z.cyan("=".repeat(t.length)));break;case"code":console.log(),console.log(z.gray(" "+t)),console.log();break}}getPino(){return this.pino}child(e){const t=new D({useTerminalFormat:this.useTerminalFormat});return t.pino=this.pino.child(e),t}}class L{static AGIFLOW_DIR=ue.join(Et.homedir(),".agiflow");static async ensureDir(e){await le.ensureDir(e)}static async exists(e){try{return await le.access(e),!0}catch{return!1}}static async readJson(e){const t=await le.readFile(e,"utf-8");return JSON.parse(t)}static async writeJson(e,t,s){await le.ensureDir(ue.dirname(e));const n=JSON.stringify(t,null,s?.spaces??2);await le.writeFile(e,n,"utf-8")}static async copy(e,t){await le.copy(e,t)}static async remove(e){await le.remove(e)}static getCurrentDirectory(){return process.cwd()}static resolvePath(...e){return ue.resolve(process.cwd(),...e)}static async getFiles(e,t){const s=await le.readdir(e);return t?s.filter(n=>t.test(n)):s}static getAbsolutePath(e){return e?e.startsWith("~/")?ue.join(Et.homedir(),e.slice(2)):e==="~"?Et.homedir():ue.isAbsolute(e)?e:ue.resolve(process.cwd(),e):process.cwd()}}class fn{static SESSIONS_FILE=ue.join(L.AGIFLOW_DIR,"sessions.json");static async getSessionSettings(e){try{return await L.exists(this.SESSIONS_FILE)&&(await L.readJson(this.SESSIONS_FILE))[e]||null}catch(t){return console.error("[SessionSettings] Failed to read session settings:",t),null}}static async setSessionSettings(e,t){try{let s={};await L.exists(this.SESSIONS_FILE)&&(s=await L.readJson(this.SESSIONS_FILE)),s[e]=t,await L.writeJson(this.SESSIONS_FILE,s,{spaces:2})}catch(s){throw console.error("[SessionSettings] Failed to write session settings:",s),s}}static async removeSessionSettings(e){try{if(!await L.exists(this.SESSIONS_FILE))return;const s=await L.readJson(this.SESSIONS_FILE);delete s[e],await L.writeJson(this.SESSIONS_FILE,s,{spaces:2})}catch(t){throw console.error("[SessionSettings] Failed to remove session settings:",t),t}}static async getAllSessions(){try{return await L.exists(this.SESSIONS_FILE)?await L.readJson(this.SESSIONS_FILE):{}}catch(e){return console.error("[SessionSettings] Failed to read all session settings:",e),{}}}static async clearAllSessions(){try{await L.writeJson(this.SESSIONS_FILE,{},{spaces:2})}catch(e){throw console.error("[SessionSettings] Failed to clear session settings:",e),e}}}class on{filePath;cache=null;dirty=!1;constructor(e){this.filePath=e||ue.join(L.AGIFLOW_DIR,"credentials.json")}async load(){if(this.cache)return this.cache;try{if(!await L.exists(this.filePath))return null;const t=await L.readJson(this.filePath);return this.cache=t,t}catch{return null}}async flush(){!this.dirty||!this.cache||(await L.ensureDir(L.AGIFLOW_DIR),await L.writeJson(this.filePath,this.cache),this.dirty=!1)}async setApiKey(e){this.cache={apiKey:e.apiKey,organizationId:e.organizationId,deviceId:e.deviceId||this.cache?.deviceId,expiresAt:e.expiresAt},this.dirty=!0,await this.flush()}async setDeviceId(e){const t=await this.load()||{apiKey:"",organizationId:""};t.deviceId=e,this.cache=t,this.dirty=!0,await this.flush()}async getApiKey(){return(await this.load())?.apiKey||null}async getAgentCreds(){const e=await this.load();if(!e)throw new Error("Cred not set");return{apiKey:e.apiKey,organizationId:e.organizationId,deviceId:e.deviceId}}async getOrganizationId(){return(await this.load())?.organizationId||null}async getDeviceId(){return(await this.load())?.deviceId||null}async isExpired(e=300*1e3){const t=await this.load();return t?.expiresAt?Date.now()>=t.expiresAt-e:!1}async clear(){this.cache=null,this.dirty=!1;try{await L.exists(this.filePath)&&await L.remove(this.filePath)}catch{}}async buildAuthHeaders(){const e=await this.load();return e?.apiKey?{"x-api-key":e.apiKey}:{}}async buildDeviceAuthHeaders(e){const t=await this.load();if(!t?.apiKey)return{};const s={"x-api-key":t.apiKey};return e&&(s["x-device-guid"]=e),t.deviceId&&(s["x-device-id"]=t.deviceId),t.organizationId&&(s["x-organization-id"]=t.organizationId),s}async buildAgentAuthHeaders(e){let t=e;if(t||(t=await this.getApiKey()||void 0),t||(t=ve.apiKey),!t)return{};const s={"x-api-key":t,"Content-Type":"application/json"},n=await this.getOrganizationId();n&&(s["x-organization-id"]=n);const a=await this.getDeviceId();return a&&(s["x-device-id"]=a),s}}N({limit:te().min(1).max(100).optional(),offset:te().min(0).optional(),messageType:Ft.optional(),sort:A().optional(),order:wt(["asc","desc"]).optional()});class cn{options;authService;credentials;logger;constructor(e){this.options=e,this.authService=e.authService,this.credentials=e.credentials??new on,this.logger=e.logger??new D({verbose:!1})}async getAuthHeaders(){let e=await this.credentials.getApiKey(),t=await this.credentials.getOrganizationId();if((!e||!t)&&this.authService){const n=await this.authService.getValidApiKey();e=n.api_key,t=n.organization_id,await this.credentials.setApiKey({apiKey:e,organizationId:t,expiresAt:n.expires_at})}if(!e&&this.options.apiKey&&(e=this.options.apiKey),!t&&this.options.organizationId&&(t=this.options.organizationId),e&&t)return this.options.organizationId=t,{"Content-Type":"application/json","x-api-key":e};const s=this.options.authToken;if(!s)throw new Error("Authentication token is required for agent message operations");if(!this.options.organizationId)throw new Error("Organization ID is required for agent message operations");return{"Content-Type":"application/json",Authorization:`Bearer ${s}`}}async makeAuthenticatedRequest(e,t,s=!0){const n=await fetch(e,t);if(n.status===401&&s&&this.authService){const a=await n.text();if(a.includes("Invalid API key")){this.logger.info("= API key expired or invalid, clearing tokens and retrying authentication..."),await this.authService.clearTokens();try{await this.credentials.clear()}catch{}this.logger.info("= Retrying authentication...");const i=await this.getAuthHeaders(),o={...t,headers:{...t.headers,...i}};return await this.makeAuthenticatedRequest(e,o,!1)}if(a.includes("Invalid or expired session")){const i=ve.isContainerMode;if(this.logger.error("🚫 Session validation failed:",new Error(`Session validation failed for ${e}. Docker mode: ${i}, Method: ${t.method||"GET"}, Timestamp: ${new Date().toISOString()}`)),i)return this.logger.warn("🐳 Docker session timing issue detected, waiting and retrying..."),await new Promise(o=>setTimeout(o,2e3)),await this.makeAuthenticatedRequest(e,t,!1)}}return n.status===429&&this.logger.warn("= Rate limit exceeded, keeping credentials but not retrying"),n}async sendMessage(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for sending agent messages");const n=Yt(e);try{_s.parse(n)}catch(a){throw new Error(`Invalid message payload: ${a instanceof Error?a.message:a}`)}try{const a=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e.sessionId}/messages`,{method:"POST",headers:t,body:JSON.stringify(n)});if(!a.ok){const o=await a.text();throw new Error(`Failed to send agent message: ${a.status} ${o}`)}return await a.json()}catch(a){throw new Error(`Failed to send agent message: ${a instanceof Error?a.message:a}`)}}async sendMessageBatch(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for sending agent messages");const a=(t||[]).map(i=>Yt(i));try{const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages/batch`,{method:"POST",headers:s,body:JSON.stringify({messages:a})});if(!i.ok){const d=await i.text();throw new Error(`Failed to send agent message batch: ${i.status} ${d}`)}return await i.json()}catch(i){throw new Error(`Failed to send agent message batch: ${i instanceof Error?i.message:i}`)}}async getSessionMessages(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for fetching agent messages");const a=new URLSearchParams;t?.limit&&a.append("limit",t.limit.toString()),t?.offset&&a.append("offset",t.offset.toString()),t?.messageType&&a.append("messageType",t.messageType),t?.sort&&a.append("sort",t.sort),t?.order&&a.append("order",t.order);const i=`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages?${a.toString()}`;try{const o=await this.makeAuthenticatedRequest(i,{method:"GET",headers:s});if(!o.ok){const u=await o.text();throw new Error(`Failed to fetch session messages: ${o.status} ${u}`)}return await o.json()}catch(o){throw new Error(`Failed to fetch session messages: ${o instanceof Error?o.message:o}`)}}async uploadMessageContent(e,t,s,n){const a=await this.getAuthHeaders(),i=this.options.organizationId;if(!i)throw new Error("Organization ID is required for uploading message content");const o=typeof s=="string"?Buffer.from(s,"utf-8"):s,d=o.length;try{const u=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${i}/agent-sessions/${e}/messages/presign`,{method:"POST",headers:a,body:JSON.stringify({messageType:t,contentSize:d})});if(!u.ok){const S=await u.text();throw new Error(`Failed to get presigned URL: ${u.status} ${S}`)}const{uploadUrl:g}=await u.json(),k=await fetch(g,{method:"PUT",body:o,headers:{"Content-Type":"application/octet-stream","Content-Length":d.toString()}});if(!k.ok)throw new Error(`Failed to upload content to R2: ${k.status}`);const j={sessionId:e,messageType:t,contentSize:d,metadata:n};return await this.sendMessage(j)}catch(u){throw new Error(`Failed to upload message content: ${u instanceof Error?u.message:u}`)}}async startMessage(e,t){const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)throw new Error("Organization ID is required for starting agent messages");try{Zr.parse(t)}catch(a){throw new Error(`Invalid start message payload: ${a instanceof Error?a.message:a}`)}try{const a=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/agent-sessions/${e}/messages/start`,{method:"POST",headers:s,body:JSON.stringify(t)});if(!a.ok){const o=await a.text();throw new Error(`Failed to start agent message: ${a.status} ${o}`)}return await a.json()}catch(a){throw new Error(`Failed to start agent message: ${a instanceof Error?a.message:a}`)}}async updateMessage(e,t,s){const n=await this.getAuthHeaders(),a=this.options.organizationId;if(!a)throw new Error("Organization ID is required for updating agent messages");try{Vr.parse(s)}catch(o){throw this.logger.error("=❌ Update message validation failed",new Error(`Update message validation failed: ${o instanceof Error?o.message:o}`)),new Error(`Invalid update message payload: ${o instanceof Error?o.message:o}`)}const i=JSON.stringify(s);try{const o=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${a}/agent-sessions/${e}/messages/${t}`,{method:"PATCH",headers:n,body:i});if(!o.ok){const u=await o.text();throw new Error(`Failed to update agent message: ${o.status} ${u}`)}return await o.json()}catch(o){throw new Error(`Failed to update agent message: ${o instanceof Error?o.message:o}`)}}async deleteSessionMessages(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for deleting session messages");this.logger.info(`=� Deleting all messages for session ${e}...`);try{const n=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e}/messages`,{method:"DELETE",headers:t},!1);if(!n.ok){const i=await n.text().catch(()=>"Unknown error");return this.logger.warn(`� Failed to delete session messages: ${n.status} ${i}`),0}const{deletedCount:a}=await n.json();return this.logger.success(` Deleted ${a} messages for session ${e}`),a}catch(n){return this.logger.warn("� Failed to delete session messages:",n),0}}async getAgentSession(e){const t=await this.getAuthHeaders(),s=this.options.organizationId;if(!s)throw new Error("Organization ID is required for fetching agent session");try{const n=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${s}/agent-sessions/${e}`,{method:"GET",headers:t});if(!n.ok){const i=await n.text();throw new Error(`Failed to fetch agent session: ${n.status} ${i}`)}return await n.json()}catch(n){throw new Error(`Failed to fetch agent session: ${n instanceof Error?n.message:n}`)}}async createTaskComment(e,t,s,n){try{const a=await this.getAuthHeaders(),i=this.options.organizationId;if(!i)return this.logger.warn("Organization ID is required for creating task comment"),null;const o=t&&t.length>1e4?t.substring(0,1e4):t,d=await this.getAgentSession(e);if(!d)return this.logger.warn("Agent session not found for task comment creation"),null;if(!d.taskId)return this.logger.debug("Agent session has no associated task - skipping comment creation"),null;const u=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${i}/tasks/${d.taskId}/comments`,{method:"POST",headers:a,body:JSON.stringify({content:o,assigneeId:s,info:n})});if(!u.ok){const k=await u.text();return this.logger.warn(`Failed to create task comment: ${u.status} ${k}`),null}const g=await u.json();return this.logger.debug("Task comment created successfully"),g}catch(a){return this.logger.warn(`Failed to create task comment: ${a instanceof Error?a.message:a}`),null}}async updateTaskDevInfo(e,t){try{const s=await this.getAuthHeaders(),n=this.options.organizationId;if(!n)return this.logger.warn("Organization ID is required for updating task devInfo"),null;const a=await this.getAgentSession(e);if(!a)return this.logger.warn("Agent session not found for task devInfo update"),null;if(!a.taskId)return this.logger.debug("Agent session has no associated task - skipping devInfo update"),null;const i=await this.makeAuthenticatedRequest(`${this.options.apiUrl}/api/v1/organizations/${n}/tasks/${a.taskId}`,{method:"PATCH",headers:s,body:JSON.stringify({devInfo:t})});if(!i.ok){const d=await i.text();return this.logger.warn(`Failed to update task devInfo: ${i.status} ${d}`),null}const o=await i.json();return this.logger.debug("Task devInfo updated successfully"),o}catch(s){return this.logger.warn(`Failed to update task devInfo: ${s instanceof Error?s.message:s}`),null}}}const vt=Oe.join(cs.tmpdir(),"claude-posttooluse-logs"),ln=Oe.join(vt,"posttooluse.jsonl");oe.existsSync(vt)||oe.mkdirSync(vt,{recursive:!0});class un{agentHttpService=null;sessionId;currentMessageId=null;enableRemote=!1;constructor(){this.sessionId=ve.sessionId||"",this.currentMessageId=null,this.setupRemoteService()}setupRemoteService(){let e=ve.serverUrl||"";e.startsWith("wss://")?e="https://"+e.slice(6):e.startsWith("ws://")&&(e="http://"+e.slice(5));const t=ve.apiKey||"",s=ve.organizationId||"";if(this.enableRemote=!!(this.sessionId&&e&&t&&s),this.enableRemote&&e)try{this.agentHttpService=new cn({apiUrl:e,organizationId:s,apiKey:t})}catch(n){this.enableRemote=!1,this.logToFile({type:"error",message:"Failed to initialize remote service",error:n instanceof Error?n.message:String(n)})}}logToFile(e){const t={timestamp:new Date().toISOString(),sessionId:this.sessionId,...e};oe.appendFileSync(ln,JSON.stringify(t)+`
7
+ `)}findMessageIdFromTranscript(e){try{const s=oe.readFileSync(e,"utf-8").trim().split(`
8
+ `);let n=null;for(let a=s.length-1;a>=0;a--)try{const i=JSON.parse(s[a]);if(i.type==="assistant"&&i.message?.id){n=i.message.id;break}}catch{}return n}catch{return null}}async processToolExecution(e){try{try{this.logToFile({type:"tool-execution",tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response,cwd:e.cwd})}catch{}if(e.transcript_path&&(this.currentMessageId=this.findMessageIdFromTranscript(e.transcript_path),this.currentMessageId))try{this.logToFile({type:"message-id-found",messageId:this.currentMessageId,source:"transcript"})}catch{}if(this.enableRemote&&this.agentHttpService&&this.currentMessageId)try{const t={parts:[{type:"tool-invocation",toolInvocation:{toolCallId:`tool_${e.tool_name}_${Date.now()}`,toolName:e.tool_name,state:"result",args:e.tool_input,result:e.tool_response}}],metadata:{tool_name:e.tool_name,tool_input:e.tool_input,has_error:this.hasError(e.tool_response),response_size:JSON.stringify(e.tool_response).length,execution_time:new Date().toISOString(),cwd:e.cwd}};await this.agentHttpService.updateMessage(this.sessionId,this.currentMessageId,t);try{this.logToFile({type:"message-updated",messageId:this.currentMessageId,tool_name:e.tool_name})}catch{}}catch(t){try{this.logToFile({type:"remote-update-error",error:t instanceof Error?t.message:String(t),tool_name:e.tool_name,messageId:this.currentMessageId})}catch{}}if(this.hasError(e.tool_response))try{this.logToFile({type:"tool-error",tool_name:e.tool_name,error:this.extractErrorMessage(e.tool_response)})}catch{}}catch{}return{decision:"approve"}}hasError(e){if(e.error||e.errorMessage||e.success===!1)return!0;const t=typeof e=="string"?e:JSON.stringify(e);return!!(t.includes("Error:")||t.includes("Failed")||t.includes("Exception"))}extractErrorMessage(e){return e.error?String(e.error):e.errorMessage?String(e.errorMessage):e.message?String(e.message):typeof e=="string"?e:"Unknown error occurred"}}async function dn(){try{let r;try{const n=[];for await(const i of process.stdin)n.push(i);const a=Buffer.concat(n).toString();r=JSON.parse(a);try{oe.appendFileSync(Oe.join(vt,"raw-input.jsonl"),JSON.stringify({timestamp:new Date().toISOString(),raw:a})+`
9
9
  `)}catch{}}catch{console.log(JSON.stringify({decision:"approve"})),process.exit(0);return}const t=await new un().processToolExecution(r),s=Object.keys(t).length>0?t:{decision:"approve"};console.log(JSON.stringify(s)),process.exit(0)}catch{console.log(JSON.stringify({decision:"approve"})),process.exit(0)}}dn().catch(r=>{console.log(JSON.stringify({decision:"approve"})),console.error("Main execution failed:",r),process.exit(0)});
10
10
  //# sourceMappingURL=claudePostToolUse.js.map