@hashgraphonline/standards-agent-kit 0.2.113 → 0.2.115

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/cjs/standards-agent-kit.cjs +1 -1
  2. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  3. package/dist/cjs/tools/inscriber/InscribeFromBufferTool.d.ts +4 -4
  4. package/dist/cjs/tools/inscriber/InscribeFromFileTool.d.ts +2 -2
  5. package/dist/cjs/tools/inscriber/InscribeFromUrlTool.d.ts +6 -0
  6. package/dist/cjs/tools/inscriber/InscribeHashinalTool.d.ts +6 -0
  7. package/dist/es/standards-agent-kit.es33.js +22 -10
  8. package/dist/es/standards-agent-kit.es33.js.map +1 -1
  9. package/dist/es/standards-agent-kit.es35.js +2 -2
  10. package/dist/es/standards-agent-kit.es35.js.map +1 -1
  11. package/dist/es/standards-agent-kit.es36.js +20 -8
  12. package/dist/es/standards-agent-kit.es36.js.map +1 -1
  13. package/dist/es/tools/inscriber/InscribeFromBufferTool.d.ts +4 -4
  14. package/dist/es/tools/inscriber/InscribeFromFileTool.d.ts +2 -2
  15. package/dist/es/tools/inscriber/InscribeFromUrlTool.d.ts +6 -0
  16. package/dist/es/tools/inscriber/InscribeHashinalTool.d.ts +6 -0
  17. package/dist/umd/standards-agent-kit.umd.js +1 -1
  18. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  19. package/dist/umd/tools/inscriber/InscribeFromBufferTool.d.ts +4 -4
  20. package/dist/umd/tools/inscriber/InscribeFromFileTool.d.ts +2 -2
  21. package/dist/umd/tools/inscriber/InscribeFromUrlTool.d.ts +6 -0
  22. package/dist/umd/tools/inscriber/InscribeHashinalTool.d.ts +6 -0
  23. package/package.json +1 -1
  24. package/src/tools/inscriber/InscribeFromBufferTool.ts +4 -4
  25. package/src/tools/inscriber/InscribeFromUrlTool.ts +28 -10
  26. package/src/tools/inscriber/InscribeHashinalTool.ts +26 -8
