@agiflowai/agent-cli 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.5
4
+ - Fix Claude Code context issue.
5
+
6
+ ## 0.0.4
7
+ - Update to support Claude Code 2.0.
8
+
3
9
  ## 0.0.3
4
10
  - Fix wrong Docker image reference.
5
11
 
@@ -1,6 +1,6 @@
1
- "use strict";const Os=require("node:fs"),Is=require("node:os"),Ss=require("node:path"),ge=require("path"),ce=require("fs-extra"),kt=require("os");require("node:crypto");require("@inquirer/prompts");function $t(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 at=$t(Os),Ns=$t(Is),Tt=$t(Ss);function os(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}const xt=10,Ut=(r=0)=>e=>`\x1B[${e+r}m`,qt=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Yt=(r=0)=>(e,t,s)=>`\x1B[${38+r};2;${e};${t};${s}m`,R={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(R.modifier);const Rs=Object.keys(R.color),Cs=Object.keys(R.bgColor);[...Rs,...Cs];function js(){const r=new Map;for(const[e,t]of Object.entries(R)){for(const[s,n]of Object.entries(t))R[s]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[s]=R[s],r.set(n[0],n[1]);Object.defineProperty(R,e,{value:t,enumerable:!1})}return Object.defineProperty(R,"codes",{value:r,enumerable:!1}),R.color.close="\x1B[39m",R.bgColor.close="\x1B[49m",R.color.ansi=Ut(),R.color.ansi256=qt(),R.color.ansi16m=Yt(),R.bgColor.ansi=Ut(xt),R.bgColor.ansi256=qt(xt),R.bgColor.ansi16m=Yt(xt),Object.defineProperties(R,{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=>R.rgbToAnsi256(...R.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)=>R.ansi256ToAnsi(R.rgbToAnsi256(e,t,s)),enumerable:!1},hexToAnsi:{value:e=>R.ansi256ToAnsi(R.hexToAnsi256(e)),enumerable:!1}}),R}const X=js(),Ht=(()=>{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})(),Kt=Ht!==0&&{level:Ht},Ls={stdout:Kt,stderr:Kt};function $s(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 zs(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
1
+ "use strict";const Os=require("node:fs"),Is=require("node:os"),Ss=require("node:path"),ge=require("path"),ce=require("fs-extra"),Tt=require("os");require("node:crypto");require("@inquirer/prompts");function $t(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 at=$t(Os),Ns=$t(Is),kt=$t(Ss);function os(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}const xt=10,Ut=(r=0)=>e=>`\x1B[${e+r}m`,qt=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,Yt=(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 Rs=Object.keys(C.color),Cs=Object.keys(C.bgColor);[...Rs,...Cs];function js(){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=Ut(),C.color.ansi256=qt(),C.color.ansi16m=Yt(),C.bgColor.ansi=Ut(xt),C.bgColor.ansi256=qt(xt),C.bgColor.ansi16m=Yt(xt),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=js(),Ht=(()=>{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})(),Kt=Ht!==0&&{level:Ht},Ls={stdout:Kt,stderr:Kt};function $s(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 zs(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
2
  `:`
3
3
  `)+t,n=s+1,s=r.indexOf(`
4
4
  `,n)}while(s!==-1);return a+=r.slice(n),a}const{stdout:Wt,stderr:Jt}=Ls,It=Symbol("GENERATOR"),Oe=Symbol("STYLER"),$e=Symbol("IS_EMPTY"),Xt=["ansi","ansi","ansi256","ansi16m"],Ie=Object.create(null),Ms=(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=Wt?Wt.level:0;r.level=e.level===void 0?t:e.level},Ds=r=>{const e=(...t)=>t.join(" ");return Ms(e,r),Object.setPrototypeOf(e,Ke.prototype),e};function Ke(r){return Ds(r)}Object.setPrototypeOf(Ke.prototype,Function.prototype);for(const[r,e]of Object.entries(X))Ie[r]={get(){const t=lt(this,Nt(e.open,e.close,this[Oe]),this[$e]);return Object.defineProperty(this,r,{value:t}),t}};Ie.visible={get(){const r=lt(this,this[Oe],!0);return Object.defineProperty(this,"visible",{value:r}),r}};const St=(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"?St("rgb",e,t,...X.hexToRgb(...s)):X[t][r](...s),Gs=["rgb","hex","ansi256"];for(const r of Gs){Ie[r]={get(){const{level:t}=this;return function(...s){const n=Nt(St(r,Xt[t],"color",...s),X.color.close,this[Oe]);return lt(this,n,this[$e])}}};const e="bg"+r[0].toUpperCase()+r.slice(1);Ie[e]={get(){const{level:t}=this;return function(...s){const n=Nt(St(r,Xt[t],"bgColor",...s),X.bgColor.close,this[Oe]);return lt(this,n,this[$e])}}}}const Fs=Object.defineProperties(()=>{},{...Ie,level:{enumerable:!0,get(){return this[It].level},set(r){this[It].level=r}}}),Nt=(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}},lt=(r,e,t)=>{const s=(...n)=>Ps(s,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(s,Fs),s[It]=r,s[Oe]=e,s[$e]=t,s},Ps=(r,e)=>{if(r.level<=0||!e)return r[$e]?"":e;let t=r[Oe];if(t===void 0)return e;const{openAll:s,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=$s(e,t.close,t.open),t=t.parent;const a=e.indexOf(`
5
- `);return a!==-1&&(e=zs(e,n,s,a)),s+e+n};Object.defineProperties(Ke.prototype,Ie);const z=Ke();Ke({level:Jt?Jt.level:0});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 Rt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Rt||(Rt={}));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"]),Vs=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 Se=(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 cs=Se;function Zs(r){cs=r}function ut(){return cs}const dt=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}},Bs=[];function f(r,e){const t=ut(),s=dt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Se?void 0:Se].filter(n=>!!n)});r.common.issues.push(s)}class P{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 P.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"}),xe=r=>({status:"dirty",value:r}),Z=r=>({status:"valid",value:r}),Ct=r=>r.status==="aborted",jt=r=>r.status==="dirty",ve=r=>r.status==="valid",ze=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(ve(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 E{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 P,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(ze(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 ve(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=>ve(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(ze(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 J({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 fe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return Re.create(this,this._def)}or(e){return Fe.create([this,e],this._def)}and(e){return Pe.create(this,e,this._def)}transform(e){return new J({...w(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new qe({...w(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new zt({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ye({...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 We.create(this,e)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Us=/^c[^\s-]{8,}$/i,qs=/^[0-9a-z]+$/,Ys=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Hs=/^[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,Ks=/^[a-z0-9_-]{21}$/i,Ws=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Js=/^[-+]?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)?)??$/,Xs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let At;const er=/^(?:(?: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])$/,tr=/^(?:(?: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])$/,sr=/^(([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]))$/,rr=/^(([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])$/,nr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ar=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ls="((\\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])))",ir=new RegExp(`^${ls}$`);function us(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 or(r){return new RegExp(`^${us(r)}$`)}function ds(r){let e=`${ls}T${us(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 cr(r,e){return!!((e==="v4"||!e)&&er.test(r)||(e==="v6"||!e)&&sr.test(r))}function lr(r,e){if(!Ws.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 ur(r,e){return!!((e==="v4"||!e)&&tr.test(r)||(e==="v6"||!e)&&rr.test(r))}class K extends E{_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 P;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")Xs.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")At||(At=new RegExp(Qs,"u")),At.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")Hs.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")Ks.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")Us.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")qs.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")Ys.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"?ds(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"?ir.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?or(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"?Js.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?cr(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"?lr(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"?ur(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"?nr.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?ar.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 dr(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 le extends E{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 P;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"?dr(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 le({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new le({...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)}}le.create=r=>new le({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...w(r)});class ue extends E{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 P;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 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]})}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}}ue.create=r=>new ue({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...w(r)});class Me extends E{_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 Z(e.data)}}Me.create=r=>new Me({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...w(r)});class _e extends E{_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 P;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 _e({...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}}_e.create=r=>new _e({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...w(r)});class ft extends E{_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 Z(e.data)}}ft.create=r=>new ft({typeName:_.ZodSymbol,...w(r)});class De extends E{_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 Z(e.data)}}De.create=r=>new De({typeName:_.ZodUndefined,...w(r)});class Ge extends E{_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 Z(e.data)}}Ge.create=r=>new Ge({typeName:_.ZodNull,...w(r)});class Ne extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return Z(e.data)}}Ne.create=r=>new Ne({typeName:_.ZodAny,...w(r)});class ye extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Z(e.data)}}ye.create=r=>new ye({typeName:_.ZodUnknown,...w(r)});class oe extends E{_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 ht extends E{_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 Z(e.data)}}ht.create=r=>new ht({typeName:_.ZodVoid,...w(r)});class W extends E{_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=>P.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new te(t,i,t.path,o)));return P.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 Te(r){if(r instanceof L){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=Q.create(Te(s))}return new L({...r._def,shape:()=>e})}else return r instanceof W?new W({...r._def,type:Te(r.element)}):r instanceof Q?Q.create(Te(r.unwrap())):r instanceof fe?fe.create(Te(r.unwrap())):r instanceof se?se.create(r.items.map(e=>Te(e))):r}class L extends E{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],k=n.data[u];d.push({key:{status:"valid",value:u},value:g._parse(new te(n,k,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 k=n.data[g];d.push({key:{status:"valid",value:g},value:u._parse(new te(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,C=await g.value;u.push({key:k,value:C,alwaysSet:g.alwaysSet})}return u}).then(u=>P.mergeObjectSync(s,u)):P.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new L({...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 L({...this._def,unknownKeys:"strip"})}passthrough(){return new L({...this._def,unknownKeys:"passthrough"})}extend(e){return new L({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new L({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 L({...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 L({...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 L({...this._def,shape:()=>t})}deepPartial(){return Te(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 L({...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 L({...this._def,shape:()=>t})}keyof(){return fs(T.objectKeys(this.shape))}}L.create=(r,e)=>new L({shape:()=>r,unknownKeys:"strip",catchall:oe.create(),typeName:_.ZodObject,...w(e)});L.strictCreate=(r,e)=>new L({shape:()=>r,unknownKeys:"strict",catchall:oe.create(),typeName:_.ZodObject,...w(e)});L.lazycreate=(r,e)=>new L({shape:r,unknownKeys:"strip",catchall:oe.create(),typeName:_.ZodObject,...w(e)});class Fe extends E{_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}}Fe.create=(r,e)=>new Fe({options:r,typeName:_.ZodUnion,...w(e)});const ne=r=>r instanceof Ze?ne(r.schema):r instanceof J?ne(r.innerType()):r instanceof Be?[r.value]:r instanceof de?r.options:r instanceof Ue?T.objectValues(r.enum):r instanceof qe?ne(r._def.innerType):r instanceof De?[void 0]:r instanceof Ge?[null]:r instanceof Q?[void 0,...ne(r.unwrap())]:r instanceof fe?[null,...ne(r.unwrap())]:r instanceof zt||r instanceof He?ne(r.unwrap()):r instanceof Ye?ne(r._def.innerType):[];class gt extends E{_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 gt({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...w(s)})}}function Lt(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=Lt(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=Lt(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 Pe extends E{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(Ct(a)||Ct(i))return v;const o=Lt(a.value,i.value);return o.valid?((jt(a)||jt(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}))}}Pe.create=(r,e,t)=>new Pe({left:r,right:e,typeName:_.ZodIntersection,...w(t)});class se extends E{_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=>P.mergeArray(t,i)):P.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 Ve extends E{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?P.mergeObjectAsync(t,n):P.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof E?new Ve({keyType:e,valueType:t,typeName:_.ZodRecord,...w(s)}):new Ve({keyType:K.create(),valueType:e,typeName:_.ZodRecord,...w(t)})}}class pt extends E{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}}}}pt.create=(r,e,t)=>new pt({valueType:e,keyType:r,typeName:_.ZodMap,...w(t)});class be extends E{_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 be({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new be({...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)}}be.create=(r,e)=>new be({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});class Ae extends E{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 dt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Se].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:d}})}function n(o,d){return dt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Se].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 Re){const o=this;return Z(async function(...d){const u=new U([]),g=await o._def.args.parseAsync(d,a).catch(A=>{throw u.addIssue(s(d,A)),u}),k=await Reflect.apply(i,this,g);return await o._def.returns._def.type.parseAsync(k,a).catch(A=>{throw u.addIssue(n(k,A)),u})})}else{const o=this;return Z(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),k=o._def.returns.safeParse(g,a);if(!k.success)throw new U([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:se.create(e).rest(ye.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||se.create([]).rest(ye.create()),returns:t||ye.create(),typeName:_.ZodFunction,...w(s)})}}class Ze extends E{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})}}Ze.create=(r,e)=>new Ze({getter:r,typeName:_.ZodLazy,...w(e)});class Be extends E{_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}}Be.create=(r,e)=>new Be({value:r,typeName:_.ZodLiteral,...w(e)});function fs(r,e){return new de({values:r,typeName:_.ZodEnum,...w(e)})}class de extends E{_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 Z(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 de.create(e,{...this._def,...t})}exclude(e,t=this._def){return de.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}de.create=fs;class Ue extends E{_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 Z(e.data)}get enum(){return this._def.values}}Ue.create=(r,e)=>new Ue({values:r,typeName:_.ZodNativeEnum,...w(e)});class Re extends E{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 Z(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Re.create=(r,e)=>new Re({type:r,typeName:_.ZodPromise,...w(e)});class J extends E{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"?xe(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"?xe(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(!ve(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=>ve(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):v);T.assertNever(n)}}J.create=(r,e,t)=>new J({schema:r,typeName:_.ZodEffects,effect:e,...w(t)});J.createWithPreprocess=(r,e,t)=>new J({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...w(t)});class Q extends E{_parse(e){return this._getType(e)===h.undefined?Z(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 fe extends E{_parse(e){return this._getType(e)===h.null?Z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fe.create=(r,e)=>new fe({innerType:r,typeName:_.ZodNullable,...w(e)});class qe extends E{_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}}qe.create=(r,e)=>new qe({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class Ye extends E{_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 ze(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}}Ye.create=(r,e)=>new Ye({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class mt extends E{_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}}}mt.create=r=>new mt({typeName:_.ZodNaN,...w(r)});const fr=Symbol("zod_brand");class zt extends E{_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 We extends E{_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(),xe(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 We({in:e,out:t,typeName:_.ZodPipeline})}}class He extends E{_parse(e){const t=this._def.innerType._parse(e),s=n=>(ve(n)&&(n.value=Object.freeze(n.value)),n);return ze(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}He.create=(r,e)=>new He({innerType:r,typeName:_.ZodReadonly,...w(e)});function es(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function hs(r,e={},t){return r?Ne.create().superRefine((s,n)=>{const a=r(s);if(a instanceof Promise)return a.then(i=>{if(!i){const o=es(e,s),d=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:d})}});if(!a){const i=es(e,s),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):Ne.create()}const hr={object:L.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 pr=(r,e={message:`Input not instance of ${r.name}`})=>hs(t=>t instanceof r,e),S=K.create,ee=le.create,mr=mt.create,gr=ue.create,Je=Me.create,yr=_e.create,vr=ft.create,_r=De.create,ps=Ge.create,he=Ne.create,yt=ye.create,br=oe.create,wr=ht.create,we=W.create,N=L.create,Er=L.strictCreate,Ee=Fe.create,kr=gt.create,Tr=Pe.create,xr=se.create,Xe=Ve.create,Ar=pt.create,Or=be.create,Ir=Ae.create,ms=Ze.create,V=Be.create,vt=de.create,Sr=Ue.create,Nr=Re.create,ts=J.create,Rr=Q.create,Cr=fe.create,jr=J.createWithPreprocess,Lr=We.create,$r=()=>S().optional(),zr=()=>ee().optional(),Mr=()=>Je().optional(),ct={string:r=>K.create({...r,coerce:!0}),number:r=>le.create({...r,coerce:!0}),boolean:r=>Me.create({...r,coerce:!0}),bigint:r=>ue.create({...r,coerce:!0}),date:r=>_e.create({...r,coerce:!0})},Dr=v,G=Object.freeze(Object.defineProperty({__proto__:null,BRAND:fr,DIRTY:xe,EMPTY_PATH:Bs,INVALID:v,NEVER:Dr,OK:Z,ParseStatus:P,Schema:E,ZodAny:Ne,ZodArray:W,ZodBigInt:ue,ZodBoolean:Me,ZodBranded:zt,ZodCatch:Ye,ZodDate:_e,ZodDefault:qe,ZodDiscriminatedUnion:gt,ZodEffects:J,ZodEnum:de,ZodError:U,get ZodFirstPartyTypeKind(){return _},ZodFunction:Ae,ZodIntersection:Pe,ZodIssueCode:l,ZodLazy:Ze,ZodLiteral:Be,ZodMap:pt,ZodNaN:mt,ZodNativeEnum:Ue,ZodNever:oe,ZodNull:Ge,ZodNullable:fe,ZodNumber:le,ZodObject:L,ZodOptional:Q,ZodParsedType:h,ZodPipeline:We,ZodPromise:Re,ZodReadonly:He,ZodRecord:Ve,ZodSchema:E,ZodSet:be,ZodString:K,ZodSymbol:ft,ZodTransformer:J,ZodTuple:se,ZodType:E,ZodUndefined:De,ZodUnion:Fe,ZodUnknown:ye,ZodVoid:ht,addIssueToContext:f,any:he,array:we,bigint:gr,boolean:Je,coerce:ct,custom:hs,date:yr,datetimeRegex:ds,defaultErrorMap:Se,discriminatedUnion:kr,effect:ts,enum:vt,function:Ir,getErrorMap:ut,getParsedType:ie,instanceof:pr,intersection:Tr,isAborted:Ct,isAsync:ze,isDirty:jt,isValid:ve,late:hr,lazy:ms,literal:V,makeIssue:dt,map:Ar,nan:mr,nativeEnum:Sr,never:br,null:ps,nullable:Cr,number:ee,object:N,get objectUtil(){return Rt},oboolean:Mr,onumber:zr,optional:Rr,ostring:$r,pipeline:Lr,preprocess:jr,promise:Nr,quotelessJson:Vs,record:Xe,set:Or,setErrorMap:Zs,strictObject:Er,string:S,symbol:vr,transformer:ts,tuple:xr,undefined:_r,union:Ee,unknown:yt,get util(){return T},void:wr},Symbol.toStringTag,{value:"Module"})),Gr={AGENT_SERVER_URL:"AGENT_SERVER_URL",AGENT_API_KEY:"AGENT_API_KEY",AGENT_ORGANIZATION_ID:"AGENT_ORGANIZATION_ID",AGENT_SESSION_ID:"AGENT_SESSION_ID",AGENT_TYPE:"AGENT_TYPE",AGENT_CONTAINER_MODE:"AGENT_CONTAINER_MODE",AGENT_DEVICE_GUID:"AGENT_DEVICE_GUID",NODE_ENV:"NODE_ENV",DEBUG:"DEBUG",VERBOSE:"VERBOSE",LOG_LEVEL:"LOG_LEVEL",AGI_NETLOG_ENABLE:"AGI_NETLOG_ENABLE",AGI_NETLOG_DEBUG:"AGI_NETLOG_DEBUG",AGI_NETLOG_MAX_BODY:"AGI_NETLOG_MAX_BODY",AGI_NETLOG_FILE:"AGI_NETLOG_FILE",AGI_NETLOG_REMOTE_ENABLE:"AGI_NETLOG_REMOTE_ENABLE",AGI_NETLOG_REMOTE_FILE:"AGI_NETLOG_REMOTE_FILE",HOSTNAME:"HOSTNAME",VITE_SAVE_RAW:"VITE_SAVE_RAW"},me=()=>G.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}},G.boolean()),Fr=()=>G.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}},G.number()),gs=G.object({NODE_ENV:G.enum(["development","production","test"]).default("production"),AGENT_CONTAINER_MODE:me().default(!1),AGENT_API_KEY:G.string().optional(),AGENT_ORGANIZATION_ID:G.string().optional(),AGENT_SESSION_ID:G.string().optional(),AGENT_SERVER_URL:G.string().optional(),AGENT_TYPE:G.string().optional(),AGENT_DEVICE_GUID:G.string().optional(),AGI_NETLOG_ENABLE:me().default(!0),AGI_NETLOG_DEBUG:me().optional(),AGI_NETLOG_FILE:G.string().optional(),AGI_NETLOG_MAX_BODY:Fr().optional(),AGI_NETLOG_REMOTE_ENABLE:me().default(!0),AGI_NETLOG_REMOTE_FILE:G.string().optional(),DEBUG:me().default(!1),VERBOSE:me().default(!1),LOG_LEVEL:G.string().optional(),HOSTNAME:G.string().optional(),VITE_SAVE_RAW:me().default(!1)});function it(r=!1){return r?"https://agiflow.io":"https://agiflow.io"}let j=gs.parse(process.env);class _t{static refresh(){j=gs.parse(process.env)}static get isContainerMode(){return!!j.AGENT_CONTAINER_MODE}static get apiKey(){return j.AGENT_API_KEY||process.env.AGENT_API_KEY}static get organizationId(){return j.AGENT_ORGANIZATION_ID||process.env.AGENT_ORGANIZATION_ID}static get sessionId(){return j.AGENT_SESSION_ID||process.env.AGENT_SESSION_ID}static get serverUrl(){return j.AGENT_SERVER_URL||process.env.AGENT_SERVER_URL||it(this.isContainerMode)}static get isNetlogEnabled(){return!!j.AGI_NETLOG_ENABLE}static get isNetlogDebug(){return!!j.AGI_NETLOG_DEBUG}static get isNetlogRemoteEnabled(){return!!j.AGI_NETLOG_REMOTE_ENABLE}static get isDebugMode(){return j.DEBUG}static get isVerbose(){return j.VERBOSE}static get logLevel(){return j.LOG_LEVEL??(j.DEBUG?"debug":"info")}static get nodeEnv(){return j.NODE_ENV}static get homeDir(){return process.env.HOME||process.env.USERPROFILE}static get isMacOS(){return process.platform==="darwin"}static get hostname(){return j.HOSTNAME}static get netlogMaxBody(){return j.AGI_NETLOG_MAX_BODY}static get netlogFile(){return j.AGI_NETLOG_FILE}static get netlogRemoteFile(){return j.AGI_NETLOG_REMOTE_FILE}static get agentType(){return j.AGENT_TYPE||process.env.AGENT_TYPE}static get deviceGuid(){return j.AGENT_DEVICE_GUID}static get isSaveRawEnabled(){return!!j.VITE_SAVE_RAW}static serializeEnv(){const e={...process.env};for(const[t,s]of Object.entries(j))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=it(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=it(!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=it(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static getEnvs(){return j}}const ss=ms(()=>Ee([ps(),S(),ee(),Je(),we(ss),Xe(ss)])),rs=N({toolCallId:S(),toolName:S(),args:he()}),Pr=N({toolCallId:S(),toolName:S(),args:he(),result:he()}),Vr=Ee([rs.extend({state:V("partial-call"),step:ee().optional()}),rs.extend({state:V("call"),step:ee().optional()}),Pr.extend({state:V("result"),step:ee().optional()})]),Zr=N({type:S(),content:S()}),Br=N({type:V("text"),text:S()}),Ur=N({type:V("reasoning"),reasoning:S(),details:we(Ee([N({type:V("text"),text:S(),signature:S().optional()}),N({type:V("redacted"),data:S()})])).optional()}),qr=N({name:V("select"),props:N({options:we(N({label:S(),value:Ee([S(),ee()]),selected:Je().optional()}))})}),Yr=N({name:V("placeholder"),props:N({})}),Hr=Ee([qr,Yr]),Kr=N({completed:Je(),component:Hr}),Wr=N({type:V("tool-invocation"),toolInvocation:Vr,input:Kr.optional(),jsx:S({description:"UI rendering"}).optional()}),Jr=N({type:V("source"),source:Zr}),Xr=N({type:V("file"),mimeType:S(),data:S()}),Qr=N({type:V("error"),text:S(),error:he().optional()}),en=N({type:V("step-start")}),ys=Ee([Br,Ur,Wr,Jr,Xr,Qr,en]),Mt=vt(["input","output","error","system"]),vs=N({messageType:Mt,parts:we(ys),metadata:Xe(S(),yt()).optional(),raw:he().optional()});N({id:S(),sessionId:S(),agentTypeId:S(),messageType:Mt,contentSize:ee().nullable(),timestamp:ct.date(),metadata:S().nullable(),raw:he().nullable().optional(),createdAt:ct.date(),updatedAt:ct.date()});const tn=N({messageType:vt(["output"]).default("output"),metadata:Xe(S(),yt()).optional()});N({id:S(),messageId:S()});const sn=N({parts:we(ys).optional(),metadata:Xe(S(),yt()).optional(),raw:he().optional()});N({messages:we(vs)});function rn(r){return[_s(r)]}function ns(r){let e=r.parts;if(!e&&r.content&&(e=rn(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 _s(r){return{type:"text",text:r}}function nn(r){return{name:"select",props:{options:r}}}function an(r,e){return{completed:r,component:e}}function on(r,e,t){return{type:"tool-invocation",toolInvocation:r,input:e,jsx:t}}class ae{static AGIFLOW_DIR=ge.join(kt.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(ge.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 ge.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("~/")?ge.join(kt.homedir(),e.slice(2)):e==="~"?kt.homedir():ge.isAbsolute(e)?e:ge.resolve(process.cwd(),e):process.cwd()}}var Le={exports:{}},Ot,as;function cn(){if(as)return Ot;as=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="",C=1-i,A=-1,Y=t&&t.length||0,O=0;O<Y;){if(t.charCodeAt(O)===37&&O+1<Y){switch(A=A>-1?A:0,t.charCodeAt(O+1)){case 100:case 102:if(C>=g||s[C]==null)break;A<O&&(k+=t.slice(A,O)),k+=Number(s[C]),A=O+2,O++;break;case 105:if(C>=g||s[C]==null)break;A<O&&(k+=t.slice(A,O)),k+=Math.floor(Number(s[C])),A=O+2,O++;break;case 79:case 111:case 106:if(C>=g||s[C]===void 0)break;A<O&&(k+=t.slice(A,O));var Qe=typeof s[C];if(Qe==="string"){k+="'"+s[C]+"'",A=O+2,O++;break}if(Qe==="function"){k+=s[C].name||"<anonymous>",A=O+2,O++;break}k+=a(s[C]),A=O+2,O++;break;case 115:if(C>=g)break;A<O&&(k+=t.slice(A,O)),k+=String(s[C]),A=O+2,O++;break;case 37:A<O&&(k+=t.slice(A,O)),k+="%",A=O+2,O++,C--;break}++C}++O}return A===-1?t:(A<Y&&(k+=t.slice(A)),k)}return Ot}var is;function ln(){if(is)return Le.exports;is=1;const r=cn();Le.exports=g;const e=As().console||{},t={mapHttpRequest:et,mapHttpResponse:et,wrapRequestSerializer:Et,wrapResponseSerializer:Et,wrapErrorSerializer:Et,req:et,res:et,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 x={};p.forEach(I=>{x[I]=b[I]?b[I]:e[I]||e[i[I]||"log"]||ke}),c[n]=x}function u(c,p){return Array.isArray(c)?c.filter(function(x){return x!=="!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 x=c.serializers||{},I=u(c.browser.serialize,x);let F=c.browser.serialize;Array.isArray(c.browser.serialize)&&c.browser.serialize.indexOf("!stdSerializers.err")>-1&&(F=!1);const q=Object.keys(c.customLevels||{}),$=["error","fatal","warn","info","debug","trace"].concat(q);typeof b=="function"&&$.forEach(function(H){b[H]=b}),(c.enabled===!1||c.browser.disabled)&&(c.level="silent");const B=c.level||"info",y=Object.create(b);y.log||(y.log=ke),d(y,$,b),o({},y),Object.defineProperty(y,"levelVal",{get:tt}),Object.defineProperty(y,"level",{get:pe,set:st});const D={transmit:p,serialize:I,asObject:c.browser.asObject,formatters:c.browser.formatters,levels:$,timestamp:ks(c),messageKey:c.messageKey||"msg",onChild:c.onChild||ke};y.levels=k(c),y.level=B,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=ke,y.serializers=x,y._serialize=I,y._stdErrSerialize=F,y.child=function(...H){return Pt.call(this,D,...H)},p&&(y._logEvent=wt());function tt(){return s(this.level,this)}function pe(){return this._level}function st(H){if(H!=="silent"&&!this.levels.values[H])throw Error("unknown level "+H);this._level=H,Y(this,D,y,"error"),Y(this,D,y,"fatal"),Y(this,D,y,"warn"),Y(this,D,y,"info"),Y(this,D,y,"debug"),Y(this,D,y,"trace"),q.forEach(re=>{Y(this,D,y,re)})}function Pt(H,re,Ce){if(!re)throw new Error("missing bindings for child Pino");Ce=Ce||{},I&&re.serializers&&(Ce.serializers=re.serializers);const Vt=Ce.serializers;if(I&&Vt){var rt=Object.assign({},x,Vt),Zt=c.browser.serialize===!0?Object.keys(rt):I;delete re.serializers,bt([re],Zt,rt,this._stdErrSerialize)}function Bt(nt){this._childLevel=(nt._childLevel|0)+1,this.bindings=re,rt&&(this.serializers=rt,this._serialize=Zt),p&&(this._logEvent=wt([].concat(nt._logEvent.bindings,re)))}Bt.prototype=this;const je=new Bt(this);return o(this,je),je.child=function(...nt){return Pt.call(this,H,...nt)},je.level=Ce.level||this.level,H.onChild(je),je}return y}function k(c){const p=c.customLevels||{},b=Object.assign({},g.levels.values,p),x=Object.assign({},g.levels.labels,C(p));return{values:b,labels:x}}function C(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:Gt,epochTime:Ft,unixTime:Ts,isoTime:xs});function A(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 Y(c,p,b,x){if(Object.defineProperty(c,x,{value:s(c.level,b)>s(x,b)?ke:b[n][x],writable:!0,enumerable:!0,configurable:!0}),c[x]===ke){if(!p.transmit)return;const F=p.transmit.level||c.level,q=s(F,b);if(s(x,b)<q)return}c[x]=Qe(c,p,b,x);const I=A(c);I.length!==0&&(c[x]=O(I,c[x]))}function O(c,p){return function(){return p.apply(this,[...c,...arguments])}}function Qe(c,p,b,x){return function(I){return function(){const q=p.timestamp(),$=new Array(arguments.length),B=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var y=0;y<$.length;y++)$[y]=arguments[y];var D=!1;if(p.serialize&&(bt($,this._serialize,this.serializers,this._stdErrSerialize),D=!0),p.asObject||p.formatters?I.call(B,ws(this,x,$,q,p)):I.apply(B,$),p.transmit){const tt=p.transmit.level||c._level,pe=s(tt,b),st=s(x,b);if(st<pe)return;Es(this,{ts:q,methodLevel:x,methodValue:st,transmitValue:b.levels.values[p.transmit.level||c._level],send:p.transmit.send,val:s(c._level,b)},$,D)}}}(c[n][x])}function ws(c,p,b,x,I){const{level:F,log:q=pe=>pe}=I.formatters||{},$=b.slice();let B=$[0];const y={};if(x&&(y.time=x),F){const pe=F(p,c.levels.values[p]);Object.assign(y,pe)}else y.level=c.levels.values[p];let D=(c._childLevel|0)+1;if(D<1&&(D=1),B!==null&&typeof B=="object"){for(;D--&&typeof $[0]=="object";)Object.assign(y,$.shift());B=$.length?r($.shift(),$):void 0}else typeof B=="string"&&(B=r($.shift(),$));return B!==void 0&&(y[I.messageKey]=B),q(y)}function bt(c,p,b,x){for(const I in c)if(x&&c[I]instanceof Error)c[I]=g.stdSerializers.err(c[I]);else if(typeof c[I]=="object"&&!Array.isArray(c[I])&&p)for(const F in c[I])p.indexOf(F)>-1&&F in b&&(c[I][F]=b[F](c[I][F]))}function Es(c,p,b,x=!1){const I=p.send,F=p.ts,q=p.methodLevel,$=p.methodValue,B=p.val,y=c._logEvent.bindings;x||bt(b,c._serialize||Object.keys(c.serializers),c.serializers,c._stdErrSerialize===void 0?!0:c._stdErrSerialize),c._logEvent.ts=F,c._logEvent.messages=b.filter(function(D){return y.indexOf(D)===-1}),c._logEvent.level.label=q,c._logEvent.level.value=$,I(q,c._logEvent,B),c._logEvent=wt(y)}function wt(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?Gt:Ft}function et(){return{}}function Et(c){return c}function ke(){}function Gt(){return!1}function Ft(){return Date.now()}function Ts(){return Math.round(Date.now()/1e3)}function xs(){return new Date(Date.now()).toISOString()}function As(){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 un=ln();const ot=os(un);class M{pino;useTerminalFormat;static instance;constructor(e={}){this.useTerminalFormat=e.useTerminalFormat??!0;const t=e.debug?"debug":e.verbose?"trace":"info";e.silent?this.pino=ot({level:"silent"}):e.logFile||e.logDir?this.pino=this.createMultiTransportLogger(t,e):this.useTerminalFormat&&process.stdout.isTTY?this.pino=ot({level:t,transport:{target:"pino-pretty",options:{colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}}):this.pino=ot({level:t})}createMultiTransportLogger(e,t){let s;if(t.logFile)s=t.logFile;else if(t.logDir){at.existsSync(t.logDir)||at.mkdirSync(t.logDir,{recursive:!0});const a=new Date().toISOString().split("T")[0];s=Tt.join(t.logDir,`app-${a}.log`)}else{const a=Tt.join(Ns.tmpdir(),"agiflow-agents","logs",`session-${process.pid}`);at.existsSync(a)||at.mkdirSync(a,{recursive:!0});const i=new Date().toISOString().split("T")[0];s=Tt.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}}),ot({level:e,transport:{targets:n}})}static getInstance(){return M.instance||(M.instance=new M),M.instance}static configure(e){M.instance=new M(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){M.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){M.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){M.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){M.getInstance().error(e,void 0,t)}debug(e,...t){this.useTerminalFormat&&process.stdout.isTTY?(_t.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){M.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){M.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){M.getInstance().code(e)}newLine(){this.useTerminalFormat&&process.stdout.isTTY&&console.log()}static newLine(){M.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 M({useTerminalFormat:this.useTerminalFormat});return t.pino=this.pino.child(e),t}}class bs{filePath;cache=null;dirty=!1;constructor(e){this.filePath=e||ge.join(ae.AGIFLOW_DIR,"credentials.json")}async load(){if(this.cache)return this.cache;try{if(!await ae.exists(this.filePath))return null;const t=await ae.readJson(this.filePath);return this.cache=t,t}catch{return null}}async flush(){!this.dirty||!this.cache||(await ae.ensureDir(ae.AGIFLOW_DIR),await ae.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 ae.exists(this.filePath)&&await ae.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=_t.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:Mt.optional(),sort:S().optional(),order:vt(["asc","desc"]).optional()});class dn{options;authService;credentials;logger;constructor(e){this.options=e,this.authService=e.authService,this.credentials=e.credentials??new bs,this.logger=e.logger??new M({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=_t.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=ns(e);try{vs.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=>ns(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 A=await u.text();throw new Error(`Failed to get presigned URL: ${u.status} ${A}`)}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 C={sessionId:e,messageType:t,contentSize:d,metadata:n};return await this.sendMessage(C)}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{tn.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{sn.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}}}exports.AgentHttpService=dn;exports.CredentialsService=bs;exports.ENV_KEYS=Gr;exports.FileSystemUtils=ae;exports.Logger=M;exports.SubEnvManager=_t;exports.chalk=z;exports.createSelectComponent=nn;exports.createTextPart=_s;exports.createToolInvocationInput=an;exports.createToolInvocationPart=on;exports.getDefaultExportFromCjs=os;exports.z=G;
6
- //# sourceMappingURL=AgentHttpService-CKoRDtlb.js.map
5
+ `);return a!==-1&&(e=zs(e,n,s,a)),s+e+n};Object.defineProperties(Ke.prototype,Ie);const z=Ke();Ke({level:Jt?Jt.level:0});var k;(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})(k||(k={}));var Rt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Rt||(Rt={}));const h=k.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=k.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"]),Vs=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,k.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 Se=(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,k.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${k.joinValues(r.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${k.joinValues(r.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${k.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}"`:k.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,k.assertNever(r)}return{message:t}};let cs=Se;function Zs(r){cs=r}function ut(){return cs}const dt=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}},Bs=[];function f(r,e){const t=ut(),s=dt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Se?void 0:Se].filter(n=>!!n)});r.common.issues.push(s)}class P{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 P.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"}),xe=r=>({status:"dirty",value:r}),Z=r=>({status:"valid",value:r}),Ct=r=>r.status==="aborted",jt=r=>r.status==="dirty",ve=r=>r.status==="valid",ze=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(ve(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 E{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 P,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(ze(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 ve(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=>ve(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(ze(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 J({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 fe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return Re.create(this,this._def)}or(e){return Fe.create([this,e],this._def)}and(e){return Pe.create(this,e,this._def)}transform(e){return new J({...w(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new qe({...w(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new zt({typeName:_.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ye({...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 We.create(this,e)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Us=/^c[^\s-]{8,}$/i,qs=/^[0-9a-z]+$/,Ys=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Hs=/^[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,Ks=/^[a-z0-9_-]{21}$/i,Ws=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Js=/^[-+]?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)?)??$/,Xs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let At;const er=/^(?:(?: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])$/,tr=/^(?:(?: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])$/,sr=/^(([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]))$/,rr=/^(([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])$/,nr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ar=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ls="((\\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])))",ir=new RegExp(`^${ls}$`);function us(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 or(r){return new RegExp(`^${us(r)}$`)}function ds(r){let e=`${ls}T${us(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 cr(r,e){return!!((e==="v4"||!e)&&er.test(r)||(e==="v6"||!e)&&sr.test(r))}function lr(r,e){if(!Ws.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 ur(r,e){return!!((e==="v4"||!e)&&tr.test(r)||(e==="v6"||!e)&&rr.test(r))}class K extends E{_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 P;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")Xs.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")At||(At=new RegExp(Qs,"u")),At.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")Hs.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")Ks.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")Us.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")qs.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")Ys.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"?ds(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"?ir.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?or(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"?Js.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?cr(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"?lr(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"?ur(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"?nr.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:l.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?ar.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:l.invalid_string,message:a.message}),s.dirty()):k.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 dr(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 le extends E{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 P;for(const a of this._def.checks)a.kind==="int"?k.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"?dr(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()):k.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 le({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:m.toString(n)}]})}_addCheck(e){return new le({...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"&&k.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)}}le.create=r=>new le({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...w(r)});class ue extends E{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 P;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()):k.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 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]})}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}}ue.create=r=>new ue({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...w(r)});class Me extends E{_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 Z(e.data)}}Me.create=r=>new Me({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...w(r)});class _e extends E{_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 P;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()):k.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new _e({...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}}_e.create=r=>new _e({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...w(r)});class ft extends E{_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 Z(e.data)}}ft.create=r=>new ft({typeName:_.ZodSymbol,...w(r)});class De extends E{_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 Z(e.data)}}De.create=r=>new De({typeName:_.ZodUndefined,...w(r)});class Ge extends E{_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 Z(e.data)}}Ge.create=r=>new Ge({typeName:_.ZodNull,...w(r)});class Ne extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return Z(e.data)}}Ne.create=r=>new Ne({typeName:_.ZodAny,...w(r)});class ye extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Z(e.data)}}ye.create=r=>new ye({typeName:_.ZodUnknown,...w(r)});class oe extends E{_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 ht extends E{_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 Z(e.data)}}ht.create=r=>new ht({typeName:_.ZodVoid,...w(r)});class W extends E{_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=>P.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new te(t,i,t.path,o)));return P.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 ke(r){if(r instanceof L){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=Q.create(ke(s))}return new L({...r._def,shape:()=>e})}else return r instanceof W?new W({...r._def,type:ke(r.element)}):r instanceof Q?Q.create(ke(r.unwrap())):r instanceof fe?fe.create(ke(r.unwrap())):r instanceof se?se.create(r.items.map(e=>ke(e))):r}class L extends E{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=k.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],T=n.data[u];d.push({key:{status:"valid",value:u},value:g._parse(new te(n,T,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 T=n.data[g];d.push({key:{status:"valid",value:g},value:u._parse(new te(n,T,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const u=[];for(const g of d){const T=await g.key,j=await g.value;u.push({key:T,value:j,alwaysSet:g.alwaysSet})}return u}).then(u=>P.mergeObjectSync(s,u)):P.mergeObjectSync(s,d)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new L({...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 L({...this._def,unknownKeys:"strip"})}passthrough(){return new L({...this._def,unknownKeys:"passthrough"})}extend(e){return new L({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new L({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 L({...this._def,catchall:e})}pick(e){const t={};for(const s of k.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new L({...this._def,shape:()=>t})}omit(e){const t={};for(const s of k.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new L({...this._def,shape:()=>t})}deepPartial(){return ke(this)}partial(e){const t={};for(const s of k.objectKeys(this.shape)){const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}return new L({...this._def,shape:()=>t})}required(e){const t={};for(const s of k.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 L({...this._def,shape:()=>t})}keyof(){return fs(k.objectKeys(this.shape))}}L.create=(r,e)=>new L({shape:()=>r,unknownKeys:"strip",catchall:oe.create(),typeName:_.ZodObject,...w(e)});L.strictCreate=(r,e)=>new L({shape:()=>r,unknownKeys:"strict",catchall:oe.create(),typeName:_.ZodObject,...w(e)});L.lazycreate=(r,e)=>new L({shape:r,unknownKeys:"strip",catchall:oe.create(),typeName:_.ZodObject,...w(e)});class Fe extends E{_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}}Fe.create=(r,e)=>new Fe({options:r,typeName:_.ZodUnion,...w(e)});const ne=r=>r instanceof Ze?ne(r.schema):r instanceof J?ne(r.innerType()):r instanceof Be?[r.value]:r instanceof de?r.options:r instanceof Ue?k.objectValues(r.enum):r instanceof qe?ne(r._def.innerType):r instanceof De?[void 0]:r instanceof Ge?[null]:r instanceof Q?[void 0,...ne(r.unwrap())]:r instanceof fe?[null,...ne(r.unwrap())]:r instanceof zt||r instanceof He?ne(r.unwrap()):r instanceof Ye?ne(r._def.innerType):[];class gt extends E{_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 gt({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...w(s)})}}function Lt(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=k.objectKeys(e),a=k.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(const o of a){const d=Lt(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=Lt(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 Pe extends E{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=(a,i)=>{if(Ct(a)||Ct(i))return v;const o=Lt(a.value,i.value);return o.valid?((jt(a)||jt(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}))}}Pe.create=(r,e,t)=>new Pe({left:r,right:e,typeName:_.ZodIntersection,...w(t)});class se extends E{_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=>P.mergeArray(t,i)):P.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 Ve extends E{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?P.mergeObjectAsync(t,n):P.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof E?new Ve({keyType:e,valueType:t,typeName:_.ZodRecord,...w(s)}):new Ve({keyType:K.create(),valueType:e,typeName:_.ZodRecord,...w(t)})}}class pt extends E{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}}}}pt.create=(r,e,t)=>new pt({valueType:e,keyType:r,typeName:_.ZodMap,...w(t)});class be extends E{_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 be({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new be({...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)}}be.create=(r,e)=>new be({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...w(e)});class Ae extends E{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 dt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Se].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:d}})}function n(o,d){return dt({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ut(),Se].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 Re){const o=this;return Z(async function(...d){const u=new U([]),g=await o._def.args.parseAsync(d,a).catch(A=>{throw u.addIssue(s(d,A)),u}),T=await Reflect.apply(i,this,g);return await o._def.returns._def.type.parseAsync(T,a).catch(A=>{throw u.addIssue(n(T,A)),u})})}else{const o=this;return Z(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),T=o._def.returns.safeParse(g,a);if(!T.success)throw new U([n(g,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ae({...this._def,args:se.create(e).rest(ye.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||se.create([]).rest(ye.create()),returns:t||ye.create(),typeName:_.ZodFunction,...w(s)})}}class Ze extends E{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})}}Ze.create=(r,e)=>new Ze({getter:r,typeName:_.ZodLazy,...w(e)});class Be extends E{_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}}Be.create=(r,e)=>new Be({value:r,typeName:_.ZodLiteral,...w(e)});function fs(r,e){return new de({values:r,typeName:_.ZodEnum,...w(e)})}class de extends E{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return f(t,{expected:k.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 Z(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 de.create(e,{...this._def,...t})}exclude(e,t=this._def){return de.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}de.create=fs;class Ue extends E{_parse(e){const t=k.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==h.string&&s.parsedType!==h.number){const n=k.objectValues(t);return f(s,{expected:k.joinValues(n),received:s.parsedType,code:l.invalid_type}),v}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=k.objectValues(t);return f(s,{received:s.data,code:l.invalid_enum_value,options:n}),v}return Z(e.data)}get enum(){return this._def.values}}Ue.create=(r,e)=>new Ue({values:r,typeName:_.ZodNativeEnum,...w(e)});class Re extends E{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 Z(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Re.create=(r,e)=>new Re({type:r,typeName:_.ZodPromise,...w(e)});class J extends E{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"?xe(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"?xe(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(!ve(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=>ve(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):v);k.assertNever(n)}}J.create=(r,e,t)=>new J({schema:r,typeName:_.ZodEffects,effect:e,...w(t)});J.createWithPreprocess=(r,e,t)=>new J({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...w(t)});class Q extends E{_parse(e){return this._getType(e)===h.undefined?Z(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 fe extends E{_parse(e){return this._getType(e)===h.null?Z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}fe.create=(r,e)=>new fe({innerType:r,typeName:_.ZodNullable,...w(e)});class qe extends E{_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}}qe.create=(r,e)=>new qe({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class Ye extends E{_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 ze(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}}Ye.create=(r,e)=>new Ye({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class mt extends E{_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}}}mt.create=r=>new mt({typeName:_.ZodNaN,...w(r)});const fr=Symbol("zod_brand");class zt extends E{_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 We extends E{_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(),xe(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 We({in:e,out:t,typeName:_.ZodPipeline})}}class He extends E{_parse(e){const t=this._def.innerType._parse(e),s=n=>(ve(n)&&(n.value=Object.freeze(n.value)),n);return ze(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}He.create=(r,e)=>new He({innerType:r,typeName:_.ZodReadonly,...w(e)});function es(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function hs(r,e={},t){return r?Ne.create().superRefine((s,n)=>{const a=r(s);if(a instanceof Promise)return a.then(i=>{if(!i){const o=es(e,s),d=o.fatal??t??!0;n.addIssue({code:"custom",...o,fatal:d})}});if(!a){const i=es(e,s),o=i.fatal??t??!0;n.addIssue({code:"custom",...i,fatal:o})}}):Ne.create()}const hr={object:L.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 pr=(r,e={message:`Input not instance of ${r.name}`})=>hs(t=>t instanceof r,e),S=K.create,ee=le.create,mr=mt.create,gr=ue.create,Je=Me.create,yr=_e.create,vr=ft.create,_r=De.create,ps=Ge.create,he=Ne.create,yt=ye.create,br=oe.create,wr=ht.create,we=W.create,N=L.create,Er=L.strictCreate,Ee=Fe.create,Tr=gt.create,kr=Pe.create,xr=se.create,Xe=Ve.create,Ar=pt.create,Or=be.create,Ir=Ae.create,ms=Ze.create,V=Be.create,vt=de.create,Sr=Ue.create,Nr=Re.create,ts=J.create,Rr=Q.create,Cr=fe.create,jr=J.createWithPreprocess,Lr=We.create,$r=()=>S().optional(),zr=()=>ee().optional(),Mr=()=>Je().optional(),ct={string:r=>K.create({...r,coerce:!0}),number:r=>le.create({...r,coerce:!0}),boolean:r=>Me.create({...r,coerce:!0}),bigint:r=>ue.create({...r,coerce:!0}),date:r=>_e.create({...r,coerce:!0})},Dr=v,D=Object.freeze(Object.defineProperty({__proto__:null,BRAND:fr,DIRTY:xe,EMPTY_PATH:Bs,INVALID:v,NEVER:Dr,OK:Z,ParseStatus:P,Schema:E,ZodAny:Ne,ZodArray:W,ZodBigInt:ue,ZodBoolean:Me,ZodBranded:zt,ZodCatch:Ye,ZodDate:_e,ZodDefault:qe,ZodDiscriminatedUnion:gt,ZodEffects:J,ZodEnum:de,ZodError:U,get ZodFirstPartyTypeKind(){return _},ZodFunction:Ae,ZodIntersection:Pe,ZodIssueCode:l,ZodLazy:Ze,ZodLiteral:Be,ZodMap:pt,ZodNaN:mt,ZodNativeEnum:Ue,ZodNever:oe,ZodNull:Ge,ZodNullable:fe,ZodNumber:le,ZodObject:L,ZodOptional:Q,ZodParsedType:h,ZodPipeline:We,ZodPromise:Re,ZodReadonly:He,ZodRecord:Ve,ZodSchema:E,ZodSet:be,ZodString:K,ZodSymbol:ft,ZodTransformer:J,ZodTuple:se,ZodType:E,ZodUndefined:De,ZodUnion:Fe,ZodUnknown:ye,ZodVoid:ht,addIssueToContext:f,any:he,array:we,bigint:gr,boolean:Je,coerce:ct,custom:hs,date:yr,datetimeRegex:ds,defaultErrorMap:Se,discriminatedUnion:Tr,effect:ts,enum:vt,function:Ir,getErrorMap:ut,getParsedType:ie,instanceof:pr,intersection:kr,isAborted:Ct,isAsync:ze,isDirty:jt,isValid:ve,late:hr,lazy:ms,literal:V,makeIssue:dt,map:Ar,nan:mr,nativeEnum:Sr,never:br,null:ps,nullable:Cr,number:ee,object:N,get objectUtil(){return Rt},oboolean:Mr,onumber:zr,optional:Rr,ostring:$r,pipeline:Lr,preprocess:jr,promise:Nr,quotelessJson:Vs,record:Xe,set:Or,setErrorMap:Zs,strictObject:Er,string:S,symbol:vr,transformer:ts,tuple:xr,undefined:_r,union:Ee,unknown:yt,get util(){return k},void:wr},Symbol.toStringTag,{value:"Module"})),Gr={AGENT_SERVER_URL:"AGENT_SERVER_URL",AGENT_API_KEY:"AGENT_API_KEY",AGENT_ORGANIZATION_ID:"AGENT_ORGANIZATION_ID",AGENT_SESSION_ID:"AGENT_SESSION_ID",AGENT_TYPE:"AGENT_TYPE",AGENT_CONTAINER_MODE:"AGENT_CONTAINER_MODE",AGENT_DEVICE_GUID:"AGENT_DEVICE_GUID",CONTEXT_DATA:"CONTEXT_DATA",NODE_ENV:"NODE_ENV",DEBUG:"DEBUG",VERBOSE:"VERBOSE",LOG_LEVEL:"LOG_LEVEL",AGI_NETLOG_ENABLE:"AGI_NETLOG_ENABLE",AGI_NETLOG_DEBUG:"AGI_NETLOG_DEBUG",AGI_NETLOG_MAX_BODY:"AGI_NETLOG_MAX_BODY",AGI_NETLOG_FILE:"AGI_NETLOG_FILE",AGI_NETLOG_REMOTE_ENABLE:"AGI_NETLOG_REMOTE_ENABLE",AGI_NETLOG_REMOTE_FILE:"AGI_NETLOG_REMOTE_FILE",HOSTNAME:"HOSTNAME",VITE_SAVE_RAW:"VITE_SAVE_RAW"},me=()=>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()),Fr=()=>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()),gs=D.object({NODE_ENV:D.enum(["development","production","test"]).default("production"),AGENT_CONTAINER_MODE:me().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:me().default(!0),AGI_NETLOG_DEBUG:me().optional(),AGI_NETLOG_FILE:D.string().optional(),AGI_NETLOG_MAX_BODY:Fr().optional(),AGI_NETLOG_REMOTE_ENABLE:me().default(!0),AGI_NETLOG_REMOTE_FILE:D.string().optional(),DEBUG:me().default(!1),VERBOSE:me().default(!1),LOG_LEVEL:D.string().optional(),HOSTNAME:D.string().optional(),VITE_SAVE_RAW:me().default(!1)});function it(r=!1){return r?"https://agiflow.io":"https://agiflow.io"}let R=gs.parse(process.env);class _t{static refresh(){R=gs.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||it(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=it(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=it(!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=it(this.isContainerMode)),e.LOG_LEVEL||(e.LOG_LEVEL=this.logLevel),e}static getEnvs(){return R}}const ss=ms(()=>Ee([ps(),S(),ee(),Je(),we(ss),Xe(ss)])),rs=N({toolCallId:S(),toolName:S(),args:he()}),Pr=N({toolCallId:S(),toolName:S(),args:he(),result:he()}),Vr=Ee([rs.extend({state:V("partial-call"),step:ee().optional()}),rs.extend({state:V("call"),step:ee().optional()}),Pr.extend({state:V("result"),step:ee().optional()})]),Zr=N({type:S(),content:S()}),Br=N({type:V("text"),text:S()}),Ur=N({type:V("reasoning"),reasoning:S(),details:we(Ee([N({type:V("text"),text:S(),signature:S().optional()}),N({type:V("redacted"),data:S()})])).optional()}),qr=N({name:V("select"),props:N({options:we(N({label:S(),value:Ee([S(),ee()]),selected:Je().optional()}))})}),Yr=N({name:V("placeholder"),props:N({})}),Hr=Ee([qr,Yr]),Kr=N({completed:Je(),component:Hr}),Wr=N({type:V("tool-invocation"),toolInvocation:Vr,input:Kr.optional(),jsx:S({description:"UI rendering"}).optional()}),Jr=N({type:V("source"),source:Zr}),Xr=N({type:V("file"),mimeType:S(),data:S()}),Qr=N({type:V("error"),text:S(),error:he().optional()}),en=N({type:V("step-start")}),ys=Ee([Br,Ur,Wr,Jr,Xr,Qr,en]),Mt=vt(["input","output","error","system"]),vs=N({messageType:Mt,parts:we(ys),metadata:Xe(S(),yt()).optional(),raw:he().optional()});N({id:S(),sessionId:S(),agentTypeId:S(),messageType:Mt,contentSize:ee().nullable(),timestamp:ct.date(),metadata:S().nullable(),raw:he().nullable().optional(),createdAt:ct.date(),updatedAt:ct.date()});const tn=N({messageType:vt(["output"]).default("output"),metadata:Xe(S(),yt()).optional()});N({id:S(),messageId:S()});const sn=N({parts:we(ys).optional(),metadata:Xe(S(),yt()).optional(),raw:he().optional()});N({messages:we(vs)});function rn(r){return[_s(r)]}function ns(r){let e=r.parts;if(!e&&r.content&&(e=rn(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 _s(r){return{type:"text",text:r}}function nn(r){return{name:"select",props:{options:r}}}function an(r,e){return{completed:r,component:e}}function on(r,e,t){return{type:"tool-invocation",toolInvocation:r,input:e,jsx:t}}class ae{static AGIFLOW_DIR=ge.join(Tt.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(ge.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 ge.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("~/")?ge.join(Tt.homedir(),e.slice(2)):e==="~"?Tt.homedir():ge.isAbsolute(e)?e:ge.resolve(process.cwd(),e):process.cwd()}}var Le={exports:{}},Ot,as;function cn(){if(as)return Ot;as=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 T="",j=1-i,A=-1,Y=t&&t.length||0,O=0;O<Y;){if(t.charCodeAt(O)===37&&O+1<Y){switch(A=A>-1?A:0,t.charCodeAt(O+1)){case 100:case 102:if(j>=g||s[j]==null)break;A<O&&(T+=t.slice(A,O)),T+=Number(s[j]),A=O+2,O++;break;case 105:if(j>=g||s[j]==null)break;A<O&&(T+=t.slice(A,O)),T+=Math.floor(Number(s[j])),A=O+2,O++;break;case 79:case 111:case 106:if(j>=g||s[j]===void 0)break;A<O&&(T+=t.slice(A,O));var Qe=typeof s[j];if(Qe==="string"){T+="'"+s[j]+"'",A=O+2,O++;break}if(Qe==="function"){T+=s[j].name||"<anonymous>",A=O+2,O++;break}T+=a(s[j]),A=O+2,O++;break;case 115:if(j>=g)break;A<O&&(T+=t.slice(A,O)),T+=String(s[j]),A=O+2,O++;break;case 37:A<O&&(T+=t.slice(A,O)),T+="%",A=O+2,O++,j--;break}++j}++O}return A===-1?t:(A<Y&&(T+=t.slice(A)),T)}return Ot}var is;function ln(){if(is)return Le.exports;is=1;const r=cn();Le.exports=g;const e=As().console||{},t={mapHttpRequest:et,mapHttpResponse:et,wrapRequestSerializer:Et,wrapResponseSerializer:Et,wrapErrorSerializer:Et,req:et,res:et,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 x={};p.forEach(I=>{x[I]=b[I]?b[I]:e[I]||e[i[I]||"log"]||Te}),c[n]=x}function u(c,p){return Array.isArray(c)?c.filter(function(x){return x!=="!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 x=c.serializers||{},I=u(c.browser.serialize,x);let F=c.browser.serialize;Array.isArray(c.browser.serialize)&&c.browser.serialize.indexOf("!stdSerializers.err")>-1&&(F=!1);const q=Object.keys(c.customLevels||{}),$=["error","fatal","warn","info","debug","trace"].concat(q);typeof b=="function"&&$.forEach(function(H){b[H]=b}),(c.enabled===!1||c.browser.disabled)&&(c.level="silent");const B=c.level||"info",y=Object.create(b);y.log||(y.log=Te),d(y,$,b),o({},y),Object.defineProperty(y,"levelVal",{get:tt}),Object.defineProperty(y,"level",{get:pe,set:st});const G={transmit:p,serialize:I,asObject:c.browser.asObject,formatters:c.browser.formatters,levels:$,timestamp:Ts(c),messageKey:c.messageKey||"msg",onChild:c.onChild||Te};y.levels=T(c),y.level=B,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=Te,y.serializers=x,y._serialize=I,y._stdErrSerialize=F,y.child=function(...H){return Pt.call(this,G,...H)},p&&(y._logEvent=wt());function tt(){return s(this.level,this)}function pe(){return this._level}function st(H){if(H!=="silent"&&!this.levels.values[H])throw Error("unknown level "+H);this._level=H,Y(this,G,y,"error"),Y(this,G,y,"fatal"),Y(this,G,y,"warn"),Y(this,G,y,"info"),Y(this,G,y,"debug"),Y(this,G,y,"trace"),q.forEach(re=>{Y(this,G,y,re)})}function Pt(H,re,Ce){if(!re)throw new Error("missing bindings for child Pino");Ce=Ce||{},I&&re.serializers&&(Ce.serializers=re.serializers);const Vt=Ce.serializers;if(I&&Vt){var rt=Object.assign({},x,Vt),Zt=c.browser.serialize===!0?Object.keys(rt):I;delete re.serializers,bt([re],Zt,rt,this._stdErrSerialize)}function Bt(nt){this._childLevel=(nt._childLevel|0)+1,this.bindings=re,rt&&(this.serializers=rt,this._serialize=Zt),p&&(this._logEvent=wt([].concat(nt._logEvent.bindings,re)))}Bt.prototype=this;const je=new Bt(this);return o(this,je),je.child=function(...nt){return Pt.call(this,H,...nt)},je.level=Ce.level||this.level,H.onChild(je),je}return y}function T(c){const p=c.customLevels||{},b=Object.assign({},g.levels.values,p),x=Object.assign({},g.levels.labels,j(p));return{values:b,labels:x}}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:Gt,epochTime:Ft,unixTime:ks,isoTime:xs});function A(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 Y(c,p,b,x){if(Object.defineProperty(c,x,{value:s(c.level,b)>s(x,b)?Te:b[n][x],writable:!0,enumerable:!0,configurable:!0}),c[x]===Te){if(!p.transmit)return;const F=p.transmit.level||c.level,q=s(F,b);if(s(x,b)<q)return}c[x]=Qe(c,p,b,x);const I=A(c);I.length!==0&&(c[x]=O(I,c[x]))}function O(c,p){return function(){return p.apply(this,[...c,...arguments])}}function Qe(c,p,b,x){return function(I){return function(){const q=p.timestamp(),$=new Array(arguments.length),B=Object.getPrototypeOf&&Object.getPrototypeOf(this)===e?e:this;for(var y=0;y<$.length;y++)$[y]=arguments[y];var G=!1;if(p.serialize&&(bt($,this._serialize,this.serializers,this._stdErrSerialize),G=!0),p.asObject||p.formatters?I.call(B,ws(this,x,$,q,p)):I.apply(B,$),p.transmit){const tt=p.transmit.level||c._level,pe=s(tt,b),st=s(x,b);if(st<pe)return;Es(this,{ts:q,methodLevel:x,methodValue:st,transmitValue:b.levels.values[p.transmit.level||c._level],send:p.transmit.send,val:s(c._level,b)},$,G)}}}(c[n][x])}function ws(c,p,b,x,I){const{level:F,log:q=pe=>pe}=I.formatters||{},$=b.slice();let B=$[0];const y={};if(x&&(y.time=x),F){const pe=F(p,c.levels.values[p]);Object.assign(y,pe)}else y.level=c.levels.values[p];let G=(c._childLevel|0)+1;if(G<1&&(G=1),B!==null&&typeof B=="object"){for(;G--&&typeof $[0]=="object";)Object.assign(y,$.shift());B=$.length?r($.shift(),$):void 0}else typeof B=="string"&&(B=r($.shift(),$));return B!==void 0&&(y[I.messageKey]=B),q(y)}function bt(c,p,b,x){for(const I in c)if(x&&c[I]instanceof Error)c[I]=g.stdSerializers.err(c[I]);else if(typeof c[I]=="object"&&!Array.isArray(c[I])&&p)for(const F in c[I])p.indexOf(F)>-1&&F in b&&(c[I][F]=b[F](c[I][F]))}function Es(c,p,b,x=!1){const I=p.send,F=p.ts,q=p.methodLevel,$=p.methodValue,B=p.val,y=c._logEvent.bindings;x||bt(b,c._serialize||Object.keys(c.serializers),c.serializers,c._stdErrSerialize===void 0?!0:c._stdErrSerialize),c._logEvent.ts=F,c._logEvent.messages=b.filter(function(G){return y.indexOf(G)===-1}),c._logEvent.level.label=q,c._logEvent.level.value=$,I(q,c._logEvent,B),c._logEvent=wt(y)}function wt(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 Ts(c){return typeof c.timestamp=="function"?c.timestamp:c.timestamp===!1?Gt:Ft}function et(){return{}}function Et(c){return c}function Te(){}function Gt(){return!1}function Ft(){return Date.now()}function ks(){return Math.round(Date.now()/1e3)}function xs(){return new Date(Date.now()).toISOString()}function As(){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 un=ln();const ot=os(un);class M{pino;useTerminalFormat;static instance;constructor(e={}){this.useTerminalFormat=e.useTerminalFormat??!0;const t=e.debug?"debug":e.verbose?"trace":"info";e.silent?this.pino=ot({level:"silent"}):e.logFile||e.logDir?this.pino=this.createMultiTransportLogger(t,e):this.useTerminalFormat&&process.stdout.isTTY?this.pino=ot({level:t,transport:{target:"pino-pretty",options:{colorize:!0,ignore:"pid,hostname",translateTime:"HH:MM:ss",messageFormat:"{msg}"}}}):this.pino=ot({level:t})}createMultiTransportLogger(e,t){let s;if(t.logFile)s=t.logFile;else if(t.logDir){at.existsSync(t.logDir)||at.mkdirSync(t.logDir,{recursive:!0});const a=new Date().toISOString().split("T")[0];s=kt.join(t.logDir,`app-${a}.log`)}else{const a=kt.join(Ns.tmpdir(),"agiflow-agents","logs",`session-${process.pid}`);at.existsSync(a)||at.mkdirSync(a,{recursive:!0});const i=new Date().toISOString().split("T")[0];s=kt.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}}),ot({level:e,transport:{targets:n}})}static getInstance(){return M.instance||(M.instance=new M),M.instance}static configure(e){M.instance=new M(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){M.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){M.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){M.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){M.getInstance().error(e,void 0,t)}debug(e,...t){this.useTerminalFormat&&process.stdout.isTTY?(_t.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){M.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){M.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){M.getInstance().code(e)}newLine(){this.useTerminalFormat&&process.stdout.isTTY&&console.log()}static newLine(){M.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 M({useTerminalFormat:this.useTerminalFormat});return t.pino=this.pino.child(e),t}}class bs{filePath;cache=null;dirty=!1;constructor(e){this.filePath=e||ge.join(ae.AGIFLOW_DIR,"credentials.json")}async load(){if(this.cache)return this.cache;try{if(!await ae.exists(this.filePath))return null;const t=await ae.readJson(this.filePath);return this.cache=t,t}catch{return null}}async flush(){!this.dirty||!this.cache||(await ae.ensureDir(ae.AGIFLOW_DIR),await ae.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 ae.exists(this.filePath)&&await ae.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=_t.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:Mt.optional(),sort:S().optional(),order:vt(["asc","desc"]).optional()});class dn{options;authService;credentials;logger;constructor(e){this.options=e,this.authService=e.authService,this.credentials=e.credentials??new bs,this.logger=e.logger??new M({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=_t.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=ns(e);try{vs.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=>ns(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 A=await u.text();throw new Error(`Failed to get presigned URL: ${u.status} ${A}`)}const{uploadUrl:g}=await u.json(),T=await fetch(g,{method:"PUT",body:o,headers:{"Content-Type":"application/octet-stream","Content-Length":d.toString()}});if(!T.ok)throw new Error(`Failed to upload content to R2: ${T.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{tn.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{sn.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 T=await u.text();return this.logger.warn(`Failed to create task comment: ${u.status} ${T}`),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}}}exports.AgentHttpService=dn;exports.CredentialsService=bs;exports.ENV_KEYS=Gr;exports.FileSystemUtils=ae;exports.Logger=M;exports.SubEnvManager=_t;exports.chalk=z;exports.createSelectComponent=nn;exports.createTextPart=_s;exports.createToolInvocationInput=an;exports.createToolInvocationPart=on;exports.getDefaultExportFromCjs=os;exports.z=D;
6
+ //# sourceMappingURL=AgentHttpService-CYYuD3Wj.js.map