@hashgraphonline/standards-agent-kit 0.2.0 → 0.2.101
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/README.md +137 -170
- package/dist/cjs/builders/hcs10/hcs10-builder.d.ts +4 -0
- package/dist/cjs/standards-agent-kit.cjs +1 -1
- package/dist/cjs/standards-agent-kit.cjs.map +1 -1
- package/dist/cjs/tools/hcs10/RegisterAgentTool.d.ts +14 -4
- package/dist/es/builders/hcs10/hcs10-builder.d.ts +4 -0
- package/dist/es/standards-agent-kit.es2.js +27 -13
- package/dist/es/standards-agent-kit.es2.js.map +1 -1
- package/dist/es/standards-agent-kit.es5.js +75 -2
- package/dist/es/standards-agent-kit.es5.js.map +1 -1
- package/dist/es/tools/hcs10/RegisterAgentTool.d.ts +14 -4
- package/dist/umd/builders/hcs10/hcs10-builder.d.ts +4 -0
- package/dist/umd/standards-agent-kit.umd.js +1 -1
- package/dist/umd/standards-agent-kit.umd.js.map +1 -1
- package/dist/umd/tools/hcs10/RegisterAgentTool.d.ts +14 -4
- package/package.json +4 -4
- package/src/builders/hcs10/hcs10-builder.ts +37 -16
- package/src/tools/hcs10/RegisterAgentTool.ts +111 -5
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("unenv/node/buffer"),require("hedera-agent-kit"),require("@hashgraphonline/standards-sdk"),require("unenv/node/fs"),require("unenv/node/path"),require("unenv/polyfill/globalthis"),require("unenv/node/timers"),require("unenv/node/process")):"function"==typeof define&&define.amd?define(["exports","unenv/node/buffer","hedera-agent-kit","@hashgraphonline/standards-sdk","unenv/node/fs","unenv/node/path","unenv/polyfill/globalthis","unenv/node/timers","unenv/node/process"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsAgentKit={},e["unenv/node/buffer"],e.HederaAgentKit,e.StandardsSDK,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],e.process)}(this,function(e,t,n,r,i,s,o,a,c){"use strict";class u extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class d extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var l,h,p;(h=l||(l={})).assertEqual=e=>{},h.assertIs=function(e){},h.assertNever=function(e){throw new Error},h.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},h.getValidEnumValues=e=>{const t=h.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const r of t)n[r]=e[r];return h.objectValues(n)},h.objectValues=e=>h.objectKeys(e).map(function(t){return e[t]}),h.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},h.find=(e,t)=>{for(const n of e)if(t(n))return n},h.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,h.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},h.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(p||(p={})).mergeShapes=(e,t)=>({...e,...t});const f=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),g=e=>{switch(typeof e){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(e)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(e)?f.array:null===e?f.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?f.promise:"undefined"!=typeof Map&&e instanceof Map?f.map:"undefined"!=typeof Set&&e instanceof Set?f.set:"undefined"!=typeof Date&&e instanceof Date?f.date:f.object;default:return f.unknown}},m=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class y extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};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(e){return e.message},n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(r);else if("invalid_return_type"===i.code)r(i.returnTypeError);else if("invalid_arguments"===i.code)r(i.argumentsError);else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof y))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}y.create=e=>new y(e);const v=(e,t)=>{let n;switch(e.code){case m.invalid_type:n=e.received===f.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,l.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:n=`Unrecognized key(s) in object: ${l.joinValues(e.keys,", ")}`;break;case m.invalid_union:n="Invalid input";break;case m.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${l.joinValues(e.options)}`;break;case m.invalid_enum_value:n=`Invalid enum value. Expected ${l.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:n="Invalid function arguments";break;case m.invalid_return_type:n="Invalid function return type";break;case m.invalid_date:n="Invalid date";break;case m.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:l.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case m.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case m.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case m.custom:n="Invalid input";break;case m.invalid_intersection_types:n="Intersection results could not be merged";break;case m.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:n="Number must be finite";break;default:n=t.defaultError,l.assertNever(e)}return{message:n}};let b=v;function w(e,t){const n=b,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(void 0!==i.message)return{...i,path:s,message:i.message};let a="";const c=r.filter(e=>!!e).slice().reverse();for(const u of c)a=u(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===v?void 0:v].filter(e=>!!e)});e.common.issues.push(r)}class _{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return I;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const r of t){const e=await r.key,t=await r.value;n.push({key:e,value:t})}return _.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:i}=r;if("aborted"===t.status)return I;if("aborted"===i.status)return I;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!r.alwaysSet||(n[t.value]=i.value)}return{status:e.value,value:n}}}const I=Object.freeze({status:"aborted"}),C=e=>({status:"dirty",value:e}),T=e=>({status:"valid",value:e}),x=e=>"aborted"===e.status,A=e=>"dirty"===e.status,k=e=>"valid"===e.status,S=e=>"undefined"!=typeof Promise&&e instanceof Promise;var R,E;(E=R||(R={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},E.toString=e=>"string"==typeof e?e:e?.message;class O{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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 N=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new y(e.common.issues);return this._error=t,this._error}}};function P(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??i.defaultError}:void 0===i.data?{message:s??r??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:s??n??i.defaultError}},description:i}}class q{get description(){return this._def.description}_getType(e){return g(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _,ctx:{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(S(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)},r=this._parseSync({data:e,path:n.path,parent:n});return N(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return k(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>k(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(S(r)?r:Promise.resolve(r));return N(n,i)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const i=e(t),s=()=>r.addIssue({code:m.custom,...n(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(s(),!1)):!!i||(s(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new Pe({schema:this,typeName:Ue.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:e=>this["~validate"](e)}}optional(){return qe.create(this,this._def)}nullable(){return $e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ye.create(this)}promise(){return Ne.create(this,this._def)}or(e){return we.create([this,e],this._def)}and(e){return Ie.create(this,e,this._def)}transform(e){return new Pe({...P(this._def),schema:this,typeName:Ue.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Me({...P(this._def),innerType:this,defaultValue:t,typeName:Ue.ZodDefault})}brand(){return new Be({typeName:Ue.ZodBranded,type:this,...P(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Fe({...P(this._def),innerType:this,catchValue:t,typeName:Ue.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return De.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const $=/^c[^\s-]{8,}$/i,M=/^[0-9a-z]+$/,F=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[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,B=/^[a-z0-9_-]{21}$/i,D=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L=/^[-+]?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)?)??$/,U=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Z;const K=/^(?:(?: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])$/,z=/^(?:(?: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])$/,H=/^(([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]))$/,V=/^(([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])$/,W=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,J=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,G="((\\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])))",X=new RegExp(`^${G}$`);function Q(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Y(e){return new RegExp(`^${Q(e)}$`)}function ee(e){let t=`${G}T${Q(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function te(e,t){return!("v4"!==t&&t||!K.test(e))||!("v6"!==t&&t||!H.test(e))}function ne(e,t){if(!D.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return"object"==typeof i&&null!==i&&((!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||i.alg===t)))}catch{return!1}}function re(e,t){return!("v4"!==t&&t||!z.test(e))||!("v6"!==t&&t||!V.test(e))}class ie extends q{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==f.string){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.string,received:t.parsedType}),I}const t=new _;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const i=e.data.length>r.value,s=e.data.length<r.value;(i||s)&&(n=this._getOrReturnCtx(e,n),i?w(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):s&&w(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"email",code:m.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)Z||(Z=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Z.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"emoji",code:m.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"uuid",code:m.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)B.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"nanoid",code:m.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)$.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid",code:m.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)M.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid2",code:m.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)F.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ulid",code:m.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),w(n,{validation:"url",code:m.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"regex",code:m.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){ee(r).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){X.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Y(r).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?L.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"duration",code:m.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?te(e.data,r.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ip",code:m.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?ne(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"jwt",code:m.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?re(e.data,r.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cidr",code:m.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?W.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64",code:m.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?J.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64url",code:m.invalid_string,message:r.message}),t.dirty()):l.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:m.invalid_string,...R.errToObj(n)})}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...R.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...R.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...R.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...R.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...R.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...R.errToObj(t)})}nonempty(e){return this.min(1,R.errToObj(e))}trim(){return new ie({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function se(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}ie.create=e=>new ie({checks:[],typeName:Ue.ZodString,coerce:e?.coerce??!1,...P(e)});class oe extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==f.number){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.number,received:t.parsedType}),I}let t;const n=new _;for(const r of this._def.checks)if("int"===r.kind)l.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty());else if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==se(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_finite,message:r.message}),n.dirty()):l.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,r){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(r)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&l.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}oe.create=e=>new oe({checks:[],typeName:Ue.ZodNumber,coerce:e?.coerce||!1,...P(e)});class ae extends q{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)!==f.bigint)return this._getInvalidInput(e);let t;const n=new _;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):l.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.bigint,received:t.parsedType}),I}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,r){return new ae({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(r)}]})}_addCheck(e){return new ae({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ae.create=e=>new ae({checks:[],typeName:Ue.ZodBigInt,coerce:e?.coerce??!1,...P(e)});class ce extends q{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==f.boolean){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.boolean,received:t.parsedType}),I}return T(e.data)}}ce.create=e=>new ce({typeName:Ue.ZodBoolean,coerce:e?.coerce||!1,...P(e)});class ue extends q{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==f.date){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.date,received:t.parsedType}),I}if(Number.isNaN(e.data.getTime())){return w(this._getOrReturnCtx(e),{code:m.invalid_date}),I}const t=new _;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):l.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:R.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:R.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ue.create=e=>new ue({checks:[],coerce:e?.coerce||!1,typeName:Ue.ZodDate,...P(e)});class de extends q{_parse(e){if(this._getType(e)!==f.symbol){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.symbol,received:t.parsedType}),I}return T(e.data)}}de.create=e=>new de({typeName:Ue.ZodSymbol,...P(e)});class le extends q{_parse(e){if(this._getType(e)!==f.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.undefined,received:t.parsedType}),I}return T(e.data)}}le.create=e=>new le({typeName:Ue.ZodUndefined,...P(e)});class he extends q{_parse(e){if(this._getType(e)!==f.null){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.null,received:t.parsedType}),I}return T(e.data)}}he.create=e=>new he({typeName:Ue.ZodNull,...P(e)});class pe extends q{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}}pe.create=e=>new pe({typeName:Ue.ZodAny,...P(e)});class fe extends q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}}fe.create=e=>new fe({typeName:Ue.ZodUnknown,...P(e)});class ge extends q{_parse(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.never,received:t.parsedType}),I}}ge.create=e=>new ge({typeName:Ue.ZodNever,...P(e)});class me extends q{_parse(e){if(this._getType(e)!==f.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.void,received:t.parsedType}),I}return T(e.data)}}me.create=e=>new me({typeName:Ue.ZodVoid,...P(e)});class ye extends q{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==f.array)return w(t,{code:m.invalid_type,expected:f.array,received:t.parsedType}),I;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(w(t,{code:e?m.too_big:m.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(w(t,{code:m.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(w(t,{code:m.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new O(t,e,t.path,n)))).then(e=>_.mergeArray(n,e));const i=[...t.data].map((e,n)=>r.type._parseSync(new O(t,e,t.path,n)));return _.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ye({...this._def,minLength:{value:e,message:R.toString(t)}})}max(e,t){return new ye({...this._def,maxLength:{value:e,message:R.toString(t)}})}length(e,t){return new ye({...this._def,exactLength:{value:e,message:R.toString(t)}})}nonempty(e){return this.min(1,e)}}function ve(e){if(e instanceof be){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=qe.create(ve(r))}return new be({...e._def,shape:()=>t})}return e instanceof ye?new ye({...e._def,type:ve(e.element)}):e instanceof qe?qe.create(ve(e.unwrap())):e instanceof $e?$e.create(ve(e.unwrap())):e instanceof Ce?Ce.create(e.items.map(e=>ve(e))):e}ye.create=(e,t)=>new ye({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ue.ZodArray,...P(t)});class be extends q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=l.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.object,received:t.parsedType}),I}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ge&&"strip"===this._def.unknownKeys))for(const a in n.data)i.includes(a)||s.push(a);const o=[];for(const a of i){const e=r[a],t=n.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new O(n,t,n.path,a)),alwaysSet:a in n.data})}if(this._def.catchall instanceof ge){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of s)o.push({key:{status:"valid",value:t},value:{status:"valid",value:n.data[t]}});else if("strict"===e)s.length>0&&(w(n,{code:m.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const r=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new O(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>_.mergeObjectSync(t,e)):_.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new be({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:R.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new be({...this._def,unknownKeys:"strip"})}passthrough(){return new be({...this._def,unknownKeys:"passthrough"})}extend(e){return new be({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new be({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ue.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new be({...this._def,catchall:e})}pick(e){const t={};for(const n of l.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new be({...this._def,shape:()=>t})}omit(e){const t={};for(const n of l.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new be({...this._def,shape:()=>t})}deepPartial(){return ve(this)}partial(e){const t={};for(const n of l.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new be({...this._def,shape:()=>t})}required(e){const t={};for(const n of l.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof qe;)e=e._def.innerType;t[n]=e}return new be({...this._def,shape:()=>t})}keyof(){return Re(l.objectKeys(this.shape))}}be.create=(e,t)=>new be({shape:()=>e,unknownKeys:"strip",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)}),be.strictCreate=(e,t)=>new be({shape:()=>e,unknownKeys:"strict",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)}),be.lazycreate=(e,t)=>new be({shape:e,unknownKeys:"strip",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)});class we extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const n=e.map(e=>new y(e.ctx.common.issues));return w(t,{code:m.invalid_union,unionErrors:n}),I});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=r.map(e=>new y(e));return w(t,{code:m.invalid_union,unionErrors:i}),I}}get options(){return this._def.options}}function _e(e,t){const n=g(e),r=g(t);if(e===t)return{valid:!0,data:e};if(n===f.object&&r===f.object){const n=l.objectKeys(t),r=l.objectKeys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const s of r){const n=_e(e[s],t[s]);if(!n.valid)return{valid:!1};i[s]=n.data}return{valid:!0,data:i}}if(n===f.array&&r===f.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const i=_e(e[r],t[r]);if(!i.valid)return{valid:!1};n.push(i.data)}return{valid:!0,data:n}}return n===f.date&&r===f.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}we.create=(e,t)=>new we({options:e,typeName:Ue.ZodUnion,...P(t)});class Ie extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(x(e)||x(r))return I;const i=_e(e.value,r.value);return i.valid?((A(e)||A(r))&&t.dirty(),{status:t.value,value:i.data}):(w(n,{code:m.invalid_intersection_types}),I)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ie.create=(e,t,n)=>new Ie({left:e,right:t,typeName:Ue.ZodIntersection,...P(n)});class Ce extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return w(n,{code:m.invalid_type,expected:f.array,received:n.parsedType}),I;if(n.data.length<this._def.items.length)return w(n,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;!this._def.rest&&n.data.length>this._def.items.length&&(w(n,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new O(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>_.mergeArray(t,e)):_.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Ce({...this._def,rest:e})}}Ce.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:e,typeName:Ue.ZodTuple,rest:null,...P(t)})};class Te extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return w(n,{code:m.invalid_type,expected:f.object,received:n.parsedType}),I;const r=[],i=this._def.keyType,s=this._def.valueType;for(const o in n.data)r.push({key:i._parse(new O(n,o,n.path,o)),value:s._parse(new O(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?_.mergeObjectAsync(t,r):_.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new Te(t instanceof q?{keyType:e,valueType:t,typeName:Ue.ZodRecord,...P(n)}:{keyType:ie.create(),valueType:e,typeName:Ue.ZodRecord,...P(t)})}}class xe extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return w(n,{code:m.invalid_type,expected:f.map,received:n.parsedType}),I;const r=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([e,t],s)=>({key:r._parse(new O(n,e,n.path,[s,"key"])),value:i._parse(new O(n,t,n.path,[s,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of s){const r=await n.key,i=await n.value;if("aborted"===r.status||"aborted"===i.status)return I;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of s){const r=n.key,i=n.value;if("aborted"===r.status||"aborted"===i.status)return I;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}}xe.create=(e,t,n)=>new xe({valueType:t,keyType:e,typeName:Ue.ZodMap,...P(n)});class Ae extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return w(n,{code:m.invalid_type,expected:f.set,received:n.parsedType}),I;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(w(n,{code:m.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(w(n,{code:m.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function s(e){const n=new Set;for(const r of e){if("aborted"===r.status)return I;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>i._parse(new O(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(e,t){return new Ae({...this._def,minSize:{value:e,message:R.toString(t)}})}max(e,t){return new Ae({...this._def,maxSize:{value:e,message:R.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ae.create=(e,t)=>new Ae({valueType:e,minSize:null,maxSize:null,typeName:Ue.ZodSet,...P(t)});class ke extends q{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})}}ke.create=(e,t)=>new ke({getter:e,typeName:Ue.ZodLazy,...P(t)});class Se extends q{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return w(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Re(e,t){return new Ee({values:e,typeName:Ue.ZodEnum,...P(t)})}Se.create=(e,t)=>new Se({value:e,typeName:Ue.ZodLiteral,...P(t)});class Ee extends q{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{expected:l.joinValues(n),received:t.parsedType,code:m.invalid_type}),I}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{received:t.data,code:m.invalid_enum_value,options:n}),I}return T(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 Ee.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ee.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ee.create=Re;class Oe extends q{_parse(e){const t=l.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){const e=l.objectValues(t);return w(n,{expected:l.joinValues(e),received:n.parsedType,code:m.invalid_type}),I}if(this._cache||(this._cache=new Set(l.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=l.objectValues(t);return w(n,{received:n.data,code:m.invalid_enum_value,options:e}),I}return T(e.data)}get enum(){return this._def.values}}Oe.create=(e,t)=>new Oe({values:e,typeName:Ue.ZodNativeEnum,...P(t)});class Ne extends q{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&!1===t.common.async)return w(t,{code:m.invalid_type,expected:f.promise,received:t.parsedType}),I;const n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return T(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:Ue.ZodPromise,...P(t)});class Pe extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ue.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{w(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===r.type){const e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return I;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?I:"dirty"===r.status||"dirty"===t.value?C(r.value):r});{if("aborted"===t.value)return I;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?I:"dirty"===r.status||"dirty"===t.value?C(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?I:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?I:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!k(e))return I;const s=r.transform(e.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>k(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):I)}l.assertNever(r)}}Pe.create=(e,t,n)=>new Pe({schema:e,typeName:Ue.ZodEffects,effect:t,...P(n)}),Pe.createWithPreprocess=(e,t,n)=>new Pe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ue.ZodEffects,...P(n)});class qe extends q{_parse(e){return this._getType(e)===f.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:Ue.ZodOptional,...P(t)});class $e extends q{_parse(e){return this._getType(e)===f.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$e.create=(e,t)=>new $e({innerType:e,typeName:Ue.ZodNullable,...P(t)});class Me extends q{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:Ue.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...P(t)});class Fe extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return S(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Fe.create=(e,t)=>new Fe({innerType:e,typeName:Ue.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...P(t)});class je extends q{_parse(e){if(this._getType(e)!==f.nan){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.nan,received:t.parsedType}),I}return{status:"valid",value:e.data}}}je.create=e=>new je({typeName:Ue.ZodNaN,...P(e)});class Be extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class De extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?I:"dirty"===e.status?(t.dirty(),C(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})()}{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?I:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new De({in:e,out:t,typeName:Ue.ZodPipeline})}}class Le extends q{_parse(e){const t=this._def.innerType._parse(e),n=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return S(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var Ue,Ze;Le.create=(e,t)=>new Le({innerType:e,typeName:Ue.ZodReadonly,...P(t)}),(Ze=Ue||(Ue={})).ZodString="ZodString",Ze.ZodNumber="ZodNumber",Ze.ZodNaN="ZodNaN",Ze.ZodBigInt="ZodBigInt",Ze.ZodBoolean="ZodBoolean",Ze.ZodDate="ZodDate",Ze.ZodSymbol="ZodSymbol",Ze.ZodUndefined="ZodUndefined",Ze.ZodNull="ZodNull",Ze.ZodAny="ZodAny",Ze.ZodUnknown="ZodUnknown",Ze.ZodNever="ZodNever",Ze.ZodVoid="ZodVoid",Ze.ZodArray="ZodArray",Ze.ZodObject="ZodObject",Ze.ZodUnion="ZodUnion",Ze.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ze.ZodIntersection="ZodIntersection",Ze.ZodTuple="ZodTuple",Ze.ZodRecord="ZodRecord",Ze.ZodMap="ZodMap",Ze.ZodSet="ZodSet",Ze.ZodFunction="ZodFunction",Ze.ZodLazy="ZodLazy",Ze.ZodLiteral="ZodLiteral",Ze.ZodEnum="ZodEnum",Ze.ZodEffects="ZodEffects",Ze.ZodNativeEnum="ZodNativeEnum",Ze.ZodOptional="ZodOptional",Ze.ZodNullable="ZodNullable",Ze.ZodDefault="ZodDefault",Ze.ZodCatch="ZodCatch",Ze.ZodPromise="ZodPromise",Ze.ZodBranded="ZodBranded",Ze.ZodPipeline="ZodPipeline",Ze.ZodReadonly="ZodReadonly";const Ke=ie.create,ze=oe.create,He=ce.create,Ve=fe.create;ge.create;const We=ye.create,Je=be.create,Ge=we.create;Ie.create,Ce.create;const Xe=Te.create,Qe=Ee.create,Ye=Oe.create;Ne.create,qe.create,$e.create;const et=Je({name:Ke().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:Ke().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:Ke().optional().describe("Optional custom username/alias for the agent"),type:Qe(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:Ke().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:We(Ye(r.AIAgentCapability)).optional().describe("Array of agent capabilities (default: [TEXT_GENERATION])"),creator:Ke().optional().describe("Creator attribution for the agent"),socials:Xe(Qe(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),Ke()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:Xe(Ve()).optional().describe("Custom metadata properties for the agent"),profilePicture:Ge([Ke().describe("URL or local file path to profile picture"),Je({url:Ke().optional(),path:Ke().optional(),filename:Ke().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:Ke().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:ze().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:Ke().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:ze().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:We(Je({amount:ze().positive(),tokenId:Ke()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:We(Ke()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:He().optional().describe("Whether to set as current agent (default: true)"),persistence:Je({prefix:Ke().optional()}).optional().describe("Optional persistence configuration")});class tt extends u{constructor(e){super(e),this.name="register_agent",this.description="Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Note: This tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=et,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,r={name:t.name};if(void 0!==t.description&&(r.bio=t.description),void 0!==t.alias&&(r.alias=t.alias),void 0!==t.type&&(r.type=t.type),void 0!==t.model&&(r.model=t.model),void 0!==t.capabilities&&(r.capabilities=t.capabilities),void 0!==t.creator&&(r.creator=t.creator),void 0!==t.socials&&(r.socials=t.socials),void 0!==t.properties&&(r.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)r.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),r.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(r.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(r.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(r.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(r.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(r.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(r.initialBalance=t.initialBalance),await n.registerAgent(r)}}const nt=Je({targetIdentifier:Ke().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),message:Ke().describe("The text message content to send."),disableMonitoring:He().optional().default(!1)});class rt extends u{constructor(e){super(e),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.specificInputSchema=nt,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e;await n.sendMessageToConnection({targetIdentifier:t.targetIdentifier,message:t.message,disableMonitoring:t.disableMonitoring})}}const it=Je({targetAccountId:Ke().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:He().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:Ke().optional().describe('Optional memo to include with the connection request (e.g., "Hello from Alice"). If not provided, defaults to "true" or "false" based on monitoring preference.')});class st extends u{constructor(e){super(e),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.specificInputSchema=it,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,r={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(r.disableMonitor=t.disableMonitor),void 0!==t.memo&&(r.memo=t.memo),await n.initiateConnection(r)}}const ot=Je({includeDetails:He().optional().describe("Whether to include detailed information about each connection"),showPending:He().optional().describe("Whether to include pending connection requests")});class at extends d{constructor(e){super(e),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.specificInputSchema=ot}async executeQuery(e){const t=this.hcs10Builder,n={};void 0!==e.includeDetails&&(n.includeDetails=e.includeDetails),void 0!==e.showPending&&(n.showPending=e.showPending),await t.listConnections(n);const r=await t.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return r}}const ct=Je({targetIdentifier:Ke().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:He().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:ze().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class ut extends d{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=ct}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const r=this.hcs10Builder;await r.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const i=await r.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return i}}const dt=Je({accountId:Ke().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:We(Ye(r.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")});class lt extends d{constructor(e){super(e),this.name="find_registrations",this.description="Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags. Returns basic registration info.",this.specificInputSchema=dt}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,r={};e&&(r.accountId=e),t&&(r.tags=t),await n.findRegistrations(r);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return i}}const ht=Je({acceptAll:He().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:Ke().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:We(Je({amount:ze(),collectorAccount:Ke().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:We(Je({amount:ze(),tokenId:Ke(),collectorAccount:Ke().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:We(Ke()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:ze().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:Ke().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class pt extends u{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=ht,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.monitorConnections({...void 0!==t.acceptAll&&{acceptAll:t.acceptAll},...void 0!==t.targetAccountId&&{targetAccountId:t.targetAccountId},...void 0!==t.monitorDurationSeconds&&{monitorDurationSeconds:t.monitorDurationSeconds},hbarFees:t.hbarFees||[],tokenFees:t.tokenFees||[],...void 0!==t.exemptAccountIds&&{exemptAccountIds:t.exemptAccountIds},...void 0!==t.defaultCollectorAccount&&{defaultCollectorAccount:t.defaultCollectorAccount}})}}const ft=Je({action:Qe(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:Ke().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class gt extends d{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=ft}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,r={action:e};void 0!==t&&(r.requestKey=t),await n.manageConnectionRequests(r);const i=await n.execute();return"rawResult"in i?i.rawResult:i}}const mt=Je({requestKey:Ke().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:ze().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:We(Ke()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class yt extends u{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=mt,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const vt=Je({accountId:Ke().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:He().optional().describe("Optional: Force refresh from the network instead of using cache.")});class bt extends d{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=vt}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,r={accountId:e};void 0!==t&&(r.disableCache=t),await n.retrieveProfile(r);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return i}}const wt=Je({});class _t extends d{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=wt}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}const It=s.join(c.cwd(),".env");class Ct{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const t=e?.disableLogging||"true"===c.env.DISABLE_LOGGING;this.logger=new r.Logger({module:"OpenConvaiState",silent:t}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new r.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const r=this.connectionsManager.getConnectionByTopicId(e);if(r)return this.convertToActiveConnection(r);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||c.env.ENV_FILE_PATH||".env",r=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const s={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const r=[...n.split("\n")];for(const[i,s]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${i}=`));-1!==e?r[e]=`${i}=${s}`:r.push(`${i}=${s}`)}i.writeFileSync(e,r.join("\n"))}(n,s)}}function Tt(e,t){return function(){return e.apply(t,arguments)}}const{toString:xt}=Object.prototype,{getPrototypeOf:At}=Object,{iterator:kt,toStringTag:St}=Symbol,Rt=(e=>t=>{const n=xt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Et=e=>(e=e.toLowerCase(),t=>Rt(t)===e),Ot=e=>t=>typeof t===e,{isArray:Nt}=Array,Pt=Ot("undefined");const qt=Et("ArrayBuffer");const $t=Ot("string"),Mt=Ot("function"),Ft=Ot("number"),jt=e=>null!==e&&"object"==typeof e,Bt=e=>{if("object"!==Rt(e))return!1;const t=At(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||St in e||kt in e)},Dt=Et("Date"),Lt=Et("File"),Ut=Et("Blob"),Zt=Et("FileList"),Kt=Et("URLSearchParams"),[zt,Ht,Vt,Wt]=["ReadableStream","Request","Response","Headers"].map(Et);function Jt(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let r,i;if("object"!=typeof e&&(e=[e]),Nt(e))for(r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else{const i=n?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(r=0;r<s;r++)o=i[r],t.call(null,e[o],o,e)}}function Gt(e,t){t=t.toLowerCase();const n=Object.keys(e);let r,i=n.length;for(;i-- >0;)if(r=n[i],t===r.toLowerCase())return r;return null}const Xt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:o,Qt=e=>!Pt(e)&&e!==Xt;const Yt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&At(Uint8Array)),en=Et("HTMLFormElement"),tn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),nn=Et("RegExp"),rn=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Jt(n,(n,i)=>{let s;!1!==(s=t(n,i,e))&&(r[i]=s||n)}),Object.defineProperties(e,r)};const sn=Et("AsyncFunction"),on=(an="function"==typeof a.setImmediate,cn=Mt(Xt.postMessage),an?a.setImmediate:cn?(un=`axios@${Math.random()}`,dn=[],Xt.addEventListener("message",({source:e,data:t})=>{e===Xt&&t===un&&dn.length&&dn.shift()()},!1),e=>{dn.push(e),Xt.postMessage(un,"*")}):e=>setTimeout(e));var an,cn,un,dn;const ln="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Xt):void 0!==c&&c.nextTick||on,hn={isArray:Nt,isArrayBuffer:qt,isBuffer:function(e){return null!==e&&!Pt(e)&&null!==e.constructor&&!Pt(e.constructor)&&Mt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Mt(e.append)&&("formdata"===(t=Rt(e))||"object"===t&&Mt(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&qt(e.buffer),t},isString:$t,isNumber:Ft,isBoolean:e=>!0===e||!1===e,isObject:jt,isPlainObject:Bt,isReadableStream:zt,isRequest:Ht,isResponse:Vt,isHeaders:Wt,isUndefined:Pt,isDate:Dt,isFile:Lt,isBlob:Ut,isRegExp:nn,isFunction:Mt,isStream:e=>jt(e)&&Mt(e.pipe),isURLSearchParams:Kt,isTypedArray:Yt,isFileList:Zt,forEach:Jt,merge:function e(){const{caseless:t}=Qt(this)&&this||{},n={},r=(r,i)=>{const s=t&&Gt(n,i)||i;Bt(n[s])&&Bt(r)?n[s]=e(n[s],r):Bt(r)?n[s]=e({},r):Nt(r)?n[s]=r.slice():n[s]=r};for(let i=0,s=arguments.length;i<s;i++)arguments[i]&&Jt(arguments[i],r);return n},extend:(e,t,n,{allOwnKeys:r}={})=>(Jt(t,(t,r)=>{n&&Mt(t)?e[r]=Tt(t,n):e[r]=t},{allOwnKeys:r}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,r)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],r&&!r(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==n&&At(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Rt,kindOfTest:Et,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return-1!==r&&r===n},toArray:e=>{if(!e)return null;if(Nt(e))return e;let t=e.length;if(!Ft(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[kt]).call(e);let r;for(;(r=n.next())&&!r.done;){const n=r.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const r=[];for(;null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:en,hasOwnProperty:tn,hasOwnProp:tn,reduceDescriptors:rn,freezeMethods:e=>{rn(e,(t,n)=>{if(Mt(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=e[n];Mt(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},r=e=>{e.forEach(e=>{n[e]=!0})};return Nt(e)?r(e):r(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Gt,global:Xt,isContextDefined:Qt,isSpecCompliantForm:function(e){return!!(e&&Mt(e.append)&&"FormData"===e[St]&&e[kt])},toJSONObject:e=>{const t=new Array(10),n=(e,r)=>{if(jt(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[r]=e;const i=Nt(e)?[]:{};return Jt(e,(e,t)=>{const s=n(e,r+1);!Pt(s)&&(i[t]=s)}),t[r]=void 0,i}}return e};return n(e,0)},isAsyncFn:sn,isThenable:e=>e&&(jt(e)||Mt(e))&&Mt(e.then)&&Mt(e.catch),setImmediate:on,asap:ln,isIterable:e=>null!=e&&Mt(e[kt])};function pn(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}hn.inherits(pn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:hn.toJSONObject(this.config),code:this.code,status:this.status}}});const fn=pn.prototype,gn={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{gn[e]={value:e}}),Object.defineProperties(pn,gn),Object.defineProperty(fn,"isAxiosError",{value:!0}),pn.from=(e,t,n,r,i,s)=>{const o=Object.create(fn);return hn.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),pn.call(o,e.message,t,n,r,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function mn(e){return hn.isPlainObject(e)||hn.isArray(e)}function yn(e){return hn.endsWith(e,"[]")?e.slice(0,-2):e}function vn(e,t,n){return e?e.concat(t).map(function(e,t){return e=yn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const bn=hn.toFlatObject(hn,{},null,function(e){return/^is[A-Z]/.test(e)});function wn(e,n,r){if(!hn.isObject(e))throw new TypeError("target must be an object");n=n||new FormData;const i=(r=hn.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!hn.isUndefined(t[e])})).metaTokens,s=r.visitor||d,o=r.dots,a=r.indexes,c=(r.Blob||"undefined"!=typeof Blob&&Blob)&&hn.isSpecCompliantForm(n);if(!hn.isFunction(s))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(hn.isDate(e))return e.toISOString();if(hn.isBoolean(e))return e.toString();if(!c&&hn.isBlob(e))throw new pn("Blob is not supported. Use a Buffer instead.");return hn.isArrayBuffer(e)||hn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):t.Buffer.from(e):e}function d(e,t,r){let s=e;if(e&&!r&&"object"==typeof e)if(hn.endsWith(t,"{}"))t=i?t:t.slice(0,-2),e=JSON.stringify(e);else if(hn.isArray(e)&&function(e){return hn.isArray(e)&&!e.some(mn)}(e)||(hn.isFileList(e)||hn.endsWith(t,"[]"))&&(s=hn.toArray(e)))return t=yn(t),s.forEach(function(e,r){!hn.isUndefined(e)&&null!==e&&n.append(!0===a?vn([t],r,o):null===a?t:t+"[]",u(e))}),!1;return!!mn(e)||(n.append(vn(r,t,o),u(e)),!1)}const l=[],h=Object.assign(bn,{defaultVisitor:d,convertValue:u,isVisitable:mn});if(!hn.isObject(e))throw new TypeError("data must be an object");return function e(t,r){if(!hn.isUndefined(t)){if(-1!==l.indexOf(t))throw Error("Circular reference detected in "+r.join("."));l.push(t),hn.forEach(t,function(t,i){!0===(!(hn.isUndefined(t)||null===t)&&s.call(n,t,hn.isString(i)?i.trim():i,r,h))&&e(t,r?r.concat(i):[i])}),l.pop()}}(e),n}function _n(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function In(e,t){this._pairs=[],e&&wn(e,this,t)}const Cn=In.prototype;function Tn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xn(e,t,n){if(!t)return e;const r=n&&n.encode||Tn;hn.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let s;if(s=i?i(t,n):hn.isURLSearchParams(t)?t.toString():new In(t,n).toString(r),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Cn.append=function(e,t){this._pairs.push([e,t])},Cn.toString=function(e){const t=e?function(t){return e.call(this,t,_n)}:_n;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class An{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){hn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const kn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Sn={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:In,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Rn="undefined"!=typeof window&&"undefined"!=typeof document,En="object"==typeof navigator&&navigator||void 0,On=Rn&&(!En||["ReactNative","NativeScript","NS"].indexOf(En.product)<0),Nn="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Pn=Rn&&window.location.href||"http://localhost",qn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Rn,hasStandardBrowserEnv:On,hasStandardBrowserWebWorkerEnv:Nn,navigator:En,origin:Pn},Symbol.toStringTag,{value:"Module"})),...Sn};function $n(e){function t(e,n,r,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&hn.isArray(r)?r.length:s,a)return hn.hasOwnProp(r,s)?r[s]=[r[s],n]:r[s]=n,!o;r[s]&&hn.isObject(r[s])||(r[s]=[]);return t(e,n,r[s],i)&&hn.isArray(r[s])&&(r[s]=function(e){const t={},n=Object.keys(e);let r;const i=n.length;let s;for(r=0;r<i;r++)s=n[r],t[s]=e[s];return t}(r[s])),!o}if(hn.isFormData(e)&&hn.isFunction(e.entries)){const n={};return hn.forEachEntry(e,(e,r)=>{t(function(e){return hn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),r,n,0)}),n}return null}const Mn={transitional:kn,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",r=n.indexOf("application/json")>-1,i=hn.isObject(e);i&&hn.isHTMLForm(e)&&(e=new FormData(e));if(hn.isFormData(e))return r?JSON.stringify($n(e)):e;if(hn.isArrayBuffer(e)||hn.isBuffer(e)||hn.isStream(e)||hn.isFile(e)||hn.isBlob(e)||hn.isReadableStream(e))return e;if(hn.isArrayBufferView(e))return e.buffer;if(hn.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return wn(e,new qn.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return qn.isNode&&hn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=hn.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return wn(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||r?(t.setContentType("application/json",!1),function(e,t,n){if(hn.isString(e))try{return(t||JSON.parse)(e),hn.trim(e)}catch(r){if("SyntaxError"!==r.name)throw r}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Mn.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(hn.isResponse(e)||hn.isReadableStream(e))return e;if(e&&hn.isString(e)&&(n&&!this.responseType||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(i){if(n){if("SyntaxError"===i.name)throw pn.from(i,pn.ERR_BAD_RESPONSE,this,null,this.response);throw i}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:qn.classes.FormData,Blob:qn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hn.forEach(["delete","get","head","post","put","patch"],e=>{Mn.headers[e]={}});const Fn=hn.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),jn=Symbol("internals");function Bn(e){return e&&String(e).trim().toLowerCase()}function Dn(e){return!1===e||null==e?e:hn.isArray(e)?e.map(Dn):String(e)}function Ln(e,t,n,r,i){return hn.isFunction(r)?r.call(this,t,n):(i&&(t=n),hn.isString(t)?hn.isString(r)?-1!==t.indexOf(r):hn.isRegExp(r)?r.test(t):void 0:void 0)}let Un=class{constructor(e){e&&this.set(e)}set(e,t,n){const r=this;function i(e,t,n){const i=Bn(t);if(!i)throw new Error("header name must be a non-empty string");const s=hn.findKey(r,i);(!s||void 0===r[s]||!0===n||void 0===n&&!1!==r[s])&&(r[s||t]=Dn(e))}const s=(e,t)=>hn.forEach(e,(e,n)=>i(e,n,t));if(hn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(hn.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,r,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),n=e.substring(0,i).trim().toLowerCase(),r=e.substring(i+1).trim(),!n||t[n]&&Fn[n]||("set-cookie"===n?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t})(e),t);else if(hn.isObject(e)&&hn.isIterable(e)){let n,r,i={};for(const t of e){if(!hn.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[r=t[0]]=(n=i[r])?hn.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,n);return this}get(e,t){if(e=Bn(e)){const n=hn.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}(e);if(hn.isFunction(t))return t.call(this,e,n);if(hn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Bn(e)){const n=hn.findKey(this,e);return!(!n||void 0===this[n]||t&&!Ln(0,this[n],n,t))}return!1}delete(e,t){const n=this;let r=!1;function i(e){if(e=Bn(e)){const i=hn.findKey(n,e);!i||t&&!Ln(0,n[i],i,t)||(delete n[i],r=!0)}}return hn.isArray(e)?e.forEach(i):i(e),r}clear(e){const t=Object.keys(this);let n=t.length,r=!1;for(;n--;){const i=t[n];e&&!Ln(0,this[i],i,e,!0)||(delete this[i],r=!0)}return r}normalize(e){const t=this,n={};return hn.forEach(this,(r,i)=>{const s=hn.findKey(n,i);if(s)return t[s]=Dn(r),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(i):String(i).trim();o!==i&&delete t[i],t[o]=Dn(r),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return hn.forEach(this,(n,r)=>{null!=n&&!1!==n&&(t[r]=e&&hn.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){const t=(this[jn]=this[jn]={accessors:{}}).accessors,n=this.prototype;function r(e){const r=Bn(e);t[r]||(!function(e,t){const n=hn.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(e,n,i){return this[r].call(this,t,e,n,i)},configurable:!0})})}(n,e),t[r]=!0)}return hn.isArray(e)?e.forEach(r):r(e),this}};function Zn(e,t){const n=this||Mn,r=t||n,i=Un.from(r.headers);let s=r.data;return hn.forEach(e,function(e){s=e.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function Kn(e){return!(!e||!e.__CANCEL__)}function zn(e,t,n){pn.call(this,null==e?"canceled":e,pn.ERR_CANCELED,t,n),this.name="CanceledError"}function Hn(e,t,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(new pn("Request failed with status code "+n.status,[pn.ERR_BAD_REQUEST,pn.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}Un.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),hn.reduceDescriptors(Un.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),hn.freezeMethods(Un),hn.inherits(zn,pn,{__CANCEL__:!0});const Vn=(e,t,n=3)=>{let r=0;const i=function(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),u=r[o];i||(i=c),n[s]=a,r[s]=c;let d=o,l=0;for(;d!==s;)l+=n[d++],d%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const h=u&&c-u;return h?Math.round(1e3*l/h):void 0}}(50,250);return function(e,t){let n,r,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,n=null,r&&(clearTimeout(r),r=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(n=e,r||(r=setTimeout(()=>{r=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-r,c=i(a);r=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:n,lengthComputable:null!=o,[t?"download":"upload"]:!0})},n)},Wn=(e,t)=>{const n=null!=e;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Jn=e=>(...t)=>hn.asap(()=>e(...t)),Gn=qn.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,qn.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(qn.origin),qn.navigator&&/(msie|trident)/i.test(qn.navigator.userAgent)):()=>!0,Xn=qn.hasStandardBrowserEnv?{write(e,t,n,r,i,s){const o=[e+"="+encodeURIComponent(t)];hn.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),hn.isString(r)&&o.push("path="+r),hn.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Qn(e,t,n){let r=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(r||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Yn=e=>e instanceof Un?{...e}:e;function er(e,t){t=t||{};const n={};function r(e,t,n,r){return hn.isPlainObject(e)&&hn.isPlainObject(t)?hn.merge.call({caseless:r},e,t):hn.isPlainObject(t)?hn.merge({},t):hn.isArray(t)?t.slice():t}function i(e,t,n,i){return hn.isUndefined(t)?hn.isUndefined(e)?void 0:r(void 0,e,0,i):r(e,t,0,i)}function s(e,t){if(!hn.isUndefined(t))return r(void 0,t)}function o(e,t){return hn.isUndefined(t)?hn.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function a(n,i,s){return s in t?r(n,i):s in e?r(void 0,n):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,n)=>i(Yn(e),Yn(t),0,!0)};return hn.forEach(Object.keys(Object.assign({},e,t)),function(r){const s=c[r]||i,o=s(e[r],t[r],r);hn.isUndefined(o)&&s!==a||(n[r]=o)}),n}const tr=e=>{const t=er({},e);let n,{data:r,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Un.from(a),t.url=xn(Qn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),hn.isFormData(r))if(qn.hasStandardBrowserEnv||qn.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(n=a.getContentType())){const[e,...t]=n?n.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(qn.hasStandardBrowserEnv&&(i&&hn.isFunction(i)&&(i=i(t)),i||!1!==i&&Gn(t.url))){const e=s&&o&&Xn.read(o);e&&a.set(s,e)}return t},nr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const r=tr(e);let i=r.data;const s=Un.from(r.headers).normalize();let o,a,c,u,d,{responseType:l,onUploadProgress:h,onDownloadProgress:p}=r;function f(){u&&u(),d&&d(),r.cancelToken&&r.cancelToken.unsubscribe(o),r.signal&&r.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const r=Un.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Hn(function(e){t(e),f()},function(e){n(e),f()},{data:l&&"text"!==l&&"json"!==l?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:r,config:e,request:g}),g=null}g.open(r.method.toUpperCase(),r.url,!0),g.timeout=r.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(n(new pn("Request aborted",pn.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new pn("Network Error",pn.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const i=r.transitional||kn;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),n(new pn(t,i.clarifyTimeoutError?pn.ETIMEDOUT:pn.ECONNABORTED,e,g)),g=null},void 0===i&&s.setContentType(null),"setRequestHeader"in g&&hn.forEach(s.toJSON(),function(e,t){g.setRequestHeader(t,e)}),hn.isUndefined(r.withCredentials)||(g.withCredentials=!!r.withCredentials),l&&"json"!==l&&(g.responseType=r.responseType),p&&([c,d]=Vn(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,u]=Vn(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",u)),(r.cancelToken||r.signal)&&(o=t=>{g&&(n(!t||t.type?new zn(null,e,g):t),g.abort(),g=null)},r.cancelToken&&r.cancelToken.subscribe(o),r.signal&&(r.signal.aborted?o():r.signal.addEventListener("abort",o)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(r.url);y&&-1===qn.protocols.indexOf(y)?n(new pn("Unsupported protocol "+y+":",pn.ERR_BAD_REQUEST,e)):g.send(i||null)})},rr=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,r=new AbortController;const i=function(e){if(!n){n=!0,o();const t=e instanceof Error?e:this.reason;r.abort(t instanceof pn?t:new zn(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,i(new pn(`timeout ${t} of ms exceeded`,pn.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=r;return a.unsubscribe=()=>hn.asap(o),a}},ir=function*(e,t){let n=e.byteLength;if(n<t)return void(yield e);let r,i=0;for(;i<n;)r=i+t,yield e.slice(i,r),i=r},sr=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)break;yield n}}finally{await t.cancel()}},or=(e,t,n,r)=>{const i=async function*(e,t){for await(const n of sr(e))yield*ir(n,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,r&&r(e))};return new ReadableStream({async pull(e){try{const{done:t,value:r}=await i.next();if(t)return a(),void e.close();let s=r.byteLength;if(n){let e=o+=s;n(e)}e.enqueue(new Uint8Array(r))}catch(t){throw a(t),t}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},ar="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,cr=ar&&"function"==typeof ReadableStream,ur=ar&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),dr=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},lr=cr&&dr(()=>{let e=!1;const t=new Request(qn.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),hr=cr&&dr(()=>hn.isReadableStream(new Response("").body)),pr={stream:hr&&(e=>e.body)};var fr;ar&&(fr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!pr[e]&&(pr[e]=hn.isFunction(fr[e])?t=>t[e]():(t,n)=>{throw new pn(`Response type '${e}' is not supported`,pn.ERR_NOT_SUPPORT,n)})}));const gr=async(e,t)=>{const n=hn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(hn.isBlob(e))return e.size;if(hn.isSpecCompliantForm(e)){const t=new Request(qn.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return hn.isArrayBufferView(e)||hn.isArrayBuffer(e)?e.byteLength:(hn.isURLSearchParams(e)&&(e+=""),hn.isString(e)?(await ur(e)).byteLength:void 0)})(t):n},mr={http:null,xhr:nr,fetch:ar&&(async e=>{let{url:t,method:n,data:r,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:u,headers:d,withCredentials:l="same-origin",fetchOptions:h}=tr(e);u=u?(u+"").toLowerCase():"text";let p,f=rr([i,s&&s.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&lr&&"get"!==n&&"head"!==n&&0!==(m=await gr(d,r))){let e,n=new Request(t,{method:"POST",body:r,duplex:"half"});if(hn.isFormData(r)&&(e=n.headers.get("content-type"))&&d.setContentType(e),n.body){const[e,t]=Wn(m,Vn(Jn(c)));r=or(n.body,65536,e,t)}}hn.isString(l)||(l=l?"include":"omit");const i="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:n.toUpperCase(),headers:d.normalize().toJSON(),body:r,duplex:"half",credentials:i?l:void 0});let s=await fetch(p,h);const o=hr&&("stream"===u||"response"===u);if(hr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=hn.toFiniteNumber(s.headers.get("content-length")),[n,r]=a&&Wn(t,Vn(Jn(a),!0))||[];s=new Response(or(s.body,65536,n,()=>{r&&r(),g&&g()}),e)}u=u||"text";let y=await pr[hn.findKey(pr,u)||"text"](s,e);return!o&&g&&g(),await new Promise((t,n)=>{Hn(t,n,{data:y,headers:Un.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:p})})}catch(y){if(g&&g(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new pn("Network Error",pn.ERR_NETWORK,e,p),{cause:y.cause||y});throw pn.from(y,y&&y.code,e,p)}})};hn.forEach(mr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const yr=e=>`- ${e}`,vr=e=>hn.isFunction(e)||null===e||!1===e,br=e=>{e=hn.isArray(e)?e:[e];const{length:t}=e;let n,r;const i={};for(let s=0;s<t;s++){let t;if(n=e[s],r=n,!vr(n)&&(r=mr[(t=String(n)).toLowerCase()],void 0===r))throw new pn(`Unknown adapter '${t}'`);if(r)break;i[t||"#"+s]=r}if(!r){const e=Object.entries(i).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new pn("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(yr).join("\n"):" "+yr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r};function wr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new zn(null,e)}function _r(e){wr(e),e.headers=Un.from(e.headers),e.data=Zn.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return br(e.adapter||Mn.adapter)(e).then(function(t){return wr(e),t.data=Zn.call(e,e.transformResponse,t),t.headers=Un.from(t.headers),t},function(t){return Kn(t)||(wr(e),t&&t.response&&(t.response.data=Zn.call(e,e.transformResponse,t.response),t.response.headers=Un.from(t.response.headers))),Promise.reject(t)})}const Ir="1.10.0",Cr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Cr[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Tr={};Cr.transitional=function(e,t,n){function r(e,t){return"[Axios v"+Ir+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,i,s)=>{if(!1===e)throw new pn(r(i," has been removed"+(t?" in "+t:"")),pn.ERR_DEPRECATED);return t&&!Tr[i]&&(Tr[i]=!0,console.warn(r(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,i,s)}},Cr.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const xr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new pn("options must be an object",pn.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const t=e[s],n=void 0===t||o(t,s,e);if(!0!==n)throw new pn("option "+s+" must be "+n,pn.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new pn("Unknown option "+s,pn.ERR_BAD_OPTION)}},validators:Cr},Ar=xr.validators;let kr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new An,response:new An}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{n.stack?t&&!String(n.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(n.stack+="\n"+t):n.stack=t}catch(r){}}throw n}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=er(this.defaults,t);const{transitional:n,paramsSerializer:r,headers:i}=t;void 0!==n&&xr.assertOptions(n,{silentJSONParsing:Ar.transitional(Ar.boolean),forcedJSONParsing:Ar.transitional(Ar.boolean),clarifyTimeoutError:Ar.transitional(Ar.boolean)},!1),null!=r&&(hn.isFunction(r)?t.paramsSerializer={serialize:r}:xr.assertOptions(r,{encode:Ar.function,serialize:Ar.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xr.assertOptions(t,{baseUrl:Ar.spelling("baseURL"),withXsrfToken:Ar.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&hn.merge(i.common,i[t.method]);i&&hn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=Un.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const c=[];let u;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let d,l=0;if(!a){const e=[_r.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),d=e.length,u=Promise.resolve(t);l<d;)u=u.then(e[l++],e[l++]);return u}d=o.length;let h=t;for(l=0;l<d;){const e=o[l++],t=o[l++];try{h=e(h)}catch(p){t.call(this,p);break}}try{u=_r.call(this,h)}catch(p){return Promise.reject(p)}for(l=0,d=c.length;l<d;)u=u.then(c[l++],c[l++]);return u}getUri(e){return xn(Qn((e=er(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};hn.forEach(["delete","get","head","options"],function(e){kr.prototype[e]=function(t,n){return this.request(er(n||{},{method:e,url:t,data:(n||{}).data}))}}),hn.forEach(["post","put","patch"],function(e){function t(t){return function(n,r,i){return this.request(er(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}kr.prototype[e]=t(),kr.prototype[e+"Form"]=t(!0)});const Sr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Sr).forEach(([e,t])=>{Sr[t]=e});const Rr=function e(t){const n=new kr(t),r=Tt(kr.prototype.request,n);return hn.extend(r,kr.prototype,n,{allOwnKeys:!0}),hn.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return e(er(t,n))},r}(Mn);Rr.Axios=kr,Rr.CanceledError=zn,Rr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const r=new Promise(e=>{n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e(function(e,r,i){n.reason||(n.reason=new zn(e,r,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},Rr.isCancel=Kn,Rr.VERSION=Ir,Rr.toFormData=wn,Rr.AxiosError=pn,Rr.Cancel=Rr.CanceledError,Rr.all=function(e){return Promise.all(e)},Rr.spread=function(e){return function(t){return e.apply(null,t)}},Rr.isAxiosError=function(e){return hn.isObject(e)&&!0===e.isAxiosError},Rr.mergeConfig=er,Rr.AxiosHeaders=Un,Rr.formToJSON=e=>$n(hn.isHTMLForm(e)?new FormData(e):e),Rr.getAdapter=br,Rr.HttpStatusCode=Sr,Rr.default=Rr;const{Axios:Er,AxiosError:Or,CanceledError:Nr,isCancel:Pr,CancelToken:qr,VERSION:$r,all:Mr,Cancel:Fr,isAxiosError:jr,spread:Br,toFormData:Dr,AxiosHeaders:Lr,HttpStatusCode:Ur,formToJSON:Zr,getAdapter:Kr,mergeConfig:zr}=Rr,Hr="ConnectionsManager not initialized";class Vr extends n.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const s=this.hederaKit.signer.getAccountId().toString(),o=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new r.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new r.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:o,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,n,r){try{const i=await this.standardClient.handleConnectionRequest(e,t,n,r);return i&&i.connectionTopicId&&"object"==typeof i.connectionTopicId&&"toString"in i.connectionTopicId&&(i.connectionTopicId=i.connectionTopicId.toString()),i}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async sendMessage(e,t,n){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const r=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:r.topicSequenceNumber?.toNumber(),receipt:r,transactionId:"transactionId"in r?r.transactionId?.toString():void 0}}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const n=await Rr.get(e,{responseType:"arraybuffer"}),r=t.Buffer.from(n.data),i=new URL(e).pathname;return{buffer:r,filename:s.basename(i)||"profile.png"}}{if(!i.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=i.readFileSync(e);return{buffer:t,filename:s.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const n=await Rr.get(e.url,{responseType:"arraybuffer"}),r=t.Buffer.from(n.data);return{buffer:r,filename:e.filename||"profile.png"}}if(e.path){if(!i.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=i.readFileSync(e.path);return{buffer:t,filename:e.filename||s.basename(e.path)}}return null}catch(n){return this.logger.error("Failed to load profile picture:",n),null}}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?t.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let t=null;e.profilePicture&&(t=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==t?.buffer&&{pfpBuffer:t.buffer},...void 0!==t?.filename&&{pfpFileName:t.filename}};if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,i,s)}const i=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.state?.agentMetadata?.accountId}}}catch(t){throw this.logger.error("Failed to register agent:",t),t}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const n=t.topicInfo.inboundTopic;let r;void 0!==e.memo?r=e.memo:(r=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${r}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const i=await this.submitConnectionRequest(n,r);this.executeResult={success:!0,transactionId:"transactionId"in i?i.transactionId?.toString():void 0,receipt:i,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...i}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const n=this.stateManager?.getCurrentAgent();if(!n)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(Hr);await i.fetchConnectionData(n.accountId);const s=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const o=s.targetAccountId,a=s.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,i)}const u=await this.getInboundTopicId(),d=await this.handleConnectionRequest(u,o,a,c);let l=d?.connectionTopicId;if(l&&"object"==typeof l&&"toString"in l&&(l=l?.toString()),!l||"string"!=typeof l)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(l)}`);if(this.stateManager){const e=s.targetAgentName||`Agent ${o}`;s.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${o}'.`);let n=s.targetInboundTopicId||"";if(!n)try{const e=await this.getAgentProfile(o);e.success&&e.topicInfo?.inboundTopic&&(n=e.topicInfo.inboundTopic)}catch(t){this.logger.warn(`Could not fetch profile for ${o}:`,t)}const r={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:l,status:"established",created:new Date};this.stateManager.addActiveConnection(r),i.markConnectionRequestProcessed(s.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId:l,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:d}}}catch(n){throw this.logger.error("Failed to accept connection:",n),n}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let n;if(e.targetIdentifier.includes("@")){const t=e.targetIdentifier.split("@");if(2===t.length){const r=t[1];n=this.stateManager.getConnectionByIdentifier(r),n||this.addNote(`Could not find connection using request key '${e.targetIdentifier}', extracted account ID '${r}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(e.targetIdentifier)),!n){const t=this.stateManager.listConnections().map(e=>`${e.targetAccountId} (${e.connectionTopicId})`);throw new Error(`Connection not found for identifier: ${e.targetIdentifier}. Available connections: ${t.join(", ")||"none"}. Use 'list_connections' to see details.`)}let r=n.connectionTopicId;if(r&&"object"==typeof r&&"toString"in r&&(r=r?.toString()),!r||"string"!=typeof r)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(r)} (type: ${typeof r})`);const i=n.targetAgentName,s=`${t.inboundTopicId}@${t.accountId}`,o=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!o.sequenceNumber)throw new Error("Failed to send message");let a=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):a=await this.monitorResponses(r,s,o.sequenceNumber),this.executeResult={success:!0,transactionId:o.transactionId,receipt:o.receipt,scheduleId:void 0,rawResult:{targetAgentName:i,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:o.sequenceNumber,reply:a,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:o}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let r=0;for(;r<30;){try{const r=await this.getMessageStream(e);for(const e of r.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(i){this.logger.error(`Error monitoring responses: ${i}`)}await new Promise(e=>setTimeout(e,4e3)),r++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:t=!1,targetAccountId:n,monitorDurationSeconds:i=120,hbarFees:s=[],tokenFees:o=[],exemptAccountIds:a=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const u=await this.getInboundTopicId(),d=Date.now()+1e3*i;let l=0,h=0;const p=new Set;for(;Date.now()<d;){try{const e=(await this.getMessages(u)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||p.has(e))continue;const d=i.operator_id?.split("@")[1];if(d)if(l++,n&&d!==n)this.logger.info(`Skipping request from ${d} (not target account)`);else if(t||n===d){let t;if(this.logger.info(`Accepting connection request from ${d}`),s.length>0||o.length>0){const e=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,a)}for(const t of o){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,a)}t=e}await this.handleConnectionRequest(u,d,e,t),p.add(e),h++}}}catch(f){this.logger.error("Error during connection monitoring:",f)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:l,acceptedConnections:h,monitorDurationSeconds:i,processedRequestIds:Array.from(p)}},this.addNote(`Monitoring completed. Found ${l} requests, accepted ${h}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(Hr);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const r=t.getPendingRequests(),i=t.getConnectionsNeedingConfirmation(),s=[...r,...i];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:s.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const n=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,n=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const r=e.filter(e=>"established"===e.status),i=e.filter(e=>e.isPending),s=e.filter(e=>e.needsConfirmation);let o="";r.length>0&&(o+=`🟢 Active Connections (${r.length}):\n`,r.forEach((e,n)=>{o+=this.formatConnection(e,n,t)}),o+="\n"),n&&s.length>0&&(o+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach((e,n)=>{o+=this.formatConnection(e,n,t)}),o+="\n"),n&&i.length>0&&(o+=`⚪ Pending Connection Requests (${i.length}):\n`,i.forEach((e,n)=>{o+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:o.trim(),activeCount:r.length,pendingCount:i.length,needsConfirmationCount:s.length}}}catch(r){this.logger.error("Failed to list connections:",r),this.executeResult={success:!1,error:`Failed to list connections: ${r instanceof Error?r.message:String(r)}`}}return this}formatConnection(e,t,n){const r=e;let i=`${t+1}. ${r.profileInfo?.display_name||r.targetAgentName||"Unknown Agent"} (${r.targetAccountId})\n`;i+=` Topic: ${r.isPending?"(Pending Request)":r.connectionTopicId}\n`;if(i+=` Status: ${r.status||"unknown"}\n`,n){if(r.profileInfo?.bio&&(i+=` Bio: ${r.profileInfo.bio.substring(0,100)}${r.profileInfo.bio.length>100?"...":""}\n`),r.created){i+=` ${r.isPending?"Request sent":"Connection established"}: ${r.created.toLocaleString()}\n`}r.lastActivity&&(i+=` Last activity: ${r.lastActivity.toLocaleString()}\n`)}return i}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(Hr),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const r of n)this.stateManager.addActiveConnection(r);return n}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const r=t.targetAgentName,i=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${r} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${i})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let o=[],a=i;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;o=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${i}`),o=t.filter(e=>1e6*e.timestamp>i),o.length>0&&(a=o.reduce((e,t)=>Math.max(e,1e6*t.timestamp),i));if(0===o.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${r} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${o.length} message(s).`);let u=c?`Latest message(s) from ${r}:\n`:`New messages from ${r}:\n`;const d=[];for(const e of o){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}u+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,d.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(s){const t=`Error processing message (Seq: ${e.sequence_number}): ${s instanceof Error?s.message:String(s)}`;this.logger.error(t),u+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>i&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:d,formattedOutput:u.trim(),targetAgentName:r,connectionTopicId:n}}}catch(s){this.logger.error(`Failed to check messages for topic ${n}: ${s}`),this.executeResult={success:!1,error:`Error checking messages for ${r}: ${s instanceof Error?s.message:String(s)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const r=n.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${r}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const n=t.profile,r=t.topicInfo;let i=`Profile for ${e.accountId}:\n`;i+=`Name: ${n.name||"Unknown"}\n`,i+=`Bio: ${n.bio||"No bio provided"}\n`,i+=`Type: ${n.type||"Unknown"}\n`,i+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?i+=`Capabilities: ${n.capabilities.join(", ")}\n`:i+="Capabilities: None listed\n",r&&(i+=`Inbound Topic: ${r.inboundTopic||"Unknown"}\n`,i+=`Outbound Topic: ${r.outboundTopic||"Unknown"}\n`,i+=`Profile Topic: ${r.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(i+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(i+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:i,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class Wr extends n.BasePlugin{constructor(){super(...arguments),this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new n.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>n.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>n.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>n.PluginRegistry}),e.AcceptConnectionRequestTool=yt,e.BaseHCS10QueryTool=d,e.BaseHCS10TransactionTool=u,e.CheckMessagesTool=ut,e.ConnectionMonitorTool=pt,e.FindRegistrationsTool=lt,e.HCS10Builder=Vr,e.HCS10Client=class{constructor(e,t,n,i){this.standardClient=new r.HCS10Client({network:n,operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const s="true"===c.env.DISABLE_LOGGING;this.logger=new r.Logger({level:i?.logLevel||"info",silent:s})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,r){try{return await this.standardClient.handleConnectionRequest(e,t,n,r)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,r=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,r)}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),r=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return r?.metadata?.inboundTopicId&&r?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:r.metadata.inboundTopicId,outboundTopicId:r.metadata.outboundTopicId}),r}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,n,r){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,r);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,t){return this.standardClient=new r.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HbarPricePlugin=Wr,e.InitiateConnectionTool=st,e.ListConnectionsTool=at,e.ListUnapprovedConnectionRequestsTool=_t,e.ManageConnectionRequestsTool=gt,e.OpenConvaiState=Ct,e.RegisterAgentTool=tt,e.RetrieveProfileTool=bt,e.SendMessageToConnectionTool=rt,e.initializeStandardsAgentKit=async e=>{const t=e?.clientConfig||{},i=t.operatorId||c.env.HEDERA_OPERATOR_ID,s=t.operatorKey||c.env.HEDERA_OPERATOR_KEY,o=t.network||c.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===o?a="mainnet":("testnet"===o||console.warn(`Unsupported network specified: '${o}'. Defaulting to 'testnet'.`),a="testnet"),!i||!s)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const u="true"===c.env.DISABLE_LOGGING,d=r.Logger.getInstance({level:t.logLevel||"info",silent:u}),l=e?.stateManager||new Ct({defaultEnvFilePath:It,defaultPrefix:"TODD"});d.info("State manager initialized");const h=new n.ServerSigner(i,s,a),p=new n.HederaAgentKit(h);await p.initialize(),d.info(`HederaAgentKit initialized for ${i} on ${a}`);const f=new Vr(p,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:t.logLevel});let g,m;if(e?.monitoringClient){const e=new n.ServerSigner(i,s,a);g=new n.HederaAgentKit(e),await g.initialize(),m=new Vr(g,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new tt({hederaKit:p,hcs10Builder:f,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new lt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.retrieveProfileTool=new bt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.initiateConnectionTool=new st({hederaKit:p,hcs10Builder:f,logger:void 0}),y.listConnectionsTool=new at({hederaKit:p,hcs10Builder:f,logger:void 0}),y.sendMessageToConnectionTool=new rt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.checkMessagesTool=new ut({hederaKit:p,hcs10Builder:f,logger:void 0}),y.connectionMonitorTool=new pt({hederaKit:g||p,hcs10Builder:m||f,logger:void 0}),y.manageConnectionRequestsTool=new gt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.acceptConnectionRequestTool=new yt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new _t({hederaKit:p,hcs10Builder:f,logger:void 0}),d.info("All tools initialized")),{hederaKit:p,hcs10Builder:f,monitoringHederaKit:g,monitoringHcs10Builder:m,tools:y,stateManager:l}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("unenv/node/buffer"),require("hedera-agent-kit"),require("@hashgraphonline/standards-sdk"),require("unenv/node/fs"),require("unenv/node/path"),require("unenv/polyfill/globalthis"),require("unenv/node/timers"),require("unenv/node/process")):"function"==typeof define&&define.amd?define(["exports","unenv/node/buffer","hedera-agent-kit","@hashgraphonline/standards-sdk","unenv/node/fs","unenv/node/path","unenv/polyfill/globalthis","unenv/node/timers","unenv/node/process"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsAgentKit={},e["unenv/node/buffer"],e.HederaAgentKit,e.StandardsSDK,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],e.process)}(this,function(e,t,n,r,i,s,o,a,c){"use strict";class d extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class u extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var l,h,p;(h=l||(l={})).assertEqual=e=>{},h.assertIs=function(e){},h.assertNever=function(e){throw new Error},h.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},h.getValidEnumValues=e=>{const t=h.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const r of t)n[r]=e[r];return h.objectValues(n)},h.objectValues=e=>h.objectKeys(e).map(function(t){return e[t]}),h.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},h.find=(e,t)=>{for(const n of e)if(t(n))return n},h.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,h.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},h.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(p||(p={})).mergeShapes=(e,t)=>({...e,...t});const f=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),g=e=>{switch(typeof e){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(e)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(e)?f.array:null===e?f.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?f.promise:"undefined"!=typeof Map&&e instanceof Map?f.map:"undefined"!=typeof Set&&e instanceof Set?f.set:"undefined"!=typeof Date&&e instanceof Date?f.date:f.object;default:return f.unknown}},m=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class y extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};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(e){return e.message},n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(r);else if("invalid_return_type"===i.code)r(i.returnTypeError);else if("invalid_arguments"===i.code)r(i.argumentsError);else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof y))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}y.create=e=>new y(e);const v=(e,t)=>{let n;switch(e.code){case m.invalid_type:n=e.received===f.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,l.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:n=`Unrecognized key(s) in object: ${l.joinValues(e.keys,", ")}`;break;case m.invalid_union:n="Invalid input";break;case m.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${l.joinValues(e.options)}`;break;case m.invalid_enum_value:n=`Invalid enum value. Expected ${l.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:n="Invalid function arguments";break;case m.invalid_return_type:n="Invalid function return type";break;case m.invalid_date:n="Invalid date";break;case m.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:l.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case m.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case m.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case m.custom:n="Invalid input";break;case m.invalid_intersection_types:n="Intersection results could not be merged";break;case m.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:n="Number must be finite";break;default:n=t.defaultError,l.assertNever(e)}return{message:n}};let b=v;function w(e,t){const n=b,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(void 0!==i.message)return{...i,path:s,message:i.message};let a="";const c=r.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===v?void 0:v].filter(e=>!!e)});e.common.issues.push(r)}class _{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return I;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const r of t){const e=await r.key,t=await r.value;n.push({key:e,value:t})}return _.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:i}=r;if("aborted"===t.status)return I;if("aborted"===i.status)return I;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!r.alwaysSet||(n[t.value]=i.value)}return{status:e.value,value:n}}}const I=Object.freeze({status:"aborted"}),C=e=>({status:"dirty",value:e}),T=e=>({status:"valid",value:e}),x=e=>"aborted"===e.status,A=e=>"dirty"===e.status,k=e=>"valid"===e.status,S=e=>"undefined"!=typeof Promise&&e instanceof Promise;var R,E;(E=R||(R={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},E.toString=e=>"string"==typeof e?e:e?.message;class O{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}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 N=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new y(e.common.issues);return this._error=t,this._error}}};function P(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??i.defaultError}:void 0===i.data?{message:s??r??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:s??n??i.defaultError}},description:i}}class q{get description(){return this._def.description}_getType(e){return g(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _,ctx:{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(S(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)},r=this._parseSync({data:e,path:n.path,parent:n});return N(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return k(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>k(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(S(r)?r:Promise.resolve(r));return N(n,i)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const i=e(t),s=()=>r.addIssue({code:m.custom,...n(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(s(),!1)):!!i||(s(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new Pe({schema:this,typeName:Ue.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:e=>this["~validate"](e)}}optional(){return qe.create(this,this._def)}nullable(){return $e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ye.create(this)}promise(){return Ne.create(this,this._def)}or(e){return we.create([this,e],this._def)}and(e){return Ie.create(this,e,this._def)}transform(e){return new Pe({...P(this._def),schema:this,typeName:Ue.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Me({...P(this._def),innerType:this,defaultValue:t,typeName:Ue.ZodDefault})}brand(){return new Be({typeName:Ue.ZodBranded,type:this,...P(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Fe({...P(this._def),innerType:this,catchValue:t,typeName:Ue.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return De.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const $=/^c[^\s-]{8,}$/i,M=/^[0-9a-z]+$/,F=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[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,B=/^[a-z0-9_-]{21}$/i,D=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L=/^[-+]?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)?)??$/,U=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Z;const K=/^(?:(?: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])$/,z=/^(?:(?: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])$/,H=/^(([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]))$/,V=/^(([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])$/,W=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,J=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,G="((\\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])))",X=new RegExp(`^${G}$`);function Q(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Y(e){return new RegExp(`^${Q(e)}$`)}function ee(e){let t=`${G}T${Q(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function te(e,t){return!("v4"!==t&&t||!K.test(e))||!("v6"!==t&&t||!H.test(e))}function ne(e,t){if(!D.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return"object"==typeof i&&null!==i&&((!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||i.alg===t)))}catch{return!1}}function re(e,t){return!("v4"!==t&&t||!z.test(e))||!("v6"!==t&&t||!V.test(e))}class ie extends q{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==f.string){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.string,received:t.parsedType}),I}const t=new _;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const i=e.data.length>r.value,s=e.data.length<r.value;(i||s)&&(n=this._getOrReturnCtx(e,n),i?w(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):s&&w(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"email",code:m.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)Z||(Z=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Z.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"emoji",code:m.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"uuid",code:m.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)B.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"nanoid",code:m.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)$.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid",code:m.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)M.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid2",code:m.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)F.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ulid",code:m.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),w(n,{validation:"url",code:m.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"regex",code:m.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){ee(r).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){X.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Y(r).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?L.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"duration",code:m.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?te(e.data,r.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ip",code:m.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?ne(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"jwt",code:m.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?re(e.data,r.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cidr",code:m.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?W.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64",code:m.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?J.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64url",code:m.invalid_string,message:r.message}),t.dirty()):l.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:m.invalid_string,...R.errToObj(n)})}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...R.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...R.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...R.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...R.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...R.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...R.errToObj(t)})}nonempty(e){return this.min(1,R.errToObj(e))}trim(){return new ie({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function se(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}ie.create=e=>new ie({checks:[],typeName:Ue.ZodString,coerce:e?.coerce??!1,...P(e)});class oe extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==f.number){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.number,received:t.parsedType}),I}let t;const n=new _;for(const r of this._def.checks)if("int"===r.kind)l.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty());else if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==se(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_finite,message:r.message}),n.dirty()):l.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,r){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(r)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&l.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}oe.create=e=>new oe({checks:[],typeName:Ue.ZodNumber,coerce:e?.coerce||!1,...P(e)});class ae extends q{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)!==f.bigint)return this._getInvalidInput(e);let t;const n=new _;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):l.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.bigint,received:t.parsedType}),I}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,r){return new ae({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(r)}]})}_addCheck(e){return new ae({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ae.create=e=>new ae({checks:[],typeName:Ue.ZodBigInt,coerce:e?.coerce??!1,...P(e)});class ce extends q{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==f.boolean){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.boolean,received:t.parsedType}),I}return T(e.data)}}ce.create=e=>new ce({typeName:Ue.ZodBoolean,coerce:e?.coerce||!1,...P(e)});class de extends q{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==f.date){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.date,received:t.parsedType}),I}if(Number.isNaN(e.data.getTime())){return w(this._getOrReturnCtx(e),{code:m.invalid_date}),I}const t=new _;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):l.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:R.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:R.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}de.create=e=>new de({checks:[],coerce:e?.coerce||!1,typeName:Ue.ZodDate,...P(e)});class ue extends q{_parse(e){if(this._getType(e)!==f.symbol){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.symbol,received:t.parsedType}),I}return T(e.data)}}ue.create=e=>new ue({typeName:Ue.ZodSymbol,...P(e)});class le extends q{_parse(e){if(this._getType(e)!==f.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.undefined,received:t.parsedType}),I}return T(e.data)}}le.create=e=>new le({typeName:Ue.ZodUndefined,...P(e)});class he extends q{_parse(e){if(this._getType(e)!==f.null){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.null,received:t.parsedType}),I}return T(e.data)}}he.create=e=>new he({typeName:Ue.ZodNull,...P(e)});class pe extends q{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}}pe.create=e=>new pe({typeName:Ue.ZodAny,...P(e)});class fe extends q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}}fe.create=e=>new fe({typeName:Ue.ZodUnknown,...P(e)});class ge extends q{_parse(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.never,received:t.parsedType}),I}}ge.create=e=>new ge({typeName:Ue.ZodNever,...P(e)});class me extends q{_parse(e){if(this._getType(e)!==f.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.void,received:t.parsedType}),I}return T(e.data)}}me.create=e=>new me({typeName:Ue.ZodVoid,...P(e)});class ye extends q{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==f.array)return w(t,{code:m.invalid_type,expected:f.array,received:t.parsedType}),I;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(w(t,{code:e?m.too_big:m.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(w(t,{code:m.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(w(t,{code:m.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new O(t,e,t.path,n)))).then(e=>_.mergeArray(n,e));const i=[...t.data].map((e,n)=>r.type._parseSync(new O(t,e,t.path,n)));return _.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ye({...this._def,minLength:{value:e,message:R.toString(t)}})}max(e,t){return new ye({...this._def,maxLength:{value:e,message:R.toString(t)}})}length(e,t){return new ye({...this._def,exactLength:{value:e,message:R.toString(t)}})}nonempty(e){return this.min(1,e)}}function ve(e){if(e instanceof be){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=qe.create(ve(r))}return new be({...e._def,shape:()=>t})}return e instanceof ye?new ye({...e._def,type:ve(e.element)}):e instanceof qe?qe.create(ve(e.unwrap())):e instanceof $e?$e.create(ve(e.unwrap())):e instanceof Ce?Ce.create(e.items.map(e=>ve(e))):e}ye.create=(e,t)=>new ye({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ue.ZodArray,...P(t)});class be extends q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=l.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.object,received:t.parsedType}),I}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ge&&"strip"===this._def.unknownKeys))for(const a in n.data)i.includes(a)||s.push(a);const o=[];for(const a of i){const e=r[a],t=n.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new O(n,t,n.path,a)),alwaysSet:a in n.data})}if(this._def.catchall instanceof ge){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of s)o.push({key:{status:"valid",value:t},value:{status:"valid",value:n.data[t]}});else if("strict"===e)s.length>0&&(w(n,{code:m.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const r=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new O(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>_.mergeObjectSync(t,e)):_.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new be({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:R.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new be({...this._def,unknownKeys:"strip"})}passthrough(){return new be({...this._def,unknownKeys:"passthrough"})}extend(e){return new be({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new be({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ue.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new be({...this._def,catchall:e})}pick(e){const t={};for(const n of l.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new be({...this._def,shape:()=>t})}omit(e){const t={};for(const n of l.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new be({...this._def,shape:()=>t})}deepPartial(){return ve(this)}partial(e){const t={};for(const n of l.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new be({...this._def,shape:()=>t})}required(e){const t={};for(const n of l.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof qe;)e=e._def.innerType;t[n]=e}return new be({...this._def,shape:()=>t})}keyof(){return Re(l.objectKeys(this.shape))}}be.create=(e,t)=>new be({shape:()=>e,unknownKeys:"strip",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)}),be.strictCreate=(e,t)=>new be({shape:()=>e,unknownKeys:"strict",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)}),be.lazycreate=(e,t)=>new be({shape:e,unknownKeys:"strip",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)});class we extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const n=e.map(e=>new y(e.ctx.common.issues));return w(t,{code:m.invalid_union,unionErrors:n}),I});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=r.map(e=>new y(e));return w(t,{code:m.invalid_union,unionErrors:i}),I}}get options(){return this._def.options}}function _e(e,t){const n=g(e),r=g(t);if(e===t)return{valid:!0,data:e};if(n===f.object&&r===f.object){const n=l.objectKeys(t),r=l.objectKeys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const s of r){const n=_e(e[s],t[s]);if(!n.valid)return{valid:!1};i[s]=n.data}return{valid:!0,data:i}}if(n===f.array&&r===f.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const i=_e(e[r],t[r]);if(!i.valid)return{valid:!1};n.push(i.data)}return{valid:!0,data:n}}return n===f.date&&r===f.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}we.create=(e,t)=>new we({options:e,typeName:Ue.ZodUnion,...P(t)});class Ie extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(x(e)||x(r))return I;const i=_e(e.value,r.value);return i.valid?((A(e)||A(r))&&t.dirty(),{status:t.value,value:i.data}):(w(n,{code:m.invalid_intersection_types}),I)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ie.create=(e,t,n)=>new Ie({left:e,right:t,typeName:Ue.ZodIntersection,...P(n)});class Ce extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return w(n,{code:m.invalid_type,expected:f.array,received:n.parsedType}),I;if(n.data.length<this._def.items.length)return w(n,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;!this._def.rest&&n.data.length>this._def.items.length&&(w(n,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new O(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>_.mergeArray(t,e)):_.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Ce({...this._def,rest:e})}}Ce.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:e,typeName:Ue.ZodTuple,rest:null,...P(t)})};class Te extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return w(n,{code:m.invalid_type,expected:f.object,received:n.parsedType}),I;const r=[],i=this._def.keyType,s=this._def.valueType;for(const o in n.data)r.push({key:i._parse(new O(n,o,n.path,o)),value:s._parse(new O(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?_.mergeObjectAsync(t,r):_.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new Te(t instanceof q?{keyType:e,valueType:t,typeName:Ue.ZodRecord,...P(n)}:{keyType:ie.create(),valueType:e,typeName:Ue.ZodRecord,...P(t)})}}class xe extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return w(n,{code:m.invalid_type,expected:f.map,received:n.parsedType}),I;const r=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([e,t],s)=>({key:r._parse(new O(n,e,n.path,[s,"key"])),value:i._parse(new O(n,t,n.path,[s,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of s){const r=await n.key,i=await n.value;if("aborted"===r.status||"aborted"===i.status)return I;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of s){const r=n.key,i=n.value;if("aborted"===r.status||"aborted"===i.status)return I;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}}xe.create=(e,t,n)=>new xe({valueType:t,keyType:e,typeName:Ue.ZodMap,...P(n)});class Ae extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return w(n,{code:m.invalid_type,expected:f.set,received:n.parsedType}),I;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(w(n,{code:m.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(w(n,{code:m.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function s(e){const n=new Set;for(const r of e){if("aborted"===r.status)return I;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>i._parse(new O(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(e,t){return new Ae({...this._def,minSize:{value:e,message:R.toString(t)}})}max(e,t){return new Ae({...this._def,maxSize:{value:e,message:R.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ae.create=(e,t)=>new Ae({valueType:e,minSize:null,maxSize:null,typeName:Ue.ZodSet,...P(t)});class ke extends q{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})}}ke.create=(e,t)=>new ke({getter:e,typeName:Ue.ZodLazy,...P(t)});class Se extends q{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return w(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Re(e,t){return new Ee({values:e,typeName:Ue.ZodEnum,...P(t)})}Se.create=(e,t)=>new Se({value:e,typeName:Ue.ZodLiteral,...P(t)});class Ee extends q{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{expected:l.joinValues(n),received:t.parsedType,code:m.invalid_type}),I}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{received:t.data,code:m.invalid_enum_value,options:n}),I}return T(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 Ee.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ee.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ee.create=Re;class Oe extends q{_parse(e){const t=l.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){const e=l.objectValues(t);return w(n,{expected:l.joinValues(e),received:n.parsedType,code:m.invalid_type}),I}if(this._cache||(this._cache=new Set(l.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=l.objectValues(t);return w(n,{received:n.data,code:m.invalid_enum_value,options:e}),I}return T(e.data)}get enum(){return this._def.values}}Oe.create=(e,t)=>new Oe({values:e,typeName:Ue.ZodNativeEnum,...P(t)});class Ne extends q{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&!1===t.common.async)return w(t,{code:m.invalid_type,expected:f.promise,received:t.parsedType}),I;const n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return T(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:Ue.ZodPromise,...P(t)});class Pe extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ue.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{w(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===r.type){const e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return I;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?I:"dirty"===r.status||"dirty"===t.value?C(r.value):r});{if("aborted"===t.value)return I;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?I:"dirty"===r.status||"dirty"===t.value?C(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?I:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?I:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!k(e))return I;const s=r.transform(e.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>k(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):I)}l.assertNever(r)}}Pe.create=(e,t,n)=>new Pe({schema:e,typeName:Ue.ZodEffects,effect:t,...P(n)}),Pe.createWithPreprocess=(e,t,n)=>new Pe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ue.ZodEffects,...P(n)});class qe extends q{_parse(e){return this._getType(e)===f.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:Ue.ZodOptional,...P(t)});class $e extends q{_parse(e){return this._getType(e)===f.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$e.create=(e,t)=>new $e({innerType:e,typeName:Ue.ZodNullable,...P(t)});class Me extends q{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:Ue.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...P(t)});class Fe extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return S(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Fe.create=(e,t)=>new Fe({innerType:e,typeName:Ue.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...P(t)});class je extends q{_parse(e){if(this._getType(e)!==f.nan){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.nan,received:t.parsedType}),I}return{status:"valid",value:e.data}}}je.create=e=>new je({typeName:Ue.ZodNaN,...P(e)});class Be extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class De extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?I:"dirty"===e.status?(t.dirty(),C(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})()}{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?I:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new De({in:e,out:t,typeName:Ue.ZodPipeline})}}class Le extends q{_parse(e){const t=this._def.innerType._parse(e),n=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return S(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var Ue,Ze;Le.create=(e,t)=>new Le({innerType:e,typeName:Ue.ZodReadonly,...P(t)}),(Ze=Ue||(Ue={})).ZodString="ZodString",Ze.ZodNumber="ZodNumber",Ze.ZodNaN="ZodNaN",Ze.ZodBigInt="ZodBigInt",Ze.ZodBoolean="ZodBoolean",Ze.ZodDate="ZodDate",Ze.ZodSymbol="ZodSymbol",Ze.ZodUndefined="ZodUndefined",Ze.ZodNull="ZodNull",Ze.ZodAny="ZodAny",Ze.ZodUnknown="ZodUnknown",Ze.ZodNever="ZodNever",Ze.ZodVoid="ZodVoid",Ze.ZodArray="ZodArray",Ze.ZodObject="ZodObject",Ze.ZodUnion="ZodUnion",Ze.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ze.ZodIntersection="ZodIntersection",Ze.ZodTuple="ZodTuple",Ze.ZodRecord="ZodRecord",Ze.ZodMap="ZodMap",Ze.ZodSet="ZodSet",Ze.ZodFunction="ZodFunction",Ze.ZodLazy="ZodLazy",Ze.ZodLiteral="ZodLiteral",Ze.ZodEnum="ZodEnum",Ze.ZodEffects="ZodEffects",Ze.ZodNativeEnum="ZodNativeEnum",Ze.ZodOptional="ZodOptional",Ze.ZodNullable="ZodNullable",Ze.ZodDefault="ZodDefault",Ze.ZodCatch="ZodCatch",Ze.ZodPromise="ZodPromise",Ze.ZodBranded="ZodBranded",Ze.ZodPipeline="ZodPipeline",Ze.ZodReadonly="ZodReadonly";const Ke=ie.create,ze=oe.create,He=ce.create,Ve=fe.create;ge.create;const We=ye.create,Je=be.create,Ge=we.create;Ie.create,Ce.create;const Xe=Te.create,Qe=Ee.create,Ye=Oe.create;Ne.create,qe.create,$e.create;const et=Je({name:Ke().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:Ke().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:Ke().optional().transform(e=>{if(!e||e.toLowerCase().includes("random")){return`bot${Date.now().toString(36)}${Math.random().toString(36)}`}return e}).describe('Optional custom username/alias for the agent. Use "random" to generate a unique alias'),type:Qe(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:Ke().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:We(Ye(r.AIAgentCapability)).optional().describe("Array of agent capabilities (default: [TEXT_GENERATION])"),creator:Ke().optional().describe("Creator attribution for the agent"),socials:Xe(Qe(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),Ke()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:Xe(Ve()).optional().describe("Custom metadata properties for the agent"),profilePicture:Ge([Ke().describe("URL or local file path to profile picture"),Je({url:Ke().optional(),path:Ke().optional(),filename:Ke().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:Ke().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:ze().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:Ke().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:ze().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:We(Je({amount:ze().positive(),tokenId:Ke()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:We(Ke()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:He().optional().describe("Whether to set as current agent (default: true)"),persistence:Je({prefix:Ke().optional()}).optional().describe("Optional persistence configuration")});class tt extends d{constructor(e){super(e),this.name="register_agent",this.description='Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Note: This tool requires multiple transactions and cannot be used in returnBytes mode. If alias is set to "random" or contains "random", a unique alias will be generated.',this.specificInputSchema=et,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;this.specificArgs=t;const r={name:t.name};if(void 0!==t.description&&(r.bio=t.description),void 0!==t.alias)r.alias=t.alias;else{const e=Date.now().toString(36);r.alias=`${t.name}${e}`}if(void 0!==t.type&&(r.type=t.type),void 0!==t.model&&(r.model=t.model),void 0!==t.capabilities&&(r.capabilities=t.capabilities),void 0!==t.creator&&(r.creator=t.creator),void 0!==t.socials&&(r.socials=t.socials),void 0!==t.properties&&(r.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)r.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),r.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(r.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(r.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(r.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(r.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(r.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(r.initialBalance=t.initialBalance),await n.registerAgent(r)}async _call(e,t){const n=await super._call(e,t),r=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&r)try{const e=JSON.parse(n);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(i){}return n}_handleRegistrationResult(e){let t=e.accountId||e.metadata?.accountId;if(!t&&e.state?.createdResources){const n=e.state.createdResources.find(e=>e.startsWith("account:"));n&&(t=n.split(":")[1])}const n=e.inboundTopicId||e.metadata?.inboundTopicId||e.state?.inboundTopicId,r=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,i=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,s=e.privateKey||e.metadata?.privateKey;if(t&&n&&r&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:n,outboundTopicId:r,profileTopicId:i,privateKey:s},o=this.getServiceBuilder().getStateManager();if(o&&(o.setCurrentAgent(e),o.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");o.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const nt=Je({targetIdentifier:Ke().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),message:Ke().describe("The text message content to send."),disableMonitoring:He().optional().default(!1)});class rt extends d{constructor(e){super(e),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.specificInputSchema=nt,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e;await n.sendMessageToConnection({targetIdentifier:t.targetIdentifier,message:t.message,disableMonitoring:t.disableMonitoring})}}const it=Je({targetAccountId:Ke().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:He().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:Ke().optional().describe('Optional memo to include with the connection request (e.g., "Hello from Alice"). If not provided, defaults to "true" or "false" based on monitoring preference.')});class st extends d{constructor(e){super(e),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.specificInputSchema=it,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,r={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(r.disableMonitor=t.disableMonitor),void 0!==t.memo&&(r.memo=t.memo),await n.initiateConnection(r)}}const ot=Je({includeDetails:He().optional().describe("Whether to include detailed information about each connection"),showPending:He().optional().describe("Whether to include pending connection requests")});class at extends u{constructor(e){super(e),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.specificInputSchema=ot}async executeQuery(e){const t=this.hcs10Builder,n={};void 0!==e.includeDetails&&(n.includeDetails=e.includeDetails),void 0!==e.showPending&&(n.showPending=e.showPending),await t.listConnections(n);const r=await t.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return r}}const ct=Je({targetIdentifier:Ke().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:He().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:ze().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class dt extends u{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=ct}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const r=this.hcs10Builder;await r.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const i=await r.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return i}}const ut=Je({accountId:Ke().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:We(Ye(r.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")});class lt extends u{constructor(e){super(e),this.name="find_registrations",this.description="Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags. Returns basic registration info.",this.specificInputSchema=ut}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,r={};e&&(r.accountId=e),t&&(r.tags=t),await n.findRegistrations(r);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return i}}const ht=Je({acceptAll:He().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:Ke().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:We(Je({amount:ze(),collectorAccount:Ke().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:We(Je({amount:ze(),tokenId:Ke(),collectorAccount:Ke().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:We(Ke()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:ze().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:Ke().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class pt extends d{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=ht,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.monitorConnections({...void 0!==t.acceptAll&&{acceptAll:t.acceptAll},...void 0!==t.targetAccountId&&{targetAccountId:t.targetAccountId},...void 0!==t.monitorDurationSeconds&&{monitorDurationSeconds:t.monitorDurationSeconds},hbarFees:t.hbarFees||[],tokenFees:t.tokenFees||[],...void 0!==t.exemptAccountIds&&{exemptAccountIds:t.exemptAccountIds},...void 0!==t.defaultCollectorAccount&&{defaultCollectorAccount:t.defaultCollectorAccount}})}}const ft=Je({action:Qe(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:Ke().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class gt extends u{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=ft}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,r={action:e};void 0!==t&&(r.requestKey=t),await n.manageConnectionRequests(r);const i=await n.execute();return"rawResult"in i?i.rawResult:i}}const mt=Je({requestKey:Ke().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:ze().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:We(Ke()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class yt extends d{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=mt,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const vt=Je({accountId:Ke().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:He().optional().describe("Optional: Force refresh from the network instead of using cache.")});class bt extends u{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=vt}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,r={accountId:e};void 0!==t&&(r.disableCache=t),await n.retrieveProfile(r);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return i}}const wt=Je({});class _t extends u{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=wt}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}const It=s.join(c.cwd(),".env");class Ct{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const t=e?.disableLogging||"true"===c.env.DISABLE_LOGGING;this.logger=new r.Logger({module:"OpenConvaiState",silent:t}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new r.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const r=this.connectionsManager.getConnectionByTopicId(e);if(r)return this.convertToActiveConnection(r);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||c.env.ENV_FILE_PATH||".env",r=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const s={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const r=[...n.split("\n")];for(const[i,s]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${i}=`));-1!==e?r[e]=`${i}=${s}`:r.push(`${i}=${s}`)}i.writeFileSync(e,r.join("\n"))}(n,s)}}function Tt(e,t){return function(){return e.apply(t,arguments)}}const{toString:xt}=Object.prototype,{getPrototypeOf:At}=Object,{iterator:kt,toStringTag:St}=Symbol,Rt=(e=>t=>{const n=xt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Et=e=>(e=e.toLowerCase(),t=>Rt(t)===e),Ot=e=>t=>typeof t===e,{isArray:Nt}=Array,Pt=Ot("undefined");const qt=Et("ArrayBuffer");const $t=Ot("string"),Mt=Ot("function"),Ft=Ot("number"),jt=e=>null!==e&&"object"==typeof e,Bt=e=>{if("object"!==Rt(e))return!1;const t=At(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||St in e||kt in e)},Dt=Et("Date"),Lt=Et("File"),Ut=Et("Blob"),Zt=Et("FileList"),Kt=Et("URLSearchParams"),[zt,Ht,Vt,Wt]=["ReadableStream","Request","Response","Headers"].map(Et);function Jt(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let r,i;if("object"!=typeof e&&(e=[e]),Nt(e))for(r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else{const i=n?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(r=0;r<s;r++)o=i[r],t.call(null,e[o],o,e)}}function Gt(e,t){t=t.toLowerCase();const n=Object.keys(e);let r,i=n.length;for(;i-- >0;)if(r=n[i],t===r.toLowerCase())return r;return null}const Xt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:o,Qt=e=>!Pt(e)&&e!==Xt;const Yt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&At(Uint8Array)),en=Et("HTMLFormElement"),tn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),nn=Et("RegExp"),rn=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Jt(n,(n,i)=>{let s;!1!==(s=t(n,i,e))&&(r[i]=s||n)}),Object.defineProperties(e,r)};const sn=Et("AsyncFunction"),on=(an="function"==typeof a.setImmediate,cn=Mt(Xt.postMessage),an?a.setImmediate:cn?(dn=`axios@${Math.random()}`,un=[],Xt.addEventListener("message",({source:e,data:t})=>{e===Xt&&t===dn&&un.length&&un.shift()()},!1),e=>{un.push(e),Xt.postMessage(dn,"*")}):e=>setTimeout(e));var an,cn,dn,un;const ln="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Xt):void 0!==c&&c.nextTick||on,hn={isArray:Nt,isArrayBuffer:qt,isBuffer:function(e){return null!==e&&!Pt(e)&&null!==e.constructor&&!Pt(e.constructor)&&Mt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Mt(e.append)&&("formdata"===(t=Rt(e))||"object"===t&&Mt(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&qt(e.buffer),t},isString:$t,isNumber:Ft,isBoolean:e=>!0===e||!1===e,isObject:jt,isPlainObject:Bt,isReadableStream:zt,isRequest:Ht,isResponse:Vt,isHeaders:Wt,isUndefined:Pt,isDate:Dt,isFile:Lt,isBlob:Ut,isRegExp:nn,isFunction:Mt,isStream:e=>jt(e)&&Mt(e.pipe),isURLSearchParams:Kt,isTypedArray:Yt,isFileList:Zt,forEach:Jt,merge:function e(){const{caseless:t}=Qt(this)&&this||{},n={},r=(r,i)=>{const s=t&&Gt(n,i)||i;Bt(n[s])&&Bt(r)?n[s]=e(n[s],r):Bt(r)?n[s]=e({},r):Nt(r)?n[s]=r.slice():n[s]=r};for(let i=0,s=arguments.length;i<s;i++)arguments[i]&&Jt(arguments[i],r);return n},extend:(e,t,n,{allOwnKeys:r}={})=>(Jt(t,(t,r)=>{n&&Mt(t)?e[r]=Tt(t,n):e[r]=t},{allOwnKeys:r}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,r)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],r&&!r(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==n&&At(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Rt,kindOfTest:Et,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return-1!==r&&r===n},toArray:e=>{if(!e)return null;if(Nt(e))return e;let t=e.length;if(!Ft(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[kt]).call(e);let r;for(;(r=n.next())&&!r.done;){const n=r.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const r=[];for(;null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:en,hasOwnProperty:tn,hasOwnProp:tn,reduceDescriptors:rn,freezeMethods:e=>{rn(e,(t,n)=>{if(Mt(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=e[n];Mt(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},r=e=>{e.forEach(e=>{n[e]=!0})};return Nt(e)?r(e):r(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Gt,global:Xt,isContextDefined:Qt,isSpecCompliantForm:function(e){return!!(e&&Mt(e.append)&&"FormData"===e[St]&&e[kt])},toJSONObject:e=>{const t=new Array(10),n=(e,r)=>{if(jt(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[r]=e;const i=Nt(e)?[]:{};return Jt(e,(e,t)=>{const s=n(e,r+1);!Pt(s)&&(i[t]=s)}),t[r]=void 0,i}}return e};return n(e,0)},isAsyncFn:sn,isThenable:e=>e&&(jt(e)||Mt(e))&&Mt(e.then)&&Mt(e.catch),setImmediate:on,asap:ln,isIterable:e=>null!=e&&Mt(e[kt])};function pn(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}hn.inherits(pn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:hn.toJSONObject(this.config),code:this.code,status:this.status}}});const fn=pn.prototype,gn={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{gn[e]={value:e}}),Object.defineProperties(pn,gn),Object.defineProperty(fn,"isAxiosError",{value:!0}),pn.from=(e,t,n,r,i,s)=>{const o=Object.create(fn);return hn.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),pn.call(o,e.message,t,n,r,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function mn(e){return hn.isPlainObject(e)||hn.isArray(e)}function yn(e){return hn.endsWith(e,"[]")?e.slice(0,-2):e}function vn(e,t,n){return e?e.concat(t).map(function(e,t){return e=yn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const bn=hn.toFlatObject(hn,{},null,function(e){return/^is[A-Z]/.test(e)});function wn(e,n,r){if(!hn.isObject(e))throw new TypeError("target must be an object");n=n||new FormData;const i=(r=hn.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!hn.isUndefined(t[e])})).metaTokens,s=r.visitor||u,o=r.dots,a=r.indexes,c=(r.Blob||"undefined"!=typeof Blob&&Blob)&&hn.isSpecCompliantForm(n);if(!hn.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(hn.isDate(e))return e.toISOString();if(hn.isBoolean(e))return e.toString();if(!c&&hn.isBlob(e))throw new pn("Blob is not supported. Use a Buffer instead.");return hn.isArrayBuffer(e)||hn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):t.Buffer.from(e):e}function u(e,t,r){let s=e;if(e&&!r&&"object"==typeof e)if(hn.endsWith(t,"{}"))t=i?t:t.slice(0,-2),e=JSON.stringify(e);else if(hn.isArray(e)&&function(e){return hn.isArray(e)&&!e.some(mn)}(e)||(hn.isFileList(e)||hn.endsWith(t,"[]"))&&(s=hn.toArray(e)))return t=yn(t),s.forEach(function(e,r){!hn.isUndefined(e)&&null!==e&&n.append(!0===a?vn([t],r,o):null===a?t:t+"[]",d(e))}),!1;return!!mn(e)||(n.append(vn(r,t,o),d(e)),!1)}const l=[],h=Object.assign(bn,{defaultVisitor:u,convertValue:d,isVisitable:mn});if(!hn.isObject(e))throw new TypeError("data must be an object");return function e(t,r){if(!hn.isUndefined(t)){if(-1!==l.indexOf(t))throw Error("Circular reference detected in "+r.join("."));l.push(t),hn.forEach(t,function(t,i){!0===(!(hn.isUndefined(t)||null===t)&&s.call(n,t,hn.isString(i)?i.trim():i,r,h))&&e(t,r?r.concat(i):[i])}),l.pop()}}(e),n}function _n(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function In(e,t){this._pairs=[],e&&wn(e,this,t)}const Cn=In.prototype;function Tn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xn(e,t,n){if(!t)return e;const r=n&&n.encode||Tn;hn.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let s;if(s=i?i(t,n):hn.isURLSearchParams(t)?t.toString():new In(t,n).toString(r),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Cn.append=function(e,t){this._pairs.push([e,t])},Cn.toString=function(e){const t=e?function(t){return e.call(this,t,_n)}:_n;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class An{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){hn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const kn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Sn={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:In,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Rn="undefined"!=typeof window&&"undefined"!=typeof document,En="object"==typeof navigator&&navigator||void 0,On=Rn&&(!En||["ReactNative","NativeScript","NS"].indexOf(En.product)<0),Nn="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Pn=Rn&&window.location.href||"http://localhost",qn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Rn,hasStandardBrowserEnv:On,hasStandardBrowserWebWorkerEnv:Nn,navigator:En,origin:Pn},Symbol.toStringTag,{value:"Module"})),...Sn};function $n(e){function t(e,n,r,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&hn.isArray(r)?r.length:s,a)return hn.hasOwnProp(r,s)?r[s]=[r[s],n]:r[s]=n,!o;r[s]&&hn.isObject(r[s])||(r[s]=[]);return t(e,n,r[s],i)&&hn.isArray(r[s])&&(r[s]=function(e){const t={},n=Object.keys(e);let r;const i=n.length;let s;for(r=0;r<i;r++)s=n[r],t[s]=e[s];return t}(r[s])),!o}if(hn.isFormData(e)&&hn.isFunction(e.entries)){const n={};return hn.forEachEntry(e,(e,r)=>{t(function(e){return hn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),r,n,0)}),n}return null}const Mn={transitional:kn,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",r=n.indexOf("application/json")>-1,i=hn.isObject(e);i&&hn.isHTMLForm(e)&&(e=new FormData(e));if(hn.isFormData(e))return r?JSON.stringify($n(e)):e;if(hn.isArrayBuffer(e)||hn.isBuffer(e)||hn.isStream(e)||hn.isFile(e)||hn.isBlob(e)||hn.isReadableStream(e))return e;if(hn.isArrayBufferView(e))return e.buffer;if(hn.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return wn(e,new qn.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return qn.isNode&&hn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=hn.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return wn(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||r?(t.setContentType("application/json",!1),function(e,t,n){if(hn.isString(e))try{return(t||JSON.parse)(e),hn.trim(e)}catch(r){if("SyntaxError"!==r.name)throw r}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Mn.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(hn.isResponse(e)||hn.isReadableStream(e))return e;if(e&&hn.isString(e)&&(n&&!this.responseType||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(i){if(n){if("SyntaxError"===i.name)throw pn.from(i,pn.ERR_BAD_RESPONSE,this,null,this.response);throw i}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:qn.classes.FormData,Blob:qn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hn.forEach(["delete","get","head","post","put","patch"],e=>{Mn.headers[e]={}});const Fn=hn.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),jn=Symbol("internals");function Bn(e){return e&&String(e).trim().toLowerCase()}function Dn(e){return!1===e||null==e?e:hn.isArray(e)?e.map(Dn):String(e)}function Ln(e,t,n,r,i){return hn.isFunction(r)?r.call(this,t,n):(i&&(t=n),hn.isString(t)?hn.isString(r)?-1!==t.indexOf(r):hn.isRegExp(r)?r.test(t):void 0:void 0)}let Un=class{constructor(e){e&&this.set(e)}set(e,t,n){const r=this;function i(e,t,n){const i=Bn(t);if(!i)throw new Error("header name must be a non-empty string");const s=hn.findKey(r,i);(!s||void 0===r[s]||!0===n||void 0===n&&!1!==r[s])&&(r[s||t]=Dn(e))}const s=(e,t)=>hn.forEach(e,(e,n)=>i(e,n,t));if(hn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(hn.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,r,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),n=e.substring(0,i).trim().toLowerCase(),r=e.substring(i+1).trim(),!n||t[n]&&Fn[n]||("set-cookie"===n?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t})(e),t);else if(hn.isObject(e)&&hn.isIterable(e)){let n,r,i={};for(const t of e){if(!hn.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[r=t[0]]=(n=i[r])?hn.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,n);return this}get(e,t){if(e=Bn(e)){const n=hn.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}(e);if(hn.isFunction(t))return t.call(this,e,n);if(hn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Bn(e)){const n=hn.findKey(this,e);return!(!n||void 0===this[n]||t&&!Ln(0,this[n],n,t))}return!1}delete(e,t){const n=this;let r=!1;function i(e){if(e=Bn(e)){const i=hn.findKey(n,e);!i||t&&!Ln(0,n[i],i,t)||(delete n[i],r=!0)}}return hn.isArray(e)?e.forEach(i):i(e),r}clear(e){const t=Object.keys(this);let n=t.length,r=!1;for(;n--;){const i=t[n];e&&!Ln(0,this[i],i,e,!0)||(delete this[i],r=!0)}return r}normalize(e){const t=this,n={};return hn.forEach(this,(r,i)=>{const s=hn.findKey(n,i);if(s)return t[s]=Dn(r),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(i):String(i).trim();o!==i&&delete t[i],t[o]=Dn(r),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return hn.forEach(this,(n,r)=>{null!=n&&!1!==n&&(t[r]=e&&hn.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){const t=(this[jn]=this[jn]={accessors:{}}).accessors,n=this.prototype;function r(e){const r=Bn(e);t[r]||(!function(e,t){const n=hn.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(e,n,i){return this[r].call(this,t,e,n,i)},configurable:!0})})}(n,e),t[r]=!0)}return hn.isArray(e)?e.forEach(r):r(e),this}};function Zn(e,t){const n=this||Mn,r=t||n,i=Un.from(r.headers);let s=r.data;return hn.forEach(e,function(e){s=e.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function Kn(e){return!(!e||!e.__CANCEL__)}function zn(e,t,n){pn.call(this,null==e?"canceled":e,pn.ERR_CANCELED,t,n),this.name="CanceledError"}function Hn(e,t,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(new pn("Request failed with status code "+n.status,[pn.ERR_BAD_REQUEST,pn.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}Un.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),hn.reduceDescriptors(Un.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),hn.freezeMethods(Un),hn.inherits(zn,pn,{__CANCEL__:!0});const Vn=(e,t,n=3)=>{let r=0;const i=function(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=r[o];i||(i=c),n[s]=a,r[s]=c;let u=o,l=0;for(;u!==s;)l+=n[u++],u%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const h=d&&c-d;return h?Math.round(1e3*l/h):void 0}}(50,250);return function(e,t){let n,r,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,n=null,r&&(clearTimeout(r),r=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(n=e,r||(r=setTimeout(()=>{r=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-r,c=i(a);r=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:n,lengthComputable:null!=o,[t?"download":"upload"]:!0})},n)},Wn=(e,t)=>{const n=null!=e;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Jn=e=>(...t)=>hn.asap(()=>e(...t)),Gn=qn.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,qn.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(qn.origin),qn.navigator&&/(msie|trident)/i.test(qn.navigator.userAgent)):()=>!0,Xn=qn.hasStandardBrowserEnv?{write(e,t,n,r,i,s){const o=[e+"="+encodeURIComponent(t)];hn.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),hn.isString(r)&&o.push("path="+r),hn.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Qn(e,t,n){let r=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(r||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Yn=e=>e instanceof Un?{...e}:e;function er(e,t){t=t||{};const n={};function r(e,t,n,r){return hn.isPlainObject(e)&&hn.isPlainObject(t)?hn.merge.call({caseless:r},e,t):hn.isPlainObject(t)?hn.merge({},t):hn.isArray(t)?t.slice():t}function i(e,t,n,i){return hn.isUndefined(t)?hn.isUndefined(e)?void 0:r(void 0,e,0,i):r(e,t,0,i)}function s(e,t){if(!hn.isUndefined(t))return r(void 0,t)}function o(e,t){return hn.isUndefined(t)?hn.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function a(n,i,s){return s in t?r(n,i):s in e?r(void 0,n):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,n)=>i(Yn(e),Yn(t),0,!0)};return hn.forEach(Object.keys(Object.assign({},e,t)),function(r){const s=c[r]||i,o=s(e[r],t[r],r);hn.isUndefined(o)&&s!==a||(n[r]=o)}),n}const tr=e=>{const t=er({},e);let n,{data:r,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Un.from(a),t.url=xn(Qn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),hn.isFormData(r))if(qn.hasStandardBrowserEnv||qn.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(n=a.getContentType())){const[e,...t]=n?n.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(qn.hasStandardBrowserEnv&&(i&&hn.isFunction(i)&&(i=i(t)),i||!1!==i&&Gn(t.url))){const e=s&&o&&Xn.read(o);e&&a.set(s,e)}return t},nr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const r=tr(e);let i=r.data;const s=Un.from(r.headers).normalize();let o,a,c,d,u,{responseType:l,onUploadProgress:h,onDownloadProgress:p}=r;function f(){d&&d(),u&&u(),r.cancelToken&&r.cancelToken.unsubscribe(o),r.signal&&r.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const r=Un.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Hn(function(e){t(e),f()},function(e){n(e),f()},{data:l&&"text"!==l&&"json"!==l?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:r,config:e,request:g}),g=null}g.open(r.method.toUpperCase(),r.url,!0),g.timeout=r.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(n(new pn("Request aborted",pn.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new pn("Network Error",pn.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const i=r.transitional||kn;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),n(new pn(t,i.clarifyTimeoutError?pn.ETIMEDOUT:pn.ECONNABORTED,e,g)),g=null},void 0===i&&s.setContentType(null),"setRequestHeader"in g&&hn.forEach(s.toJSON(),function(e,t){g.setRequestHeader(t,e)}),hn.isUndefined(r.withCredentials)||(g.withCredentials=!!r.withCredentials),l&&"json"!==l&&(g.responseType=r.responseType),p&&([c,u]=Vn(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,d]=Vn(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",d)),(r.cancelToken||r.signal)&&(o=t=>{g&&(n(!t||t.type?new zn(null,e,g):t),g.abort(),g=null)},r.cancelToken&&r.cancelToken.subscribe(o),r.signal&&(r.signal.aborted?o():r.signal.addEventListener("abort",o)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(r.url);y&&-1===qn.protocols.indexOf(y)?n(new pn("Unsupported protocol "+y+":",pn.ERR_BAD_REQUEST,e)):g.send(i||null)})},rr=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,r=new AbortController;const i=function(e){if(!n){n=!0,o();const t=e instanceof Error?e:this.reason;r.abort(t instanceof pn?t:new zn(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,i(new pn(`timeout ${t} of ms exceeded`,pn.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=r;return a.unsubscribe=()=>hn.asap(o),a}},ir=function*(e,t){let n=e.byteLength;if(n<t)return void(yield e);let r,i=0;for(;i<n;)r=i+t,yield e.slice(i,r),i=r},sr=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)break;yield n}}finally{await t.cancel()}},or=(e,t,n,r)=>{const i=async function*(e,t){for await(const n of sr(e))yield*ir(n,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,r&&r(e))};return new ReadableStream({async pull(e){try{const{done:t,value:r}=await i.next();if(t)return a(),void e.close();let s=r.byteLength;if(n){let e=o+=s;n(e)}e.enqueue(new Uint8Array(r))}catch(t){throw a(t),t}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},ar="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,cr=ar&&"function"==typeof ReadableStream,dr=ar&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),ur=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},lr=cr&&ur(()=>{let e=!1;const t=new Request(qn.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),hr=cr&&ur(()=>hn.isReadableStream(new Response("").body)),pr={stream:hr&&(e=>e.body)};var fr;ar&&(fr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!pr[e]&&(pr[e]=hn.isFunction(fr[e])?t=>t[e]():(t,n)=>{throw new pn(`Response type '${e}' is not supported`,pn.ERR_NOT_SUPPORT,n)})}));const gr=async(e,t)=>{const n=hn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(hn.isBlob(e))return e.size;if(hn.isSpecCompliantForm(e)){const t=new Request(qn.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return hn.isArrayBufferView(e)||hn.isArrayBuffer(e)?e.byteLength:(hn.isURLSearchParams(e)&&(e+=""),hn.isString(e)?(await dr(e)).byteLength:void 0)})(t):n},mr={http:null,xhr:nr,fetch:ar&&(async e=>{let{url:t,method:n,data:r,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:u,withCredentials:l="same-origin",fetchOptions:h}=tr(e);d=d?(d+"").toLowerCase():"text";let p,f=rr([i,s&&s.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&lr&&"get"!==n&&"head"!==n&&0!==(m=await gr(u,r))){let e,n=new Request(t,{method:"POST",body:r,duplex:"half"});if(hn.isFormData(r)&&(e=n.headers.get("content-type"))&&u.setContentType(e),n.body){const[e,t]=Wn(m,Vn(Jn(c)));r=or(n.body,65536,e,t)}}hn.isString(l)||(l=l?"include":"omit");const i="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:n.toUpperCase(),headers:u.normalize().toJSON(),body:r,duplex:"half",credentials:i?l:void 0});let s=await fetch(p,h);const o=hr&&("stream"===d||"response"===d);if(hr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=hn.toFiniteNumber(s.headers.get("content-length")),[n,r]=a&&Wn(t,Vn(Jn(a),!0))||[];s=new Response(or(s.body,65536,n,()=>{r&&r(),g&&g()}),e)}d=d||"text";let y=await pr[hn.findKey(pr,d)||"text"](s,e);return!o&&g&&g(),await new Promise((t,n)=>{Hn(t,n,{data:y,headers:Un.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:p})})}catch(y){if(g&&g(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new pn("Network Error",pn.ERR_NETWORK,e,p),{cause:y.cause||y});throw pn.from(y,y&&y.code,e,p)}})};hn.forEach(mr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const yr=e=>`- ${e}`,vr=e=>hn.isFunction(e)||null===e||!1===e,br=e=>{e=hn.isArray(e)?e:[e];const{length:t}=e;let n,r;const i={};for(let s=0;s<t;s++){let t;if(n=e[s],r=n,!vr(n)&&(r=mr[(t=String(n)).toLowerCase()],void 0===r))throw new pn(`Unknown adapter '${t}'`);if(r)break;i[t||"#"+s]=r}if(!r){const e=Object.entries(i).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new pn("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(yr).join("\n"):" "+yr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r};function wr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new zn(null,e)}function _r(e){wr(e),e.headers=Un.from(e.headers),e.data=Zn.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return br(e.adapter||Mn.adapter)(e).then(function(t){return wr(e),t.data=Zn.call(e,e.transformResponse,t),t.headers=Un.from(t.headers),t},function(t){return Kn(t)||(wr(e),t&&t.response&&(t.response.data=Zn.call(e,e.transformResponse,t.response),t.response.headers=Un.from(t.response.headers))),Promise.reject(t)})}const Ir="1.10.0",Cr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Cr[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Tr={};Cr.transitional=function(e,t,n){function r(e,t){return"[Axios v"+Ir+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,i,s)=>{if(!1===e)throw new pn(r(i," has been removed"+(t?" in "+t:"")),pn.ERR_DEPRECATED);return t&&!Tr[i]&&(Tr[i]=!0,console.warn(r(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,i,s)}},Cr.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const xr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new pn("options must be an object",pn.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const t=e[s],n=void 0===t||o(t,s,e);if(!0!==n)throw new pn("option "+s+" must be "+n,pn.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new pn("Unknown option "+s,pn.ERR_BAD_OPTION)}},validators:Cr},Ar=xr.validators;let kr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new An,response:new An}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{n.stack?t&&!String(n.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(n.stack+="\n"+t):n.stack=t}catch(r){}}throw n}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=er(this.defaults,t);const{transitional:n,paramsSerializer:r,headers:i}=t;void 0!==n&&xr.assertOptions(n,{silentJSONParsing:Ar.transitional(Ar.boolean),forcedJSONParsing:Ar.transitional(Ar.boolean),clarifyTimeoutError:Ar.transitional(Ar.boolean)},!1),null!=r&&(hn.isFunction(r)?t.paramsSerializer={serialize:r}:xr.assertOptions(r,{encode:Ar.function,serialize:Ar.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xr.assertOptions(t,{baseUrl:Ar.spelling("baseURL"),withXsrfToken:Ar.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&hn.merge(i.common,i[t.method]);i&&hn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=Un.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let u,l=0;if(!a){const e=[_r.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,d=Promise.resolve(t);l<u;)d=d.then(e[l++],e[l++]);return d}u=o.length;let h=t;for(l=0;l<u;){const e=o[l++],t=o[l++];try{h=e(h)}catch(p){t.call(this,p);break}}try{d=_r.call(this,h)}catch(p){return Promise.reject(p)}for(l=0,u=c.length;l<u;)d=d.then(c[l++],c[l++]);return d}getUri(e){return xn(Qn((e=er(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};hn.forEach(["delete","get","head","options"],function(e){kr.prototype[e]=function(t,n){return this.request(er(n||{},{method:e,url:t,data:(n||{}).data}))}}),hn.forEach(["post","put","patch"],function(e){function t(t){return function(n,r,i){return this.request(er(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}kr.prototype[e]=t(),kr.prototype[e+"Form"]=t(!0)});const Sr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Sr).forEach(([e,t])=>{Sr[t]=e});const Rr=function e(t){const n=new kr(t),r=Tt(kr.prototype.request,n);return hn.extend(r,kr.prototype,n,{allOwnKeys:!0}),hn.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return e(er(t,n))},r}(Mn);Rr.Axios=kr,Rr.CanceledError=zn,Rr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const r=new Promise(e=>{n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e(function(e,r,i){n.reason||(n.reason=new zn(e,r,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},Rr.isCancel=Kn,Rr.VERSION=Ir,Rr.toFormData=wn,Rr.AxiosError=pn,Rr.Cancel=Rr.CanceledError,Rr.all=function(e){return Promise.all(e)},Rr.spread=function(e){return function(t){return e.apply(null,t)}},Rr.isAxiosError=function(e){return hn.isObject(e)&&!0===e.isAxiosError},Rr.mergeConfig=er,Rr.AxiosHeaders=Un,Rr.formToJSON=e=>$n(hn.isHTMLForm(e)?new FormData(e):e),Rr.getAdapter=br,Rr.HttpStatusCode=Sr,Rr.default=Rr;const{Axios:Er,AxiosError:Or,CanceledError:Nr,isCancel:Pr,CancelToken:qr,VERSION:$r,all:Mr,Cancel:Fr,isAxiosError:jr,spread:Br,toFormData:Dr,AxiosHeaders:Lr,HttpStatusCode:Ur,formToJSON:Zr,getAdapter:Kr,mergeConfig:zr}=Rr,Hr="ConnectionsManager not initialized";class Vr extends n.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const s=this.hederaKit.signer.getAccountId().toString(),o=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new r.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new r.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:o,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getStateManager(){return this.stateManager}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,n,r){try{const i=await this.standardClient.handleConnectionRequest(e,t,n,r);return i&&i.connectionTopicId&&"object"==typeof i.connectionTopicId&&"toString"in i.connectionTopicId&&(i.connectionTopicId=i.connectionTopicId.toString()),i}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async sendMessage(e,t,n){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const r=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:r.topicSequenceNumber?.toNumber(),receipt:r,transactionId:"transactionId"in r?r.transactionId?.toString():void 0}}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const n=await Rr.get(e,{responseType:"arraybuffer"}),r=t.Buffer.from(n.data),i=new URL(e).pathname;return{buffer:r,filename:s.basename(i)||"profile.png"}}{if(!i.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=i.readFileSync(e);return{buffer:t,filename:s.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const n=await Rr.get(e.url,{responseType:"arraybuffer"}),r=t.Buffer.from(n.data);return{buffer:r,filename:e.filename||"profile.png"}}if(e.path){if(!i.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=i.readFileSync(e.path);return{buffer:t,filename:e.filename||s.basename(e.path)}}return null}catch(n){return this.logger.error("Failed to load profile picture:",n),null}}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?t.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let t=null;e.profilePicture&&(t=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==t?.buffer&&{pfpBuffer:t.buffer},...void 0!==t?.filename&&{pfpFileName:t.filename}};if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,i,s)}const i=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.state?.agentMetadata?.accountId}}}catch(t){throw this.logger.error("Failed to register agent:",t),t}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const n=t.topicInfo.inboundTopic;let r;void 0!==e.memo?r=e.memo:(r=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${r}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const i=await this.submitConnectionRequest(n,r);this.executeResult={success:!0,transactionId:"transactionId"in i?i.transactionId?.toString():void 0,receipt:i,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...i}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const n=this.stateManager?.getCurrentAgent();if(!n)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(Hr);await i.fetchConnectionData(n.accountId);const s=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const o=s.targetAccountId,a=s.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,i)}const d=await this.getInboundTopicId(),u=await this.handleConnectionRequest(d,o,a,c);let l=u?.connectionTopicId;if(l&&"object"==typeof l&&"toString"in l&&(l=l?.toString()),!l||"string"!=typeof l)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(l)}`);if(this.stateManager){const e=s.targetAgentName||`Agent ${o}`;s.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${o}'.`);let n=s.targetInboundTopicId||"";if(!n)try{const e=await this.getAgentProfile(o);e.success&&e.topicInfo?.inboundTopic&&(n=e.topicInfo.inboundTopic)}catch(t){this.logger.warn(`Could not fetch profile for ${o}:`,t)}const r={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:l,status:"established",created:new Date};this.stateManager.addActiveConnection(r),i.markConnectionRequestProcessed(s.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId:l,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:u}}}catch(n){throw this.logger.error("Failed to accept connection:",n),n}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let n;if(e.targetIdentifier.includes("@")){const t=e.targetIdentifier.split("@");if(2===t.length){const r=t[1];n=this.stateManager.getConnectionByIdentifier(r),n||this.addNote(`Could not find connection using request key '${e.targetIdentifier}', extracted account ID '${r}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(e.targetIdentifier)),!n){const t=this.stateManager.listConnections().map(e=>`${e.targetAccountId} (${e.connectionTopicId})`);throw new Error(`Connection not found for identifier: ${e.targetIdentifier}. Available connections: ${t.join(", ")||"none"}. Use 'list_connections' to see details.`)}let r=n.connectionTopicId;if(r&&"object"==typeof r&&"toString"in r&&(r=r?.toString()),!r||"string"!=typeof r)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(r)} (type: ${typeof r})`);const i=n.targetAgentName,s=`${t.inboundTopicId}@${t.accountId}`,o=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!o.sequenceNumber)throw new Error("Failed to send message");let a=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):a=await this.monitorResponses(r,s,o.sequenceNumber),this.executeResult={success:!0,transactionId:o.transactionId,receipt:o.receipt,scheduleId:void 0,rawResult:{targetAgentName:i,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:o.sequenceNumber,reply:a,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:o}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let r=0;for(;r<30;){try{const r=await this.getMessageStream(e);for(const e of r.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(i){this.logger.error(`Error monitoring responses: ${i}`)}await new Promise(e=>setTimeout(e,4e3)),r++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:t=!1,targetAccountId:n,monitorDurationSeconds:i=120,hbarFees:s=[],tokenFees:o=[],exemptAccountIds:a=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const d=await this.getInboundTopicId(),u=Date.now()+1e3*i;let l=0,h=0;const p=new Set;for(;Date.now()<u;){try{const e=(await this.getMessages(d)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||p.has(e))continue;const u=i.operator_id?.split("@")[1];if(u)if(l++,n&&u!==n)this.logger.info(`Skipping request from ${u} (not target account)`);else if(t||n===u){let t;if(this.logger.info(`Accepting connection request from ${u}`),s.length>0||o.length>0){const e=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,a)}for(const t of o){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,a)}t=e}await this.handleConnectionRequest(d,u,e,t),p.add(e),h++}}}catch(f){this.logger.error("Error during connection monitoring:",f)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:l,acceptedConnections:h,monitorDurationSeconds:i,processedRequestIds:Array.from(p)}},this.addNote(`Monitoring completed. Found ${l} requests, accepted ${h}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(Hr);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const r=t.getPendingRequests(),i=t.getConnectionsNeedingConfirmation(),s=[...r,...i];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:s.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const n=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,n=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const r=e.filter(e=>"established"===e.status),i=e.filter(e=>e.isPending),s=e.filter(e=>e.needsConfirmation);let o="";r.length>0&&(o+=`🟢 Active Connections (${r.length}):\n`,r.forEach((e,n)=>{o+=this.formatConnection(e,n,t)}),o+="\n"),n&&s.length>0&&(o+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach((e,n)=>{o+=this.formatConnection(e,n,t)}),o+="\n"),n&&i.length>0&&(o+=`⚪ Pending Connection Requests (${i.length}):\n`,i.forEach((e,n)=>{o+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:o.trim(),activeCount:r.length,pendingCount:i.length,needsConfirmationCount:s.length}}}catch(r){this.logger.error("Failed to list connections:",r),this.executeResult={success:!1,error:`Failed to list connections: ${r instanceof Error?r.message:String(r)}`}}return this}formatConnection(e,t,n){const r=e;let i=`${t+1}. ${r.profileInfo?.display_name||r.targetAgentName||"Unknown Agent"} (${r.targetAccountId})\n`;i+=` Topic: ${r.isPending?"(Pending Request)":r.connectionTopicId}\n`;if(i+=` Status: ${r.status||"unknown"}\n`,n){if(r.profileInfo?.bio&&(i+=` Bio: ${r.profileInfo.bio.substring(0,100)}${r.profileInfo.bio.length>100?"...":""}\n`),r.created){i+=` ${r.isPending?"Request sent":"Connection established"}: ${r.created.toLocaleString()}\n`}r.lastActivity&&(i+=` Last activity: ${r.lastActivity.toLocaleString()}\n`)}return i}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(Hr),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const r of n)this.stateManager.addActiveConnection(r);return n}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const r=t.targetAgentName,i=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${r} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${i})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let o=[],a=i;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;o=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${i}`),o=t.filter(e=>1e6*e.timestamp>i),o.length>0&&(a=o.reduce((e,t)=>Math.max(e,1e6*t.timestamp),i));if(0===o.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${r} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${o.length} message(s).`);let d=c?`Latest message(s) from ${r}:\n`:`New messages from ${r}:\n`;const u=[];for(const e of o){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}d+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,u.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(s){const t=`Error processing message (Seq: ${e.sequence_number}): ${s instanceof Error?s.message:String(s)}`;this.logger.error(t),d+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>i&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:u,formattedOutput:d.trim(),targetAgentName:r,connectionTopicId:n}}}catch(s){this.logger.error(`Failed to check messages for topic ${n}: ${s}`),this.executeResult={success:!1,error:`Error checking messages for ${r}: ${s instanceof Error?s.message:String(s)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const r=n.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${r}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const n=t.profile,r=t.topicInfo;let i=`Profile for ${e.accountId}:\n`;i+=`Name: ${n.name||"Unknown"}\n`,i+=`Bio: ${n.bio||"No bio provided"}\n`,i+=`Type: ${n.type||"Unknown"}\n`,i+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?i+=`Capabilities: ${n.capabilities.join(", ")}\n`:i+="Capabilities: None listed\n",r&&(i+=`Inbound Topic: ${r.inboundTopic||"Unknown"}\n`,i+=`Outbound Topic: ${r.outboundTopic||"Unknown"}\n`,i+=`Profile Topic: ${r.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(i+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(i+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:i,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class Wr extends n.BasePlugin{constructor(){super(...arguments),this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new n.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>n.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>n.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>n.PluginRegistry}),e.AcceptConnectionRequestTool=yt,e.BaseHCS10QueryTool=u,e.BaseHCS10TransactionTool=d,e.CheckMessagesTool=dt,e.ConnectionMonitorTool=pt,e.FindRegistrationsTool=lt,e.HCS10Builder=Vr,e.HCS10Client=class{constructor(e,t,n,i){this.standardClient=new r.HCS10Client({network:n,operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const s="true"===c.env.DISABLE_LOGGING;this.logger=new r.Logger({level:i?.logLevel||"info",silent:s})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,r){try{return await this.standardClient.handleConnectionRequest(e,t,n,r)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,r=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,r)}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),r=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return r?.metadata?.inboundTopicId&&r?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:r.metadata.inboundTopicId,outboundTopicId:r.metadata.outboundTopicId}),r}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,n,r){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,r);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,t){return this.standardClient=new r.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HbarPricePlugin=Wr,e.InitiateConnectionTool=st,e.ListConnectionsTool=at,e.ListUnapprovedConnectionRequestsTool=_t,e.ManageConnectionRequestsTool=gt,e.OpenConvaiState=Ct,e.RegisterAgentTool=tt,e.RetrieveProfileTool=bt,e.SendMessageToConnectionTool=rt,e.initializeStandardsAgentKit=async e=>{const t=e?.clientConfig||{},i=t.operatorId||c.env.HEDERA_OPERATOR_ID,s=t.operatorKey||c.env.HEDERA_OPERATOR_KEY,o=t.network||c.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===o?a="mainnet":("testnet"===o||console.warn(`Unsupported network specified: '${o}'. Defaulting to 'testnet'.`),a="testnet"),!i||!s)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const d="true"===c.env.DISABLE_LOGGING,u=r.Logger.getInstance({level:t.logLevel||"info",silent:d}),l=e?.stateManager||new Ct({defaultEnvFilePath:It,defaultPrefix:"TODD"});u.info("State manager initialized");const h=new n.ServerSigner(i,s,a),p=new n.HederaAgentKit(h);await p.initialize(),u.info(`HederaAgentKit initialized for ${i} on ${a}`);const f=new Vr(p,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:t.logLevel});let g,m;if(e?.monitoringClient){const e=new n.ServerSigner(i,s,a);g=new n.HederaAgentKit(e),await g.initialize(),m=new Vr(g,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),u.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new tt({hederaKit:p,hcs10Builder:f,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new lt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.retrieveProfileTool=new bt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.initiateConnectionTool=new st({hederaKit:p,hcs10Builder:f,logger:void 0}),y.listConnectionsTool=new at({hederaKit:p,hcs10Builder:f,logger:void 0}),y.sendMessageToConnectionTool=new rt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.checkMessagesTool=new dt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.connectionMonitorTool=new pt({hederaKit:g||p,hcs10Builder:m||f,logger:void 0}),y.manageConnectionRequestsTool=new gt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.acceptConnectionRequestTool=new yt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new _t({hederaKit:p,hcs10Builder:f,logger:void 0}),u.info("All tools initialized")),{hederaKit:p,hcs10Builder:f,monitoringHederaKit:g,monitoringHcs10Builder:m,tools:y,stateManager:l}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
2
2
|
//# sourceMappingURL=standards-agent-kit.umd.js.map
|