@@ -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"),require("unenv/node/fs/promises")):"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","unenv/node/fs/promises"],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,e["unenv/node/fs/promises"])}(this,function(e,t,n,i,r,s,o,a,c,d){"use strict";function l(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const u=l(s),p=l(d);class h extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class g extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var f,m,y;(m=f||(f={})).assertEqual=e=>{},m.assertIs=function(e){},m.assertNever=function(e){throw new Error},m.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},m.getValidEnumValues=e=>{const t=m.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const i of t)n[i]=e[i];return m.objectValues(n)},m.objectValues=e=>m.objectKeys(e).map(function(t){return e[t]}),m.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},m.find=(e,t)=>{for(const n of e)if(t(n))return n},m.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,m.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},m.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(y||(y={})).mergeShapes=(e,t)=>({...e,...t});const b=f.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),w=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:null===e?b.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?b.promise:"undefined"!=typeof Map&&e instanceof Map?b.map:"undefined"!=typeof Set&&e instanceof Set?b.set:"undefined"!=typeof Date&&e instanceof Date?b.date:b.object;default:return b.unknown}},v=f.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 I 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:[]},i=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(i);else if("invalid_return_type"===r.code)i(r.returnTypeError);else if("invalid_arguments"===r.code)i(r.argumentsError);else if(0===r.path.length)n._errors.push(t(r));else{let e=n,i=0;for(;i<r.path.length;){const n=r.path[i];i===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],i++}}};return i(this),n}static assert(e){if(!(e instanceof I))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,f.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const i of this.issues)if(i.path.length>0){const n=i.path[0];t[n]=t[n]||[],t[n].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}I.create=e=>new I(e);const T=(e,t)=>{let n;switch(e.code){case v.invalid_type:n=e.received===b.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,f.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${f.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${f.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${f.joinValues(e.options)}, received '${e.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.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}"`:f.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case v.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 v.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 v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=t.defaultError,f.assertNever(e)}return{message:n}};let A=T;function _(e,t){const n=A,i=(e=>{const{data:t,path:n,errorMaps:i,issueData:r}=e,s=[...n,...r.path||[]],o={...r,path:s};if(void 0!==r.message)return{...r,path:s,message:r.message};let a="";const c=i.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...r,path:s,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===T?void 0:T].filter(e=>!!e)});e.common.issues.push(i)}class C{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 i of t){if("aborted"===i.status)return E;"dirty"===i.status&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const i of t){const e=await i.key,t=await i.value;n.push({key:e,value:t})}return C.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const i of t){const{key:t,value:r}=i;if("aborted"===t.status)return E;if("aborted"===r.status)return E;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),"__proto__"===t.value||void 0===r.value&&!i.alwaysSet||(n[t.value]=r.value)}return{status:e.value,value:n}}}const E=Object.freeze({status:"aborted"}),R=e=>({status:"dirty",value:e}),S=e=>({status:"valid",value:e}),x=e=>"aborted"===e.status,k=e=>"dirty"===e.status,N=e=>"valid"===e.status,O=e=>"undefined"!=typeof Promise&&e instanceof Promise;var $,P;(P=$||($={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},P.toString=e=>"string"==typeof e?e:e?.message;class M{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}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 F=(e,t)=>{if(N(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 I(e.common.issues);return this._error=t,this._error}}};function B(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:i,description:r}=e;if(t&&(n||i))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(t,r)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??r.defaultError}:void 0===r.data?{message:s??i??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:s??n??r.defaultError}},description:r}}class D{get description(){return this._def.description}_getType(e){return w(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:w(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:w(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(O(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:w(e)},i=this._parseSync({data:e,path:n.path,parent:n});return F(n,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:w(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return N(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=>N(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:w(e)},i=this._parse({data:e,path:n.path,parent:n}),r=await(O(i)?i:Promise.resolve(i));return F(n,r)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,i)=>{const r=e(t),s=()=>i.addIssue({code:v.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then(e=>!!e||(s(),!1)):!!r||(s(),!1)})}refinement(e,t){return this._refinement((n,i)=>!!e(n)||(i.addIssue("function"==typeof t?t(n,i):t),!1))}_refinement(e){return new Be({schema:this,typeName:ze.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 De.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ie.create(this)}promise(){return Fe.create(this,this._def)}or(e){return _e.create([this,e],this._def)}and(e){return Ee.create(this,e,this._def)}transform(e){return new Be({...B(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new qe({...B(this._def),innerType:this,defaultValue:t,typeName:ze.ZodDefault})}brand(){return new Ke({typeName:ze.ZodBranded,type:this,...B(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...B(this._def),innerType:this,catchValue:t,typeName:ze.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return He.create(this,e)}readonly(){return Ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const L=/^c[^\s-]{8,}$/i,q=/^[0-9a-z]+$/,U=/^[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,K=/^[a-z0-9_-]{21}$/i,H=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Z=/^[-+]?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)?)??$/,z=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let G;const W=/^(?:(?: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])$/,V=/^(?:(?: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])$/,J=/^(([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]))$/,Q=/^(([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])$/,X=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Y=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ee="((\\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])))",te=new RegExp(`^${ee}$`);function ne(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 ie(e){return new RegExp(`^${ne(e)}$`)}function re(e){let t=`${ee}T${ne(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 se(e,t){return!("v4"!==t&&t||!W.test(e))||!("v6"!==t&&t||!J.test(e))}function oe(e,t){if(!H.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const i=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(i));return"object"==typeof r&&null!==r&&((!("typ"in r)||"JWT"===r?.typ)&&(!!r.alg&&(!t||r.alg===t)))}catch{return!1}}function ae(e,t){return!("v4"!==t&&t||!V.test(e))||!("v6"!==t&&t||!Q.test(e))}class ce extends D{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==b.string){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.string,received:t.parsedType}),E}const t=new C;let n;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const r=e.data.length>i.value,s=e.data.length<i.value;(r||s)&&(n=this._getOrReturnCtx(e,n),r?_(n,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&_(n,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)z.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"email",code:v.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)G||(G=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),G.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"emoji",code:v.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"uuid",code:v.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)K.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"nanoid",code:v.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)L.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cuid",code:v.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)q.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cuid2",code:v.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"ulid",code:v.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),_(n,{validation:"url",code:v.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"regex",code:v.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){re(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){te.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){ie(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?Z.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"duration",code:v.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?se(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"ip",code:v.invalid_string,message:i.message}),t.dirty()):"jwt"===i.kind?oe(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"jwt",code:v.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?ae(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cidr",code:v.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?X.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"base64",code:v.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Y.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"base64url",code:v.invalid_string,message:i.message}),t.dirty()):f.assertNever(i);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:v.invalid_string,...$.errToObj(n)})}_addCheck(e){return new ce({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$.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,...$.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,...$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...$.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...$.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...$.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...$.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...$.errToObj(t)})}nonempty(e){return this.min(1,$.errToObj(e))}trim(){return new ce({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ce({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ce({...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 de(e,t){const n=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,r=n>i?n:i;return Number.parseInt(e.toFixed(r).replace(".",""))%Number.parseInt(t.toFixed(r).replace(".",""))/10**r}ce.create=e=>new ce({checks:[],typeName:ze.ZodString,coerce:e?.coerce??!1,...B(e)});class le extends D{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)!==b.number){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.number,received:t.parsedType}),E}let t;const n=new C;for(const i of this._def.checks)if("int"===i.kind)f.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),_(t,{code:v.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty());else if("min"===i.kind){(i.inclusive?e.data<i.value:e.data<=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty())}else if("max"===i.kind){(i.inclusive?e.data>i.value:e.data>=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty())}else"multipleOf"===i.kind?0!==de(e.data,i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),_(t,{code:v.not_finite,message:i.message}),n.dirty()):f.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,n,i){return new le({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$.toString(i)}]})}_addCheck(e){return new le({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:$.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$.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&&f.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)}}le.create=e=>new le({checks:[],typeName:ze.ZodNumber,coerce:e?.coerce||!1,...B(e)});class ue extends D{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)!==b.bigint)return this._getInvalidInput(e);let t;const n=new C;for(const i of this._def.checks)if("min"===i.kind){(i.inclusive?e.data<i.value:e.data<=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty())}else if("max"===i.kind){(i.inclusive?e.data>i.value:e.data>=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty())}else"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):f.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.bigint,received:t.parsedType}),E}gte(e,t){return this.setLimit("min",e,!0,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,n,i){return new ue({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$.toString(i)}]})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.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}}ue.create=e=>new ue({checks:[],typeName:ze.ZodBigInt,coerce:e?.coerce??!1,...B(e)});class pe extends D{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==b.boolean){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.boolean,received:t.parsedType}),E}return S(e.data)}}pe.create=e=>new pe({typeName:ze.ZodBoolean,coerce:e?.coerce||!1,...B(e)});class he extends D{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==b.date){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.date,received:t.parsedType}),E}if(Number.isNaN(e.data.getTime())){return _(this._getOrReturnCtx(e),{code:v.invalid_date}),E}const t=new C;let n;for(const i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),t.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):f.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new he({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$.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}}he.create=e=>new he({checks:[],coerce:e?.coerce||!1,typeName:ze.ZodDate,...B(e)});class ge extends D{_parse(e){if(this._getType(e)!==b.symbol){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.symbol,received:t.parsedType}),E}return S(e.data)}}ge.create=e=>new ge({typeName:ze.ZodSymbol,...B(e)});class fe extends D{_parse(e){if(this._getType(e)!==b.undefined){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.undefined,received:t.parsedType}),E}return S(e.data)}}fe.create=e=>new fe({typeName:ze.ZodUndefined,...B(e)});class me extends D{_parse(e){if(this._getType(e)!==b.null){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.null,received:t.parsedType}),E}return S(e.data)}}me.create=e=>new me({typeName:ze.ZodNull,...B(e)});class ye extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return S(e.data)}}ye.create=e=>new ye({typeName:ze.ZodAny,...B(e)});class be extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return S(e.data)}}be.create=e=>new be({typeName:ze.ZodUnknown,...B(e)});class we extends D{_parse(e){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.never,received:t.parsedType}),E}}we.create=e=>new we({typeName:ze.ZodNever,...B(e)});class ve extends D{_parse(e){if(this._getType(e)!==b.undefined){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.void,received:t.parsedType}),E}return S(e.data)}}ve.create=e=>new ve({typeName:ze.ZodVoid,...B(e)});class Ie extends D{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==b.array)return _(t,{code:v.invalid_type,expected:b.array,received:t.parsedType}),E;if(null!==i.exactLength){const e=t.data.length>i.exactLength.value,r=t.data.length<i.exactLength.value;(e||r)&&(_(t,{code:e?v.too_big:v.too_small,minimum:r?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(_(t,{code:v.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(_(t,{code:v.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>i.type._parseAsync(new M(t,e,t.path,n)))).then(e=>C.mergeArray(n,e));const r=[...t.data].map((e,n)=>i.type._parseSync(new M(t,e,t.path,n)));return C.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new Ie({...this._def,minLength:{value:e,message:$.toString(t)}})}max(e,t){return new Ie({...this._def,maxLength:{value:e,message:$.toString(t)}})}length(e,t){return new Ie({...this._def,exactLength:{value:e,message:$.toString(t)}})}nonempty(e){return this.min(1,e)}}function Te(e){if(e instanceof Ae){const t={};for(const n in e.shape){const i=e.shape[n];t[n]=De.create(Te(i))}return new Ae({...e._def,shape:()=>t})}return e instanceof Ie?new Ie({...e._def,type:Te(e.element)}):e instanceof De?De.create(Te(e.unwrap())):e instanceof Le?Le.create(Te(e.unwrap())):e instanceof Re?Re.create(e.items.map(e=>Te(e))):e}Ie.create=(e,t)=>new Ie({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...B(t)});class Ae extends D{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=f.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==b.object){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.object,received:t.parsedType}),E}const{status:t,ctx:n}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),s=[];if(!(this._def.catchall instanceof we&&"strip"===this._def.unknownKeys))for(const a in n.data)r.includes(a)||s.push(a);const o=[];for(const a of r){const e=i[a],t=n.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new M(n,t,n.path,a)),alwaysSet:a in n.data})}if(this._def.catchall instanceof we){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&&(_(n,{code:v.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 i=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new M(n,i,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,i=await t.value;e.push({key:n,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>C.mergeObjectSync(t,e)):C.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return $.errToObj,new Ae({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const i=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:$.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new Ae({...this._def,unknownKeys:"strip"})}passthrough(){return new Ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ze.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ae({...this._def,catchall:e})}pick(e){const t={};for(const n of f.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new Ae({...this._def,shape:()=>t})}omit(e){const t={};for(const n of f.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new Ae({...this._def,shape:()=>t})}deepPartial(){return Te(this)}partial(e){const t={};for(const n of f.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new Ae({...this._def,shape:()=>t})}required(e){const t={};for(const n of f.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof De;)e=e._def.innerType;t[n]=e}return new Ae({...this._def,shape:()=>t})}keyof(){return $e(f.objectKeys(this.shape))}}Ae.create=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strip",catchall:we.create(),typeName:ze.ZodObject,...B(t)}),Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:we.create(),typeName:ze.ZodObject,...B(t)}),Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:we.create(),typeName:ze.ZodObject,...B(t)});class _e extends D{_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 i of e)if("dirty"===i.result.status)return t.common.issues.push(...i.ctx.common.issues),i.result;const n=e.map(e=>new I(e.ctx.common.issues));return _(t,{code:v.invalid_union,unionErrors:n}),E});{let e;const i=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},r=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===r.status)return r;"dirty"!==r.status||e||(e={result:r,ctx:n}),n.common.issues.length&&i.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=i.map(e=>new I(e));return _(t,{code:v.invalid_union,unionErrors:r}),E}}get options(){return this._def.options}}function Ce(e,t){const n=w(e),i=w(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&i===b.object){const n=f.objectKeys(t),i=f.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const s of i){const n=Ce(e[s],t[s]);if(!n.valid)return{valid:!1};r[s]=n.data}return{valid:!0,data:r}}if(n===b.array&&i===b.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let i=0;i<e.length;i++){const r=Ce(e[i],t[i]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===b.date&&i===b.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}_e.create=(e,t)=>new _e({options:e,typeName:ze.ZodUnion,...B(t)});class Ee extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=(e,i)=>{if(x(e)||x(i))return E;const r=Ce(e.value,i.value);return r.valid?((k(e)||k(i))&&t.dirty(),{status:t.value,value:r.data}):(_(n,{code:v.invalid_intersection_types}),E)};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])=>i(e,t)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ee.create=(e,t,n)=>new Ee({left:e,right:t,typeName:ze.ZodIntersection,...B(n)});class Re extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.array)return _(n,{code:v.invalid_type,expected:b.array,received:n.parsedType}),E;if(n.data.length<this._def.items.length)return _(n,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&n.data.length>this._def.items.length&&(_(n,{code:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((e,t)=>{const i=this._def.items[t]||this._def.rest;return i?i._parse(new M(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(i).then(e=>C.mergeArray(t,e)):C.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Re({...this._def,rest:e})}}Re.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Re({items:e,typeName:ze.ZodTuple,rest:null,...B(t)})};class Se extends D{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!==b.object)return _(n,{code:v.invalid_type,expected:b.object,received:n.parsedType}),E;const i=[],r=this._def.keyType,s=this._def.valueType;for(const o in n.data)i.push({key:r._parse(new M(n,o,n.path,o)),value:s._parse(new M(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?C.mergeObjectAsync(t,i):C.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return new Se(t instanceof D?{keyType:e,valueType:t,typeName:ze.ZodRecord,...B(n)}:{keyType:ce.create(),valueType:e,typeName:ze.ZodRecord,...B(t)})}}class xe extends D{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!==b.map)return _(n,{code:v.invalid_type,expected:b.map,received:n.parsedType}),E;const i=this._def.keyType,r=this._def.valueType,s=[...n.data.entries()].map(([e,t],s)=>({key:i._parse(new M(n,e,n.path,[s,"key"])),value:r._parse(new M(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 i=await n.key,r=await n.value;if("aborted"===i.status||"aborted"===r.status)return E;"dirty"!==i.status&&"dirty"!==r.status||t.dirty(),e.set(i.value,r.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of s){const i=n.key,r=n.value;if("aborted"===i.status||"aborted"===r.status)return E;"dirty"!==i.status&&"dirty"!==r.status||t.dirty(),e.set(i.value,r.value)}return{status:t.value,value:e}}}}xe.create=(e,t,n)=>new xe({valueType:t,keyType:e,typeName:ze.ZodMap,...B(n)});class ke extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return _(n,{code:v.invalid_type,expected:b.set,received:n.parsedType}),E;const i=this._def;null!==i.minSize&&n.data.size<i.minSize.value&&(_(n,{code:v.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&n.data.size>i.maxSize.value&&(_(n,{code:v.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const r=this._def.valueType;function s(e){const n=new Set;for(const i of e){if("aborted"===i.status)return E;"dirty"===i.status&&t.dirty(),n.add(i.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>r._parse(new M(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(e,t){return new ke({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new ke({...this._def,maxSize:{value:e,message:$.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ke.create=(e,t)=>new ke({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...B(t)});class Ne extends D{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})}}Ne.create=(e,t)=>new Ne({getter:e,typeName:ze.ZodLazy,...B(t)});class Oe extends D{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return _(t,{received:t.data,code:v.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}function $e(e,t){return new Pe({values:e,typeName:ze.ZodEnum,...B(t)})}Oe.create=(e,t)=>new Oe({value:e,typeName:ze.ZodLiteral,...B(t)});class Pe extends D{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return _(t,{expected:f.joinValues(n),received:t.parsedType,code:v.invalid_type}),E}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 _(t,{received:t.data,code:v.invalid_enum_value,options:n}),E}return S(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 Pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Pe.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Pe.create=$e;class Me extends D{_parse(e){const t=f.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const e=f.objectValues(t);return _(n,{expected:f.joinValues(e),received:n.parsedType,code:v.invalid_type}),E}if(this._cache||(this._cache=new Set(f.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=f.objectValues(t);return _(n,{received:n.data,code:v.invalid_enum_value,options:e}),E}return S(e.data)}get enum(){return this._def.values}}Me.create=(e,t)=>new Me({values:e,typeName:ze.ZodNativeEnum,...B(t)});class Fe extends D{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.promise&&!1===t.common.async)return _(t,{code:v.invalid_type,expected:b.promise,received:t.parsedType}),E;const n=t.parsedType===b.promise?t.data:Promise.resolve(t.data);return S(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Fe.create=(e,t)=>new Fe({type:e,typeName:ze.ZodPromise,...B(t)});class Be extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,r={addIssue:e=>{_(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),"preprocess"===i.type){const e=i.transform(n.data,r);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return E;const i=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===i.status?E:"dirty"===i.status||"dirty"===t.value?R(i.value):i});{if("aborted"===t.value)return E;const i=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===i.status?E:"dirty"===i.status||"dirty"===t.value?R(i.value):i}}if("refinement"===i.type){const e=e=>{const t=i.refinement(e,r);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 i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===i.status?E:("dirty"===i.status&&t.dirty(),e(i.value),{status:t.value,value:i.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?E:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===i.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!N(e))return E;const s=i.transform(e.value,r);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=>N(e)?Promise.resolve(i.transform(e.value,r)).then(e=>({status:t.value,value:e})):E)}f.assertNever(i)}}Be.create=(e,t,n)=>new Be({schema:e,typeName:ze.ZodEffects,effect:t,...B(n)}),Be.createWithPreprocess=(e,t,n)=>new Be({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...B(n)});class De extends D{_parse(e){return this._getType(e)===b.undefined?S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:ze.ZodOptional,...B(t)});class Le extends D{_parse(e){return this._getType(e)===b.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(e,t)=>new Le({innerType:e,typeName:ze.ZodNullable,...B(t)});class qe extends D{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===b.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:ze.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...B(t)});class Ue extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return O(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new I(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new I(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ue.create=(e,t)=>new Ue({innerType:e,typeName:ze.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...B(t)});class je extends D{_parse(e){if(this._getType(e)!==b.nan){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.nan,received:t.parsedType}),E}return{status:"valid",value:e.data}}}je.create=e=>new je({typeName:ze.ZodNaN,...B(e)});class Ke extends D{_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 He extends D{_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?E:"dirty"===e.status?(t.dirty(),R(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?E:"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 He({in:e,out:t,typeName:ze.ZodPipeline})}}class Ze extends D{_parse(e){const t=this._def.innerType._parse(e),n=e=>(N(e)&&(e.value=Object.freeze(e.value)),e);return O(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var ze,Ge;Ze.create=(e,t)=>new Ze({innerType:e,typeName:ze.ZodReadonly,...B(t)}),(Ge=ze||(ze={})).ZodString="ZodString",Ge.ZodNumber="ZodNumber",Ge.ZodNaN="ZodNaN",Ge.ZodBigInt="ZodBigInt",Ge.ZodBoolean="ZodBoolean",Ge.ZodDate="ZodDate",Ge.ZodSymbol="ZodSymbol",Ge.ZodUndefined="ZodUndefined",Ge.ZodNull="ZodNull",Ge.ZodAny="ZodAny",Ge.ZodUnknown="ZodUnknown",Ge.ZodNever="ZodNever",Ge.ZodVoid="ZodVoid",Ge.ZodArray="ZodArray",Ge.ZodObject="ZodObject",Ge.ZodUnion="ZodUnion",Ge.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ge.ZodIntersection="ZodIntersection",Ge.ZodTuple="ZodTuple",Ge.ZodRecord="ZodRecord",Ge.ZodMap="ZodMap",Ge.ZodSet="ZodSet",Ge.ZodFunction="ZodFunction",Ge.ZodLazy="ZodLazy",Ge.ZodLiteral="ZodLiteral",Ge.ZodEnum="ZodEnum",Ge.ZodEffects="ZodEffects",Ge.ZodNativeEnum="ZodNativeEnum",Ge.ZodOptional="ZodOptional",Ge.ZodNullable="ZodNullable",Ge.ZodDefault="ZodDefault",Ge.ZodCatch="ZodCatch",Ge.ZodPromise="ZodPromise",Ge.ZodBranded="ZodBranded",Ge.ZodPipeline="ZodPipeline",Ge.ZodReadonly="ZodReadonly";const We=ce.create,Ve=le.create,Je=pe.create,Qe=be.create;we.create;const Xe=Ie.create,Ye=Ae.create,et=_e.create;Ee.create,Re.create;const tt=Se.create,nt=Pe.create,it=Me.create;Fe.create,De.create,Le.create;const rt=class{static parseCapabilities(e){if(!e)return[i.AIAgentCapability.TEXT_GENERATION];const t=e.toLowerCase(),n=new Set;for(const[i,r]of Object.entries(this.CAPABILITY_MAPPINGS))t.includes(i)&&r.forEach(e=>n.add(e));return 0===n.size&&n.add(i.AIAgentCapability.TEXT_GENERATION),Array.from(n)}static parseTagsOrCapabilities(e){if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=new Set;return e.forEach(e=>{this.parseCapabilities(e).forEach(e=>t.add(e))}),Array.from(t)}return"string"==typeof e?this.parseCapabilities(e):[i.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[i.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[i.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[i.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[i.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[i.AIAgentCapability.CODE_GENERATION]:"Code Generation",[i.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[i.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[i.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[i.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[i.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[i.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[i.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[i.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[i.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[i.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[i.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[i.AIAgentCapability.API_INTEGRATION]:"API Integration",[i.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};rt.CAPABILITY_MAPPINGS={ai:[i.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[i.AIAgentCapability.TEXT_GENERATION],chat:[i.AIAgentCapability.TEXT_GENERATION],conversation:[i.AIAgentCapability.TEXT_GENERATION],text:[i.AIAgentCapability.TEXT_GENERATION],"text generation":[i.AIAgentCapability.TEXT_GENERATION],image:[i.AIAgentCapability.IMAGE_GENERATION],picture:[i.AIAgentCapability.IMAGE_GENERATION],visual:[i.AIAgentCapability.IMAGE_GENERATION],photo:[i.AIAgentCapability.IMAGE_GENERATION],audio:[i.AIAgentCapability.AUDIO_GENERATION],sound:[i.AIAgentCapability.AUDIO_GENERATION],voice:[i.AIAgentCapability.AUDIO_GENERATION],speech:[i.AIAgentCapability.AUDIO_GENERATION],video:[i.AIAgentCapability.VIDEO_GENERATION],movie:[i.AIAgentCapability.VIDEO_GENERATION],animation:[i.AIAgentCapability.VIDEO_GENERATION],code:[i.AIAgentCapability.CODE_GENERATION],programming:[i.AIAgentCapability.CODE_GENERATION],development:[i.AIAgentCapability.CODE_GENERATION],coding:[i.AIAgentCapability.CODE_GENERATION],translate:[i.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[i.AIAgentCapability.LANGUAGE_TRANSLATION],language:[i.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[i.AIAgentCapability.DATA_INTEGRATION],"data processing":[i.AIAgentCapability.DATA_INTEGRATION],"data integration":[i.AIAgentCapability.DATA_INTEGRATION],etl:[i.AIAgentCapability.DATA_INTEGRATION],market:[i.AIAgentCapability.MARKET_INTELLIGENCE],trading:[i.AIAgentCapability.MARKET_INTELLIGENCE],finance:[i.AIAgentCapability.MARKET_INTELLIGENCE],financial:[i.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[i.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[i.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[i.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[i.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[i.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[i.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[i.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[i.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[i.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[i.AIAgentCapability.GOVERNANCE_FACILITATION],security:[i.AIAgentCapability.SECURITY_MONITORING],monitoring:[i.AIAgentCapability.SECURITY_MONITORING],threat:[i.AIAgentCapability.SECURITY_MONITORING],compliance:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[i.AIAgentCapability.FRAUD_DETECTION],detection:[i.AIAgentCapability.FRAUD_DETECTION],anomaly:[i.AIAgentCapability.FRAUD_DETECTION],coordination:[i.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[i.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[i.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[i.AIAgentCapability.API_INTEGRATION],integration:[i.AIAgentCapability.API_INTEGRATION],webhook:[i.AIAgentCapability.API_INTEGRATION],workflow:[i.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[i.AIAgentCapability.WORKFLOW_AUTOMATION],process:[i.AIAgentCapability.WORKFLOW_AUTOMATION]};let st=rt;const ot=Ye({name:We().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:We().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:We().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:nt(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:We().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:et([Xe(it(i.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Agent capabilities - can be capability names (e.g. "ai", "data processing"), capability enum values, or array of either. Common values: "ai"/"text" (TEXT_GENERATION), "data" (DATA_INTEGRATION), "analytics" (TRANSACTION_ANALYTICS)'),tags:et([Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):st.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:We().optional().describe("Creator attribution for the agent"),socials:tt(nt(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),We()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:tt(Qe()).optional().describe("Custom metadata properties for the agent"),profilePicture:et([We().describe("URL or local file path to profile picture"),Ye({url:We().optional(),path:We().optional(),filename:We().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:We().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:Ve().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:We().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:Ve().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:Xe(Ye({amount:Ve().positive(),tokenId:We()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Xe(We()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Je().optional().describe("Whether to set as current agent (default: true)"),persistence:Ye({prefix:We().optional()}).optional().describe("Optional persistence configuration")});class at extends h{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. Supports natural language for capabilities/tags like "ai", "data processing", "analytics". 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=ot,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;this.specificArgs=t;const i={name:t.name};if(void 0!==t.description&&(i.bio=t.description),void 0!==t.alias)i.alias=t.alias;else{const e=Date.now().toString(36);i.alias=`${t.name}${e}`}if(void 0!==t.type&&(i.type=t.type),void 0!==t.model&&(i.model=t.model),void 0!==t.tags?i.capabilities=t.tags:void 0!==t.capabilities&&(i.capabilities=t.capabilities),void 0!==t.creator&&(i.creator=t.creator),void 0!==t.socials&&(i.socials=t.socials),void 0!==t.properties&&(i.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)i.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),i.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(i.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(i.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(i.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(i.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(i.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(i.initialBalance=t.initialBalance),await n.registerAgent(i)}async _call(e,t){const n=await super._call(e,t),i=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&i)try{const e=JSON.parse(n);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(r){}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,i=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,r=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,s=e.privateKey||e.metadata?.privateKey;if(t&&n&&i&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:n,outboundTopicId:i,profileTopicId:r,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 ct=Ye({targetIdentifier:We().optional().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."),connectionId:We().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:We().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:We().describe("The text message content to send."),disableMonitoring:Je().optional().default(!1)});class dt extends h{constructor(e){super(e),this.name="send_message_to_connection",this.description="Use this to send a message to an agent you already have an active connection with. Provide the target agent's account ID (e.g., 0.0.12345) and your message. If no active connection exists, this will fail - use initiate_connection instead to create a new connection first.",this.specificInputSchema=ct,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e,i=t.targetIdentifier||t.agentId||t.connectionId;if(!i)throw new Error("Either targetIdentifier, connectionId, or agentId must be provided");const r=n.getStateManager();if(r){const e=r.getConnectionsManager();if(e)try{const t=r.getCurrentAgent();t&&t.accountId&&await e.fetchConnectionData(t.accountId)}catch(s){console.debug("Could not refresh connections:",s)}if(i.match(/^\d+$/)){const e=r.listConnections(),s=parseInt(i)-1,o=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(s>=0&&s<o.length){const e=o[s];if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}if(i.match(/^\d+\.\d+\.\d+$/)){const e=r.listConnections().find(e=>!(e.targetAccountId!==i&&e.targetAccountId!==`0.0.${i}`||"established"!==e.status||e.isPending||e.needsConfirmation));if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}await n.sendMessageToConnection({targetIdentifier:i,message:t.message,disableMonitoring:t.disableMonitoring})}}const lt=Ye({targetAccountId:We().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:Je().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:We().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 ut extends h{constructor(e){super(e),this.name="initiate_connection",this.description="ONLY use this to START a BRAND NEW connection to an agent you have NEVER connected to before. If you already have an active connection to this agent, use send_message_to_connection instead. This creates a new connection request and waits for acceptance.",this.specificInputSchema=lt,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,i={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(i.disableMonitor=t.disableMonitor),void 0!==t.memo&&(i.memo=t.memo),await n.initiateConnection(i)}}const pt=Ye({includeDetails:Je().optional().describe("Whether to include detailed information about each connection"),showPending:Je().optional().describe("Whether to include pending connection requests")});class ht extends g{constructor(e){super(e),this.name="list_connections",this.description="Lists all active HCS-10 connections. Use this FIRST before sending messages to check if you already have an active connection to a target agent. Shows connection details and agent information for each active connection.",this.specificInputSchema=pt}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 i=await t.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return i}}const gt=Ye({targetIdentifier:We().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:Je().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:Ve().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class ft extends g{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=gt}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const i=this.hcs10Builder;await i.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return r}}const mt=Ye({accountId:We().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:et([Xe(it(i.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class yt extends g{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/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=mt}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,i={};e&&(i.accountId=e),t&&(i.tags=t),await n.findRegistrations(i);const r=await n.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return r}}const bt=Ye({acceptAll:Je().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:We().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:Xe(Ye({amount:Ve(),collectorAccount:We().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Xe(Ye({amount:Ve(),tokenId:We(),collectorAccount:We().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:Xe(We()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:Ve().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:We().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class wt extends h{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=bt,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 vt=Ye({action:nt(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:We().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class It extends g{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=vt}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,i={action:e};void 0!==t&&(i.requestKey=t),await n.manageConnectionRequests(i);const r=await n.execute();return"rawResult"in r?r.rawResult:r}}const Tt=Ye({requestKey:We().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:Ve().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:Xe(We()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class At extends h{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=Tt,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 _t=Ye({accountId:We().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:Je().optional().describe("Optional: Force refresh from the network instead of using cache.")});class Ct extends g{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=_t}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,i={accountId:e};void 0!==t&&(i.disableCache=t),await n.retrieveProfile(i);const r=await n.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return r}}const Et=Ye({});class Rt extends g{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=Et}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class St extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class xt extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const kt=Ye({registryType:it(i.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:Ve().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:et([We(),Je()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:et([We(),Je()]).optional().describe("Submit key: public key string or true to use operator key")});const Nt=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:We().optional().describe("Optional metadata URI (HIP-412 format)"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const Ot=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:We().describe("The unique ID of the entry to update"),metadata:We().optional().describe("Optional metadata URI (HIP-412 format)"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const $t=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:We().describe("The unique ID of the entry to delete"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const Pt=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:We().optional().describe("Optional metadata URI for migration details"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const Mt=Ye({topicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:Ve().int().positive().optional().describe("Maximum number of entries to return"),order:nt(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:Ve().int().min(0).optional().describe("Number of entries to skip")});class Ft extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Bt extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const Dt=Ye({ttl:Ve().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),adminKey:et([Je(),We()]).optional().describe("Admin key for the registry topic. Can be boolean (use operator key) or a public key string"),submitKey:et([Je(),We()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Lt=Ye({metadata:tt(Qe()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:Ye({base64:We().optional().describe("Base64 encoded data for the hashinal"),url:We().optional().describe("URL to fetch data from"),mimeType:We().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:We().optional().describe("Optional memo for the registration"),ttl:Ve().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:We().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:We().optional().describe("Submit key for the registry (required if registry has a submit key)")});const qt=Ye({registryTopicId:We().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:tt(Qe()).describe("Updated metadata object for the hashinal"),data:Ye({base64:We().optional().describe("Base64 encoded data for the updated hashinal"),url:We().optional().describe("URL to fetch updated data from"),mimeType:We().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:We().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:We().describe("Submit key for the registry (required to update)")});const Ut=Ye({topicId:We().describe("The registry topic ID to query"),limit:Ve().optional().default(100).describe("Maximum number of entries to retrieve"),order:nt(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:Ve().optional().describe("Number of entries to skip")});class jt extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}class Kt extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}const Ht=Ye({url:We().url().describe("The URL of the content to inscribe"),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Qe()).optional().describe("Metadata to attach to the inscription"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),apiKey:We().optional().describe("API key for inscription service")});const Zt=Ye({filePath:We().min(1,"File path cannot be empty").describe("The file path of the content to inscribe. Must point to a valid, non-empty file."),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Qe()).optional().describe("Metadata to attach to the inscription"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:We().optional().describe("API key for inscription service")});const zt=Ye({base64Data:We().min(1,"Base64 data cannot be empty").describe("Base64 encoded content to inscribe. Must contain valid, non-empty content (minimum 10 bytes after decoding)."),fileName:We().min(1,"File name cannot be empty").describe("Name for the inscribed content. Required for all inscriptions."),mimeType:We().optional().describe("MIME type of the content"),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Qe()).optional().describe("Metadata to attach to the inscription"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:We().optional().describe("API key for inscription service")});const Gt=Ye({url:We().url().describe("The URL of the content to inscribe as Hashinal NFT"),name:We().describe("Name of the Hashinal NFT"),creator:We().describe("Creator account ID or name"),description:We().describe("Description of the Hashinal NFT"),type:We().describe('Type of NFT (e.g., "image", "video", "audio")'),attributes:Xe(Ye({trait_type:We(),value:et([We(),Ve()])})).optional().describe("NFT attributes"),properties:tt(Qe()).optional().describe("Additional properties"),jsonFileURL:We().url().optional().describe("URL to JSON metadata file"),tags:Xe(We()).optional().describe("Tags to categorize the NFT"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),apiKey:We().optional().describe("API key for inscription service")});const Wt=Ye({transactionId:We().describe("The transaction ID of the inscription to retrieve"),apiKey:We().optional().describe("API key for inscription service")});const Vt=s.join(c.cwd(),".env");class Jt{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 i.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 i.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 i=this.connectionsManager.getConnectionByTopicId(e);if(i)return this.convertToActiveConnection(i);const r=this.connectionsManager.getConnectionByAccountId(e);return r?this.convertToActiveConnection(r):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",i=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const s={[`${i}_ACCOUNT_ID`]:e.accountId,[`${i}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${i}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${i}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${i}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";r.existsSync(e)&&(n=r.readFileSync(e,"utf8"));const i=[...n.split("\n")];for(const[r,s]of Object.entries(t)){const e=i.findIndex(e=>e.startsWith(`${r}=`));-1!==e?i[e]=`${r}=${s}`:i.push(`${r}=${s}`)}r.writeFileSync(e,i.join("\n"))}(n,s)}}function Qt(e,t){return function(){return e.apply(t,arguments)}}const{toString:Xt}=Object.prototype,{getPrototypeOf:Yt}=Object,{iterator:en,toStringTag:tn}=Symbol,nn=(e=>t=>{const n=Xt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),rn=e=>(e=e.toLowerCase(),t=>nn(t)===e),sn=e=>t=>typeof t===e,{isArray:on}=Array,an=sn("undefined");function cn(e){return null!==e&&!an(e)&&null!==e.constructor&&!an(e.constructor)&&un(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const dn=rn("ArrayBuffer");const ln=sn("string"),un=sn("function"),pn=sn("number"),hn=e=>null!==e&&"object"==typeof e,gn=e=>{if("object"!==nn(e))return!1;const t=Yt(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||tn in e||en in e)},fn=rn("Date"),mn=rn("File"),yn=rn("Blob"),bn=rn("FileList"),wn=rn("URLSearchParams"),[vn,In,Tn,An]=["ReadableStream","Request","Response","Headers"].map(rn);function _n(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),on(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(cn(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let o;for(i=0;i<s;i++)o=r[i],t.call(null,e[o],o,e)}}function Cn(e,t){if(cn(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const En="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:o,Rn=e=>!an(e)&&e!==En;const Sn=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Yt(Uint8Array)),xn=rn("HTMLFormElement"),kn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Nn=rn("RegExp"),On=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};_n(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const $n=rn("AsyncFunction"),Pn=(Mn="function"==typeof a.setImmediate,Fn=un(En.postMessage),Mn?a.setImmediate:Fn?(Bn=`axios@${Math.random()}`,Dn=[],En.addEventListener("message",({source:e,data:t})=>{e===En&&t===Bn&&Dn.length&&Dn.shift()()},!1),e=>{Dn.push(e),En.postMessage(Bn,"*")}):e=>setTimeout(e));var Mn,Fn,Bn,Dn;const Ln="undefined"!=typeof queueMicrotask?queueMicrotask.bind(En):void 0!==c&&c.nextTick||Pn,qn={isArray:on,isArrayBuffer:dn,isBuffer:cn,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||un(e.append)&&("formdata"===(t=nn(e))||"object"===t&&un(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&dn(e.buffer),t},isString:ln,isNumber:pn,isBoolean:e=>!0===e||!1===e,isObject:hn,isPlainObject:gn,isEmptyObject:e=>{if(!hn(e)||cn(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:vn,isRequest:In,isResponse:Tn,isHeaders:An,isUndefined:an,isDate:fn,isFile:mn,isBlob:yn,isRegExp:Nn,isFunction:un,isStream:e=>hn(e)&&un(e.pipe),isURLSearchParams:wn,isTypedArray:Sn,isFileList:bn,forEach:_n,merge:function e(){const{caseless:t}=Rn(this)&&this||{},n={},i=(i,r)=>{const s=t&&Cn(n,r)||r;gn(n[s])&&gn(i)?n[s]=e(n[s],i):gn(i)?n[s]=e({},i):on(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&_n(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(_n(t,(t,i)=>{n&&un(t)?e[i]=Qt(t,n):e[i]=t},{allOwnKeys:i}),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,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,s,o;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)o=r[s],i&&!i(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==n&&Yt(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:nn,kindOfTest:rn,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(on(e))return e;let t=e.length;if(!pn(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[en]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:xn,hasOwnProperty:kn,hasOwnProp:kn,reduceDescriptors:On,freezeMethods:e=>{On(e,(t,n)=>{if(un(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];un(i)&&(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={},i=e=>{e.forEach(e=>{n[e]=!0})};return on(e)?i(e):i(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:Cn,global:En,isContextDefined:Rn,isSpecCompliantForm:function(e){return!!(e&&un(e.append)&&"FormData"===e[tn]&&e[en])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(hn(e)){if(t.indexOf(e)>=0)return;if(cn(e))return e;if(!("toJSON"in e)){t[i]=e;const r=on(e)?[]:{};return _n(e,(e,t)=>{const s=n(e,i+1);!an(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:$n,isThenable:e=>e&&(hn(e)||un(e))&&un(e.then)&&un(e.catch),setImmediate:Pn,asap:Ln,isIterable:e=>null!=e&&un(e[en])};function Un(e,t,n,i,r){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),i&&(this.request=i),r&&(this.response=r,this.status=r.status?r.status:null)}qn.inherits(Un,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:qn.toJSONObject(this.config),code:this.code,status:this.status}}});const jn=Un.prototype,Kn={};["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=>{Kn[e]={value:e}}),Object.defineProperties(Un,Kn),Object.defineProperty(jn,"isAxiosError",{value:!0}),Un.from=(e,t,n,i,r,s)=>{const o=Object.create(jn);return qn.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Un.call(o,e.message,t,n,i,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Hn(e){return qn.isPlainObject(e)||qn.isArray(e)}function Zn(e){return qn.endsWith(e,"[]")?e.slice(0,-2):e}function zn(e,t,n){return e?e.concat(t).map(function(e,t){return e=Zn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Gn=qn.toFlatObject(qn,{},null,function(e){return/^is[A-Z]/.test(e)});function Wn(e,n,i){if(!qn.isObject(e))throw new TypeError("target must be an object");n=n||new FormData;const r=(i=qn.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!qn.isUndefined(t[e])})).metaTokens,s=i.visitor||l,o=i.dots,a=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&qn.isSpecCompliantForm(n);if(!qn.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(qn.isDate(e))return e.toISOString();if(qn.isBoolean(e))return e.toString();if(!c&&qn.isBlob(e))throw new Un("Blob is not supported. Use a Buffer instead.");return qn.isArrayBuffer(e)||qn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):t.Buffer.from(e):e}function l(e,t,i){let s=e;if(e&&!i&&"object"==typeof e)if(qn.endsWith(t,"{}"))t=r?t:t.slice(0,-2),e=JSON.stringify(e);else if(qn.isArray(e)&&function(e){return qn.isArray(e)&&!e.some(Hn)}(e)||(qn.isFileList(e)||qn.endsWith(t,"[]"))&&(s=qn.toArray(e)))return t=Zn(t),s.forEach(function(e,i){!qn.isUndefined(e)&&null!==e&&n.append(!0===a?zn([t],i,o):null===a?t:t+"[]",d(e))}),!1;return!!Hn(e)||(n.append(zn(i,t,o),d(e)),!1)}const u=[],p=Object.assign(Gn,{defaultVisitor:l,convertValue:d,isVisitable:Hn});if(!qn.isObject(e))throw new TypeError("data must be an object");return function e(t,i){if(!qn.isUndefined(t)){if(-1!==u.indexOf(t))throw Error("Circular reference detected in "+i.join("."));u.push(t),qn.forEach(t,function(t,r){!0===(!(qn.isUndefined(t)||null===t)&&s.call(n,t,qn.isString(r)?r.trim():r,i,p))&&e(t,i?i.concat(r):[r])}),u.pop()}}(e),n}function Vn(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Jn(e,t){this._pairs=[],e&&Wn(e,this,t)}const Qn=Jn.prototype;function Xn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Yn(e,t,n){if(!t)return e;const i=n&&n.encode||Xn;qn.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):qn.isURLSearchParams(t)?t.toString():new Jn(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Qn.append=function(e,t){this._pairs.push([e,t])},Qn.toString=function(e){const t=e?function(t){return e.call(this,t,Vn)}:Vn;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class ei{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){qn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const ti={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ni={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Jn,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},ii="undefined"!=typeof window&&"undefined"!=typeof document,ri="object"==typeof navigator&&navigator||void 0,si=ii&&(!ri||["ReactNative","NativeScript","NS"].indexOf(ri.product)<0),oi="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,ai=ii&&window.location.href||"http://localhost",ci={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ii,hasStandardBrowserEnv:si,hasStandardBrowserWebWorkerEnv:oi,navigator:ri,origin:ai},Symbol.toStringTag,{value:"Module"})),...ni};function di(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=r>=e.length;if(s=!s&&qn.isArray(i)?i.length:s,a)return qn.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!o;i[s]&&qn.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&qn.isArray(i[s])&&(i[s]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],t[s]=e[s];return t}(i[s])),!o}if(qn.isFormData(e)&&qn.isFunction(e.entries)){const n={};return qn.forEachEntry(e,(e,i)=>{t(function(e){return qn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const li={transitional:ti,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=qn.isObject(e);r&&qn.isHTMLForm(e)&&(e=new FormData(e));if(qn.isFormData(e))return i?JSON.stringify(di(e)):e;if(qn.isArrayBuffer(e)||qn.isBuffer(e)||qn.isStream(e)||qn.isFile(e)||qn.isBlob(e)||qn.isReadableStream(e))return e;if(qn.isArrayBufferView(e))return e.buffer;if(qn.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Wn(e,new ci.classes.URLSearchParams,{visitor:function(e,t,n,i){return ci.isNode&&qn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=qn.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 r||i?(t.setContentType("application/json",!1),function(e,t,n){if(qn.isString(e))try{return(t||JSON.parse)(e),qn.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||li.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(qn.isResponse(e)||qn.isReadableStream(e))return e;if(e&&qn.isString(e)&&(n&&!this.responseType||i)){const n=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(r){if(n){if("SyntaxError"===r.name)throw Un.from(r,Un.ERR_BAD_RESPONSE,this,null,this.response);throw r}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ci.classes.FormData,Blob:ci.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};qn.forEach(["delete","get","head","post","put","patch"],e=>{li.headers[e]={}});const ui=qn.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"]),pi=Symbol("internals");function hi(e){return e&&String(e).trim().toLowerCase()}function gi(e){return!1===e||null==e?e:qn.isArray(e)?e.map(gi):String(e)}function fi(e,t,n,i,r){return qn.isFunction(i)?i.call(this,t,n):(r&&(t=n),qn.isString(t)?qn.isString(i)?-1!==t.indexOf(i):qn.isRegExp(i)?i.test(t):void 0:void 0)}let mi=class{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=hi(t);if(!r)throw new Error("header name must be a non-empty string");const s=qn.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=gi(e))}const s=(e,t)=>qn.forEach(e,(e,n)=>r(e,n,t));if(qn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(qn.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),n=e.substring(0,r).trim().toLowerCase(),i=e.substring(r+1).trim(),!n||t[n]&&ui[n]||("set-cookie"===n?t[n]?t[n].push(i):t[n]=[i]:t[n]=t[n]?t[n]+", "+i:i)}),t})(e),t);else if(qn.isObject(e)&&qn.isIterable(e)){let n,i,r={};for(const t of e){if(!qn.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?qn.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(r,t)}else null!=e&&r(t,e,n);return this}get(e,t){if(e=hi(e)){const n=qn.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 i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(qn.isFunction(t))return t.call(this,e,n);if(qn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=hi(e)){const n=qn.findKey(this,e);return!(!n||void 0===this[n]||t&&!fi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=hi(e)){const r=qn.findKey(n,e);!r||t&&!fi(0,n[r],r,t)||(delete n[r],i=!0)}}return qn.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!fi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return qn.forEach(this,(i,r)=>{const s=qn.findKey(n,r);if(s)return t[s]=gi(i),void delete t[r];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();o!==r&&delete t[r],t[o]=gi(i),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return qn.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&qn.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[pi]=this[pi]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=hi(e);t[i]||(!function(e,t){const n=qn.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+n,{value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})})}(n,e),t[i]=!0)}return qn.isArray(e)?e.forEach(i):i(e),this}};function yi(e,t){const n=this||li,i=t||n,r=mi.from(i.headers);let s=i.data;return qn.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function bi(e){return!(!e||!e.__CANCEL__)}function wi(e,t,n){Un.call(this,null==e?"canceled":e,Un.ERR_CANCELED,t,n),this.name="CanceledError"}function vi(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Un("Request failed with status code "+n.status,[Un.ERR_BAD_REQUEST,Un.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}mi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),qn.reduceDescriptors(mi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),qn.freezeMethods(mi),qn.inherits(wi,Un,{__CANCEL__:!0});const Ii=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];r||(r=c),n[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=n[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-r<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const o=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-r;a>=s?o(e,t):(n=e,i||(i=setTimeout(()=>{i=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-i,c=r(a);i=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)},Ti=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Ai=e=>(...t)=>qn.asap(()=>e(...t)),_i=ci.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,ci.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(ci.origin),ci.navigator&&/(msie|trident)/i.test(ci.navigator.userAgent)):()=>!0,Ci=ci.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const o=[e+"="+encodeURIComponent(t)];qn.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),qn.isString(i)&&o.push("path="+i),qn.isString(r)&&o.push("domain="+r),!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 Ei(e,t,n){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Ri=e=>e instanceof mi?{...e}:e;function Si(e,t){t=t||{};const n={};function i(e,t,n,i){return qn.isPlainObject(e)&&qn.isPlainObject(t)?qn.merge.call({caseless:i},e,t):qn.isPlainObject(t)?qn.merge({},t):qn.isArray(t)?t.slice():t}function r(e,t,n,r){return qn.isUndefined(t)?qn.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!qn.isUndefined(t))return i(void 0,t)}function o(e,t){return qn.isUndefined(t)?qn.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(n,r,s){return s in t?i(n,r):s in e?i(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)=>r(Ri(e),Ri(t),0,!0)};return qn.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,o=s(e[i],t[i],i);qn.isUndefined(o)&&s!==a||(n[i]=o)}),n}const xi=e=>{const t=Si({},e);let n,{data:i,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=mi.from(a),t.url=Yn(Ei(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),qn.isFormData(i))if(ci.hasStandardBrowserEnv||ci.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(ci.hasStandardBrowserEnv&&(r&&qn.isFunction(r)&&(r=r(t)),r||!1!==r&&_i(t.url))){const e=s&&o&&Ci.read(o);e&&a.set(s,e)}return t},ki="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=xi(e);let r=i.data;const s=mi.from(i.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function g(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let f=new XMLHttpRequest;function m(){if(!f)return;const i=mi.from("getAllResponseHeaders"in f&&f.getAllResponseHeaders());vi(function(e){t(e),g()},function(e){n(e),g()},{data:u&&"text"!==u&&"json"!==u?f.response:f.responseText,status:f.status,statusText:f.statusText,headers:i,config:e,request:f}),f=null}f.open(i.method.toUpperCase(),i.url,!0),f.timeout=i.timeout,"onloadend"in f?f.onloadend=m:f.onreadystatechange=function(){f&&4===f.readyState&&(0!==f.status||f.responseURL&&0===f.responseURL.indexOf("file:"))&&setTimeout(m)},f.onabort=function(){f&&(n(new Un("Request aborted",Un.ECONNABORTED,e,f)),f=null)},f.onerror=function(){n(new Un("Network Error",Un.ERR_NETWORK,e,f)),f=null},f.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||ti;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new Un(t,r.clarifyTimeoutError?Un.ETIMEDOUT:Un.ECONNABORTED,e,f)),f=null},void 0===r&&s.setContentType(null),"setRequestHeader"in f&&qn.forEach(s.toJSON(),function(e,t){f.setRequestHeader(t,e)}),qn.isUndefined(i.withCredentials)||(f.withCredentials=!!i.withCredentials),u&&"json"!==u&&(f.responseType=i.responseType),h&&([c,l]=Ii(h,!0),f.addEventListener("progress",c)),p&&f.upload&&([a,d]=Ii(p),f.upload.addEventListener("progress",a),f.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(o=t=>{f&&(n(!t||t.type?new wi(null,e,f):t),f.abort(),f=null)},i.cancelToken&&i.cancelToken.subscribe(o),i.signal&&(i.signal.aborted?o():i.signal.addEventListener("abort",o)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===ci.protocols.indexOf(y)?n(new Un("Unsupported protocol "+y+":",Un.ERR_BAD_REQUEST,e)):f.send(r||null)})},Ni=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,o();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Un?t:new wi(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new Un(`timeout ${t} of ms exceeded`,Un.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:a}=i;return a.unsubscribe=()=>qn.asap(o),a}},Oi=function*(e,t){let n=e.byteLength;if(n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},$i=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()}},Pi=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of $i(e))yield*Oi(n,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return a(),void e.close();let s=i.byteLength;if(n){let e=o+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),r.return())},{highWaterMark:2})},Mi="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Fi=Mi&&"function"==typeof ReadableStream,Bi=Mi&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Di=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},Li=Fi&&Di(()=>{let e=!1;const t=new Request(ci.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),qi=Fi&&Di(()=>qn.isReadableStream(new Response("").body)),Ui={stream:qi&&(e=>e.body)};var ji;Mi&&(ji=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ui[e]&&(Ui[e]=qn.isFunction(ji[e])?t=>t[e]():(t,n)=>{throw new Un(`Response type '${e}' is not supported`,Un.ERR_NOT_SUPPORT,n)})}));const Ki=async(e,t)=>{const n=qn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(qn.isBlob(e))return e.size;if(qn.isSpecCompliantForm(e)){const t=new Request(ci.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return qn.isArrayBufferView(e)||qn.isArrayBuffer(e)?e.byteLength:(qn.isURLSearchParams(e)&&(e+=""),qn.isString(e)?(await Bi(e)).byteLength:void 0)})(t):n},Hi={http:null,xhr:ki,fetch:Mi&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=xi(e);d=d?(d+"").toLowerCase():"text";let h,g=Ni([r,s&&s.toAbortSignal()],o);const f=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let m;try{if(c&&Li&&"get"!==n&&"head"!==n&&0!==(m=await Ki(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(qn.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=Ti(m,Ii(Ai(c)));i=Pi(n.body,65536,e,t)}}qn.isString(u)||(u=u?"include":"omit");const r="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:n.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:r?u:void 0});let s=await fetch(h,p);const o=qi&&("stream"===d||"response"===d);if(qi&&(a||o&&f)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=qn.toFiniteNumber(s.headers.get("content-length")),[n,i]=a&&Ti(t,Ii(Ai(a),!0))||[];s=new Response(Pi(s.body,65536,n,()=>{i&&i(),f&&f()}),e)}d=d||"text";let y=await Ui[qn.findKey(Ui,d)||"text"](s,e);return!o&&f&&f(),await new Promise((t,n)=>{vi(t,n,{data:y,headers:mi.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(y){if(f&&f(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new Un("Network Error",Un.ERR_NETWORK,e,h),{cause:y.cause||y});throw Un.from(y,y&&y.code,e,h)}})};qn.forEach(Hi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Zi=e=>`- ${e}`,zi=e=>qn.isFunction(e)||null===e||!1===e,Gi=e=>{e=qn.isArray(e)?e:[e];const{length:t}=e;let n,i;const r={};for(let s=0;s<t;s++){let t;if(n=e[s],i=n,!zi(n)&&(i=Hi[(t=String(n)).toLowerCase()],void 0===i))throw new Un(`Unknown adapter '${t}'`);if(i)break;r[t||"#"+s]=i}if(!i){const e=Object.entries(r).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new Un("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Zi).join("\n"):" "+Zi(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Wi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new wi(null,e)}function Vi(e){Wi(e),e.headers=mi.from(e.headers),e.data=yi.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Gi(e.adapter||li.adapter)(e).then(function(t){return Wi(e),t.data=yi.call(e,e.transformResponse,t),t.headers=mi.from(t.headers),t},function(t){return bi(t)||(Wi(e),t&&t.response&&(t.response.data=yi.call(e,e.transformResponse,t.response),t.response.headers=mi.from(t.response.headers))),Promise.reject(t)})}const Ji="1.11.0",Qi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Qi[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Xi={};Qi.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Ji+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new Un(i(r," has been removed"+(t?" in "+t:"")),Un.ERR_DEPRECATED);return t&&!Xi[r]&&(Xi[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,s)}},Qi.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const Yi={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Un("options must be an object",Un.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],o=t[s];if(o){const t=e[s],n=void 0===t||o(t,s,e);if(!0!==n)throw new Un("option "+s+" must be "+n,Un.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Un("Unknown option "+s,Un.ERR_BAD_OPTION)}},validators:Qi},er=Yi.validators;let tr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ei,response:new ei}}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(i){}}throw n}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Si(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&Yi.assertOptions(n,{silentJSONParsing:er.transitional(er.boolean),forcedJSONParsing:er.transitional(er.boolean),clarifyTimeoutError:er.transitional(er.boolean)},!1),null!=i&&(qn.isFunction(i)?t.paramsSerializer={serialize:i}:Yi.assertOptions(i,{encode:er.function,serialize:er.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Yi.assertOptions(t,{baseUrl:er.spelling("baseURL"),withXsrfToken:er.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&qn.merge(r.common,r[t.method]);r&&qn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=mi.concat(s,r);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 l,u=0;if(!a){const e=[Vi.bind(this),void 0];for(e.unshift(...o),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{d=Vi.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return Yn(Ei((e=Si(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};qn.forEach(["delete","get","head","options"],function(e){tr.prototype[e]=function(t,n){return this.request(Si(n||{},{method:e,url:t,data:(n||{}).data}))}}),qn.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Si(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}tr.prototype[e]=t(),tr.prototype[e+"Form"]=t(!0)});const nr={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(nr).forEach(([e,t])=>{nr[t]=e});const ir=function e(t){const n=new tr(t),i=Qt(tr.prototype.request,n);return qn.extend(i,tr.prototype,n,{allOwnKeys:!0}),qn.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Si(t,n))},i}(li);ir.Axios=tr,ir.CanceledError=wi,ir.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 i=new Promise(e=>{n.subscribe(e),t=e}).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e(function(e,i,r){n.reason||(n.reason=new wi(e,i,r),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}}},ir.isCancel=bi,ir.VERSION=Ji,ir.toFormData=Wn,ir.AxiosError=Un,ir.Cancel=ir.CanceledError,ir.all=function(e){return Promise.all(e)},ir.spread=function(e){return function(t){return e.apply(null,t)}},ir.isAxiosError=function(e){return qn.isObject(e)&&!0===e.isAxiosError},ir.mergeConfig=Si,ir.AxiosHeaders=mi,ir.formToJSON=e=>di(qn.isHTMLForm(e)?new FormData(e):e),ir.getAdapter=Gi,ir.HttpStatusCode=nr,ir.default=ir;const{Axios:rr,AxiosError:sr,CanceledError:or,isCancel:ar,CancelToken:cr,VERSION:dr,all:lr,Cancel:ur,isAxiosError:pr,spread:hr,toFormData:gr,AxiosHeaders:fr,HttpStatusCode:mr,formToJSON:yr,getAdapter:br,mergeConfig:wr}=ir,vr="ConnectionsManager not initialized";class Ir extends n.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const r=this.hederaKit.client.network;this.network=r.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 i.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new i.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,i){try{const r=await this.standardClient.handleConnectionRequest(e,t,n,i);return r&&r.connectionTopicId&&"object"==typeof r.connectionTopicId&&"toString"in r.connectionTopicId&&(r.connectionTopicId=r.connectionTopicId.toString()),r}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}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 i=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:i.topicSequenceNumber?.toNumber(),receipt:i,transactionId:"transactionId"in i?i.transactionId?.toString():void 0}}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){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 ir.get(e,{responseType:"arraybuffer"}),i=t.Buffer.from(n.data),r=new URL(e).pathname;return{buffer:i,filename:s.basename(r)||"profile.png"}}{if(!r.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=r.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 ir.get(e.url,{responseType:"arraybuffer"}),i=t.Buffer.from(n.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!r.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=r.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 i.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[i.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(i.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(i.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 i.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:r}=this.getAccountAndSigner();if(!r)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${r}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==r&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,r,s)}const r=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:r.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...r,name:e.name,accountId:r?.metadata?.accountId||r.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 i;void 0!==e.memo?i=e.memo:(i=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${i}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const r=await this.submitConnectionRequest(n,i);this.executeResult={success:!0,transactionId:"transactionId"in r?r.transactionId?.toString():void 0,receipt:r,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...r}}}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 r=this.stateManager?.getConnectionsManager();if(!r)throw new Error(vr);await r.fetchConnectionData(n.accountId);const s=[...r.getPendingRequests(),...r.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 i.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 r=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,r)}const d=await this.getInboundTopicId(),l=await this.handleConnectionRequest(d,o,a,c);let u=l?.connectionTopicId;if(u&&"object"==typeof u&&"toString"in u&&(u=u?.toString()),!u||"string"!=typeof u)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(u)}`);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 i={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:u,status:"established",created:new Date};this.stateManager.addActiveConnection(i),r.markConnectionRequestProcessed(s.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId:u,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:l}}}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;const i=e.targetIdentifier;if(i.includes("@")){const e=i.split("@");if(2===e.length){const t=e[1];n=this.stateManager.getConnectionByIdentifier(t),n||this.addNote(`Could not find connection using request key '${i}', extracted account ID '${t}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(i)),!n&&!i.startsWith("0.0.")&&/^\d+$/.test(i)){const e=`0.0.${i}`;n=this.stateManager.getConnectionByIdentifier(e),n&&this.addNote(`Found connection using account ID with prefix: ${e}`)}if(!n&&/^[1-9]\d*$/.test(i)){const e=this.stateManager.listConnections(),t=parseInt(i)-1;t>=0&&t<e.length&&(n=e[t],n&&this.addNote(`Found connection by index ${i}: ${n.targetAccountId}`))}if(!n){const e=this.stateManager.listConnections().map((e,t)=>`${t+1}. ${e.targetAccountId} (Topic: ${e.connectionTopicId})`);let t=`Connection not found for identifier: "${i}"\n`;throw t+=`Available connections:\n${e.join("\n")||"No active connections"}`,t+="\n\nYou can use:\n",t+='- Connection number (e.g., "1", "2")\n',t+='- Account ID (e.g., "0.0.6412936")\n',t+="- Connection topic ID\n",t+="Use 'list_connections' to see all active connections.",new Error(t)}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 s=n.targetAgentName,o=`${t.inboundTopicId}@${t.accountId}`,a=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!a.sequenceNumber)throw new Error("Failed to send message");let c=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):c=await this.monitorResponses(r,o,a.sequenceNumber),this.executeResult={success:!0,transactionId:a.transactionId,receipt:a.receipt,scheduleId:void 0,rawResult:{targetAgentName:s,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:a.sequenceNumber,reply:c,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:a}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let i=0;for(;i<30;){try{const i=await this.getMessageStream(e);for(const e of i.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(r){this.logger.error(`Error monitoring responses: ${r}`)}await new Promise(e=>setTimeout(e,4e3)),i++}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:r=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(),l=Date.now()+1e3*r;let u=0,p=0;const h=new Set;for(;Date.now()<l;){try{const e=(await this.getMessages(d)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const r of e){const e=r.sequence_number;if(!e||h.has(e))continue;const l=r.operator_id?.split("@")[1];if(l)if(u++,n&&l!==n)this.logger.info(`Skipping request from ${l} (not target account)`);else if(t||n===l){let t;if(this.logger.info(`Accepting connection request from ${l}`),s.length>0||o.length>0){const e=new i.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,l,e,t),h.add(e),p++}}}catch(g){this.logger.error("Error during connection monitoring:",g)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:u,acceptedConnections:p,monitorDurationSeconds:r,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${p}.`),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(vr);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const i=t.getPendingRequests(),r=t.getConnectionsNeedingConfirmation(),s=[...i,...r];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 i=e.filter(e=>"established"===e.status),r=e.filter(e=>e.isPending),s=e.filter(e=>e.needsConfirmation);let o="";i.length>0&&(o+=`🟢 Active Connections (${i.length}):\n`,i.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&&r.length>0&&(o+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach((e,n)=>{o+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:o.trim(),activeCount:i.length,pendingCount:r.length,needsConfirmationCount:s.length}}}catch(i){this.logger.error("Failed to list connections:",i),this.executeResult={success:!1,error:`Failed to list connections: ${i instanceof Error?i.message:String(i)}`}}return this}formatConnection(e,t,n){const i=e;let r=`${t+1}. ${i.profileInfo?.display_name||i.targetAgentName||"Unknown Agent"} (${i.targetAccountId})\n`;r+=` Topic: ${i.isPending?"(Pending Request)":i.connectionTopicId}\n`;if(r+=` Status: ${i.status||"unknown"}\n`,n){if(i.profileInfo?.bio&&(r+=` Bio: ${i.profileInfo.bio.substring(0,100)}${i.profileInfo.bio.length>100?"...":""}\n`),i.created){r+=` ${i.isPending?"Request sent":"Connection established"}: ${i.created.toLocaleString()}\n`}i.lastActivity&&(r+=` Last activity: ${i.lastActivity.toLocaleString()}\n`)}return r}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(vr),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const i of n)this.stateManager.addActiveConnection(i);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 i=t.targetAgentName,r=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${i} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${r})`);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=r;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 ${r}`),o=t.filter(e=>1e6*e.timestamp>r),o.length>0&&(a=o.reduce((e,t)=>Math.max(e,1e6*t.timestamp),r));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 ${i} 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 ${i}:\n`:`New messages from ${i}:\n`;const l=[];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`,l.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>r&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:l,formattedOutput:d.trim(),targetAgentName:i,connectionTopicId:n}}}catch(s){this.logger.error(`Failed to check messages for topic ${n}: ${s}`),this.executeResult={success:!1,error:`Error checking messages for ${i}: ${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 i=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${i}`}}}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,i=t.topicInfo;let r=`Profile for ${e.accountId}:\n`;r+=`Name: ${n.name||"Unknown"}\n`,r+=`Bio: ${n.bio||"No bio provided"}\n`,r+=`Type: ${n.type||"Unknown"}\n`,r+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?r+=`Capabilities: ${n.capabilities.join(", ")}\n`:r+="Capabilities: None listed\n",i&&(r+=`Inbound Topic: ${i.inboundTopic||"Unknown"}\n`,r+=`Outbound Topic: ${i.outboundTopic||"Unknown"}\n`,r+=`Profile Topic: ${i.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(r+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(r+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:r,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 Tr 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}}class Ar extends n.BaseServiceBuilder{constructor(e){super(e)}async getHCS2Client(){if(!this.hcs2Client){const e=this.hederaKit.signer.getAccountId().toString(),t=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:t};this.hcs2Client=new i.HCS2Client(n)}return this.hcs2Client}async createRegistry(e={}){const t=await this.getHCS2Client();return await t.createRegistry(e)}async registerEntry(e,t){const n=await this.getHCS2Client();return await n.registerEntry(e,t)}async updateEntry(e,t){const n=await this.getHCS2Client();return await n.updateEntry(e,t)}async deleteEntry(e,t){const n=await this.getHCS2Client();return await n.deleteEntry(e,t)}async migrateRegistry(e,t){const n=await this.getHCS2Client();return await n.migrateRegistry(e,t)}async getRegistry(e,t={}){const n=await this.getHCS2Client();return await n.getRegistry(e,t)}async submitMessage(e,t){const n=await this.getHCS2Client();return await n.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS2Client();return await t.getTopicInfo(e)}async close(){this.hcs2Client&&(this.hcs2Client.close(),this.hcs2Client=void 0)}}class _r extends n.BaseServiceBuilder{constructor(e){super(e)}async getHCS6Client(){if(!this.hcs6Client){const e=this.hederaKit.signer.getAccountId().toString(),t=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:t};this.hcs6Client=new i.HCS6Client(n)}return this.hcs6Client}async createRegistry(e={}){const t=await this.getHCS6Client();return await t.createRegistry(e)}async registerEntry(e,t){const n=await this.getHCS6Client();return await n.registerEntry(e,t)}async getRegistry(e,t={}){const n=await this.getHCS6Client();return await n.getRegistry(e,t)}async createHashinal(e){const t=await this.getHCS6Client();return await t.createHashinal(e)}async register(e){const t=await this.getHCS6Client();return await t.register(e)}async submitMessage(e,t){const n=await this.getHCS6Client();return await n.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS6Client();return await t.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}class Cr extends n.BaseServiceBuilder{constructor(e){super(e)}async getInscriptionSDK(e){return null}async inscribe(e,t){const n={accountId:this.hederaKit.signer.getAccountId().toString(),privateKey:this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};return await i.inscribe(e,n,t)}async inscribeWithSigner(e,t,n){return await i.inscribeWithSigner(e,t,n)}async retrieveInscription(e,t){const n=this.hederaKit.signer.getAccountId().toString(),r=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";return await i.retrieveInscription(e,{...t,accountId:n,privateKey:r})}async close(){this.inscriptionSDK=void 0}}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=At,e.BaseHCS10QueryTool=g,e.BaseHCS10TransactionTool=h,e.BaseHCS2QueryTool=xt,e.BaseHCS2TransactionTool=St,e.BaseHCS6QueryTool=Bt,e.BaseHCS6TransactionTool=Ft,e.BaseInscriberQueryTool=Kt,e.BaseInscriberTransactionTool=jt,e.CheckMessagesTool=ft,e.ConnectionMonitorTool=wt,e.CreateDynamicRegistryTool=class extends Ft{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content",this.schema=Dt}async _call(e){try{const t=await this.hcs6Builder.createRegistry({ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to create dynamic registry");return{status:"success",data:{topicId:t.topicId,transactionId:t.transactionId,ttl:e.ttl,memo:`hcs-6:1:${e.ttl}`}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.CreateRegistryTool=class extends xt{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create a new HCS-2 registry topic for storing decentralized data"}get specificInputSchema(){return kt}async executeQuery(e,t){try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to create registry");return`Successfully created HCS-2 registry!\n\nTopic ID: ${t.topicId}\nRegistry Type: ${1===e.registryType?"Non-Indexed":"Indexed"}\nTTL: ${e.ttl||86400} seconds\n\nYou can now register entries to this registry using the topic ID.`}catch(n){const e=n instanceof Error?n.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},e.DeleteEntryTool=class extends xt{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return $t}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to delete entry");return`Successfully deleted entry from HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been removed from the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to delete entry";throw new Error(`Entry deletion failed: ${e}`)}}},e.FindRegistrationsTool=yt,e.HCS10Builder=Ir,e.HCS10Client=class{constructor(e,t,n,r){this.standardClient=new i.HCS10Client({network:n,operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:r?.registryUrl,logLevel:r?.logLevel}),this.guardedRegistryBaseUrl=r?.registryUrl||"",this.useEncryption=r?.useEncryption||!1;const s="true"===c.env.DISABLE_LOGGING;this.logger=new i.Logger({level:r?.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,i){try{return await this.standardClient.handleConnectionRequest(e,t,n,i)}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,i=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,i)}async createAndRegisterAgent(e){const t=(new i.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[i.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(i.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(i.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),i=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return i?.metadata?.inboundTopicId&&i?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:i.metadata.inboundTopicId,outboundTopicId:i.metadata.outboundTopicId}),i}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,i){this.useEncryption;try{const r=await this.standardClient.sendMessage(e,t,n,i);return r.topicSequenceNumber?.toNumber()}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){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 i.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.HCS2Builder=Ar,e.HCS6Builder=_r,e.HbarPricePlugin=Tr,e.InitiateConnectionTool=ut,e.InscribeFromBufferTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description="Inscribe content that you already have retrieved or generated. ALWAYS use this tool for: web page articles (after using MCP tools), API responses, text data, or any content from MCP tools. Steps: 1) Retrieve content using appropriate tool, 2) Convert to base64, 3) Use this tool. NEVER use inscribeFromUrl for web pages - that tool is ONLY for direct file downloads like PDFs or images."}get specificInputSchema(){return zt}async executeQuery(e,n){if(console.log("[DEBUG] InscribeFromBufferTool.executeQuery called"),console.log(`[DEBUG] Buffer tool received base64Data length: ${e.base64Data?.length||0}`),console.log(`[DEBUG] Buffer tool fileName: ${e.fileName}`),console.log(`[DEBUG] Buffer tool mimeType: ${e.mimeType}`),!e.base64Data||""===e.base64Data.trim())throw console.log("[InscribeFromBufferTool] ERROR: No data provided"),new Error("No data provided. Cannot inscribe empty content. Please provide valid base64 encoded data.");if(!e.fileName||""===e.fileName.trim())throw console.log("[InscribeFromBufferTool] ERROR: No fileName provided"),new Error("No fileName provided. A valid fileName is required for inscription.");let i;try{i=t.Buffer.from(e.base64Data,"base64")}catch(s){throw console.log("[InscribeFromBufferTool] ERROR: Invalid base64 data"),new Error("Invalid base64 data provided. Please ensure the data is properly base64 encoded.")}if(console.log(`[InscribeFromBufferTool] Buffer length after conversion: ${i.length}`),0===i.length)throw console.log("[InscribeFromBufferTool] ERROR: Buffer is empty after conversion"),new Error("Buffer is empty after base64 conversion. The provided data appears to be invalid or empty.");if(i.length<10)throw console.log(`[InscribeFromBufferTool] WARNING: Buffer is very small (${i.length} bytes)`),console.log(`[InscribeFromBufferTool] Buffer content preview: ${i.toString("utf8",0,Math.min(i.length,50))}`),new Error(`Buffer content is too small (${i.length} bytes). This may indicate empty or invalid content. Please verify the source data contains actual content.`);if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e.base64Data))throw console.log("[InscribeFromBufferTool] ERROR: Invalid base64 format"),new Error("Invalid base64 format. The data does not appear to be properly base64 encoded.");if(""===i.toString("utf8",0,Math.min(i.length,100)).trim())throw console.log("[InscribeFromBufferTool] ERROR: Buffer contains only whitespace or empty content"),new Error("Buffer contains only whitespace or empty content. Cannot inscribe meaningless data.");const r={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{let t;if(e.timeoutMs){const n=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:e.fileName,mimeType:e.mimeType},r),n])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:e.fileName,mimeType:e.mimeType},r);if(t.confirmed){const e=t.inscription?.topic_id||t.result.topicId,n=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${r.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(s){const e=s instanceof Error?s.message:"Failed to inscribe from buffer";throw new Error(`Inscription failed: ${e}`)}}},e.InscribeFromFileTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromFile",this.description="Inscribe content from a local file to the Hedera network using a file path. IMPORTANT: Only use this tool when you have a valid file path to actual content. The file must exist and contain meaningful data (minimum 10 bytes). For files accessed through MCP filesystem tools, consider reading the file content first and using inscribeFromBuffer instead."}get specificInputSchema(){return Zt}async executeQuery(e,n){let i;console.log(`[DEBUG] InscribeFromFileTool.executeQuery called with: ${e.filePath}`);try{console.log(`[DEBUG] Checking file: ${e.filePath}`),console.log(`[DEBUG] Current working directory: ${c.cwd()}`);const t=await p.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(console.log(`[DEBUG] File size: ${t.size} bytes`),0===t.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(t.size<10)throw new Error(`File "${e.filePath}" is too small (${t.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(t.size>104857600&&console.log(`[InscribeFromFileTool] WARNING: Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await p.readFile(e.filePath),this.logger?.info(`Read ${i.length} bytes from file`),!i||0===i.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(i.length<10)throw new Error(`File "${e.filePath}" content is too small (${i.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const n=u.basename(e.filePath),r=this.getMimeType(n);if(r.startsWith("text/")||"application/json"===r){if(""===i.toString("utf8",0,Math.min(i.length,1e3)).trim())throw new Error(`File "${e.filePath}" contains only whitespace or empty content. Cannot inscribe meaningless data.`)}}catch(d){if(d instanceof Error){if(d.message.includes("ENOENT"))throw new Error(`File not found: "${e.filePath}"`);throw d}throw new Error(`Failed to read file: ${d}`)}const r=i.toString("base64");this.logger?.info(`Converted to base64: ${r.length} characters`);const s=u.basename(e.filePath),o=this.getMimeType(s);this.logger?.info(`File: ${s}, MIME type: ${o}`);const a={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{let n;if(e.timeoutMs){const i=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});n=await Promise.race([this.inscriberBuilder.inscribe({type:"buffer",buffer:t.Buffer.from(r,"base64"),fileName:s,mimeType:o},a),i])}else n=await this.inscriberBuilder.inscribe({type:"buffer",buffer:t.Buffer.from(r,"base64"),fileName:s,mimeType:o},a);if(n.confirmed){const e=n.inscription?.topic_id||n.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${a.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${n.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${n.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(d){const e=d instanceof Error?d.message:"Failed to inscribe from file";throw new Error(`Inscription failed: ${e}`)}}getMimeType(e){return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".pdf":"application/pdf",".json":"application/json",".txt":"text/plain",".html":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".mp4":"video/mp4",".mp3":"audio/mpeg",".wav":"audio/wav",".zip":"application/zip"}[u.extname(e).toLowerCase()]||"application/octet-stream"}},e.InscribeFromUrlTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromUrl",this.description="Inscribe content ONLY from URLs that point directly to downloadable files (PDF, image, JSON, ZIP, etc). This tool will FAIL for web pages, news sites, or social media. Examples of VALID URLs: https://example.com/document.pdf, https://cdn.example.com/image.jpg, https://api.example.com/data.json. For web page articles or any content you retrieve via MCP tools, you MUST use inscribeFromBuffer instead after retrieving the content."}get specificInputSchema(){return Ht}async executeQuery(e,t){if(console.log(`[DEBUG] InscribeFromUrlTool.executeQuery called with URL: ${e.url}`),!e.url||""===e.url.trim())throw new Error("URL cannot be empty. Please provide a valid URL.");try{const t=new URL(e.url);if(!t.protocol||!t.host)throw new Error("Invalid URL format. Please provide a complete URL with protocol (http/https).");if(!["http:","https:"].includes(t.protocol))throw new Error("Only HTTP and HTTPS URLs are supported for inscription.")}catch(i){throw new Error(`Invalid URL: ${e.url}. Please provide a valid URL.`)}console.log("[InscribeFromUrlTool] Validating URL content before inscription...");try{const t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{const i=await fetch(e.url,{method:"HEAD",signal:t.signal});if(clearTimeout(n),!i.ok)throw new Error(`URL returned error status ${i.status}: ${i.statusText}. Cannot inscribe content from inaccessible URLs.`);const s=i.headers.get("content-type")||"",o=i.headers.get("content-length");if(["text/html","application/xhtml+xml","text/xml"].some(e=>s.toLowerCase().includes(e)))throw new Error(`URL returns HTML/web page content (Content-Type: ${s}). This tool only works with direct file URLs (PDFs, images, JSON, etc.). For web page content, first retrieve the content using the appropriate MCP tool or web scraper, then use inscribeFromBuffer to inscribe it.`);if(o&&0===parseInt(o))throw new Error("URL returns empty content (Content-Length: 0). Cannot inscribe empty content.");if(o&&parseInt(o)<10)throw new Error(`URL content is too small (${o} bytes). Content must be at least 10 bytes.`);if(!s||"application/octet-stream"===s){console.log("[InscribeFromUrlTool] Content-Type unclear, fetching first 1KB to verify...");const t=new AbortController,n=setTimeout(()=>t.abort(),5e3);try{const i=await fetch(e.url,{signal:t.signal,headers:{Range:"bytes=0-1023"}});if(clearTimeout(n),i.ok||206===i.status){const e=await i.arrayBuffer(),t=new Uint8Array(e),n=new TextDecoder("utf-8",{fatal:!1}).decode(t.slice(0,512));if(n.toLowerCase().includes("<!doctype html")||n.toLowerCase().includes("<html")||n.match(/<meta\s+[^>]*>/i)||n.match(/<title>/i))throw new Error("URL returns HTML content. This tool only works with direct file URLs. For web page content, first retrieve it using the appropriate tool, then use inscribeFromBuffer.")}}catch(r){if(clearTimeout(n),r instanceof Error&&r.message.includes("HTML content"))throw r;console.log(`[InscribeFromUrlTool] Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}console.log(`[InscribeFromUrlTool] URL validation passed. Content-Type: ${s}, Content-Length: ${o||"unknown"}`)}catch(s){throw clearTimeout(n),s}}catch(i){if(i instanceof Error)if("AbortError"===i.name)console.log("[InscribeFromUrlTool] Warning: URL validation timed out after 10 seconds. Proceeding with inscription attempt.");else{if(i.message.includes("URL returned error")||i.message.includes("empty content")||i.message.includes("too small")||i.message.includes("HTML"))throw i;console.log(`[InscribeFromUrlTool] Warning: Could not validate URL with HEAD request: ${i.message}. Proceeding with inscription attempt.`)}}const n={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{const t=new Promise((e,t)=>{setTimeout(()=>t(new Error("Inscription timed out after 30 seconds")),3e4)}),i=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},n),t]);if(i.confirmed){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${n.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(i){const e=i instanceof Error?i.message:"Failed to inscribe from URL";throw new Error(`Inscription failed: ${e}`)}}},e.InscribeHashinalTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeHashinal",this.description="Inscribe content as a Hashinal NFT on the Hedera network"}get specificInputSchema(){return Gt}async executeQuery(e,t){const n={mode:"hashinal",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes,properties:e.properties},jsonFileURL:e.jsonFileURL,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{const t=new Promise((e,t)=>{setTimeout(()=>t(new Error("Inscription timed out after 30 seconds")),3e4)}),i=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},n),t]);if(i.confirmed){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${n.network||"testnet"}`:null;return`Successfully inscribed and confirmed Hashinal NFT on the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe Hashinal NFT is now available.`}return`Successfully submitted Hashinal NFT inscription to the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(i){const e=i instanceof Error?i.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}},e.InscriberBuilder=Cr,e.ListConnectionsTool=ht,e.ListUnapprovedConnectionRequestsTool=Rt,e.ManageConnectionRequestsTool=It,e.MigrateRegistryTool=class extends xt{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return Pt}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to migrate registry");return`Successfully migrated HCS-2 registry!\n\nFrom Registry Topic: ${e.registryTopicId}\nTo Target Topic: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe registry has been migrated to the new topic.`}catch(n){const e=n instanceof Error?n.message:"Failed to migrate registry";throw new Error(`Registry migration failed: ${e}`)}}},e.NaturalLanguageMapper=st,e.OpenConvaiState=Jt,e.QueryDynamicRegistryTool=class extends Bt{constructor(e){super(e),this.name="queryDynamicRegistry",this.description="Query a dynamic registry to get the current state of a dynamic hashinal",this.schema=Ut}async _call(e){try{const t=await this.hcs6Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip});return{status:"success",data:{topicId:t.topicId,registryType:"NON_INDEXED",ttl:t.ttl,latestEntry:t.latestEntry?{topicId:t.latestEntry.message.t_id,timestamp:t.latestEntry.timestamp,memo:t.latestEntry.message.m,sequence:t.latestEntry.sequence,payer:t.latestEntry.payer}:null,totalEntries:t.entries.length}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.QueryRegistryTool=class extends xt{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry"}get specificInputSchema(){return Mt}async executeQuery(e,t){const n=await this.hcs2Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip});return{topicId:n.topicId,registryType:0===n.registryType?"indexed":"non-indexed",ttl:n.ttl,totalEntries:n.entries.length,entries:n.entries.map(e=>({sequence:e.sequence,timestamp:e.timestamp,payer:e.payer,operation:e.message.op,targetTopicId:e.message.t_id,uid:e.message.uid,metadata:e.message.metadata,memo:e.message.m}))}}},e.RegisterAgentTool=at,e.RegisterDynamicHashinalTool=class extends Ft{constructor(e){super(e),this.name="registerDynamicHashinal",this.description="Create and register a new dynamic hashinal that can be updated over time",this.schema=Lt}async _call(e){try{const t=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,ttl:e.ttl,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!t.success||!t.registryTopicId||!t.inscriptionTopicId)throw new Error(t.error||"Failed to register dynamic hashinal");return{status:"success",data:{registryTopicId:t.registryTopicId,inscriptionTopicId:t.inscriptionTopicId,transactionId:t.transactionId}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.RegisterEntryTool=class extends xt{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register a new entry in an HCS-2 registry"}get specificInputSchema(){return Nt}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to register entry");return`Successfully registered entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nTarget Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been added to the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to register entry";throw new Error(`Entry registration failed: ${e}`)}}},e.RetrieveInscriptionTool=class extends Kt{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return Wt}async executeQuery(e,t){const n=await this.inscriberBuilder.retrieveInscription(e.transactionId,{apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"});return{inscriptionId:n.inscriptionId,transactionId:n.transactionId,topicId:n.topic_id,status:n.status,holderId:n.holderId,metadata:n.metadata,tags:n.tags,mode:n.mode,chunks:n.chunks,createdAt:n.createdAt,completedAt:n.completed||n.completedAt,fileUrl:n.fileUrl,mimeType:n.mimeType,fileSize:n.fileSize}}},e.RetrieveProfileTool=Ct,e.SendMessageToConnectionTool=dt,e.UpdateDynamicHashinalTool=class extends Ft{constructor(e){super(e),this.name="updateDynamicHashinal",this.description="Update an existing dynamic hashinal with new content while maintaining the same registry",this.schema=qt}async _call(e){try{const t=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to update dynamic hashinal");return{status:"success",data:{registryTopicId:t.registryTopicId,newInscriptionTopicId:t.inscriptionTopicId,transactionId:t.transactionId,updateMemo:e.memo}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.UpdateEntryTool=class extends xt{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return Ot}async executeQuery(e,t){try{const t=await this.hcs2Builder.updateEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,uid:e.uid,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to update entry");return`Successfully updated entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}\nNew Target Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been updated in the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to update entry";throw new Error(`Entry update failed: ${e}`)}}},e.initializeStandardsAgentKit=async e=>{const t=e?.clientConfig||{},r=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"),!r||!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,l=i.Logger.getInstance({level:t.logLevel||"info",silent:d}),u=e?.stateManager||new Jt({defaultEnvFilePath:Vt,defaultPrefix:"TODD"});l.info("State manager initialized");const p=new n.ServerSigner(r,s,a),h=new n.HederaAgentKit(p);await h.initialize(),l.info(`HederaAgentKit initialized for ${r} on ${a}`);const g=new Ir(h,u,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:t.logLevel});let f,m;if(e?.monitoringClient){const e=new n.ServerSigner(r,s,a);f=new n.HederaAgentKit(e),await f.initialize(),m=new Ir(f,u,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),l.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new at({hederaKit:h,hcs10Builder:g,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new yt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.retrieveProfileTool=new Ct({hederaKit:h,hcs10Builder:g,logger:void 0}),y.initiateConnectionTool=new ut({hederaKit:h,hcs10Builder:g,logger:void 0}),y.listConnectionsTool=new ht({hederaKit:h,hcs10Builder:g,logger:void 0}),y.sendMessageToConnectionTool=new dt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.checkMessagesTool=new ft({hederaKit:h,hcs10Builder:g,logger:void 0}),y.connectionMonitorTool=new wt({hederaKit:f||h,hcs10Builder:m||g,logger:void 0}),y.manageConnectionRequestsTool=new It({hederaKit:h,hcs10Builder:g,logger:void 0}),y.acceptConnectionRequestTool=new At({hederaKit:h,hcs10Builder:g,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new Rt({hederaKit:h,hcs10Builder:g,logger:void 0}),l.info("All tools initialized")),{hederaKit:h,hcs10Builder:g,monitoringHederaKit:f,monitoringHcs10Builder:m,tools:y,stateManager:u}},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"),require("unenv/node/fs/promises")):"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","unenv/node/fs/promises"],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,e["unenv/node/fs/promises"])}(this,function(e,t,n,i,r,s,o,a,c,d){"use strict";function l(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const u=l(s),p=l(d);class h extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class g extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var f,m,y;(m=f||(f={})).assertEqual=e=>{},m.assertIs=function(e){},m.assertNever=function(e){throw new Error},m.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},m.getValidEnumValues=e=>{const t=m.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const i of t)n[i]=e[i];return m.objectValues(n)},m.objectValues=e=>m.objectKeys(e).map(function(t){return e[t]}),m.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},m.find=(e,t)=>{for(const n of e)if(t(n))return n},m.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,m.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},m.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(y||(y={})).mergeShapes=(e,t)=>({...e,...t});const b=f.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),w=e=>{switch(typeof e){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN(e)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":return Array.isArray(e)?b.array:null===e?b.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?b.promise:"undefined"!=typeof Map&&e instanceof Map?b.map:"undefined"!=typeof Set&&e instanceof Set?b.set:"undefined"!=typeof Date&&e instanceof Date?b.date:b.object;default:return b.unknown}},v=f.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 I 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:[]},i=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(i);else if("invalid_return_type"===r.code)i(r.returnTypeError);else if("invalid_arguments"===r.code)i(r.argumentsError);else if(0===r.path.length)n._errors.push(t(r));else{let e=n,i=0;for(;i<r.path.length;){const n=r.path[i];i===r.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(r))):e[n]=e[n]||{_errors:[]},e=e[n],i++}}};return i(this),n}static assert(e){if(!(e instanceof I))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,f.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const i of this.issues)if(i.path.length>0){const n=i.path[0];t[n]=t[n]||[],t[n].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}I.create=e=>new I(e);const T=(e,t)=>{let n;switch(e.code){case v.invalid_type:n=e.received===b.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case v.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,f.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${f.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${f.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${f.joinValues(e.options)}, received '${e.received}'`;break;case v.invalid_arguments:n="Invalid function arguments";break;case v.invalid_return_type:n="Invalid function return type";break;case v.invalid_date:n="Invalid date";break;case v.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}"`:f.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case v.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 v.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 v.custom:n="Invalid input";break;case v.invalid_intersection_types:n="Intersection results could not be merged";break;case v.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case v.not_finite:n="Number must be finite";break;default:n=t.defaultError,f.assertNever(e)}return{message:n}};let A=T;function _(e,t){const n=A,i=(e=>{const{data:t,path:n,errorMaps:i,issueData:r}=e,s=[...n,...r.path||[]],o={...r,path:s};if(void 0!==r.message)return{...r,path:s,message:r.message};let a="";const c=i.filter(e=>!!e).slice().reverse();for(const d of c)a=d(o,{data:t,defaultError:a}).message;return{...r,path:s,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===T?void 0:T].filter(e=>!!e)});e.common.issues.push(i)}class C{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 i of t){if("aborted"===i.status)return E;"dirty"===i.status&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const i of t){const e=await i.key,t=await i.value;n.push({key:e,value:t})}return C.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const i of t){const{key:t,value:r}=i;if("aborted"===t.status)return E;if("aborted"===r.status)return E;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),"__proto__"===t.value||void 0===r.value&&!i.alwaysSet||(n[t.value]=r.value)}return{status:e.value,value:n}}}const E=Object.freeze({status:"aborted"}),R=e=>({status:"dirty",value:e}),S=e=>({status:"valid",value:e}),x=e=>"aborted"===e.status,N=e=>"dirty"===e.status,k=e=>"valid"===e.status,O=e=>"undefined"!=typeof Promise&&e instanceof Promise;var $,P;(P=$||($={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},P.toString=e=>"string"==typeof e?e:e?.message;class M{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}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 F=(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 I(e.common.issues);return this._error=t,this._error}}};function B(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:i,description:r}=e;if(t&&(n||i))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(t,r)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??r.defaultError}:void 0===r.data?{message:s??i??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:s??n??r.defaultError}},description:r}}class D{get description(){return this._def.description}_getType(e){return w(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:w(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:w(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(O(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:w(e)},i=this._parseSync({data:e,path:n.path,parent:n});return F(n,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:w(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:w(e)},i=this._parse({data:e,path:n.path,parent:n}),r=await(O(i)?i:Promise.resolve(i));return F(n,r)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,i)=>{const r=e(t),s=()=>i.addIssue({code:v.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then(e=>!!e||(s(),!1)):!!r||(s(),!1)})}refinement(e,t){return this._refinement((n,i)=>!!e(n)||(i.addIssue("function"==typeof t?t(n,i):t),!1))}_refinement(e){return new Be({schema:this,typeName:ze.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 De.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ie.create(this)}promise(){return Fe.create(this,this._def)}or(e){return _e.create([this,e],this._def)}and(e){return Ee.create(this,e,this._def)}transform(e){return new Be({...B(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new qe({...B(this._def),innerType:this,defaultValue:t,typeName:ze.ZodDefault})}brand(){return new Ke({typeName:ze.ZodBranded,type:this,...B(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...B(this._def),innerType:this,catchValue:t,typeName:ze.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return He.create(this,e)}readonly(){return Ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const L=/^c[^\s-]{8,}$/i,q=/^[0-9a-z]+$/,U=/^[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,K=/^[a-z0-9_-]{21}$/i,H=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Z=/^[-+]?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)?)??$/,z=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let G;const W=/^(?:(?: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])$/,V=/^(?:(?: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])$/,J=/^(([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]))$/,Q=/^(([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])$/,X=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Y=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ee="((\\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])))",te=new RegExp(`^${ee}$`);function ne(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 ie(e){return new RegExp(`^${ne(e)}$`)}function re(e){let t=`${ee}T${ne(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 se(e,t){return!("v4"!==t&&t||!W.test(e))||!("v6"!==t&&t||!J.test(e))}function oe(e,t){if(!H.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const i=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(i));return"object"==typeof r&&null!==r&&((!("typ"in r)||"JWT"===r?.typ)&&(!!r.alg&&(!t||r.alg===t)))}catch{return!1}}function ae(e,t){return!("v4"!==t&&t||!V.test(e))||!("v6"!==t&&t||!Q.test(e))}class ce extends D{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==b.string){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.string,received:t.parsedType}),E}const t=new C;let n;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const r=e.data.length>i.value,s=e.data.length<i.value;(r||s)&&(n=this._getOrReturnCtx(e,n),r?_(n,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&_(n,{code:v.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)z.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"email",code:v.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)G||(G=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),G.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"emoji",code:v.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"uuid",code:v.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)K.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"nanoid",code:v.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)L.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cuid",code:v.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)q.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cuid2",code:v.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"ulid",code:v.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),_(n,{validation:"url",code:v.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"regex",code:v.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){re(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){te.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){ie(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?Z.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"duration",code:v.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?se(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"ip",code:v.invalid_string,message:i.message}),t.dirty()):"jwt"===i.kind?oe(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"jwt",code:v.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?ae(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cidr",code:v.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?X.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"base64",code:v.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Y.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"base64url",code:v.invalid_string,message:i.message}),t.dirty()):f.assertNever(i);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:v.invalid_string,...$.errToObj(n)})}_addCheck(e){return new ce({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$.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,...$.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,...$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...$.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...$.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...$.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...$.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...$.errToObj(t)})}nonempty(e){return this.min(1,$.errToObj(e))}trim(){return new ce({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ce({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ce({...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 de(e,t){const n=(e.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,r=n>i?n:i;return Number.parseInt(e.toFixed(r).replace(".",""))%Number.parseInt(t.toFixed(r).replace(".",""))/10**r}ce.create=e=>new ce({checks:[],typeName:ze.ZodString,coerce:e?.coerce??!1,...B(e)});class le extends D{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)!==b.number){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.number,received:t.parsedType}),E}let t;const n=new C;for(const i of this._def.checks)if("int"===i.kind)f.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),_(t,{code:v.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty());else if("min"===i.kind){(i.inclusive?e.data<i.value:e.data<=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty())}else if("max"===i.kind){(i.inclusive?e.data>i.value:e.data>=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty())}else"multipleOf"===i.kind?0!==de(e.data,i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),_(t,{code:v.not_finite,message:i.message}),n.dirty()):f.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,n,i){return new le({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$.toString(i)}]})}_addCheck(e){return new le({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:$.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$.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&&f.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)}}le.create=e=>new le({checks:[],typeName:ze.ZodNumber,coerce:e?.coerce||!1,...B(e)});class ue extends D{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)!==b.bigint)return this._getInvalidInput(e);let t;const n=new C;for(const i of this._def.checks)if("min"===i.kind){(i.inclusive?e.data<i.value:e.data<=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty())}else if("max"===i.kind){(i.inclusive?e.data>i.value:e.data>=i.value)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty())}else"multipleOf"===i.kind?e.data%i.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),_(t,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):f.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.bigint,received:t.parsedType}),E}gte(e,t){return this.setLimit("min",e,!0,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,n,i){return new ue({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$.toString(i)}]})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.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}}ue.create=e=>new ue({checks:[],typeName:ze.ZodBigInt,coerce:e?.coerce??!1,...B(e)});class pe extends D{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==b.boolean){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.boolean,received:t.parsedType}),E}return S(e.data)}}pe.create=e=>new pe({typeName:ze.ZodBoolean,coerce:e?.coerce||!1,...B(e)});class he extends D{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==b.date){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.date,received:t.parsedType}),E}if(Number.isNaN(e.data.getTime())){return _(this._getOrReturnCtx(e),{code:v.invalid_date}),E}const t=new C;let n;for(const i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),t.dirty()):"max"===i.kind?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),_(n,{code:v.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):f.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new he({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$.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}}he.create=e=>new he({checks:[],coerce:e?.coerce||!1,typeName:ze.ZodDate,...B(e)});class ge extends D{_parse(e){if(this._getType(e)!==b.symbol){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.symbol,received:t.parsedType}),E}return S(e.data)}}ge.create=e=>new ge({typeName:ze.ZodSymbol,...B(e)});class fe extends D{_parse(e){if(this._getType(e)!==b.undefined){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.undefined,received:t.parsedType}),E}return S(e.data)}}fe.create=e=>new fe({typeName:ze.ZodUndefined,...B(e)});class me extends D{_parse(e){if(this._getType(e)!==b.null){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.null,received:t.parsedType}),E}return S(e.data)}}me.create=e=>new me({typeName:ze.ZodNull,...B(e)});class ye extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return S(e.data)}}ye.create=e=>new ye({typeName:ze.ZodAny,...B(e)});class be extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return S(e.data)}}be.create=e=>new be({typeName:ze.ZodUnknown,...B(e)});class we extends D{_parse(e){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.never,received:t.parsedType}),E}}we.create=e=>new we({typeName:ze.ZodNever,...B(e)});class ve extends D{_parse(e){if(this._getType(e)!==b.undefined){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.void,received:t.parsedType}),E}return S(e.data)}}ve.create=e=>new ve({typeName:ze.ZodVoid,...B(e)});class Ie extends D{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==b.array)return _(t,{code:v.invalid_type,expected:b.array,received:t.parsedType}),E;if(null!==i.exactLength){const e=t.data.length>i.exactLength.value,r=t.data.length<i.exactLength.value;(e||r)&&(_(t,{code:e?v.too_big:v.too_small,minimum:r?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&(_(t,{code:v.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&(_(t,{code:v.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>i.type._parseAsync(new M(t,e,t.path,n)))).then(e=>C.mergeArray(n,e));const r=[...t.data].map((e,n)=>i.type._parseSync(new M(t,e,t.path,n)));return C.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new Ie({...this._def,minLength:{value:e,message:$.toString(t)}})}max(e,t){return new Ie({...this._def,maxLength:{value:e,message:$.toString(t)}})}length(e,t){return new Ie({...this._def,exactLength:{value:e,message:$.toString(t)}})}nonempty(e){return this.min(1,e)}}function Te(e){if(e instanceof Ae){const t={};for(const n in e.shape){const i=e.shape[n];t[n]=De.create(Te(i))}return new Ae({...e._def,shape:()=>t})}return e instanceof Ie?new Ie({...e._def,type:Te(e.element)}):e instanceof De?De.create(Te(e.unwrap())):e instanceof Le?Le.create(Te(e.unwrap())):e instanceof Re?Re.create(e.items.map(e=>Te(e))):e}Ie.create=(e,t)=>new Ie({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...B(t)});class Ae extends D{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=f.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==b.object){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.object,received:t.parsedType}),E}const{status:t,ctx:n}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),s=[];if(!(this._def.catchall instanceof we&&"strip"===this._def.unknownKeys))for(const a in n.data)r.includes(a)||s.push(a);const o=[];for(const a of r){const e=i[a],t=n.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new M(n,t,n.path,a)),alwaysSet:a in n.data})}if(this._def.catchall instanceof we){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&&(_(n,{code:v.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 i=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new M(n,i,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,i=await t.value;e.push({key:n,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>C.mergeObjectSync(t,e)):C.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return $.errToObj,new Ae({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const i=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:$.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new Ae({...this._def,unknownKeys:"strip"})}passthrough(){return new Ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ze.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new Ae({...this._def,catchall:e})}pick(e){const t={};for(const n of f.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new Ae({...this._def,shape:()=>t})}omit(e){const t={};for(const n of f.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new Ae({...this._def,shape:()=>t})}deepPartial(){return Te(this)}partial(e){const t={};for(const n of f.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new Ae({...this._def,shape:()=>t})}required(e){const t={};for(const n of f.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof De;)e=e._def.innerType;t[n]=e}return new Ae({...this._def,shape:()=>t})}keyof(){return $e(f.objectKeys(this.shape))}}Ae.create=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strip",catchall:we.create(),typeName:ze.ZodObject,...B(t)}),Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:we.create(),typeName:ze.ZodObject,...B(t)}),Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:we.create(),typeName:ze.ZodObject,...B(t)});class _e extends D{_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 i of e)if("dirty"===i.result.status)return t.common.issues.push(...i.ctx.common.issues),i.result;const n=e.map(e=>new I(e.ctx.common.issues));return _(t,{code:v.invalid_union,unionErrors:n}),E});{let e;const i=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},r=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===r.status)return r;"dirty"!==r.status||e||(e={result:r,ctx:n}),n.common.issues.length&&i.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=i.map(e=>new I(e));return _(t,{code:v.invalid_union,unionErrors:r}),E}}get options(){return this._def.options}}function Ce(e,t){const n=w(e),i=w(t);if(e===t)return{valid:!0,data:e};if(n===b.object&&i===b.object){const n=f.objectKeys(t),i=f.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const s of i){const n=Ce(e[s],t[s]);if(!n.valid)return{valid:!1};r[s]=n.data}return{valid:!0,data:r}}if(n===b.array&&i===b.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let i=0;i<e.length;i++){const r=Ce(e[i],t[i]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===b.date&&i===b.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}_e.create=(e,t)=>new _e({options:e,typeName:ze.ZodUnion,...B(t)});class Ee extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=(e,i)=>{if(x(e)||x(i))return E;const r=Ce(e.value,i.value);return r.valid?((N(e)||N(i))&&t.dirty(),{status:t.value,value:r.data}):(_(n,{code:v.invalid_intersection_types}),E)};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])=>i(e,t)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ee.create=(e,t,n)=>new Ee({left:e,right:t,typeName:ze.ZodIntersection,...B(n)});class Re extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.array)return _(n,{code:v.invalid_type,expected:b.array,received:n.parsedType}),E;if(n.data.length<this._def.items.length)return _(n,{code:v.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&n.data.length>this._def.items.length&&(_(n,{code:v.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((e,t)=>{const i=this._def.items[t]||this._def.rest;return i?i._parse(new M(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(i).then(e=>C.mergeArray(t,e)):C.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Re({...this._def,rest:e})}}Re.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Re({items:e,typeName:ze.ZodTuple,rest:null,...B(t)})};class Se extends D{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!==b.object)return _(n,{code:v.invalid_type,expected:b.object,received:n.parsedType}),E;const i=[],r=this._def.keyType,s=this._def.valueType;for(const o in n.data)i.push({key:r._parse(new M(n,o,n.path,o)),value:s._parse(new M(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?C.mergeObjectAsync(t,i):C.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return new Se(t instanceof D?{keyType:e,valueType:t,typeName:ze.ZodRecord,...B(n)}:{keyType:ce.create(),valueType:e,typeName:ze.ZodRecord,...B(t)})}}class xe extends D{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!==b.map)return _(n,{code:v.invalid_type,expected:b.map,received:n.parsedType}),E;const i=this._def.keyType,r=this._def.valueType,s=[...n.data.entries()].map(([e,t],s)=>({key:i._parse(new M(n,e,n.path,[s,"key"])),value:r._parse(new M(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 i=await n.key,r=await n.value;if("aborted"===i.status||"aborted"===r.status)return E;"dirty"!==i.status&&"dirty"!==r.status||t.dirty(),e.set(i.value,r.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of s){const i=n.key,r=n.value;if("aborted"===i.status||"aborted"===r.status)return E;"dirty"!==i.status&&"dirty"!==r.status||t.dirty(),e.set(i.value,r.value)}return{status:t.value,value:e}}}}xe.create=(e,t,n)=>new xe({valueType:t,keyType:e,typeName:ze.ZodMap,...B(n)});class Ne extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return _(n,{code:v.invalid_type,expected:b.set,received:n.parsedType}),E;const i=this._def;null!==i.minSize&&n.data.size<i.minSize.value&&(_(n,{code:v.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&n.data.size>i.maxSize.value&&(_(n,{code:v.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const r=this._def.valueType;function s(e){const n=new Set;for(const i of e){if("aborted"===i.status)return E;"dirty"===i.status&&t.dirty(),n.add(i.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>r._parse(new M(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(e,t){return new Ne({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new Ne({...this._def,maxSize:{value:e,message:$.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ne.create=(e,t)=>new Ne({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...B(t)});class ke extends D{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:ze.ZodLazy,...B(t)});class Oe extends D{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return _(t,{received:t.data,code:v.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}function $e(e,t){return new Pe({values:e,typeName:ze.ZodEnum,...B(t)})}Oe.create=(e,t)=>new Oe({value:e,typeName:ze.ZodLiteral,...B(t)});class Pe extends D{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return _(t,{expected:f.joinValues(n),received:t.parsedType,code:v.invalid_type}),E}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 _(t,{received:t.data,code:v.invalid_enum_value,options:n}),E}return S(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 Pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Pe.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Pe.create=$e;class Me extends D{_parse(e){const t=f.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const e=f.objectValues(t);return _(n,{expected:f.joinValues(e),received:n.parsedType,code:v.invalid_type}),E}if(this._cache||(this._cache=new Set(f.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=f.objectValues(t);return _(n,{received:n.data,code:v.invalid_enum_value,options:e}),E}return S(e.data)}get enum(){return this._def.values}}Me.create=(e,t)=>new Me({values:e,typeName:ze.ZodNativeEnum,...B(t)});class Fe extends D{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==b.promise&&!1===t.common.async)return _(t,{code:v.invalid_type,expected:b.promise,received:t.parsedType}),E;const n=t.parsedType===b.promise?t.data:Promise.resolve(t.data);return S(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Fe.create=(e,t)=>new Fe({type:e,typeName:ze.ZodPromise,...B(t)});class Be extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,r={addIssue:e=>{_(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(r.addIssue=r.addIssue.bind(r),"preprocess"===i.type){const e=i.transform(n.data,r);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return E;const i=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===i.status?E:"dirty"===i.status||"dirty"===t.value?R(i.value):i});{if("aborted"===t.value)return E;const i=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===i.status?E:"dirty"===i.status||"dirty"===t.value?R(i.value):i}}if("refinement"===i.type){const e=e=>{const t=i.refinement(e,r);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 i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===i.status?E:("dirty"===i.status&&t.dirty(),e(i.value),{status:t.value,value:i.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?E:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===i.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!k(e))return E;const s=i.transform(e.value,r);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(i.transform(e.value,r)).then(e=>({status:t.value,value:e})):E)}f.assertNever(i)}}Be.create=(e,t,n)=>new Be({schema:e,typeName:ze.ZodEffects,effect:t,...B(n)}),Be.createWithPreprocess=(e,t,n)=>new Be({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...B(n)});class De extends D{_parse(e){return this._getType(e)===b.undefined?S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:ze.ZodOptional,...B(t)});class Le extends D{_parse(e){return this._getType(e)===b.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(e,t)=>new Le({innerType:e,typeName:ze.ZodNullable,...B(t)});class qe extends D{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===b.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:ze.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...B(t)});class Ue extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return O(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new I(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new I(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ue.create=(e,t)=>new Ue({innerType:e,typeName:ze.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...B(t)});class je extends D{_parse(e){if(this._getType(e)!==b.nan){const t=this._getOrReturnCtx(e);return _(t,{code:v.invalid_type,expected:b.nan,received:t.parsedType}),E}return{status:"valid",value:e.data}}}je.create=e=>new je({typeName:ze.ZodNaN,...B(e)});class Ke extends D{_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 He extends D{_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?E:"dirty"===e.status?(t.dirty(),R(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?E:"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 He({in:e,out:t,typeName:ze.ZodPipeline})}}class Ze extends D{_parse(e){const t=this._def.innerType._parse(e),n=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return O(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var ze,Ge;Ze.create=(e,t)=>new Ze({innerType:e,typeName:ze.ZodReadonly,...B(t)}),(Ge=ze||(ze={})).ZodString="ZodString",Ge.ZodNumber="ZodNumber",Ge.ZodNaN="ZodNaN",Ge.ZodBigInt="ZodBigInt",Ge.ZodBoolean="ZodBoolean",Ge.ZodDate="ZodDate",Ge.ZodSymbol="ZodSymbol",Ge.ZodUndefined="ZodUndefined",Ge.ZodNull="ZodNull",Ge.ZodAny="ZodAny",Ge.ZodUnknown="ZodUnknown",Ge.ZodNever="ZodNever",Ge.ZodVoid="ZodVoid",Ge.ZodArray="ZodArray",Ge.ZodObject="ZodObject",Ge.ZodUnion="ZodUnion",Ge.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ge.ZodIntersection="ZodIntersection",Ge.ZodTuple="ZodTuple",Ge.ZodRecord="ZodRecord",Ge.ZodMap="ZodMap",Ge.ZodSet="ZodSet",Ge.ZodFunction="ZodFunction",Ge.ZodLazy="ZodLazy",Ge.ZodLiteral="ZodLiteral",Ge.ZodEnum="ZodEnum",Ge.ZodEffects="ZodEffects",Ge.ZodNativeEnum="ZodNativeEnum",Ge.ZodOptional="ZodOptional",Ge.ZodNullable="ZodNullable",Ge.ZodDefault="ZodDefault",Ge.ZodCatch="ZodCatch",Ge.ZodPromise="ZodPromise",Ge.ZodBranded="ZodBranded",Ge.ZodPipeline="ZodPipeline",Ge.ZodReadonly="ZodReadonly";const We=ce.create,Ve=le.create,Je=pe.create,Qe=be.create;we.create;const Xe=Ie.create,Ye=Ae.create,et=_e.create;Ee.create,Re.create;const tt=Se.create,nt=Pe.create,it=Me.create;Fe.create,De.create,Le.create;const rt=class{static parseCapabilities(e){if(!e)return[i.AIAgentCapability.TEXT_GENERATION];const t=e.toLowerCase(),n=new Set;for(const[i,r]of Object.entries(this.CAPABILITY_MAPPINGS))t.includes(i)&&r.forEach(e=>n.add(e));return 0===n.size&&n.add(i.AIAgentCapability.TEXT_GENERATION),Array.from(n)}static parseTagsOrCapabilities(e){if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=new Set;return e.forEach(e=>{this.parseCapabilities(e).forEach(e=>t.add(e))}),Array.from(t)}return"string"==typeof e?this.parseCapabilities(e):[i.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[i.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[i.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[i.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[i.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[i.AIAgentCapability.CODE_GENERATION]:"Code Generation",[i.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[i.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[i.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[i.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[i.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[i.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[i.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[i.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[i.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[i.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[i.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[i.AIAgentCapability.API_INTEGRATION]:"API Integration",[i.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};rt.CAPABILITY_MAPPINGS={ai:[i.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[i.AIAgentCapability.TEXT_GENERATION],chat:[i.AIAgentCapability.TEXT_GENERATION],conversation:[i.AIAgentCapability.TEXT_GENERATION],text:[i.AIAgentCapability.TEXT_GENERATION],"text generation":[i.AIAgentCapability.TEXT_GENERATION],image:[i.AIAgentCapability.IMAGE_GENERATION],picture:[i.AIAgentCapability.IMAGE_GENERATION],visual:[i.AIAgentCapability.IMAGE_GENERATION],photo:[i.AIAgentCapability.IMAGE_GENERATION],audio:[i.AIAgentCapability.AUDIO_GENERATION],sound:[i.AIAgentCapability.AUDIO_GENERATION],voice:[i.AIAgentCapability.AUDIO_GENERATION],speech:[i.AIAgentCapability.AUDIO_GENERATION],video:[i.AIAgentCapability.VIDEO_GENERATION],movie:[i.AIAgentCapability.VIDEO_GENERATION],animation:[i.AIAgentCapability.VIDEO_GENERATION],code:[i.AIAgentCapability.CODE_GENERATION],programming:[i.AIAgentCapability.CODE_GENERATION],development:[i.AIAgentCapability.CODE_GENERATION],coding:[i.AIAgentCapability.CODE_GENERATION],translate:[i.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[i.AIAgentCapability.LANGUAGE_TRANSLATION],language:[i.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[i.AIAgentCapability.DATA_INTEGRATION],"data processing":[i.AIAgentCapability.DATA_INTEGRATION],"data integration":[i.AIAgentCapability.DATA_INTEGRATION],etl:[i.AIAgentCapability.DATA_INTEGRATION],market:[i.AIAgentCapability.MARKET_INTELLIGENCE],trading:[i.AIAgentCapability.MARKET_INTELLIGENCE],finance:[i.AIAgentCapability.MARKET_INTELLIGENCE],financial:[i.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[i.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[i.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[i.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[i.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[i.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[i.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[i.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[i.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[i.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[i.AIAgentCapability.GOVERNANCE_FACILITATION],security:[i.AIAgentCapability.SECURITY_MONITORING],monitoring:[i.AIAgentCapability.SECURITY_MONITORING],threat:[i.AIAgentCapability.SECURITY_MONITORING],compliance:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[i.AIAgentCapability.FRAUD_DETECTION],detection:[i.AIAgentCapability.FRAUD_DETECTION],anomaly:[i.AIAgentCapability.FRAUD_DETECTION],coordination:[i.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[i.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[i.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[i.AIAgentCapability.API_INTEGRATION],integration:[i.AIAgentCapability.API_INTEGRATION],webhook:[i.AIAgentCapability.API_INTEGRATION],workflow:[i.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[i.AIAgentCapability.WORKFLOW_AUTOMATION],process:[i.AIAgentCapability.WORKFLOW_AUTOMATION]};let st=rt;const ot=Ye({name:We().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:We().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:We().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:nt(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:We().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:et([Xe(it(i.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Agent capabilities - can be capability names (e.g. "ai", "data processing"), capability enum values, or array of either. Common values: "ai"/"text" (TEXT_GENERATION), "data" (DATA_INTEGRATION), "analytics" (TRANSACTION_ANALYTICS)'),tags:et([Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):st.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:We().optional().describe("Creator attribution for the agent"),socials:tt(nt(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),We()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:tt(Qe()).optional().describe("Custom metadata properties for the agent"),profilePicture:et([We().describe("URL or local file path to profile picture"),Ye({url:We().optional(),path:We().optional(),filename:We().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:We().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:Ve().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:We().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:Ve().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:Xe(Ye({amount:Ve().positive(),tokenId:We()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Xe(We()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Je().optional().describe("Whether to set as current agent (default: true)"),persistence:Ye({prefix:We().optional()}).optional().describe("Optional persistence configuration")});class at extends h{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. Supports natural language for capabilities/tags like "ai", "data processing", "analytics". 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=ot,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;this.specificArgs=t;const i={name:t.name};if(void 0!==t.description&&(i.bio=t.description),void 0!==t.alias)i.alias=t.alias;else{const e=Date.now().toString(36);i.alias=`${t.name}${e}`}if(void 0!==t.type&&(i.type=t.type),void 0!==t.model&&(i.model=t.model),void 0!==t.tags?i.capabilities=t.tags:void 0!==t.capabilities&&(i.capabilities=t.capabilities),void 0!==t.creator&&(i.creator=t.creator),void 0!==t.socials&&(i.socials=t.socials),void 0!==t.properties&&(i.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)i.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),i.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(i.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(i.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(i.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(i.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(i.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(i.initialBalance=t.initialBalance),await n.registerAgent(i)}async _call(e,t){const n=await super._call(e,t),i=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&i)try{const e=JSON.parse(n);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(r){}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,i=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,r=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,s=e.privateKey||e.metadata?.privateKey;if(t&&n&&i&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:n,outboundTopicId:i,profileTopicId:r,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 ct=Ye({targetIdentifier:We().optional().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."),connectionId:We().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:We().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:We().describe("The text message content to send."),disableMonitoring:Je().optional().default(!1)});class dt extends h{constructor(e){super(e),this.name="send_message_to_connection",this.description="Use this to send a message to an agent you already have an active connection with. Provide the target agent's account ID (e.g., 0.0.12345) and your message. If no active connection exists, this will fail - use initiate_connection instead to create a new connection first.",this.specificInputSchema=ct,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e,i=t.targetIdentifier||t.agentId||t.connectionId;if(!i)throw new Error("Either targetIdentifier, connectionId, or agentId must be provided");const r=n.getStateManager();if(r){const e=r.getConnectionsManager();if(e)try{const t=r.getCurrentAgent();t&&t.accountId&&await e.fetchConnectionData(t.accountId)}catch(s){console.debug("Could not refresh connections:",s)}if(i.match(/^\d+$/)){const e=r.listConnections(),s=parseInt(i)-1,o=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(s>=0&&s<o.length){const e=o[s];if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}if(i.match(/^\d+\.\d+\.\d+$/)){const e=r.listConnections().find(e=>!(e.targetAccountId!==i&&e.targetAccountId!==`0.0.${i}`||"established"!==e.status||e.isPending||e.needsConfirmation));if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}await n.sendMessageToConnection({targetIdentifier:i,message:t.message,disableMonitoring:t.disableMonitoring})}}const lt=Ye({targetAccountId:We().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:Je().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:We().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 ut extends h{constructor(e){super(e),this.name="initiate_connection",this.description="ONLY use this to START a BRAND NEW connection to an agent you have NEVER connected to before. If you already have an active connection to this agent, use send_message_to_connection instead. This creates a new connection request and waits for acceptance.",this.specificInputSchema=lt,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,i={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(i.disableMonitor=t.disableMonitor),void 0!==t.memo&&(i.memo=t.memo),await n.initiateConnection(i)}}const pt=Ye({includeDetails:Je().optional().describe("Whether to include detailed information about each connection"),showPending:Je().optional().describe("Whether to include pending connection requests")});class ht extends g{constructor(e){super(e),this.name="list_connections",this.description="Lists all active HCS-10 connections. Use this FIRST before sending messages to check if you already have an active connection to a target agent. Shows connection details and agent information for each active connection.",this.specificInputSchema=pt}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 i=await t.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return i}}const gt=Ye({targetIdentifier:We().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:Je().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:Ve().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class ft extends g{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=gt}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const i=this.hcs10Builder;await i.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const r=await i.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return r}}const mt=Ye({accountId:We().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:et([Xe(it(i.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class yt extends g{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/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=mt}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,i={};e&&(i.accountId=e),t&&(i.tags=t),await n.findRegistrations(i);const r=await n.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return r}}const bt=Ye({acceptAll:Je().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:We().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:Xe(Ye({amount:Ve(),collectorAccount:We().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Xe(Ye({amount:Ve(),tokenId:We(),collectorAccount:We().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:Xe(We()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:Ve().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:We().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class wt extends h{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=bt,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 vt=Ye({action:nt(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:We().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class It extends g{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=vt}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,i={action:e};void 0!==t&&(i.requestKey=t),await n.manageConnectionRequests(i);const r=await n.execute();return"rawResult"in r?r.rawResult:r}}const Tt=Ye({requestKey:We().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:Ve().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:Xe(We()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class At extends h{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=Tt,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 _t=Ye({accountId:We().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:Je().optional().describe("Optional: Force refresh from the network instead of using cache.")});class Ct extends g{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=_t}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,i={accountId:e};void 0!==t&&(i.disableCache=t),await n.retrieveProfile(i);const r=await n.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return r}}const Et=Ye({});class Rt extends g{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=Et}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class St extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class xt extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const Nt=Ye({registryType:it(i.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:Ve().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:et([We(),Je()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:et([We(),Je()]).optional().describe("Submit key: public key string or true to use operator key")});const kt=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:We().optional().describe("Optional metadata URI (HIP-412 format)"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const Ot=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:We().describe("The unique ID of the entry to update"),metadata:We().optional().describe("Optional metadata URI (HIP-412 format)"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const $t=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:We().describe("The unique ID of the entry to delete"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const Pt=Ye({registryTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:We().optional().describe("Optional metadata URI for migration details"),memo:We().max(500).optional().describe("Optional memo (max 500 characters)")});const Mt=Ye({topicId:We().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:Ve().int().positive().optional().describe("Maximum number of entries to return"),order:nt(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:Ve().int().min(0).optional().describe("Number of entries to skip")});class Ft extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Bt extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const Dt=Ye({ttl:Ve().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),adminKey:et([Je(),We()]).optional().describe("Admin key for the registry topic. Can be boolean (use operator key) or a public key string"),submitKey:et([Je(),We()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Lt=Ye({metadata:tt(Qe()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:Ye({base64:We().optional().describe("Base64 encoded data for the hashinal"),url:We().optional().describe("URL to fetch data from"),mimeType:We().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:We().optional().describe("Optional memo for the registration"),ttl:Ve().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:We().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:We().optional().describe("Submit key for the registry (required if registry has a submit key)")});const qt=Ye({registryTopicId:We().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:tt(Qe()).describe("Updated metadata object for the hashinal"),data:Ye({base64:We().optional().describe("Base64 encoded data for the updated hashinal"),url:We().optional().describe("URL to fetch updated data from"),mimeType:We().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:We().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:We().describe("Submit key for the registry (required to update)")});const Ut=Ye({topicId:We().describe("The registry topic ID to query"),limit:Ve().optional().default(100).describe("Maximum number of entries to retrieve"),order:nt(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:Ve().optional().describe("Number of entries to skip")});class jt extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}class Kt extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}const Ht=Ye({url:We().url().describe("ONLY direct file download URLs ending in .pdf, .jpg, .png, .json, .zip etc. NOT for web pages or articles"),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Qe()).optional().describe("Metadata to attach to the inscription"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:We().optional().describe("API key for inscription service")});const Zt=Ye({filePath:We().min(1,"File path cannot be empty").describe("The file path of the content to inscribe. Must point to a valid, non-empty file."),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Qe()).optional().describe("Metadata to attach to the inscription"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:We().optional().describe("API key for inscription service")});const zt=Ye({base64Data:We().min(1,"Base64 data cannot be empty").describe("Base64 encoded content to inscribe. Must contain valid, non-empty content (minimum 10 bytes after decoding)."),fileName:We().min(1,"File name cannot be empty").describe("Name for the inscribed content. Required for all inscriptions."),mimeType:We().optional().describe("MIME type of the content"),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Qe()).optional().describe("Metadata to attach to the inscription"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:We().optional().describe("API key for inscription service")});const Gt=Ye({url:We().url().describe("The URL of the content to inscribe as Hashinal NFT"),name:We().describe("Name of the Hashinal NFT"),creator:We().describe("Creator account ID or name"),description:We().describe("Description of the Hashinal NFT"),type:We().describe('Type of NFT (e.g., "image", "video", "audio")'),attributes:Xe(Ye({trait_type:We(),value:et([We(),Ve()])})).optional().describe("NFT attributes"),properties:tt(Qe()).optional().describe("Additional properties"),jsonFileURL:We().url().optional().describe("URL to JSON metadata file"),tags:Xe(We()).optional().describe("Tags to categorize the NFT"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:We().optional().describe("API key for inscription service")});const Wt=Ye({transactionId:We().describe("The transaction ID of the inscription to retrieve"),apiKey:We().optional().describe("API key for inscription service")});const Vt=s.join(c.cwd(),".env");class Jt{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 i.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 i.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 i=this.connectionsManager.getConnectionByTopicId(e);if(i)return this.convertToActiveConnection(i);const r=this.connectionsManager.getConnectionByAccountId(e);return r?this.convertToActiveConnection(r):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",i=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const s={[`${i}_ACCOUNT_ID`]:e.accountId,[`${i}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${i}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${i}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${i}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";r.existsSync(e)&&(n=r.readFileSync(e,"utf8"));const i=[...n.split("\n")];for(const[r,s]of Object.entries(t)){const e=i.findIndex(e=>e.startsWith(`${r}=`));-1!==e?i[e]=`${r}=${s}`:i.push(`${r}=${s}`)}r.writeFileSync(e,i.join("\n"))}(n,s)}}function Qt(e,t){return function(){return e.apply(t,arguments)}}const{toString:Xt}=Object.prototype,{getPrototypeOf:Yt}=Object,{iterator:en,toStringTag:tn}=Symbol,nn=(e=>t=>{const n=Xt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),rn=e=>(e=e.toLowerCase(),t=>nn(t)===e),sn=e=>t=>typeof t===e,{isArray:on}=Array,an=sn("undefined");function cn(e){return null!==e&&!an(e)&&null!==e.constructor&&!an(e.constructor)&&un(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const dn=rn("ArrayBuffer");const ln=sn("string"),un=sn("function"),pn=sn("number"),hn=e=>null!==e&&"object"==typeof e,gn=e=>{if("object"!==nn(e))return!1;const t=Yt(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||tn in e||en in e)},fn=rn("Date"),mn=rn("File"),yn=rn("Blob"),bn=rn("FileList"),wn=rn("URLSearchParams"),[vn,In,Tn,An]=["ReadableStream","Request","Response","Headers"].map(rn);function _n(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),on(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(cn(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let o;for(i=0;i<s;i++)o=r[i],t.call(null,e[o],o,e)}}function Cn(e,t){if(cn(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const En="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:o,Rn=e=>!an(e)&&e!==En;const Sn=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Yt(Uint8Array)),xn=rn("HTMLFormElement"),Nn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),kn=rn("RegExp"),On=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};_n(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const $n=rn("AsyncFunction"),Pn=(Mn="function"==typeof a.setImmediate,Fn=un(En.postMessage),Mn?a.setImmediate:Fn?(Bn=`axios@${Math.random()}`,Dn=[],En.addEventListener("message",({source:e,data:t})=>{e===En&&t===Bn&&Dn.length&&Dn.shift()()},!1),e=>{Dn.push(e),En.postMessage(Bn,"*")}):e=>setTimeout(e));var Mn,Fn,Bn,Dn;const Ln="undefined"!=typeof queueMicrotask?queueMicrotask.bind(En):void 0!==c&&c.nextTick||Pn,qn={isArray:on,isArrayBuffer:dn,isBuffer:cn,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||un(e.append)&&("formdata"===(t=nn(e))||"object"===t&&un(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&dn(e.buffer),t},isString:ln,isNumber:pn,isBoolean:e=>!0===e||!1===e,isObject:hn,isPlainObject:gn,isEmptyObject:e=>{if(!hn(e)||cn(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:vn,isRequest:In,isResponse:Tn,isHeaders:An,isUndefined:an,isDate:fn,isFile:mn,isBlob:yn,isRegExp:kn,isFunction:un,isStream:e=>hn(e)&&un(e.pipe),isURLSearchParams:wn,isTypedArray:Sn,isFileList:bn,forEach:_n,merge:function e(){const{caseless:t}=Rn(this)&&this||{},n={},i=(i,r)=>{const s=t&&Cn(n,r)||r;gn(n[s])&&gn(i)?n[s]=e(n[s],i):gn(i)?n[s]=e({},i):on(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&_n(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(_n(t,(t,i)=>{n&&un(t)?e[i]=Qt(t,n):e[i]=t},{allOwnKeys:i}),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,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,s,o;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)o=r[s],i&&!i(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==n&&Yt(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:nn,kindOfTest:rn,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(on(e))return e;let t=e.length;if(!pn(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[en]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:xn,hasOwnProperty:Nn,hasOwnProp:Nn,reduceDescriptors:On,freezeMethods:e=>{On(e,(t,n)=>{if(un(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];un(i)&&(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={},i=e=>{e.forEach(e=>{n[e]=!0})};return on(e)?i(e):i(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:Cn,global:En,isContextDefined:Rn,isSpecCompliantForm:function(e){return!!(e&&un(e.append)&&"FormData"===e[tn]&&e[en])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(hn(e)){if(t.indexOf(e)>=0)return;if(cn(e))return e;if(!("toJSON"in e)){t[i]=e;const r=on(e)?[]:{};return _n(e,(e,t)=>{const s=n(e,i+1);!an(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:$n,isThenable:e=>e&&(hn(e)||un(e))&&un(e.then)&&un(e.catch),setImmediate:Pn,asap:Ln,isIterable:e=>null!=e&&un(e[en])};function Un(e,t,n,i,r){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),i&&(this.request=i),r&&(this.response=r,this.status=r.status?r.status:null)}qn.inherits(Un,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:qn.toJSONObject(this.config),code:this.code,status:this.status}}});const jn=Un.prototype,Kn={};["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=>{Kn[e]={value:e}}),Object.defineProperties(Un,Kn),Object.defineProperty(jn,"isAxiosError",{value:!0}),Un.from=(e,t,n,i,r,s)=>{const o=Object.create(jn);return qn.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Un.call(o,e.message,t,n,i,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Hn(e){return qn.isPlainObject(e)||qn.isArray(e)}function Zn(e){return qn.endsWith(e,"[]")?e.slice(0,-2):e}function zn(e,t,n){return e?e.concat(t).map(function(e,t){return e=Zn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Gn=qn.toFlatObject(qn,{},null,function(e){return/^is[A-Z]/.test(e)});function Wn(e,n,i){if(!qn.isObject(e))throw new TypeError("target must be an object");n=n||new FormData;const r=(i=qn.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!qn.isUndefined(t[e])})).metaTokens,s=i.visitor||l,o=i.dots,a=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&qn.isSpecCompliantForm(n);if(!qn.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(qn.isDate(e))return e.toISOString();if(qn.isBoolean(e))return e.toString();if(!c&&qn.isBlob(e))throw new Un("Blob is not supported. Use a Buffer instead.");return qn.isArrayBuffer(e)||qn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):t.Buffer.from(e):e}function l(e,t,i){let s=e;if(e&&!i&&"object"==typeof e)if(qn.endsWith(t,"{}"))t=r?t:t.slice(0,-2),e=JSON.stringify(e);else if(qn.isArray(e)&&function(e){return qn.isArray(e)&&!e.some(Hn)}(e)||(qn.isFileList(e)||qn.endsWith(t,"[]"))&&(s=qn.toArray(e)))return t=Zn(t),s.forEach(function(e,i){!qn.isUndefined(e)&&null!==e&&n.append(!0===a?zn([t],i,o):null===a?t:t+"[]",d(e))}),!1;return!!Hn(e)||(n.append(zn(i,t,o),d(e)),!1)}const u=[],p=Object.assign(Gn,{defaultVisitor:l,convertValue:d,isVisitable:Hn});if(!qn.isObject(e))throw new TypeError("data must be an object");return function e(t,i){if(!qn.isUndefined(t)){if(-1!==u.indexOf(t))throw Error("Circular reference detected in "+i.join("."));u.push(t),qn.forEach(t,function(t,r){!0===(!(qn.isUndefined(t)||null===t)&&s.call(n,t,qn.isString(r)?r.trim():r,i,p))&&e(t,i?i.concat(r):[r])}),u.pop()}}(e),n}function Vn(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Jn(e,t){this._pairs=[],e&&Wn(e,this,t)}const Qn=Jn.prototype;function Xn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Yn(e,t,n){if(!t)return e;const i=n&&n.encode||Xn;qn.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):qn.isURLSearchParams(t)?t.toString():new Jn(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Qn.append=function(e,t){this._pairs.push([e,t])},Qn.toString=function(e){const t=e?function(t){return e.call(this,t,Vn)}:Vn;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class ei{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){qn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const ti={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ni={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Jn,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},ii="undefined"!=typeof window&&"undefined"!=typeof document,ri="object"==typeof navigator&&navigator||void 0,si=ii&&(!ri||["ReactNative","NativeScript","NS"].indexOf(ri.product)<0),oi="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,ai=ii&&window.location.href||"http://localhost",ci={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ii,hasStandardBrowserEnv:si,hasStandardBrowserWebWorkerEnv:oi,navigator:ri,origin:ai},Symbol.toStringTag,{value:"Module"})),...ni};function di(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=r>=e.length;if(s=!s&&qn.isArray(i)?i.length:s,a)return qn.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!o;i[s]&&qn.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&qn.isArray(i[s])&&(i[s]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],t[s]=e[s];return t}(i[s])),!o}if(qn.isFormData(e)&&qn.isFunction(e.entries)){const n={};return qn.forEachEntry(e,(e,i)=>{t(function(e){return qn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const li={transitional:ti,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=qn.isObject(e);r&&qn.isHTMLForm(e)&&(e=new FormData(e));if(qn.isFormData(e))return i?JSON.stringify(di(e)):e;if(qn.isArrayBuffer(e)||qn.isBuffer(e)||qn.isStream(e)||qn.isFile(e)||qn.isBlob(e)||qn.isReadableStream(e))return e;if(qn.isArrayBufferView(e))return e.buffer;if(qn.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Wn(e,new ci.classes.URLSearchParams,{visitor:function(e,t,n,i){return ci.isNode&&qn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=qn.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 r||i?(t.setContentType("application/json",!1),function(e,t,n){if(qn.isString(e))try{return(t||JSON.parse)(e),qn.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||li.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(qn.isResponse(e)||qn.isReadableStream(e))return e;if(e&&qn.isString(e)&&(n&&!this.responseType||i)){const n=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(r){if(n){if("SyntaxError"===r.name)throw Un.from(r,Un.ERR_BAD_RESPONSE,this,null,this.response);throw r}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ci.classes.FormData,Blob:ci.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};qn.forEach(["delete","get","head","post","put","patch"],e=>{li.headers[e]={}});const ui=qn.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"]),pi=Symbol("internals");function hi(e){return e&&String(e).trim().toLowerCase()}function gi(e){return!1===e||null==e?e:qn.isArray(e)?e.map(gi):String(e)}function fi(e,t,n,i,r){return qn.isFunction(i)?i.call(this,t,n):(r&&(t=n),qn.isString(t)?qn.isString(i)?-1!==t.indexOf(i):qn.isRegExp(i)?i.test(t):void 0:void 0)}let mi=class{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=hi(t);if(!r)throw new Error("header name must be a non-empty string");const s=qn.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=gi(e))}const s=(e,t)=>qn.forEach(e,(e,n)=>r(e,n,t));if(qn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(qn.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),n=e.substring(0,r).trim().toLowerCase(),i=e.substring(r+1).trim(),!n||t[n]&&ui[n]||("set-cookie"===n?t[n]?t[n].push(i):t[n]=[i]:t[n]=t[n]?t[n]+", "+i:i)}),t})(e),t);else if(qn.isObject(e)&&qn.isIterable(e)){let n,i,r={};for(const t of e){if(!qn.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?qn.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(r,t)}else null!=e&&r(t,e,n);return this}get(e,t){if(e=hi(e)){const n=qn.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 i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(qn.isFunction(t))return t.call(this,e,n);if(qn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=hi(e)){const n=qn.findKey(this,e);return!(!n||void 0===this[n]||t&&!fi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=hi(e)){const r=qn.findKey(n,e);!r||t&&!fi(0,n[r],r,t)||(delete n[r],i=!0)}}return qn.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!fi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return qn.forEach(this,(i,r)=>{const s=qn.findKey(n,r);if(s)return t[s]=gi(i),void delete t[r];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();o!==r&&delete t[r],t[o]=gi(i),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return qn.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&qn.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[pi]=this[pi]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=hi(e);t[i]||(!function(e,t){const n=qn.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+n,{value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})})}(n,e),t[i]=!0)}return qn.isArray(e)?e.forEach(i):i(e),this}};function yi(e,t){const n=this||li,i=t||n,r=mi.from(i.headers);let s=i.data;return qn.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function bi(e){return!(!e||!e.__CANCEL__)}function wi(e,t,n){Un.call(this,null==e?"canceled":e,Un.ERR_CANCELED,t,n),this.name="CanceledError"}function vi(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Un("Request failed with status code "+n.status,[Un.ERR_BAD_REQUEST,Un.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}mi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),qn.reduceDescriptors(mi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),qn.freezeMethods(mi),qn.inherits(wi,Un,{__CANCEL__:!0});const Ii=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];r||(r=c),n[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=n[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-r<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const o=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-r;a>=s?o(e,t):(n=e,i||(i=setTimeout(()=>{i=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-i,c=r(a);i=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)},Ti=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Ai=e=>(...t)=>qn.asap(()=>e(...t)),_i=ci.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,ci.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(ci.origin),ci.navigator&&/(msie|trident)/i.test(ci.navigator.userAgent)):()=>!0,Ci=ci.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const o=[e+"="+encodeURIComponent(t)];qn.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),qn.isString(i)&&o.push("path="+i),qn.isString(r)&&o.push("domain="+r),!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 Ei(e,t,n){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Ri=e=>e instanceof mi?{...e}:e;function Si(e,t){t=t||{};const n={};function i(e,t,n,i){return qn.isPlainObject(e)&&qn.isPlainObject(t)?qn.merge.call({caseless:i},e,t):qn.isPlainObject(t)?qn.merge({},t):qn.isArray(t)?t.slice():t}function r(e,t,n,r){return qn.isUndefined(t)?qn.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!qn.isUndefined(t))return i(void 0,t)}function o(e,t){return qn.isUndefined(t)?qn.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(n,r,s){return s in t?i(n,r):s in e?i(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)=>r(Ri(e),Ri(t),0,!0)};return qn.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,o=s(e[i],t[i],i);qn.isUndefined(o)&&s!==a||(n[i]=o)}),n}const xi=e=>{const t=Si({},e);let n,{data:i,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=mi.from(a),t.url=Yn(Ei(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),qn.isFormData(i))if(ci.hasStandardBrowserEnv||ci.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(ci.hasStandardBrowserEnv&&(r&&qn.isFunction(r)&&(r=r(t)),r||!1!==r&&_i(t.url))){const e=s&&o&&Ci.read(o);e&&a.set(s,e)}return t},Ni="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=xi(e);let r=i.data;const s=mi.from(i.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function g(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let f=new XMLHttpRequest;function m(){if(!f)return;const i=mi.from("getAllResponseHeaders"in f&&f.getAllResponseHeaders());vi(function(e){t(e),g()},function(e){n(e),g()},{data:u&&"text"!==u&&"json"!==u?f.response:f.responseText,status:f.status,statusText:f.statusText,headers:i,config:e,request:f}),f=null}f.open(i.method.toUpperCase(),i.url,!0),f.timeout=i.timeout,"onloadend"in f?f.onloadend=m:f.onreadystatechange=function(){f&&4===f.readyState&&(0!==f.status||f.responseURL&&0===f.responseURL.indexOf("file:"))&&setTimeout(m)},f.onabort=function(){f&&(n(new Un("Request aborted",Un.ECONNABORTED,e,f)),f=null)},f.onerror=function(){n(new Un("Network Error",Un.ERR_NETWORK,e,f)),f=null},f.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||ti;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new Un(t,r.clarifyTimeoutError?Un.ETIMEDOUT:Un.ECONNABORTED,e,f)),f=null},void 0===r&&s.setContentType(null),"setRequestHeader"in f&&qn.forEach(s.toJSON(),function(e,t){f.setRequestHeader(t,e)}),qn.isUndefined(i.withCredentials)||(f.withCredentials=!!i.withCredentials),u&&"json"!==u&&(f.responseType=i.responseType),h&&([c,l]=Ii(h,!0),f.addEventListener("progress",c)),p&&f.upload&&([a,d]=Ii(p),f.upload.addEventListener("progress",a),f.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(o=t=>{f&&(n(!t||t.type?new wi(null,e,f):t),f.abort(),f=null)},i.cancelToken&&i.cancelToken.subscribe(o),i.signal&&(i.signal.aborted?o():i.signal.addEventListener("abort",o)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===ci.protocols.indexOf(y)?n(new Un("Unsupported protocol "+y+":",Un.ERR_BAD_REQUEST,e)):f.send(r||null)})},ki=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,o();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Un?t:new wi(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new Un(`timeout ${t} of ms exceeded`,Un.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:a}=i;return a.unsubscribe=()=>qn.asap(o),a}},Oi=function*(e,t){let n=e.byteLength;if(n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},$i=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()}},Pi=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of $i(e))yield*Oi(n,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return a(),void e.close();let s=i.byteLength;if(n){let e=o+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),r.return())},{highWaterMark:2})},Mi="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Fi=Mi&&"function"==typeof ReadableStream,Bi=Mi&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Di=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},Li=Fi&&Di(()=>{let e=!1;const t=new Request(ci.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),qi=Fi&&Di(()=>qn.isReadableStream(new Response("").body)),Ui={stream:qi&&(e=>e.body)};var ji;Mi&&(ji=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ui[e]&&(Ui[e]=qn.isFunction(ji[e])?t=>t[e]():(t,n)=>{throw new Un(`Response type '${e}' is not supported`,Un.ERR_NOT_SUPPORT,n)})}));const Ki=async(e,t)=>{const n=qn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(qn.isBlob(e))return e.size;if(qn.isSpecCompliantForm(e)){const t=new Request(ci.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return qn.isArrayBufferView(e)||qn.isArrayBuffer(e)?e.byteLength:(qn.isURLSearchParams(e)&&(e+=""),qn.isString(e)?(await Bi(e)).byteLength:void 0)})(t):n},Hi={http:null,xhr:Ni,fetch:Mi&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=xi(e);d=d?(d+"").toLowerCase():"text";let h,g=ki([r,s&&s.toAbortSignal()],o);const f=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let m;try{if(c&&Li&&"get"!==n&&"head"!==n&&0!==(m=await Ki(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(qn.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=Ti(m,Ii(Ai(c)));i=Pi(n.body,65536,e,t)}}qn.isString(u)||(u=u?"include":"omit");const r="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:n.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:r?u:void 0});let s=await fetch(h,p);const o=qi&&("stream"===d||"response"===d);if(qi&&(a||o&&f)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=qn.toFiniteNumber(s.headers.get("content-length")),[n,i]=a&&Ti(t,Ii(Ai(a),!0))||[];s=new Response(Pi(s.body,65536,n,()=>{i&&i(),f&&f()}),e)}d=d||"text";let y=await Ui[qn.findKey(Ui,d)||"text"](s,e);return!o&&f&&f(),await new Promise((t,n)=>{vi(t,n,{data:y,headers:mi.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(y){if(f&&f(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new Un("Network Error",Un.ERR_NETWORK,e,h),{cause:y.cause||y});throw Un.from(y,y&&y.code,e,h)}})};qn.forEach(Hi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Zi=e=>`- ${e}`,zi=e=>qn.isFunction(e)||null===e||!1===e,Gi=e=>{e=qn.isArray(e)?e:[e];const{length:t}=e;let n,i;const r={};for(let s=0;s<t;s++){let t;if(n=e[s],i=n,!zi(n)&&(i=Hi[(t=String(n)).toLowerCase()],void 0===i))throw new Un(`Unknown adapter '${t}'`);if(i)break;r[t||"#"+s]=i}if(!i){const e=Object.entries(r).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new Un("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Zi).join("\n"):" "+Zi(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Wi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new wi(null,e)}function Vi(e){Wi(e),e.headers=mi.from(e.headers),e.data=yi.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Gi(e.adapter||li.adapter)(e).then(function(t){return Wi(e),t.data=yi.call(e,e.transformResponse,t),t.headers=mi.from(t.headers),t},function(t){return bi(t)||(Wi(e),t&&t.response&&(t.response.data=yi.call(e,e.transformResponse,t.response),t.response.headers=mi.from(t.response.headers))),Promise.reject(t)})}const Ji="1.11.0",Qi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Qi[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Xi={};Qi.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Ji+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new Un(i(r," has been removed"+(t?" in "+t:"")),Un.ERR_DEPRECATED);return t&&!Xi[r]&&(Xi[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,s)}},Qi.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const Yi={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Un("options must be an object",Un.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],o=t[s];if(o){const t=e[s],n=void 0===t||o(t,s,e);if(!0!==n)throw new Un("option "+s+" must be "+n,Un.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Un("Unknown option "+s,Un.ERR_BAD_OPTION)}},validators:Qi},er=Yi.validators;let tr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ei,response:new ei}}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(i){}}throw n}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Si(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&Yi.assertOptions(n,{silentJSONParsing:er.transitional(er.boolean),forcedJSONParsing:er.transitional(er.boolean),clarifyTimeoutError:er.transitional(er.boolean)},!1),null!=i&&(qn.isFunction(i)?t.paramsSerializer={serialize:i}:Yi.assertOptions(i,{encode:er.function,serialize:er.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Yi.assertOptions(t,{baseUrl:er.spelling("baseURL"),withXsrfToken:er.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&qn.merge(r.common,r[t.method]);r&&qn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=mi.concat(s,r);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 l,u=0;if(!a){const e=[Vi.bind(this),void 0];for(e.unshift(...o),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{d=Vi.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return Yn(Ei((e=Si(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};qn.forEach(["delete","get","head","options"],function(e){tr.prototype[e]=function(t,n){return this.request(Si(n||{},{method:e,url:t,data:(n||{}).data}))}}),qn.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Si(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}tr.prototype[e]=t(),tr.prototype[e+"Form"]=t(!0)});const nr={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(nr).forEach(([e,t])=>{nr[t]=e});const ir=function e(t){const n=new tr(t),i=Qt(tr.prototype.request,n);return qn.extend(i,tr.prototype,n,{allOwnKeys:!0}),qn.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Si(t,n))},i}(li);ir.Axios=tr,ir.CanceledError=wi,ir.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 i=new Promise(e=>{n.subscribe(e),t=e}).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e(function(e,i,r){n.reason||(n.reason=new wi(e,i,r),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}}},ir.isCancel=bi,ir.VERSION=Ji,ir.toFormData=Wn,ir.AxiosError=Un,ir.Cancel=ir.CanceledError,ir.all=function(e){return Promise.all(e)},ir.spread=function(e){return function(t){return e.apply(null,t)}},ir.isAxiosError=function(e){return qn.isObject(e)&&!0===e.isAxiosError},ir.mergeConfig=Si,ir.AxiosHeaders=mi,ir.formToJSON=e=>di(qn.isHTMLForm(e)?new FormData(e):e),ir.getAdapter=Gi,ir.HttpStatusCode=nr,ir.default=ir;const{Axios:rr,AxiosError:sr,CanceledError:or,isCancel:ar,CancelToken:cr,VERSION:dr,all:lr,Cancel:ur,isAxiosError:pr,spread:hr,toFormData:gr,AxiosHeaders:fr,HttpStatusCode:mr,formToJSON:yr,getAdapter:br,mergeConfig:wr}=ir,vr="ConnectionsManager not initialized";class Ir extends n.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const r=this.hederaKit.client.network;this.network=r.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 i.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new i.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,i){try{const r=await this.standardClient.handleConnectionRequest(e,t,n,i);return r&&r.connectionTopicId&&"object"==typeof r.connectionTopicId&&"toString"in r.connectionTopicId&&(r.connectionTopicId=r.connectionTopicId.toString()),r}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}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 i=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:i.topicSequenceNumber?.toNumber(),receipt:i,transactionId:"transactionId"in i?i.transactionId?.toString():void 0}}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){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 ir.get(e,{responseType:"arraybuffer"}),i=t.Buffer.from(n.data),r=new URL(e).pathname;return{buffer:i,filename:s.basename(r)||"profile.png"}}{if(!r.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=r.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 ir.get(e.url,{responseType:"arraybuffer"}),i=t.Buffer.from(n.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!r.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=r.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 i.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[i.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(i.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(i.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 i.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:r}=this.getAccountAndSigner();if(!r)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${r}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==r&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,r,s)}const r=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:r.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...r,name:e.name,accountId:r?.metadata?.accountId||r.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 i;void 0!==e.memo?i=e.memo:(i=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${i}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const r=await this.submitConnectionRequest(n,i);this.executeResult={success:!0,transactionId:"transactionId"in r?r.transactionId?.toString():void 0,receipt:r,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...r}}}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 r=this.stateManager?.getConnectionsManager();if(!r)throw new Error(vr);await r.fetchConnectionData(n.accountId);const s=[...r.getPendingRequests(),...r.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 i.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 r=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,r)}const d=await this.getInboundTopicId(),l=await this.handleConnectionRequest(d,o,a,c);let u=l?.connectionTopicId;if(u&&"object"==typeof u&&"toString"in u&&(u=u?.toString()),!u||"string"!=typeof u)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(u)}`);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 i={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:u,status:"established",created:new Date};this.stateManager.addActiveConnection(i),r.markConnectionRequestProcessed(s.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId:u,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:l}}}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;const i=e.targetIdentifier;if(i.includes("@")){const e=i.split("@");if(2===e.length){const t=e[1];n=this.stateManager.getConnectionByIdentifier(t),n||this.addNote(`Could not find connection using request key '${i}', extracted account ID '${t}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(i)),!n&&!i.startsWith("0.0.")&&/^\d+$/.test(i)){const e=`0.0.${i}`;n=this.stateManager.getConnectionByIdentifier(e),n&&this.addNote(`Found connection using account ID with prefix: ${e}`)}if(!n&&/^[1-9]\d*$/.test(i)){const e=this.stateManager.listConnections(),t=parseInt(i)-1;t>=0&&t<e.length&&(n=e[t],n&&this.addNote(`Found connection by index ${i}: ${n.targetAccountId}`))}if(!n){const e=this.stateManager.listConnections().map((e,t)=>`${t+1}. ${e.targetAccountId} (Topic: ${e.connectionTopicId})`);let t=`Connection not found for identifier: "${i}"\n`;throw t+=`Available connections:\n${e.join("\n")||"No active connections"}`,t+="\n\nYou can use:\n",t+='- Connection number (e.g., "1", "2")\n',t+='- Account ID (e.g., "0.0.6412936")\n',t+="- Connection topic ID\n",t+="Use 'list_connections' to see all active connections.",new Error(t)}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 s=n.targetAgentName,o=`${t.inboundTopicId}@${t.accountId}`,a=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!a.sequenceNumber)throw new Error("Failed to send message");let c=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):c=await this.monitorResponses(r,o,a.sequenceNumber),this.executeResult={success:!0,transactionId:a.transactionId,receipt:a.receipt,scheduleId:void 0,rawResult:{targetAgentName:s,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:a.sequenceNumber,reply:c,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:a}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let i=0;for(;i<30;){try{const i=await this.getMessageStream(e);for(const e of i.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(r){this.logger.error(`Error monitoring responses: ${r}`)}await new Promise(e=>setTimeout(e,4e3)),i++}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:r=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(),l=Date.now()+1e3*r;let u=0,p=0;const h=new Set;for(;Date.now()<l;){try{const e=(await this.getMessages(d)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const r of e){const e=r.sequence_number;if(!e||h.has(e))continue;const l=r.operator_id?.split("@")[1];if(l)if(u++,n&&l!==n)this.logger.info(`Skipping request from ${l} (not target account)`);else if(t||n===l){let t;if(this.logger.info(`Accepting connection request from ${l}`),s.length>0||o.length>0){const e=new i.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,l,e,t),h.add(e),p++}}}catch(g){this.logger.error("Error during connection monitoring:",g)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:u,acceptedConnections:p,monitorDurationSeconds:r,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${p}.`),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(vr);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const i=t.getPendingRequests(),r=t.getConnectionsNeedingConfirmation(),s=[...i,...r];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 i=e.filter(e=>"established"===e.status),r=e.filter(e=>e.isPending),s=e.filter(e=>e.needsConfirmation);let o="";i.length>0&&(o+=`🟢 Active Connections (${i.length}):\n`,i.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&&r.length>0&&(o+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach((e,n)=>{o+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:o.trim(),activeCount:i.length,pendingCount:r.length,needsConfirmationCount:s.length}}}catch(i){this.logger.error("Failed to list connections:",i),this.executeResult={success:!1,error:`Failed to list connections: ${i instanceof Error?i.message:String(i)}`}}return this}formatConnection(e,t,n){const i=e;let r=`${t+1}. ${i.profileInfo?.display_name||i.targetAgentName||"Unknown Agent"} (${i.targetAccountId})\n`;r+=` Topic: ${i.isPending?"(Pending Request)":i.connectionTopicId}\n`;if(r+=` Status: ${i.status||"unknown"}\n`,n){if(i.profileInfo?.bio&&(r+=` Bio: ${i.profileInfo.bio.substring(0,100)}${i.profileInfo.bio.length>100?"...":""}\n`),i.created){r+=` ${i.isPending?"Request sent":"Connection established"}: ${i.created.toLocaleString()}\n`}i.lastActivity&&(r+=` Last activity: ${i.lastActivity.toLocaleString()}\n`)}return r}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(vr),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const i of n)this.stateManager.addActiveConnection(i);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 i=t.targetAgentName,r=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${i} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${r})`);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=r;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 ${r}`),o=t.filter(e=>1e6*e.timestamp>r),o.length>0&&(a=o.reduce((e,t)=>Math.max(e,1e6*t.timestamp),r));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 ${i} 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 ${i}:\n`:`New messages from ${i}:\n`;const l=[];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`,l.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>r&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:l,formattedOutput:d.trim(),targetAgentName:i,connectionTopicId:n}}}catch(s){this.logger.error(`Failed to check messages for topic ${n}: ${s}`),this.executeResult={success:!1,error:`Error checking messages for ${i}: ${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 i=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${i}`}}}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,i=t.topicInfo;let r=`Profile for ${e.accountId}:\n`;r+=`Name: ${n.name||"Unknown"}\n`,r+=`Bio: ${n.bio||"No bio provided"}\n`,r+=`Type: ${n.type||"Unknown"}\n`,r+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?r+=`Capabilities: ${n.capabilities.join(", ")}\n`:r+="Capabilities: None listed\n",i&&(r+=`Inbound Topic: ${i.inboundTopic||"Unknown"}\n`,r+=`Outbound Topic: ${i.outboundTopic||"Unknown"}\n`,r+=`Profile Topic: ${i.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(r+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(r+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:r,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 Tr 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}}class Ar extends n.BaseServiceBuilder{constructor(e){super(e)}async getHCS2Client(){if(!this.hcs2Client){const e=this.hederaKit.signer.getAccountId().toString(),t=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:t};this.hcs2Client=new i.HCS2Client(n)}return this.hcs2Client}async createRegistry(e={}){const t=await this.getHCS2Client();return await t.createRegistry(e)}async registerEntry(e,t){const n=await this.getHCS2Client();return await n.registerEntry(e,t)}async updateEntry(e,t){const n=await this.getHCS2Client();return await n.updateEntry(e,t)}async deleteEntry(e,t){const n=await this.getHCS2Client();return await n.deleteEntry(e,t)}async migrateRegistry(e,t){const n=await this.getHCS2Client();return await n.migrateRegistry(e,t)}async getRegistry(e,t={}){const n=await this.getHCS2Client();return await n.getRegistry(e,t)}async submitMessage(e,t){const n=await this.getHCS2Client();return await n.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS2Client();return await t.getTopicInfo(e)}async close(){this.hcs2Client&&(this.hcs2Client.close(),this.hcs2Client=void 0)}}class _r extends n.BaseServiceBuilder{constructor(e){super(e)}async getHCS6Client(){if(!this.hcs6Client){const e=this.hederaKit.signer.getAccountId().toString(),t=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:t};this.hcs6Client=new i.HCS6Client(n)}return this.hcs6Client}async createRegistry(e={}){const t=await this.getHCS6Client();return await t.createRegistry(e)}async registerEntry(e,t){const n=await this.getHCS6Client();return await n.registerEntry(e,t)}async getRegistry(e,t={}){const n=await this.getHCS6Client();return await n.getRegistry(e,t)}async createHashinal(e){const t=await this.getHCS6Client();return await t.createHashinal(e)}async register(e){const t=await this.getHCS6Client();return await t.register(e)}async submitMessage(e,t){const n=await this.getHCS6Client();return await n.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS6Client();return await t.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}class Cr extends n.BaseServiceBuilder{constructor(e){super(e)}async getInscriptionSDK(e){return null}async inscribe(e,t){const n={accountId:this.hederaKit.signer.getAccountId().toString(),privateKey:this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};return await i.inscribe(e,n,t)}async inscribeWithSigner(e,t,n){return await i.inscribeWithSigner(e,t,n)}async retrieveInscription(e,t){const n=this.hederaKit.signer.getAccountId().toString(),r=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";return await i.retrieveInscription(e,{...t,accountId:n,privateKey:r})}async close(){this.inscriptionSDK=void 0}}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=At,e.BaseHCS10QueryTool=g,e.BaseHCS10TransactionTool=h,e.BaseHCS2QueryTool=xt,e.BaseHCS2TransactionTool=St,e.BaseHCS6QueryTool=Bt,e.BaseHCS6TransactionTool=Ft,e.BaseInscriberQueryTool=Kt,e.BaseInscriberTransactionTool=jt,e.CheckMessagesTool=ft,e.ConnectionMonitorTool=wt,e.CreateDynamicRegistryTool=class extends Ft{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content",this.schema=Dt}async _call(e){try{const t=await this.hcs6Builder.createRegistry({ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to create dynamic registry");return{status:"success",data:{topicId:t.topicId,transactionId:t.transactionId,ttl:e.ttl,memo:`hcs-6:1:${e.ttl}`}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.CreateRegistryTool=class extends xt{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create a new HCS-2 registry topic for storing decentralized data"}get specificInputSchema(){return Nt}async executeQuery(e,t){try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to create registry");return`Successfully created HCS-2 registry!\n\nTopic ID: ${t.topicId}\nRegistry Type: ${1===e.registryType?"Non-Indexed":"Indexed"}\nTTL: ${e.ttl||86400} seconds\n\nYou can now register entries to this registry using the topic ID.`}catch(n){const e=n instanceof Error?n.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},e.DeleteEntryTool=class extends xt{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return $t}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to delete entry");return`Successfully deleted entry from HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been removed from the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to delete entry";throw new Error(`Entry deletion failed: ${e}`)}}},e.FindRegistrationsTool=yt,e.HCS10Builder=Ir,e.HCS10Client=class{constructor(e,t,n,r){this.standardClient=new i.HCS10Client({network:n,operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:r?.registryUrl,logLevel:r?.logLevel}),this.guardedRegistryBaseUrl=r?.registryUrl||"",this.useEncryption=r?.useEncryption||!1;const s="true"===c.env.DISABLE_LOGGING;this.logger=new i.Logger({level:r?.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,i){try{return await this.standardClient.handleConnectionRequest(e,t,n,i)}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,i=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,i)}async createAndRegisterAgent(e){const t=(new i.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[i.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(i.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(i.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),i=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return i?.metadata?.inboundTopicId&&i?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:i.metadata.inboundTopicId,outboundTopicId:i.metadata.outboundTopicId}),i}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,i){this.useEncryption;try{const r=await this.standardClient.sendMessage(e,t,n,i);return r.topicSequenceNumber?.toNumber()}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){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 i.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.HCS2Builder=Ar,e.HCS6Builder=_r,e.HbarPricePlugin=Tr,e.InitiateConnectionTool=ut,e.InscribeFromBufferTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description="Use this for ANY web page, article, or content you retrieve. If user asks to inscribe a web page or article, FIRST retrieve it, THEN use this tool. This is the CORRECT tool for: web pages, news articles, blog posts, social media content, API responses, or any text content. Steps: 1) Retrieve content, 2) Convert to base64, 3) Use this tool. DO NOT use inscribeFromUrl for web content."}get specificInputSchema(){return zt}async executeQuery(e,n){if(console.log("[DEBUG] InscribeFromBufferTool.executeQuery called"),console.log(`[DEBUG] Buffer tool received base64Data length: ${e.base64Data?.length||0}`),console.log(`[DEBUG] Buffer tool fileName: ${e.fileName}`),console.log(`[DEBUG] Buffer tool mimeType: ${e.mimeType}`),!e.base64Data||""===e.base64Data.trim())throw console.log("[InscribeFromBufferTool] ERROR: No data provided"),new Error("No data provided. Cannot inscribe empty content. Please provide valid base64 encoded data.");if(!e.fileName||""===e.fileName.trim())throw console.log("[InscribeFromBufferTool] ERROR: No fileName provided"),new Error("No fileName provided. A valid fileName is required for inscription.");let i;try{i=t.Buffer.from(e.base64Data,"base64")}catch(s){throw console.log("[InscribeFromBufferTool] ERROR: Invalid base64 data"),new Error("Invalid base64 data provided. Please ensure the data is properly base64 encoded.")}if(console.log(`[InscribeFromBufferTool] Buffer length after conversion: ${i.length}`),0===i.length)throw console.log("[InscribeFromBufferTool] ERROR: Buffer is empty after conversion"),new Error("Buffer is empty after base64 conversion. The provided data appears to be invalid or empty.");if(i.length<10)throw console.log(`[InscribeFromBufferTool] WARNING: Buffer is very small (${i.length} bytes)`),console.log(`[InscribeFromBufferTool] Buffer content preview: ${i.toString("utf8",0,Math.min(i.length,50))}`),new Error(`Buffer content is too small (${i.length} bytes). This may indicate empty or invalid content. Please verify the source data contains actual content.`);if(!/^[A-Za-z0-9+/]*={0,2}$/.test(e.base64Data))throw console.log("[InscribeFromBufferTool] ERROR: Invalid base64 format"),new Error("Invalid base64 format. The data does not appear to be properly base64 encoded.");if(""===i.toString("utf8",0,Math.min(i.length,100)).trim())throw console.log("[InscribeFromBufferTool] ERROR: Buffer contains only whitespace or empty content"),new Error("Buffer contains only whitespace or empty content. Cannot inscribe meaningless data.");const r={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{let t;if(e.timeoutMs){const n=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:e.fileName,mimeType:e.mimeType},r),n])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:e.fileName,mimeType:e.mimeType},r);if(t.confirmed){const e=t.inscription?.topic_id||t.result.topicId,n=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${r.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(s){const e=s instanceof Error?s.message:"Failed to inscribe from buffer";throw new Error(`Inscription failed: ${e}`)}}},e.InscribeFromFileTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromFile",this.description="Inscribe content from a local file to the Hedera network using a file path. IMPORTANT: Only use this tool when you have a valid file path to actual content. The file must exist and contain meaningful data (minimum 10 bytes). For files accessed through MCP filesystem tools, consider reading the file content first and using inscribeFromBuffer instead."}get specificInputSchema(){return Zt}async executeQuery(e,n){let i;console.log(`[DEBUG] InscribeFromFileTool.executeQuery called with: ${e.filePath}`);try{console.log(`[DEBUG] Checking file: ${e.filePath}`),console.log(`[DEBUG] Current working directory: ${c.cwd()}`);const t=await p.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(console.log(`[DEBUG] File size: ${t.size} bytes`),0===t.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(t.size<10)throw new Error(`File "${e.filePath}" is too small (${t.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(t.size>104857600&&console.log(`[InscribeFromFileTool] WARNING: Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await p.readFile(e.filePath),this.logger?.info(`Read ${i.length} bytes from file`),!i||0===i.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(i.length<10)throw new Error(`File "${e.filePath}" content is too small (${i.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const n=u.basename(e.filePath),r=this.getMimeType(n);if(r.startsWith("text/")||"application/json"===r){if(""===i.toString("utf8",0,Math.min(i.length,1e3)).trim())throw new Error(`File "${e.filePath}" contains only whitespace or empty content. Cannot inscribe meaningless data.`)}}catch(d){if(d instanceof Error){if(d.message.includes("ENOENT"))throw new Error(`File not found: "${e.filePath}"`);throw d}throw new Error(`Failed to read file: ${d}`)}const r=i.toString("base64");this.logger?.info(`Converted to base64: ${r.length} characters`);const s=u.basename(e.filePath),o=this.getMimeType(s);this.logger?.info(`File: ${s}, MIME type: ${o}`);const a={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{let n;if(e.timeoutMs){const i=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});n=await Promise.race([this.inscriberBuilder.inscribe({type:"buffer",buffer:t.Buffer.from(r,"base64"),fileName:s,mimeType:o},a),i])}else n=await this.inscriberBuilder.inscribe({type:"buffer",buffer:t.Buffer.from(r,"base64"),fileName:s,mimeType:o},a);if(n.confirmed){const e=n.inscription?.topic_id||n.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${a.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${n.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${n.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(d){const e=d instanceof Error?d.message:"Failed to inscribe from file";throw new Error(`Inscription failed: ${e}`)}}getMimeType(e){return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".pdf":"application/pdf",".json":"application/json",".txt":"text/plain",".html":"text/html",".css":"text/css",".js":"application/javascript",".ts":"application/typescript",".mp4":"video/mp4",".mp3":"audio/mpeg",".wav":"audio/wav",".zip":"application/zip"}[u.extname(e).toLowerCase()]||"application/octet-stream"}},e.InscribeFromUrlTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromUrl",this.description="DO NOT use this for web pages, articles, or HTML content - it will FAIL. ONLY use for direct file downloads like PDFs, images, JSON, ZIP files. If user asks to inscribe a web page article, DO NOT use this tool. Valid examples: .pdf, .jpg, .png, .json, .zip files. Invalid examples: any web page, news article, blog post, social media content. For those, retrieve the content first then use inscribeFromBuffer."}get specificInputSchema(){return Ht}async executeQuery(e,t){if(console.log(`[DEBUG] InscribeFromUrlTool.executeQuery called with URL: ${e.url}`),!e.url||""===e.url.trim())throw new Error("URL cannot be empty. Please provide a valid URL.");try{const t=new URL(e.url);if(!t.protocol||!t.host)throw new Error("Invalid URL format. Please provide a complete URL with protocol (http/https).");if(!["http:","https:"].includes(t.protocol))throw new Error("Only HTTP and HTTPS URLs are supported for inscription.")}catch(i){throw new Error(`Invalid URL: ${e.url}. Please provide a valid URL.`)}console.log("[InscribeFromUrlTool] Validating URL content before inscription...");try{const t=new AbortController,n=setTimeout(()=>t.abort(),1e4);try{const i=await fetch(e.url,{method:"HEAD",signal:t.signal});if(clearTimeout(n),!i.ok)throw new Error(`URL returned error status ${i.status}: ${i.statusText}. Cannot inscribe content from inaccessible URLs.`);const s=i.headers.get("content-type")||"",o=i.headers.get("content-length");if(["text/html","application/xhtml+xml","text/xml"].some(e=>s.toLowerCase().includes(e)))throw new Error(`URL returns HTML/web page content (Content-Type: ${s}). This tool only works with direct file URLs (PDFs, images, JSON, etc.). For web page content, first retrieve the content using the appropriate MCP tool or web scraper, then use inscribeFromBuffer to inscribe it.`);if(o&&0===parseInt(o))throw new Error("URL returns empty content (Content-Length: 0). Cannot inscribe empty content.");if(o&&parseInt(o)<10)throw new Error(`URL content is too small (${o} bytes). Content must be at least 10 bytes.`);if(!s||"application/octet-stream"===s){console.log("[InscribeFromUrlTool] Content-Type unclear, fetching first 1KB to verify...");const t=new AbortController,n=setTimeout(()=>t.abort(),5e3);try{const i=await fetch(e.url,{signal:t.signal,headers:{Range:"bytes=0-1023"}});if(clearTimeout(n),i.ok||206===i.status){const e=await i.arrayBuffer(),t=new Uint8Array(e),n=new TextDecoder("utf-8",{fatal:!1}).decode(t.slice(0,512));if(n.toLowerCase().includes("<!doctype html")||n.toLowerCase().includes("<html")||n.match(/<meta\s+[^>]*>/i)||n.match(/<title>/i))throw new Error("URL returns HTML content. This tool only works with direct file URLs. For web page content, first retrieve it using the appropriate tool, then use inscribeFromBuffer.")}}catch(r){if(clearTimeout(n),r instanceof Error&&r.message.includes("HTML content"))throw r;console.log(`[InscribeFromUrlTool] Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}console.log(`[InscribeFromUrlTool] URL validation passed. Content-Type: ${s}, Content-Length: ${o||"unknown"}`)}catch(s){throw clearTimeout(n),s}}catch(i){if(i instanceof Error)if("AbortError"===i.name)console.log("[InscribeFromUrlTool] Warning: URL validation timed out after 10 seconds. Proceeding with inscription attempt.");else{if(i.message.includes("URL returned error")||i.message.includes("empty content")||i.message.includes("too small")||i.message.includes("HTML"))throw i;console.log(`[InscribeFromUrlTool] Warning: Could not validate URL with HEAD request: ${i.message}. Proceeding with inscription attempt.`)}}const n={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{let t;if(e.timeoutMs){const i=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},n),i])}else t=await this.inscriberBuilder.inscribe({type:"url",url:e.url},n);if(t.confirmed){const e=t.inscription?.topic_id||t.result.topicId,i=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${n.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${i?`\nView inscription: ${i}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(i){const e=i instanceof Error?i.message:"Failed to inscribe from URL";throw new Error(`Inscription failed: ${e}`)}}},e.InscribeHashinalTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeHashinal",this.description="Inscribe content as a Hashinal NFT on the Hedera network"}get specificInputSchema(){return Gt}async executeQuery(e,t){const n={mode:"hashinal",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes,properties:e.properties},jsonFileURL:e.jsonFileURL,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{let t;if(e.timeoutMs){const i=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},n),i])}else t=await this.inscriberBuilder.inscribe({type:"url",url:e.url},n);if(t.confirmed){const e=t.inscription?.topic_id||t.result.topicId,i=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${n.network||"testnet"}`:null;return`Successfully inscribed and confirmed Hashinal NFT on the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\nTopic ID: ${e||"N/A"}${i?`\nView inscription: ${i}`:""}\n\nThe Hashinal NFT is now available.`}return`Successfully submitted Hashinal NFT inscription to the Hedera network!\n\nTransaction ID: ${t.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(i){const e=i instanceof Error?i.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}},e.InscriberBuilder=Cr,e.ListConnectionsTool=ht,e.ListUnapprovedConnectionRequestsTool=Rt,e.ManageConnectionRequestsTool=It,e.MigrateRegistryTool=class extends xt{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return Pt}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to migrate registry");return`Successfully migrated HCS-2 registry!\n\nFrom Registry Topic: ${e.registryTopicId}\nTo Target Topic: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe registry has been migrated to the new topic.`}catch(n){const e=n instanceof Error?n.message:"Failed to migrate registry";throw new Error(`Registry migration failed: ${e}`)}}},e.NaturalLanguageMapper=st,e.OpenConvaiState=Jt,e.QueryDynamicRegistryTool=class extends Bt{constructor(e){super(e),this.name="queryDynamicRegistry",this.description="Query a dynamic registry to get the current state of a dynamic hashinal",this.schema=Ut}async _call(e){try{const t=await this.hcs6Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip});return{status:"success",data:{topicId:t.topicId,registryType:"NON_INDEXED",ttl:t.ttl,latestEntry:t.latestEntry?{topicId:t.latestEntry.message.t_id,timestamp:t.latestEntry.timestamp,memo:t.latestEntry.message.m,sequence:t.latestEntry.sequence,payer:t.latestEntry.payer}:null,totalEntries:t.entries.length}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.QueryRegistryTool=class extends xt{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry"}get specificInputSchema(){return Mt}async executeQuery(e,t){const n=await this.hcs2Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip});return{topicId:n.topicId,registryType:0===n.registryType?"indexed":"non-indexed",ttl:n.ttl,totalEntries:n.entries.length,entries:n.entries.map(e=>({sequence:e.sequence,timestamp:e.timestamp,payer:e.payer,operation:e.message.op,targetTopicId:e.message.t_id,uid:e.message.uid,metadata:e.message.metadata,memo:e.message.m}))}}},e.RegisterAgentTool=at,e.RegisterDynamicHashinalTool=class extends Ft{constructor(e){super(e),this.name="registerDynamicHashinal",this.description="Create and register a new dynamic hashinal that can be updated over time",this.schema=Lt}async _call(e){try{const t=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,ttl:e.ttl,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!t.success||!t.registryTopicId||!t.inscriptionTopicId)throw new Error(t.error||"Failed to register dynamic hashinal");return{status:"success",data:{registryTopicId:t.registryTopicId,inscriptionTopicId:t.inscriptionTopicId,transactionId:t.transactionId}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.RegisterEntryTool=class extends xt{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register a new entry in an HCS-2 registry"}get specificInputSchema(){return kt}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to register entry");return`Successfully registered entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nTarget Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been added to the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to register entry";throw new Error(`Entry registration failed: ${e}`)}}},e.RetrieveInscriptionTool=class extends Kt{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return Wt}async executeQuery(e,t){const n=await this.inscriberBuilder.retrieveInscription(e.transactionId,{apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"});return{inscriptionId:n.inscriptionId,transactionId:n.transactionId,topicId:n.topic_id,status:n.status,holderId:n.holderId,metadata:n.metadata,tags:n.tags,mode:n.mode,chunks:n.chunks,createdAt:n.createdAt,completedAt:n.completed||n.completedAt,fileUrl:n.fileUrl,mimeType:n.mimeType,fileSize:n.fileSize}}},e.RetrieveProfileTool=Ct,e.SendMessageToConnectionTool=dt,e.UpdateDynamicHashinalTool=class extends Ft{constructor(e){super(e),this.name="updateDynamicHashinal",this.description="Update an existing dynamic hashinal with new content while maintaining the same registry",this.schema=qt}async _call(e){try{const t=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to update dynamic hashinal");return{status:"success",data:{registryTopicId:t.registryTopicId,newInscriptionTopicId:t.inscriptionTopicId,transactionId:t.transactionId,updateMemo:e.memo}}}catch(t){return{status:"error",message:t instanceof Error?t.message:"Unknown error"}}}},e.UpdateEntryTool=class extends xt{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return Ot}async executeQuery(e,t){try{const t=await this.hcs2Builder.updateEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,uid:e.uid,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to update entry");return`Successfully updated entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}\nNew Target Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been updated in the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to update entry";throw new Error(`Entry update failed: ${e}`)}}},e.initializeStandardsAgentKit=async e=>{const t=e?.clientConfig||{},r=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"),!r||!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,l=i.Logger.getInstance({level:t.logLevel||"info",silent:d}),u=e?.stateManager||new Jt({defaultEnvFilePath:Vt,defaultPrefix:"TODD"});l.info("State manager initialized");const p=new n.ServerSigner(r,s,a),h=new n.HederaAgentKit(p);await h.initialize(),l.info(`HederaAgentKit initialized for ${r} on ${a}`);const g=new Ir(h,u,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:t.logLevel});let f,m;if(e?.monitoringClient){const e=new n.ServerSigner(r,s,a);f=new n.HederaAgentKit(e),await f.initialize(),m=new Ir(f,u,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),l.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new at({hederaKit:h,hcs10Builder:g,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new yt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.retrieveProfileTool=new Ct({hederaKit:h,hcs10Builder:g,logger:void 0}),y.initiateConnectionTool=new ut({hederaKit:h,hcs10Builder:g,logger:void 0}),y.listConnectionsTool=new ht({hederaKit:h,hcs10Builder:g,logger:void 0}),y.sendMessageToConnectionTool=new dt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.checkMessagesTool=new ft({hederaKit:h,hcs10Builder:g,logger:void 0}),y.connectionMonitorTool=new wt({hederaKit:f||h,hcs10Builder:m||g,logger:void 0}),y.manageConnectionRequestsTool=new It({hederaKit:h,hcs10Builder:g,logger:void 0}),y.acceptConnectionRequestTool=new At({hederaKit:h,hcs10Builder:g,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new Rt({hederaKit:h,hcs10Builder:g,logger:void 0}),l.info("All tools initialized")),{hederaKit:h,hcs10Builder:g,monitoringHederaKit:f,monitoringHcs10Builder:m,tools:y,stateManager:u}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=standards-agent-kit.umd.js.map