@hashgraphonline/standards-agent-kit 0.2.122 → 0.2.124

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 (35) 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 +6 -0
  4. package/dist/cjs/tools/inscriber/InscribeFromFileTool.d.ts +3 -0
  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/cjs/tools/inscriber/base-inscriber-tools.d.ts +15 -0
  8. package/dist/es/standards-agent-kit.es33.js +44 -0
  9. package/dist/es/standards-agent-kit.es33.js.map +1 -1
  10. package/dist/es/standards-agent-kit.es34.js +34 -6
  11. package/dist/es/standards-agent-kit.es34.js.map +1 -1
  12. package/dist/es/standards-agent-kit.es35.js +65 -14
  13. package/dist/es/standards-agent-kit.es35.js.map +1 -1
  14. package/dist/es/standards-agent-kit.es36.js +42 -6
  15. package/dist/es/standards-agent-kit.es36.js.map +1 -1
  16. package/dist/es/standards-agent-kit.es37.js +38 -6
  17. package/dist/es/standards-agent-kit.es37.js.map +1 -1
  18. package/dist/es/tools/inscriber/InscribeFromBufferTool.d.ts +6 -0
  19. package/dist/es/tools/inscriber/InscribeFromFileTool.d.ts +3 -0
  20. package/dist/es/tools/inscriber/InscribeFromUrlTool.d.ts +6 -0
  21. package/dist/es/tools/inscriber/InscribeHashinalTool.d.ts +6 -0
  22. package/dist/es/tools/inscriber/base-inscriber-tools.d.ts +15 -0
  23. package/dist/umd/standards-agent-kit.umd.js +1 -1
  24. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  25. package/dist/umd/tools/inscriber/InscribeFromBufferTool.d.ts +6 -0
  26. package/dist/umd/tools/inscriber/InscribeFromFileTool.d.ts +3 -0
  27. package/dist/umd/tools/inscriber/InscribeFromUrlTool.d.ts +6 -0
  28. package/dist/umd/tools/inscriber/InscribeHashinalTool.d.ts +6 -0
  29. package/dist/umd/tools/inscriber/base-inscriber-tools.d.ts +15 -0
  30. package/package.json +3 -2
  31. package/src/tools/inscriber/InscribeFromBufferTool.ts +49 -9
  32. package/src/tools/inscriber/InscribeFromFileTool.ts +88 -15
  33. package/src/tools/inscriber/InscribeFromUrlTool.ts +40 -11
  34. package/src/tools/inscriber/InscribeHashinalTool.ts +43 -6
  35. package/src/tools/inscriber/base-inscriber-tools.ts +87 -0
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("unenv/node/process"),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/fs/promises")):"function"==typeof define&&define.amd?define(["exports","unenv/node/process","unenv/node/buffer","hedera-agent-kit","@hashgraphonline/standards-sdk","unenv/node/fs","unenv/node/path","unenv/polyfill/globalthis","unenv/node/timers","unenv/node/fs/promises"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsAgentKit={},e.process,e["unenv/node/buffer"],e.HederaAgentKit,e.StandardsSDK,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],e["unenv/node/fs/promises"])}(this,function(e,t,n,i,r,s,a,o,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(a),h=l(d);class p extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class g extends i.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||[]],a={...r,path:s};if(void 0!==r.message)return{...r,path:s,message:r.message};let o="";const c=i.filter(e=>!!e).slice().reverse();for(const d of c)o=d(a,{data:t,defaultError:o}).message;return{...r,path:s,message:o}})({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 $,M;(M=$||($={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},M.toString=e=>"string"==typeof e?e:e?.message;class P{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 D(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 L{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 De({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 Le.create(this,this._def)}nullable(){return Be.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 De({...D(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new qe({...D(this._def),innerType:this,defaultValue:t,typeName:ze.ZodDefault})}brand(){return new Ke({typeName:ze.ZodBranded,type:this,...D(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...D(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 B=/^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])$/,X=/^(([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]))$/,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]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Q=/^([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||!X.test(e))}function ae(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 oe(e,t){return!("v4"!==t&&t||!V.test(e))||!("v6"!==t&&t||!J.test(e))}class ce extends L{_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)B.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?ae(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"jwt",code:v.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?oe(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cidr",code:v.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Q.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,...D(e)});class le extends L{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,...D(e)});class ue extends L{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,...D(e)});class he extends L{_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)}}he.create=e=>new he({typeName:ze.ZodBoolean,coerce:e?.coerce||!1,...D(e)});class pe extends L{_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 pe({...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}}pe.create=e=>new pe({checks:[],coerce:e?.coerce||!1,typeName:ze.ZodDate,...D(e)});class ge extends L{_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,...D(e)});class fe extends L{_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,...D(e)});class me extends L{_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,...D(e)});class ye extends L{constructor(){super(...arguments),this._any=!0}_parse(e){return S(e.data)}}ye.create=e=>new ye({typeName:ze.ZodAny,...D(e)});class be extends L{constructor(){super(...arguments),this._unknown=!0}_parse(e){return S(e.data)}}be.create=e=>new be({typeName:ze.ZodUnknown,...D(e)});class we extends L{_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,...D(e)});class ve extends L{_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,...D(e)});class Ie extends L{_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 P(t,e,t.path,n)))).then(e=>C.mergeArray(n,e));const r=[...t.data].map((e,n)=>i.type._parseSync(new P(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]=Le.create(Te(i))}return new Ae({...e._def,shape:()=>t})}return e instanceof Ie?new Ie({...e._def,type:Te(e.element)}):e instanceof Le?Le.create(Te(e.unwrap())):e instanceof Be?Be.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,...D(t)});class Ae extends L{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 o in n.data)r.includes(o)||s.push(o);const a=[];for(const o of r){const e=i[o],t=n.data[o];a.push({key:{status:"valid",value:o},value:e._parse(new P(n,t,n.path,o)),alwaysSet:o in n.data})}if(this._def.catchall instanceof we){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of s)a.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];a.push({key:{status:"valid",value:t},value:e._parse(new P(n,i,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of a){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,a)}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 Le;)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,...D(t)}),Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:we.create(),typeName:ze.ZodObject,...D(t)}),Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:we.create(),typeName:ze.ZodObject,...D(t)});class _e extends L{_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,...D(t)});class Ee extends L{_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,...D(n)});class Re extends L{_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 P(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,...D(t)})};class Se extends L{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 a in n.data)i.push({key:r._parse(new P(n,a,n.path,a)),value:s._parse(new P(n,n.data[a],n.path,a)),alwaysSet:a 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 L?{keyType:e,valueType:t,typeName:ze.ZodRecord,...D(n)}:{keyType:ce.create(),valueType:e,typeName:ze.ZodRecord,...D(t)})}}class xe extends L{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 P(n,e,n.path,[s,"key"])),value:r._parse(new P(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,...D(n)});class Ne extends L{_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 a=[...n.data.values()].map((e,t)=>r._parse(new P(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>s(e)):s(a)}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,...D(t)});class ke extends L{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,...D(t)});class Oe extends L{_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 Me({values:e,typeName:ze.ZodEnum,...D(t)})}Oe.create=(e,t)=>new Oe({value:e,typeName:ze.ZodLiteral,...D(t)});class Me extends L{_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 Me.create(e,{...this._def,...t})}exclude(e,t=this._def){return Me.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Me.create=$e;class Pe extends L{_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}}Pe.create=(e,t)=>new Pe({values:e,typeName:ze.ZodNativeEnum,...D(t)});class Fe extends L{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,...D(t)});class De extends L{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)}}De.create=(e,t,n)=>new De({schema:e,typeName:ze.ZodEffects,effect:t,...D(n)}),De.createWithPreprocess=(e,t,n)=>new De({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...D(n)});class Le extends L{_parse(e){return this._getType(e)===b.undefined?S(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(e,t)=>new Le({innerType:e,typeName:ze.ZodOptional,...D(t)});class Be extends L{_parse(e){return this._getType(e)===b.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Be.create=(e,t)=>new Be({innerType:e,typeName:ze.ZodNullable,...D(t)});class qe extends L{_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,...D(t)});class Ue extends L{_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,...D(t)});class je extends L{_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,...D(e)});class Ke extends L{_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 L{_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 L{_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,...D(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,Xe=he.create,Je=be.create;we.create;const Qe=Ie.create,Ye=Ae.create,et=_e.create;Ee.create,Re.create;const tt=Se.create,nt=Me.create,it=Pe.create;Fe.create,Le.create,Be.create;const rt=class{static parseCapabilities(e){if(!e)return[r.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(r.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):[r.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[r.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[r.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[r.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[r.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[r.AIAgentCapability.CODE_GENERATION]:"Code Generation",[r.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[r.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[r.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[r.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[r.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[r.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[r.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[r.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[r.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[r.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[r.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[r.AIAgentCapability.API_INTEGRATION]:"API Integration",[r.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};rt.CAPABILITY_MAPPINGS={ai:[r.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[r.AIAgentCapability.TEXT_GENERATION],chat:[r.AIAgentCapability.TEXT_GENERATION],conversation:[r.AIAgentCapability.TEXT_GENERATION],text:[r.AIAgentCapability.TEXT_GENERATION],"text generation":[r.AIAgentCapability.TEXT_GENERATION],image:[r.AIAgentCapability.IMAGE_GENERATION],picture:[r.AIAgentCapability.IMAGE_GENERATION],visual:[r.AIAgentCapability.IMAGE_GENERATION],photo:[r.AIAgentCapability.IMAGE_GENERATION],audio:[r.AIAgentCapability.AUDIO_GENERATION],sound:[r.AIAgentCapability.AUDIO_GENERATION],voice:[r.AIAgentCapability.AUDIO_GENERATION],speech:[r.AIAgentCapability.AUDIO_GENERATION],video:[r.AIAgentCapability.VIDEO_GENERATION],movie:[r.AIAgentCapability.VIDEO_GENERATION],animation:[r.AIAgentCapability.VIDEO_GENERATION],code:[r.AIAgentCapability.CODE_GENERATION],programming:[r.AIAgentCapability.CODE_GENERATION],development:[r.AIAgentCapability.CODE_GENERATION],coding:[r.AIAgentCapability.CODE_GENERATION],translate:[r.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[r.AIAgentCapability.LANGUAGE_TRANSLATION],language:[r.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[r.AIAgentCapability.DATA_INTEGRATION],"data processing":[r.AIAgentCapability.DATA_INTEGRATION],"data integration":[r.AIAgentCapability.DATA_INTEGRATION],etl:[r.AIAgentCapability.DATA_INTEGRATION],market:[r.AIAgentCapability.MARKET_INTELLIGENCE],trading:[r.AIAgentCapability.MARKET_INTELLIGENCE],finance:[r.AIAgentCapability.MARKET_INTELLIGENCE],financial:[r.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[r.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[r.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[r.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[r.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[r.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[r.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[r.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[r.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[r.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[r.AIAgentCapability.GOVERNANCE_FACILITATION],security:[r.AIAgentCapability.SECURITY_MONITORING],monitoring:[r.AIAgentCapability.SECURITY_MONITORING],threat:[r.AIAgentCapability.SECURITY_MONITORING],compliance:[r.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[r.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[r.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[r.AIAgentCapability.FRAUD_DETECTION],detection:[r.AIAgentCapability.FRAUD_DETECTION],anomaly:[r.AIAgentCapability.FRAUD_DETECTION],coordination:[r.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[r.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[r.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[r.AIAgentCapability.API_INTEGRATION],integration:[r.AIAgentCapability.API_INTEGRATION],webhook:[r.AIAgentCapability.API_INTEGRATION],workflow:[r.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[r.AIAgentCapability.WORKFLOW_AUTOMATION],process:[r.AIAgentCapability.WORKFLOW_AUTOMATION]};let st=rt;const at=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([Qe(it(r.AIAgentCapability)),Qe(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([Qe(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(Je()).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:Qe(Ye({amount:Ve().positive(),tokenId:We()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Qe(We()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Xe().optional().describe("Whether to set as current agent (default: true)"),persistence:Ye({prefix:We().optional()}).optional().describe("Optional persistence configuration")});class ot extends p{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=at,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},a=this.getServiceBuilder().getStateManager();if(a&&(a.setCurrentAgent(e),a.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");a.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:Xe().optional().default(!1)});class dt extends p{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,a=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(s>=0&&s<a.length){const e=a[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:Xe().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 p{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 ht=Ye({includeDetails:Xe().optional().describe("Whether to include detailed information about each connection"),showPending:Xe().optional().describe("Whether to include pending connection requests")});class pt 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=ht}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:Xe().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([Qe(it(r.AIAgentCapability)),Qe(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:Xe().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:Qe(Ye({amount:Ve(),collectorAccount:We().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Qe(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:Qe(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 p{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:Qe(We()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class At extends p{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:Xe().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 i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class xt extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const Nt=Ye({registryType:it(r.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(),Xe()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:et([We(),Xe()]).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 Mt=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 Pt=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 i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Dt extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const Lt=Ye({ttl:Ve().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),submitKey:et([Xe(),We()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Bt=Ye({metadata:tt(Je()).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(Je()).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 i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}}class Kt extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}}const Ht=Ye({url:We().url().describe("ONLY direct file download URLs with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or when you already have content to inscribe."),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Je()).optional().describe("Metadata to attach to the inscription"),tags:Qe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Xe().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(Je()).optional().describe("Metadata to attach to the inscription"),tags:Qe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Xe().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={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function Gt(){return{maxInscriptionSize:parseInt(t.env.REF_MAX_SIZE||zt.maxInscriptionSize.toString(),10),minContentSize:parseInt(t.env.REF_MIN_SIZE||zt.minContentSize.toString(),10),logLevel:t.env.REF_LOG_LEVEL||zt.logLevel,enableContentValidation:"false"!==t.env.REF_ENABLE_VALIDATION}}const Wt=Ye({base64Data:We().min(1,"Data cannot be empty").describe('The content to inscribe. Accept BOTH plain text AND base64. Also accepts content reference IDs in format "content-ref:[id]". When user says "inscribe it" or "inscribe the content", use the EXACT content from your previous message or from MCP tool results. DO NOT generate new content. DO NOT create repetitive text. Pass the actual search results or other retrieved content EXACTLY as you received it.'),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(Je()).optional().describe("Metadata to attach to the inscription"),tags:Qe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Xe().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 Vt=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:Qe(Ye({trait_type:We(),value:et([We(),Ve()])})).optional().describe("NFT attributes"),properties:tt(Je()).optional().describe("Additional properties"),jsonFileURL:We().url().optional().describe("URL to JSON metadata file"),tags:Qe(We()).optional().describe("Tags to categorize the NFT"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Xe().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 Xt=Ye({transactionId:We().describe("The transaction ID of the inscription to retrieve"),apiKey:We().optional().describe("API key for inscription service")});const Jt=a.join(t.cwd(),".env");class Qt{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const n=e?.disableLogging||"true"===t.env.DISABLE_LOGGING;this.logger=new r.Logger({module:"OpenConvaiState",silent:n}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new r.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const 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,n){if(n?.type&&"env-file"!==n.type)throw new Error(`Unsupported persistence type: ${n.type}. Only 'env-file' is supported.`);const i=n?.envFilePath||this.defaultEnvFilePath||t.env.ENV_FILE_PATH||".env",r=n?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const a={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(a[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(a[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";s.existsSync(e)&&(n=s.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}`)}s.writeFileSync(e,i.join("\n"))}(i,a)}}function Yt(e,t){return function(){return e.apply(t,arguments)}}const{toString:en}=Object.prototype,{getPrototypeOf:tn}=Object,{iterator:nn,toStringTag:rn}=Symbol,sn=(e=>t=>{const n=en.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),an=e=>(e=e.toLowerCase(),t=>sn(t)===e),on=e=>t=>typeof t===e,{isArray:cn}=Array,dn=on("undefined");function ln(e){return null!==e&&!dn(e)&&null!==e.constructor&&!dn(e.constructor)&&pn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const un=an("ArrayBuffer");const hn=on("string"),pn=on("function"),gn=on("number"),fn=e=>null!==e&&"object"==typeof e,mn=e=>{if("object"!==sn(e))return!1;const t=tn(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||rn in e||nn in e)},yn=an("Date"),bn=an("File"),wn=an("Blob"),vn=an("FileList"),In=an("URLSearchParams"),[Tn,An,_n,Cn]=["ReadableStream","Request","Response","Headers"].map(an);function En(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),cn(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(ln(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let a;for(i=0;i<s;i++)a=r[i],t.call(null,e[a],a,e)}}function Rn(e,t){if(ln(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 Sn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:o,xn=e=>!dn(e)&&e!==Sn;const Nn=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&tn(Uint8Array)),kn=an("HTMLFormElement"),On=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),$n=an("RegExp"),Mn=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};En(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const Pn=an("AsyncFunction"),Fn=(Dn="function"==typeof c.setImmediate,Ln=pn(Sn.postMessage),Dn?c.setImmediate:Ln?(Bn=`axios@${Math.random()}`,qn=[],Sn.addEventListener("message",({source:e,data:t})=>{e===Sn&&t===Bn&&qn.length&&qn.shift()()},!1),e=>{qn.push(e),Sn.postMessage(Bn,"*")}):e=>setTimeout(e));var Dn,Ln,Bn,qn;const Un="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Sn):void 0!==t&&t.nextTick||Fn,jn={isArray:cn,isArrayBuffer:un,isBuffer:ln,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||pn(e.append)&&("formdata"===(t=sn(e))||"object"===t&&pn(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&un(e.buffer),t},isString:hn,isNumber:gn,isBoolean:e=>!0===e||!1===e,isObject:fn,isPlainObject:mn,isEmptyObject:e=>{if(!fn(e)||ln(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Tn,isRequest:An,isResponse:_n,isHeaders:Cn,isUndefined:dn,isDate:yn,isFile:bn,isBlob:wn,isRegExp:$n,isFunction:pn,isStream:e=>fn(e)&&pn(e.pipe),isURLSearchParams:In,isTypedArray:Nn,isFileList:vn,forEach:En,merge:function e(){const{caseless:t}=xn(this)&&this||{},n={},i=(i,r)=>{const s=t&&Rn(n,r)||r;mn(n[s])&&mn(i)?n[s]=e(n[s],i):mn(i)?n[s]=e({},i):cn(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&En(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(En(t,(t,i)=>{n&&pn(t)?e[i]=Yt(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,a;const o={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)a=r[s],i&&!i(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==n&&tn(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:sn,kindOfTest:an,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(cn(e))return e;let t=e.length;if(!gn(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[nn]).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:kn,hasOwnProperty:On,hasOwnProp:On,reduceDescriptors:Mn,freezeMethods:e=>{Mn(e,(t,n)=>{if(pn(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];pn(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 cn(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:Rn,global:Sn,isContextDefined:xn,isSpecCompliantForm:function(e){return!!(e&&pn(e.append)&&"FormData"===e[rn]&&e[nn])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(fn(e)){if(t.indexOf(e)>=0)return;if(ln(e))return e;if(!("toJSON"in e)){t[i]=e;const r=cn(e)?[]:{};return En(e,(e,t)=>{const s=n(e,i+1);!dn(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:Pn,isThenable:e=>e&&(fn(e)||pn(e))&&pn(e.then)&&pn(e.catch),setImmediate:Fn,asap:Un,isIterable:e=>null!=e&&pn(e[nn])};function Kn(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)}jn.inherits(Kn,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:jn.toJSONObject(this.config),code:this.code,status:this.status}}});const Hn=Kn.prototype,Zn={};["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=>{Zn[e]={value:e}}),Object.defineProperties(Kn,Zn),Object.defineProperty(Hn,"isAxiosError",{value:!0}),Kn.from=(e,t,n,i,r,s)=>{const a=Object.create(Hn);return jn.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Kn.call(a,e.message,t,n,i,r),a.cause=e,a.name=e.name,s&&Object.assign(a,s),a};function zn(e){return jn.isPlainObject(e)||jn.isArray(e)}function Gn(e){return jn.endsWith(e,"[]")?e.slice(0,-2):e}function Wn(e,t,n){return e?e.concat(t).map(function(e,t){return e=Gn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Vn=jn.toFlatObject(jn,{},null,function(e){return/^is[A-Z]/.test(e)});function Xn(e,t,i){if(!jn.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const r=(i=jn.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!jn.isUndefined(t[e])})).metaTokens,s=i.visitor||l,a=i.dots,o=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&jn.isSpecCompliantForm(t);if(!jn.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(jn.isDate(e))return e.toISOString();if(jn.isBoolean(e))return e.toString();if(!c&&jn.isBlob(e))throw new Kn("Blob is not supported. Use a Buffer instead.");return jn.isArrayBuffer(e)||jn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):n.Buffer.from(e):e}function l(e,n,i){let s=e;if(e&&!i&&"object"==typeof e)if(jn.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(jn.isArray(e)&&function(e){return jn.isArray(e)&&!e.some(zn)}(e)||(jn.isFileList(e)||jn.endsWith(n,"[]"))&&(s=jn.toArray(e)))return n=Gn(n),s.forEach(function(e,i){!jn.isUndefined(e)&&null!==e&&t.append(!0===o?Wn([n],i,a):null===o?n:n+"[]",d(e))}),!1;return!!zn(e)||(t.append(Wn(i,n,a),d(e)),!1)}const u=[],h=Object.assign(Vn,{defaultVisitor:l,convertValue:d,isVisitable:zn});if(!jn.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!jn.isUndefined(n)){if(-1!==u.indexOf(n))throw Error("Circular reference detected in "+i.join("."));u.push(n),jn.forEach(n,function(n,r){!0===(!(jn.isUndefined(n)||null===n)&&s.call(t,n,jn.isString(r)?r.trim():r,i,h))&&e(n,i?i.concat(r):[r])}),u.pop()}}(e),t}function Jn(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Qn(e,t){this._pairs=[],e&&Xn(e,this,t)}const Yn=Qn.prototype;function ei(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ti(e,t,n){if(!t)return e;const i=n&&n.encode||ei;jn.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):jn.isURLSearchParams(t)?t.toString():new Qn(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Yn.append=function(e,t){this._pairs.push([e,t])},Yn.toString=function(e){const t=e?function(t){return e.call(this,t,Jn)}:Jn;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class ni{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){jn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const ii={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ri={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Qn,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},si="undefined"!=typeof window&&"undefined"!=typeof document,ai="object"==typeof navigator&&navigator||void 0,oi=si&&(!ai||["ReactNative","NativeScript","NS"].indexOf(ai.product)<0),ci="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,di=si&&window.location.href||"http://localhost",li={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:si,hasStandardBrowserEnv:oi,hasStandardBrowserWebWorkerEnv:ci,navigator:ai,origin:di},Symbol.toStringTag,{value:"Module"})),...ri};function ui(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=e.length;if(s=!s&&jn.isArray(i)?i.length:s,o)return jn.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a;i[s]&&jn.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&jn.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])),!a}if(jn.isFormData(e)&&jn.isFunction(e.entries)){const n={};return jn.forEachEntry(e,(e,i)=>{t(function(e){return jn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const hi={transitional:ii,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=jn.isObject(e);r&&jn.isHTMLForm(e)&&(e=new FormData(e));if(jn.isFormData(e))return i?JSON.stringify(ui(e)):e;if(jn.isArrayBuffer(e)||jn.isBuffer(e)||jn.isStream(e)||jn.isFile(e)||jn.isBlob(e)||jn.isReadableStream(e))return e;if(jn.isArrayBufferView(e))return e.buffer;if(jn.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 Xn(e,new li.classes.URLSearchParams,{visitor:function(e,t,n,i){return li.isNode&&jn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=jn.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Xn(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(jn.isString(e))try{return(t||JSON.parse)(e),jn.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||hi.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(jn.isResponse(e)||jn.isReadableStream(e))return e;if(e&&jn.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 Kn.from(r,Kn.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:li.classes.FormData,Blob:li.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};jn.forEach(["delete","get","head","post","put","patch"],e=>{hi.headers[e]={}});const pi=jn.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"]),gi=Symbol("internals");function fi(e){return e&&String(e).trim().toLowerCase()}function mi(e){return!1===e||null==e?e:jn.isArray(e)?e.map(mi):String(e)}function yi(e,t,n,i,r){return jn.isFunction(i)?i.call(this,t,n):(r&&(t=n),jn.isString(t)?jn.isString(i)?-1!==t.indexOf(i):jn.isRegExp(i)?i.test(t):void 0:void 0)}let bi=class{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=fi(t);if(!r)throw new Error("header name must be a non-empty string");const s=jn.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=mi(e))}const s=(e,t)=>jn.forEach(e,(e,n)=>r(e,n,t));if(jn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(jn.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]&&pi[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(jn.isObject(e)&&jn.isIterable(e)){let n,i,r={};for(const t of e){if(!jn.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?jn.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=fi(e)){const n=jn.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(jn.isFunction(t))return t.call(this,e,n);if(jn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=fi(e)){const n=jn.findKey(this,e);return!(!n||void 0===this[n]||t&&!yi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=fi(e)){const r=jn.findKey(n,e);!r||t&&!yi(0,n[r],r,t)||(delete n[r],i=!0)}}return jn.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&&!yi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return jn.forEach(this,(i,r)=>{const s=jn.findKey(n,r);if(s)return t[s]=mi(i),void delete t[r];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();a!==r&&delete t[r],t[a]=mi(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return jn.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&jn.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[gi]=this[gi]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=fi(e);t[i]||(!function(e,t){const n=jn.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 jn.isArray(e)?e.forEach(i):i(e),this}};function wi(e,t){const n=this||hi,i=t||n,r=bi.from(i.headers);let s=i.data;return jn.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function vi(e){return!(!e||!e.__CANCEL__)}function Ii(e,t,n){Kn.call(this,null==e?"canceled":e,Kn.ERR_CANCELED,t,n),this.name="CanceledError"}function Ti(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Kn("Request failed with status code "+n.status,[Kn.ERR_BAD_REQUEST,Kn.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}bi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),jn.reduceDescriptors(bi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),jn.freezeMethods(bi),jn.inherits(Ii,Kn,{__CANCEL__:!0});const Ai=(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,a=0;return t=void 0!==t?t:1e3,function(o){const c=Date.now(),d=i[a];r||(r=c),n[s]=o,i[s]=c;let l=a,u=0;for(;l!==s;)u+=n[l++],l%=e;if(s=(s+1)%e,s===a&&(a=(a+1)%e),c-r<t)return;const h=d&&c-d;return h?Math.round(1e3*u/h):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const a=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),o=t-r;o>=s?a(e,t):(n=e,i||(i=setTimeout(()=>{i=null,a(n)},s-o)))},()=>n&&a(n)]}(n=>{const s=n.loaded,a=n.lengthComputable?n.total:void 0,o=s-i,c=r(o);i=s;e({loaded:s,total:a,progress:a?s/a:void 0,bytes:o,rate:c||void 0,estimated:c&&a&&s<=a?(a-s)/c:void 0,event:n,lengthComputable:null!=a,[t?"download":"upload"]:!0})},n)},_i=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Ci=e=>(...t)=>jn.asap(()=>e(...t)),Ei=li.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,li.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(li.origin),li.navigator&&/(msie|trident)/i.test(li.navigator.userAgent)):()=>!0,Ri=li.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const a=[e+"="+encodeURIComponent(t)];jn.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),jn.isString(i)&&a.push("path="+i),jn.isString(r)&&a.push("domain="+r),!0===s&&a.push("secure"),document.cookie=a.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 Si(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 xi=e=>e instanceof bi?{...e}:e;function Ni(e,t){t=t||{};const n={};function i(e,t,n,i){return jn.isPlainObject(e)&&jn.isPlainObject(t)?jn.merge.call({caseless:i},e,t):jn.isPlainObject(t)?jn.merge({},t):jn.isArray(t)?t.slice():t}function r(e,t,n,r){return jn.isUndefined(t)?jn.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!jn.isUndefined(t))return i(void 0,t)}function a(e,t){return jn.isUndefined(t)?jn.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function o(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:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t,n)=>r(xi(e),xi(t),0,!0)};return jn.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,a=s(e[i],t[i],i);jn.isUndefined(a)&&s!==o||(n[i]=a)}),n}const ki=e=>{const t=Ni({},e);let n,{data:i,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=bi.from(o),t.url=ti(Si(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),jn.isFormData(i))if(li.hasStandardBrowserEnv||li.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(!1!==(n=o.getContentType())){const[e,...t]=n?n.split(";").map(e=>e.trim()).filter(Boolean):[];o.setContentType([e||"multipart/form-data",...t].join("; "))}if(li.hasStandardBrowserEnv&&(r&&jn.isFunction(r)&&(r=r(t)),r||!1!==r&&Ei(t.url))){const e=s&&a&&Ri.read(a);e&&o.set(s,e)}return t},Oi="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=ki(e);let r=i.data;const s=bi.from(i.headers).normalize();let a,o,c,d,l,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=i;function g(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let f=new XMLHttpRequest;function m(){if(!f)return;const i=bi.from("getAllResponseHeaders"in f&&f.getAllResponseHeaders());Ti(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 Kn("Request aborted",Kn.ECONNABORTED,e,f)),f=null)},f.onerror=function(){n(new Kn("Network Error",Kn.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||ii;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new Kn(t,r.clarifyTimeoutError?Kn.ETIMEDOUT:Kn.ECONNABORTED,e,f)),f=null},void 0===r&&s.setContentType(null),"setRequestHeader"in f&&jn.forEach(s.toJSON(),function(e,t){f.setRequestHeader(t,e)}),jn.isUndefined(i.withCredentials)||(f.withCredentials=!!i.withCredentials),u&&"json"!==u&&(f.responseType=i.responseType),p&&([c,l]=Ai(p,!0),f.addEventListener("progress",c)),h&&f.upload&&([o,d]=Ai(h),f.upload.addEventListener("progress",o),f.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(a=t=>{f&&(n(!t||t.type?new Ii(null,e,f):t),f.abort(),f=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===li.protocols.indexOf(y)?n(new Kn("Unsupported protocol "+y+":",Kn.ERR_BAD_REQUEST,e)):f.send(r||null)})},$i=(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,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Kn?t:new Ii(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new Kn(`timeout ${t} of ms exceeded`,Kn.ETIMEDOUT))},t);const a=()=>{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:o}=i;return o.unsubscribe=()=>jn.asap(a),o}},Mi=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},Pi=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()}},Fi=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of Pi(e))yield*Mi(n,t)}(e,t);let s,a=0,o=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 o(),void e.close();let s=i.byteLength;if(n){let e=a+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(t){throw o(t),t}},cancel:e=>(o(e),r.return())},{highWaterMark:2})},Di="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Li=Di&&"function"==typeof ReadableStream,Bi=Di&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),qi=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},Ui=Li&&qi(()=>{let e=!1;const t=new Request(li.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),ji=Li&&qi(()=>jn.isReadableStream(new Response("").body)),Ki={stream:ji&&(e=>e.body)};var Hi;Di&&(Hi=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ki[e]&&(Ki[e]=jn.isFunction(Hi[e])?t=>t[e]():(t,n)=>{throw new Kn(`Response type '${e}' is not supported`,Kn.ERR_NOT_SUPPORT,n)})}));const Zi=async(e,t)=>{const n=jn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(jn.isBlob(e))return e.size;if(jn.isSpecCompliantForm(e)){const t=new Request(li.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return jn.isArrayBufferView(e)||jn.isArrayBuffer(e)?e.byteLength:(jn.isURLSearchParams(e)&&(e+=""),jn.isString(e)?(await Bi(e)).byteLength:void 0)})(t):n},zi={http:null,xhr:Oi,fetch:Di&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:a,onDownloadProgress:o,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:h}=ki(e);d=d?(d+"").toLowerCase():"text";let p,g=$i([r,s&&s.toAbortSignal()],a);const f=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let m;try{if(c&&Ui&&"get"!==n&&"head"!==n&&0!==(m=await Zi(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(jn.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=_i(m,Ai(Ci(c)));i=Fi(n.body,65536,e,t)}}jn.isString(u)||(u=u?"include":"omit");const r="credentials"in Request.prototype;p=new Request(t,{...h,signal:g,method:n.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:r?u:void 0});let s=await fetch(p,h);const a=ji&&("stream"===d||"response"===d);if(ji&&(o||a&&f)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=jn.toFiniteNumber(s.headers.get("content-length")),[n,i]=o&&_i(t,Ai(Ci(o),!0))||[];s=new Response(Fi(s.body,65536,n,()=>{i&&i(),f&&f()}),e)}d=d||"text";let y=await Ki[jn.findKey(Ki,d)||"text"](s,e);return!a&&f&&f(),await new Promise((t,n)=>{Ti(t,n,{data:y,headers:bi.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:p})})}catch(y){if(f&&f(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new Kn("Network Error",Kn.ERR_NETWORK,e,p),{cause:y.cause||y});throw Kn.from(y,y&&y.code,e,p)}})};jn.forEach(zi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Gi=e=>`- ${e}`,Wi=e=>jn.isFunction(e)||null===e||!1===e,Vi=e=>{e=jn.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,!Wi(n)&&(i=zi[(t=String(n)).toLowerCase()],void 0===i))throw new Kn(`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 Kn("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Gi).join("\n"):" "+Gi(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Xi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ii(null,e)}function Ji(e){Xi(e),e.headers=bi.from(e.headers),e.data=wi.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Vi(e.adapter||hi.adapter)(e).then(function(t){return Xi(e),t.data=wi.call(e,e.transformResponse,t),t.headers=bi.from(t.headers),t},function(t){return vi(t)||(Xi(e),t&&t.response&&(t.response.data=wi.call(e,e.transformResponse,t.response),t.response.headers=bi.from(t.response.headers))),Promise.reject(t)})}const Qi="1.11.0",Yi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Yi[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const er={};Yi.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Qi+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new Kn(i(r," has been removed"+(t?" in "+t:"")),Kn.ERR_DEPRECATED);return t&&!er[r]&&(er[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)}},Yi.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const tr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Kn("options must be an object",Kn.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],a=t[s];if(a){const t=e[s],n=void 0===t||a(t,s,e);if(!0!==n)throw new Kn("option "+s+" must be "+n,Kn.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Kn("Unknown option "+s,Kn.ERR_BAD_OPTION)}},validators:Yi},nr=tr.validators;let ir=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ni,response:new ni}}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=Ni(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&tr.assertOptions(n,{silentJSONParsing:nr.transitional(nr.boolean),forcedJSONParsing:nr.transitional(nr.boolean),clarifyTimeoutError:nr.transitional(nr.boolean)},!1),null!=i&&(jn.isFunction(i)?t.paramsSerializer={serialize:i}:tr.assertOptions(i,{encode:nr.function,serialize:nr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),tr.assertOptions(t,{baseUrl:nr.spelling("baseURL"),withXsrfToken:nr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&jn.merge(r.common,r[t.method]);r&&jn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=bi.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.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(!o){const e=[Ji.bind(this),void 0];for(e.unshift(...a),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=a.length;let h=t;for(u=0;u<l;){const e=a[u++],t=a[u++];try{h=e(h)}catch(p){t.call(this,p);break}}try{d=Ji.call(this,h)}catch(p){return Promise.reject(p)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return ti(Si((e=Ni(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};jn.forEach(["delete","get","head","options"],function(e){ir.prototype[e]=function(t,n){return this.request(Ni(n||{},{method:e,url:t,data:(n||{}).data}))}}),jn.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Ni(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}ir.prototype[e]=t(),ir.prototype[e+"Form"]=t(!0)});const rr={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(rr).forEach(([e,t])=>{rr[t]=e});const sr=function e(t){const n=new ir(t),i=Yt(ir.prototype.request,n);return jn.extend(i,ir.prototype,n,{allOwnKeys:!0}),jn.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Ni(t,n))},i}(hi);sr.Axios=ir,sr.CanceledError=Ii,sr.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 Ii(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}}},sr.isCancel=vi,sr.VERSION=Qi,sr.toFormData=Xn,sr.AxiosError=Kn,sr.Cancel=sr.CanceledError,sr.all=function(e){return Promise.all(e)},sr.spread=function(e){return function(t){return e.apply(null,t)}},sr.isAxiosError=function(e){return jn.isObject(e)&&!0===e.isAxiosError},sr.mergeConfig=Ni,sr.AxiosHeaders=bi,sr.formToJSON=e=>ui(jn.isHTMLForm(e)?new FormData(e):e),sr.getAdapter=Vi,sr.HttpStatusCode=rr,sr.default=sr;const{Axios:ar,AxiosError:or,CanceledError:cr,isCancel:dr,CancelToken:lr,VERSION:ur,all:hr,Cancel:pr,isAxiosError:gr,spread:fr,toFormData:mr,AxiosHeaders:yr,HttpStatusCode:br,formToJSON:wr,getAdapter:vr,mergeConfig:Ir}=sr,Tr="ConnectionsManager not initialized";class Ar extends i.BaseServiceBuilder{constructor(e,t,n){super(e),this.useEncryption=!1,this.guardedRegistryBaseUrl="",this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const s=this.hederaKit.signer.getAccountId().toString(),a=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new r.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new r.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:a,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 t=await sr.get(e,{responseType:"arraybuffer"}),i=n.Buffer.from(t.data),r=new URL(e).pathname;return{buffer:i,filename:a.basename(r)||"profile.png"}}{if(!s.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=s.readFileSync(e);return{buffer:t,filename:a.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await sr.get(e.url,{responseType:"arraybuffer"}),i=n.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!s.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=s.readFileSync(e.path);return{buffer:t,filename:e.filename||a.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?t.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let t=null;e.profilePicture&&(t=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==t?.buffer&&{pfpBuffer:t.buffer},...void 0!==t?.filename&&{pfpFileName:t.filename}};if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,i,s)}const i=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.state?.agentMetadata?.accountId}}}catch(t){throw this.logger.error("Failed to register agent:",t),t}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const n=t.topicInfo.inboundTopic;let 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 i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(Tr);await i.fetchConnectionData(n.accountId);const s=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const a=s.targetAccountId,o=s.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,i)}const d=await this.getInboundTopicId(),l=await this.handleConnectionRequest(d,a,o,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 ${a}`;s.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${a}'.`);let n=s.targetInboundTopicId||"";if(!n)try{const e=await this.getAgentProfile(a);e.success&&e.topicInfo?.inboundTopic&&(n=e.topicInfo.inboundTopic)}catch(t){this.logger.warn(`Could not fetch profile for ${a}:`,t)}const r={connectionId:`conn-${Date.now()}`,targetAccountId:a,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:u,status:"established",created:new Date};this.stateManager.addActiveConnection(r),i.markConnectionRequestProcessed(s.targetInboundTopicId||"",o)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:a,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,a=`${t.inboundTopicId}@${t.accountId}`,o=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!o.sequenceNumber)throw new Error("Failed to send message");let c=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):c=await this.monitorResponses(r,a,o.sequenceNumber),this.executeResult={success:!0,transactionId:o.transactionId,receipt:o.receipt,scheduleId:void 0,rawResult:{targetAgentName:s,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:o.sequenceNumber,reply:c,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:o}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let 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:i=120,hbarFees:s=[],tokenFees:a=[],exemptAccountIds:o=[],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*i;let u=0,h=0;const p=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 i of e){const e=i.sequence_number;if(!e||p.has(e))continue;const l=i.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||a.length>0){const e=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,o)}for(const t of a){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,o)}t=e}await this.handleConnectionRequest(d,l,e,t),p.add(e),h++}}}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:h,monitorDurationSeconds:i,processedRequestIds:Array.from(p)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${h}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(Tr);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 a="";i.length>0&&(a+=`🟢 Active Connections (${i.length}):\n`,i.forEach((e,n)=>{a+=this.formatConnection(e,n,t)}),a+="\n"),n&&s.length>0&&(a+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach((e,n)=>{a+=this.formatConnection(e,n,t)}),a+="\n"),n&&r.length>0&&(a+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach((e,n)=>{a+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:a.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(Tr),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 a=[],o=r;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;a=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${r}`),a=t.filter(e=>1e6*e.timestamp>r),a.length>0&&(o=a.reduce((e,t)=>Math.max(e,1e6*t.timestamp),r));if(0===a.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 ${a.length} message(s).`);let d=c?`Latest message(s) from ${i}:\n`:`New messages from ${i}:\n`;const l=[];for(const e of a){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&&o>r&&(this.logger.debug(`Updating timestamp for topic ${n} to ${o}`),this.stateManager.updateTimestamp(n,o)),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 _r extends i.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 i.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}class Cr extends i.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 r.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 Er extends i.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().toString():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:t};this.hcs6Client=new r.HCS6Client(n)}return this.hcs6Client}async createRegistry(e={}){const t=await this.getHCS6Client(),n={...e};return"adminKey"in n&&delete n.adminKey,await t.createRegistry(n)}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(),n={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal metadata",type:e.metadata?.type||"json",...e.metadata};return await t.createHashinal({...e,metadata:n})}async register(e){const t=await this.getHCS6Client(),n={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal registration",type:e.metadata?.type||"json",...e.metadata};return await t.register({...e,metadata:n})}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 Rr extends i.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 r.inscribe(e,n,t)}async inscribeWithSigner(e,t,n){return await r.inscribeWithSigner(e,t,n)}async retrieveInscription(e,t){const n=this.hederaKit.signer.getAccountId().toString(),i=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";return await r.retrieveInscription(e,{...t,accountId:n,privateKey:i})}async close(){this.inscriptionSDK=void 0}}Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>i.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>i.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>i.PluginRegistry}),e.AcceptConnectionRequestTool=At,e.BaseHCS10QueryTool=g,e.BaseHCS10TransactionTool=p,e.BaseHCS2QueryTool=xt,e.BaseHCS2TransactionTool=St,e.BaseHCS6QueryTool=Dt,e.BaseHCS6TransactionTool=Ft,e.BaseInscriberQueryTool=Kt,e.BaseInscriberTransactionTool=jt,e.CheckMessagesTool=ft,e.ConnectionMonitorTool=wt,e.CreateDynamicRegistryTool=class extends Dt{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return Lt}async executeQuery(e,t){const n=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!n.success)throw new Error(n.error||"Failed to create dynamic registry");return`Successfully created HCS-6 dynamic registry!\n\nTopic ID: ${n.topicId}\nTTL: ${e.ttl} seconds\n\nYou can now register dynamic hashinals to this registry using the topic ID.`}},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=Ar,e.HCS10Client=class{constructor(e,n,i,s){this.standardClient=new r.HCS10Client({network:i,operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:s?.registryUrl,logLevel:s?.logLevel}),this.guardedRegistryBaseUrl=s?.registryUrl||"",this.useEncryption=s?.useEncryption||!1;const a="true"===t.env.DISABLE_LOGGING;this.logger=new r.Logger({level:s?.logLevel||"info",silent:a})}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 r.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),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 r.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HCS2Builder=Cr,e.HCS6Builder=Er,e.HbarPricePlugin=_r,e.InitiateConnectionTool=ut,e.InscribeFromBufferTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Inscribe content that you have already retrieved or displayed. When user says "inscribe it" after you showed search results or other content, use THIS tool. The base64Data field accepts PLAIN TEXT (not just base64) and content reference IDs in format "content-ref:[id]". Pass the EXACT content from your previous response or MCP tool output. DO NOT generate new content or create repetitive text. Content references are automatically resolved to the original content for inscription.',this.config=Gt()}get specificInputSchema(){return Wt}async executeQuery(e,t){this.validateInput(e);const n=await this.resolveContent(e.base64Data,e.mimeType,e.fileName);this.validateContent(n.buffer);const i=n.buffer,r=n.mimeType||e.mimeType,s=n.fileName||e.fileName,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"},o=e.timeoutMs||(a.waitForConfirmation?6e4:void 0);try{const e=await this.executeInscription(i,s,r,a,o);return this.formatInscriptionResult(e,a)}catch(c){const e=c instanceof Error?c.message:"Failed to inscribe from buffer";throw new Error(`Inscription failed: ${e}`)}}validateInput(e){if(!e.base64Data||""===e.base64Data.trim())throw new Error("No data provided. Cannot inscribe empty content. Please provide valid content, plain text, base64 encoded data, or a content reference ID.");if(!e.fileName||""===e.fileName.trim())throw new Error("No fileName provided. A valid fileName is required for inscription.")}validateContent(e){if(0===e.length)throw new Error("Buffer is empty after conversion. The provided data appears to be invalid or empty.");if(e.length>this.config.maxInscriptionSize){const t=Math.round(this.config.maxInscriptionSize/1024),n=Math.round(e.length/1024);throw new Error(`Content is too large for inscription (${n}KB, max ${t}KB). Please summarize or extract key information before inscribing.`)}if(e.length<this.config.minContentSize)throw new Error(`Buffer content is too small (${e.length} bytes). This may indicate empty or invalid content. Please verify the source data contains actual content.`);if(""===e.toString("utf8",0,Math.min(e.length,100)).trim())throw new Error("Buffer contains only whitespace or empty content. Cannot inscribe meaningless data.");const t=e.toString("utf8");if(/<a\s+href=["'][^"']+["']\s*>\s*<\/a>/i.test(t)&&t.replace(/<[^>]+>/g,"").trim().length<50)throw new Error("Buffer contains empty HTML with only links and no actual content. When inscribing content from external sources, use the actual article text you retrieved, not empty HTML with links.")}async executeInscription(e,t,n,i,r){const s={type:"buffer",buffer:e,fileName:t,mimeType:n};if(r){const e=new Promise((e,t)=>{setTimeout(()=>t(new Error(`Inscription timed out after ${r}ms`)),r)});return Promise.race([this.inscriberBuilder.inscribe(s,i),e])}return this.inscriberBuilder.inscribe(s,i)}formatInscriptionResult(e,t){if(e.confirmed){const n=e.inscription?.topic_id||e.result.topicId,i=t.network||"testnet",r=n?`https://kiloscribe.com/api/inscription-cdn/${n}?network=${i}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\nTopic ID: ${n||"N/A"}${r?`\nView inscription: ${r}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}async resolveContent(e,t,n){const i=e.trim(),s=this.getContentResolver()||r.ContentResolverRegistry.getResolver();if(!s)return this.handleDirectContent(i,t,n);const a=s.extractReferenceId(i);if(a)try{const e=await s.resolveReference(a);return{buffer:e.content,mimeType:e.metadata?.mimeType||t,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(o){const e=o instanceof Error?o.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return this.handleDirectContent(i,t,n)}handleDirectContent(e,t,i){if(/^[A-Za-z0-9+/]*={0,2}$/.test(e))try{return{buffer:n.Buffer.from(e,"base64"),mimeType:t,fileName:i,wasReference:!1}}catch(r){throw new Error("Failed to decode base64 data. Please ensure the data is properly encoded.")}return{buffer:n.Buffer.from(e,"utf8"),mimeType:t||"text/plain",fileName:i,wasReference:!1}}},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,i){let r;console.log(`[DEBUG] InscribeFromFileTool.executeQuery called with: ${e.filePath}`);try{console.log(`[DEBUG] Checking file: ${e.filePath}`),console.log(`[DEBUG] Current working directory: ${t.cwd()}`);const n=await h.stat(e.filePath);if(!n.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(console.log(`[DEBUG] File size: ${n.size} bytes`),0===n.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(n.size<10)throw new Error(`File "${e.filePath}" is too small (${n.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(n.size>104857600&&console.log(`[InscribeFromFileTool] WARNING: Large file detected (${(n.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),r=await h.readFile(e.filePath),this.logger?.info(`Read ${r.length} bytes from file`),!r||0===r.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(r.length<10)throw new Error(`File "${e.filePath}" content is too small (${r.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const i=u.basename(e.filePath),s=this.getMimeType(i);if(s.startsWith("text/")||"application/json"===s){if(""===r.toString("utf8",0,Math.min(r.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 s=r.toString("base64");this.logger?.info(`Converted to base64: ${s.length} characters`);const a=u.basename(e.filePath),o=this.getMimeType(a);this.logger?.info(`File: ${a}, MIME type: ${o}`);const c={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:"buffer",buffer:n.Buffer.from(s,"base64"),fileName:a,mimeType:o},c),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:n.Buffer.from(s,"base64"),fileName:a,mimeType:o},c);if(t.confirmed){const e=t.inscription?.topic_id||t.result.topicId,n=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${c.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(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='ONLY for direct FILE DOWNLOAD URLs ending with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or ANY HTML content - it WILL FAIL. If you have already retrieved content from any source (including MCP tools), you MUST use inscribeFromBuffer instead. This tool downloads files from URLs - it does NOT inscribe content you already have. When asked to "inscribe it" after retrieving content, ALWAYS use inscribeFromBuffer with the actual 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){if(i instanceof Error&&i.message.includes("Cannot inscribe content from"))throw 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")||"",a=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(a&&0===parseInt(a))throw new Error("URL returns empty content (Content-Length: 0). Cannot inscribe empty content.");if(a&&parseInt(a)<10)throw new Error(`URL content is too small (${a} 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: ${a||"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 Vt}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=Rr,e.ListConnectionsTool=pt,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 Mt}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=Qt,e.QueryDynamicRegistryTool=class extends Dt{constructor(e){super(e),this.name="queryDynamicRegistry",this.description="Query a dynamic registry to get the current state of a dynamic hashinal"}get specificInputSchema(){return Ut}async executeQuery(e,t){const n=await this.hcs6Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip}),i=n.latestEntry?{topicId:n.latestEntry.message.t_id,timestamp:n.latestEntry.timestamp,memo:n.latestEntry.message.m,sequence:n.latestEntry.sequence,payer:n.latestEntry.payer}:null;return`Successfully queried dynamic registry!\n\nRegistry Topic: ${n.topicId}\nRegistry Type: NON_INDEXED\nTTL: ${n.ttl} seconds\nTotal Entries: ${n.entries.length}${i?`\n\nLatest Entry:\n- Topic ID: ${i.topicId}\n- Timestamp: ${i.timestamp}\n- Memo: ${i.memo||"N/A"}\n- Sequence: ${i.sequence}`:"\n\nNo entries found in registry."}`}},e.QueryRegistryTool=class extends xt{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry"}get specificInputSchema(){return Pt}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=ot,e.RegisterDynamicHashinalTool=class extends Dt{constructor(e){super(e),this.name="registerDynamicHashinal",this.description="Create and register a new dynamic hashinal that can be updated over time"}get specificInputSchema(){return Bt}async executeQuery(e,t){const n=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,ttl:e.ttl,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!n.success)throw new Error(n.error||"Failed to register dynamic hashinal");return`Successfully registered dynamic hashinal!\n\nRegistry Topic ID: ${n.registryTopicId}\nInscription Topic ID: ${n.inscriptionTopicId}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe dynamic hashinal has been created and can be updated using the registry topic ID.`}},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 Xt}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 Dt{constructor(e){super(e),this.name="updateDynamicHashinal",this.description="Update an existing dynamic hashinal with new content while maintaining the same registry"}get specificInputSchema(){return qt}async executeQuery(e,t){const n=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!n.success)throw new Error(n.error||"Failed to update dynamic hashinal");return`Successfully updated dynamic hashinal!\n\nRegistry Topic ID: ${e.registryTopicId}\nInscription Topic ID: ${n.inscriptionTopicId}${e.memo?`\nUpdate Memo: ${e.memo}`:""}\n\nThe dynamic hashinal has been updated with new content.`}},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 n=e?.clientConfig||{},s=n.operatorId||t.env.HEDERA_OPERATOR_ID,a=n.operatorKey||t.env.HEDERA_OPERATOR_KEY,o=n.network||t.env.HEDERA_NETWORK||"testnet";let c;if("mainnet"===o?c="mainnet":("testnet"===o||console.warn(`Unsupported network specified: '${o}'. Defaulting to 'testnet'.`),c="testnet"),!s||!a)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const d="true"===t.env.DISABLE_LOGGING,l=r.Logger.getInstance({level:n.logLevel||"info",silent:d}),u=e?.stateManager||new Qt({defaultEnvFilePath:Jt,defaultPrefix:"TODD"});l.info("State manager initialized");const h=new i.ServerSigner(s,a,c),p=new i.HederaAgentKit(h);await p.initialize(),l.info(`HederaAgentKit initialized for ${s} on ${c}`);const g=new Ar(p,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let f,m;if(e?.monitoringClient){const e=new i.ServerSigner(s,a,c);f=new i.HederaAgentKit(e),await f.initialize(),m=new Ar(f,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),l.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new ot({hederaKit:p,hcs10Builder:g,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new yt({hederaKit:p,hcs10Builder:g,logger:void 0}),y.retrieveProfileTool=new Ct({hederaKit:p,hcs10Builder:g,logger:void 0}),y.initiateConnectionTool=new ut({hederaKit:p,hcs10Builder:g,logger:void 0}),y.listConnectionsTool=new pt({hederaKit:p,hcs10Builder:g,logger:void 0}),y.sendMessageToConnectionTool=new dt({hederaKit:p,hcs10Builder:g,logger:void 0}),y.checkMessagesTool=new ft({hederaKit:p,hcs10Builder:g,logger:void 0}),y.connectionMonitorTool=new wt({hederaKit:f||p,hcs10Builder:m||g,logger:void 0}),y.manageConnectionRequestsTool=new It({hederaKit:p,hcs10Builder:g,logger:void 0}),y.acceptConnectionRequestTool=new At({hederaKit:p,hcs10Builder:g,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new Rt({hederaKit:p,hcs10Builder:g,logger:void 0}),l.info("All tools initialized")),{hederaKit:p,hcs10Builder:g,monitoringHederaKit:f,monitoringHcs10Builder:m,tools:y,stateManager:u}},e.loadConfig=Gt,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("unenv/node/process"),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/fs/promises")):"function"==typeof define&&define.amd?define(["exports","unenv/node/process","unenv/node/buffer","hedera-agent-kit","@hashgraphonline/standards-sdk","unenv/node/fs","unenv/node/path","unenv/polyfill/globalthis","unenv/node/timers","unenv/node/fs/promises"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsAgentKit={},e.process,e["unenv/node/buffer"],e.HederaAgentKit,e.StandardsSDK,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],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(o),h=l(d);class p extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class g extends i.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,O=e=>"dirty"===e.status,N=e=>"valid"===e.status,k=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 q(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(k(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(k(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 qe({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 Be.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 qe({...q(this._def),schema:this,typeName:Ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Le({...q(this._def),innerType:this,defaultValue:t,typeName:Ze.ZodDefault})}brand(){return new Ke({typeName:Ze.ZodBranded,type:this,...q(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...q(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 B=/^c[^\s-]{8,}$/i,L=/^[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])$/,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]))$/,X=/^(([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])$/,J=/^([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||!Q.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||!X.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)B.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)L.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?J.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,...q(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,...q(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,...q(e)});class he 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)}}he.create=e=>new he({typeName:Ze.ZodBoolean,coerce:e?.coerce||!1,...q(e)});class pe 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 pe({...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}}pe.create=e=>new pe({checks:[],coerce:e?.coerce||!1,typeName:Ze.ZodDate,...q(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,...q(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,...q(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,...q(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,...q(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,...q(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,...q(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,...q(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 Be?Be.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,...q(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,...q(t)}),Ae.strictCreate=(e,t)=>new Ae({shape:()=>e,unknownKeys:"strict",catchall:we.create(),typeName:Ze.ZodObject,...q(t)}),Ae.lazycreate=(e,t)=>new Ae({shape:e,unknownKeys:"strip",catchall:we.create(),typeName:Ze.ZodObject,...q(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,...q(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?((O(e)||O(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,...q(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,...q(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,...q(n)}:{keyType:ce.create(),valueType:e,typeName:Ze.ZodRecord,...q(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,...q(n)});class Oe 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 Oe({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new Oe({...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)}}Oe.create=(e,t)=>new Oe({valueType:e,minSize:null,maxSize:null,typeName:Ze.ZodSet,...q(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,...q(t)});class ke 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,...q(t)})}ke.create=(e,t)=>new ke({value:e,typeName:Ze.ZodLiteral,...q(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,...q(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,...q(t)});class qe 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)}}qe.create=(e,t,n)=>new qe({schema:e,typeName:Ze.ZodEffects,effect:t,...q(n)}),qe.createWithPreprocess=(e,t,n)=>new qe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ze.ZodEffects,...q(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,...q(t)});class Be extends D{_parse(e){return this._getType(e)===b.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Be.create=(e,t)=>new Be({innerType:e,typeName:Ze.ZodNullable,...q(t)});class Le 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}}Le.create=(e,t)=>new Le({innerType:e,typeName:Ze.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...q(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 k(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,...q(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,...q(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 k(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,...q(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,Qe=he.create,Xe=be.create;we.create;const Je=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,Be.create;const rt=class{static parseCapabilities(e){if(!e)return[r.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(r.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):[r.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[r.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[r.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[r.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[r.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[r.AIAgentCapability.CODE_GENERATION]:"Code Generation",[r.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[r.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[r.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[r.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[r.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[r.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[r.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[r.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[r.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[r.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[r.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[r.AIAgentCapability.API_INTEGRATION]:"API Integration",[r.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};rt.CAPABILITY_MAPPINGS={ai:[r.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[r.AIAgentCapability.TEXT_GENERATION],chat:[r.AIAgentCapability.TEXT_GENERATION],conversation:[r.AIAgentCapability.TEXT_GENERATION],text:[r.AIAgentCapability.TEXT_GENERATION],"text generation":[r.AIAgentCapability.TEXT_GENERATION],image:[r.AIAgentCapability.IMAGE_GENERATION],picture:[r.AIAgentCapability.IMAGE_GENERATION],visual:[r.AIAgentCapability.IMAGE_GENERATION],photo:[r.AIAgentCapability.IMAGE_GENERATION],audio:[r.AIAgentCapability.AUDIO_GENERATION],sound:[r.AIAgentCapability.AUDIO_GENERATION],voice:[r.AIAgentCapability.AUDIO_GENERATION],speech:[r.AIAgentCapability.AUDIO_GENERATION],video:[r.AIAgentCapability.VIDEO_GENERATION],movie:[r.AIAgentCapability.VIDEO_GENERATION],animation:[r.AIAgentCapability.VIDEO_GENERATION],code:[r.AIAgentCapability.CODE_GENERATION],programming:[r.AIAgentCapability.CODE_GENERATION],development:[r.AIAgentCapability.CODE_GENERATION],coding:[r.AIAgentCapability.CODE_GENERATION],translate:[r.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[r.AIAgentCapability.LANGUAGE_TRANSLATION],language:[r.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[r.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[r.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[r.AIAgentCapability.DATA_INTEGRATION],"data processing":[r.AIAgentCapability.DATA_INTEGRATION],"data integration":[r.AIAgentCapability.DATA_INTEGRATION],etl:[r.AIAgentCapability.DATA_INTEGRATION],market:[r.AIAgentCapability.MARKET_INTELLIGENCE],trading:[r.AIAgentCapability.MARKET_INTELLIGENCE],finance:[r.AIAgentCapability.MARKET_INTELLIGENCE],financial:[r.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[r.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[r.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[r.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[r.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[r.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[r.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[r.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[r.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[r.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[r.AIAgentCapability.GOVERNANCE_FACILITATION],security:[r.AIAgentCapability.SECURITY_MONITORING],monitoring:[r.AIAgentCapability.SECURITY_MONITORING],threat:[r.AIAgentCapability.SECURITY_MONITORING],compliance:[r.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[r.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[r.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[r.AIAgentCapability.FRAUD_DETECTION],detection:[r.AIAgentCapability.FRAUD_DETECTION],anomaly:[r.AIAgentCapability.FRAUD_DETECTION],coordination:[r.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[r.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[r.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[r.AIAgentCapability.API_INTEGRATION],integration:[r.AIAgentCapability.API_INTEGRATION],webhook:[r.AIAgentCapability.API_INTEGRATION],workflow:[r.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[r.AIAgentCapability.WORKFLOW_AUTOMATION],process:[r.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([Je(it(r.AIAgentCapability)),Je(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([Je(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(Xe()).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:Je(Ye({amount:Ve().positive(),tokenId:We()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Je(We()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Qe().optional().describe("Whether to set as current agent (default: true)"),persistence:Ye({prefix:We().optional()}).optional().describe("Optional persistence configuration")});class at extends p{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:Qe().optional().default(!1)});class dt extends p{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:Qe().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 p{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 ht=Ye({includeDetails:Qe().optional().describe("Whether to include detailed information about each connection"),showPending:Qe().optional().describe("Whether to include pending connection requests")});class pt 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=ht}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:Qe().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([Je(it(r.AIAgentCapability)),Je(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:Qe().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:Je(Ye({amount:Ve(),collectorAccount:We().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Je(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:Je(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 p{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:Je(We()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class At extends p{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:Qe().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 i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class xt extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const Ot=Ye({registryType:it(r.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(),Qe()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:et([We(),Qe()]).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 kt=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 i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class qt extends i.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)"),submitKey:et([Qe(),We()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Bt=Ye({metadata:tt(Xe()).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 Lt=Ye({registryTopicId:We().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:tt(Xe()).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 i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}async generateInscriptionQuote(e,t){this.inscriberBuilder.hederaKit.signer.getAccountId().toString(),this.inscriberBuilder.hederaKit.signer?.getOperatorPrivateKey()&&this.inscriberBuilder.hederaKit.signer.getOperatorPrivateKey().toStringRaw();const n={...t,quoteOnly:!0,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"},i=await this.inscriberBuilder.inscribe(e,n);if(!i.quote||i.confirmed)throw new Error("Failed to generate quote - unexpected response type");return i.result}}class Kt extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder,this.contentResolver=e.contentResolver||null}getServiceBuilder(){return this.inscriberBuilder}getContentResolver(){return this.contentResolver}async generateInscriptionQuote(e,t){this.inscriberBuilder.hederaKit.signer.getAccountId().toString(),this.inscriberBuilder.hederaKit.signer?.getOperatorPrivateKey()&&this.inscriberBuilder.hederaKit.signer.getOperatorPrivateKey().toStringRaw();const n={...t,quoteOnly:!0,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"},i=await this.inscriberBuilder.inscribe(e,n);if(!i.quote||i.confirmed)throw new Error("Failed to generate quote - unexpected response type");return i.result}}const Ht=Ye({url:We().url().describe("ONLY direct file download URLs with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or when you already have content to inscribe."),mode:nt(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:tt(Xe()).optional().describe("Metadata to attach to the inscription"),tags:Je(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Qe().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"),quoteOnly:Qe().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});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(Xe()).optional().describe("Metadata to attach to the inscription"),tags:Je(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Qe().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"),quoteOnly:Qe().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const Zt={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function Gt(){return{maxInscriptionSize:parseInt(t.env.REF_MAX_SIZE||Zt.maxInscriptionSize.toString(),10),minContentSize:parseInt(t.env.REF_MIN_SIZE||Zt.minContentSize.toString(),10),logLevel:t.env.REF_LOG_LEVEL||Zt.logLevel,enableContentValidation:"false"!==t.env.REF_ENABLE_VALIDATION}}const Wt=Ye({base64Data:We().min(1,"Data cannot be empty").describe('The content to inscribe. Accept BOTH plain text AND base64. Also accepts content reference IDs in format "content-ref:[id]". When user says "inscribe it" or "inscribe the content", use the EXACT content from your previous message or from MCP tool results. DO NOT generate new content. DO NOT create repetitive text. Pass the actual search results or other retrieved content EXACTLY as you received it.'),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(Xe()).optional().describe("Metadata to attach to the inscription"),tags:Je(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Qe().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"),quoteOnly:Qe().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const Vt=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:Je(Ye({trait_type:We(),value:et([We(),Ve()])})).optional().describe("NFT attributes"),properties:tt(Xe()).optional().describe("Additional properties"),jsonFileURL:We().url().optional().describe("URL to JSON metadata file"),tags:Je(We()).optional().describe("Tags to categorize the NFT"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Qe().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"),quoteOnly:Qe().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const Qt=Ye({transactionId:We().describe("The transaction ID of the inscription to retrieve"),apiKey:We().optional().describe("API key for inscription service")});const Xt=o.join(t.cwd(),".env");class Jt{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const n=e?.disableLogging||"true"===t.env.DISABLE_LOGGING;this.logger=new r.Logger({module:"OpenConvaiState",silent:n}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new r.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const 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,n){if(n?.type&&"env-file"!==n.type)throw new Error(`Unsupported persistence type: ${n.type}. Only 'env-file' is supported.`);const i=n?.envFilePath||this.defaultEnvFilePath||t.env.ENV_FILE_PATH||".env",r=n?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const o={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(o[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(o[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";s.existsSync(e)&&(n=s.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}`)}s.writeFileSync(e,i.join("\n"))}(i,o)}}function Yt(e,t){return function(){return e.apply(t,arguments)}}const{toString:en}=Object.prototype,{getPrototypeOf:tn}=Object,{iterator:nn,toStringTag:rn}=Symbol,sn=(e=>t=>{const n=en.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),on=e=>(e=e.toLowerCase(),t=>sn(t)===e),an=e=>t=>typeof t===e,{isArray:cn}=Array,dn=an("undefined");function ln(e){return null!==e&&!dn(e)&&null!==e.constructor&&!dn(e.constructor)&&pn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const un=on("ArrayBuffer");const hn=an("string"),pn=an("function"),gn=an("number"),fn=e=>null!==e&&"object"==typeof e,mn=e=>{if("object"!==sn(e))return!1;const t=tn(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||rn in e||nn in e)},yn=on("Date"),bn=on("File"),wn=on("Blob"),vn=on("FileList"),In=on("URLSearchParams"),[Tn,An,_n,Cn]=["ReadableStream","Request","Response","Headers"].map(on);function En(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),cn(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(ln(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 Rn(e,t){if(ln(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 Sn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:a,xn=e=>!dn(e)&&e!==Sn;const On=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&tn(Uint8Array)),Nn=on("HTMLFormElement"),kn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),$n=on("RegExp"),Pn=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};En(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const Mn=on("AsyncFunction"),Fn=(qn="function"==typeof c.setImmediate,Dn=pn(Sn.postMessage),qn?c.setImmediate:Dn?(Bn=`axios@${Math.random()}`,Ln=[],Sn.addEventListener("message",({source:e,data:t})=>{e===Sn&&t===Bn&&Ln.length&&Ln.shift()()},!1),e=>{Ln.push(e),Sn.postMessage(Bn,"*")}):e=>setTimeout(e));var qn,Dn,Bn,Ln;const Un="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Sn):void 0!==t&&t.nextTick||Fn,jn={isArray:cn,isArrayBuffer:un,isBuffer:ln,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||pn(e.append)&&("formdata"===(t=sn(e))||"object"===t&&pn(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&un(e.buffer),t},isString:hn,isNumber:gn,isBoolean:e=>!0===e||!1===e,isObject:fn,isPlainObject:mn,isEmptyObject:e=>{if(!fn(e)||ln(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Tn,isRequest:An,isResponse:_n,isHeaders:Cn,isUndefined:dn,isDate:yn,isFile:bn,isBlob:wn,isRegExp:$n,isFunction:pn,isStream:e=>fn(e)&&pn(e.pipe),isURLSearchParams:In,isTypedArray:On,isFileList:vn,forEach:En,merge:function e(){const{caseless:t}=xn(this)&&this||{},n={},i=(i,r)=>{const s=t&&Rn(n,r)||r;mn(n[s])&&mn(i)?n[s]=e(n[s],i):mn(i)?n[s]=e({},i):cn(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&En(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(En(t,(t,i)=>{n&&pn(t)?e[i]=Yt(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&&tn(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:sn,kindOfTest:on,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(cn(e))return e;let t=e.length;if(!gn(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[nn]).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:Nn,hasOwnProperty:kn,hasOwnProp:kn,reduceDescriptors:Pn,freezeMethods:e=>{Pn(e,(t,n)=>{if(pn(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];pn(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 cn(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:Rn,global:Sn,isContextDefined:xn,isSpecCompliantForm:function(e){return!!(e&&pn(e.append)&&"FormData"===e[rn]&&e[nn])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(fn(e)){if(t.indexOf(e)>=0)return;if(ln(e))return e;if(!("toJSON"in e)){t[i]=e;const r=cn(e)?[]:{};return En(e,(e,t)=>{const s=n(e,i+1);!dn(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:Mn,isThenable:e=>e&&(fn(e)||pn(e))&&pn(e.then)&&pn(e.catch),setImmediate:Fn,asap:Un,isIterable:e=>null!=e&&pn(e[nn])};function Kn(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)}jn.inherits(Kn,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:jn.toJSONObject(this.config),code:this.code,status:this.status}}});const Hn=Kn.prototype,zn={};["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=>{zn[e]={value:e}}),Object.defineProperties(Kn,zn),Object.defineProperty(Hn,"isAxiosError",{value:!0}),Kn.from=(e,t,n,i,r,s)=>{const o=Object.create(Hn);return jn.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Kn.call(o,e.message,t,n,i,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function Zn(e){return jn.isPlainObject(e)||jn.isArray(e)}function Gn(e){return jn.endsWith(e,"[]")?e.slice(0,-2):e}function Wn(e,t,n){return e?e.concat(t).map(function(e,t){return e=Gn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Vn=jn.toFlatObject(jn,{},null,function(e){return/^is[A-Z]/.test(e)});function Qn(e,t,i){if(!jn.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const r=(i=jn.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!jn.isUndefined(t[e])})).metaTokens,s=i.visitor||l,o=i.dots,a=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&jn.isSpecCompliantForm(t);if(!jn.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(jn.isDate(e))return e.toISOString();if(jn.isBoolean(e))return e.toString();if(!c&&jn.isBlob(e))throw new Kn("Blob is not supported. Use a Buffer instead.");return jn.isArrayBuffer(e)||jn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):n.Buffer.from(e):e}function l(e,n,i){let s=e;if(e&&!i&&"object"==typeof e)if(jn.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(jn.isArray(e)&&function(e){return jn.isArray(e)&&!e.some(Zn)}(e)||(jn.isFileList(e)||jn.endsWith(n,"[]"))&&(s=jn.toArray(e)))return n=Gn(n),s.forEach(function(e,i){!jn.isUndefined(e)&&null!==e&&t.append(!0===a?Wn([n],i,o):null===a?n:n+"[]",d(e))}),!1;return!!Zn(e)||(t.append(Wn(i,n,o),d(e)),!1)}const u=[],h=Object.assign(Vn,{defaultVisitor:l,convertValue:d,isVisitable:Zn});if(!jn.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!jn.isUndefined(n)){if(-1!==u.indexOf(n))throw Error("Circular reference detected in "+i.join("."));u.push(n),jn.forEach(n,function(n,r){!0===(!(jn.isUndefined(n)||null===n)&&s.call(t,n,jn.isString(r)?r.trim():r,i,h))&&e(n,i?i.concat(r):[r])}),u.pop()}}(e),t}function Xn(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&&Qn(e,this,t)}const Yn=Jn.prototype;function ei(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ti(e,t,n){if(!t)return e;const i=n&&n.encode||ei;jn.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):jn.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}Yn.append=function(e,t){this._pairs.push([e,t])},Yn.toString=function(e){const t=e?function(t){return e.call(this,t,Xn)}:Xn;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class ni{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){jn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const ii={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},ri={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"]},si="undefined"!=typeof window&&"undefined"!=typeof document,oi="object"==typeof navigator&&navigator||void 0,ai=si&&(!oi||["ReactNative","NativeScript","NS"].indexOf(oi.product)<0),ci="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,di=si&&window.location.href||"http://localhost",li={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:si,hasStandardBrowserEnv:ai,hasStandardBrowserWebWorkerEnv:ci,navigator:oi,origin:di},Symbol.toStringTag,{value:"Module"})),...ri};function ui(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&&jn.isArray(i)?i.length:s,a)return jn.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!o;i[s]&&jn.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&jn.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(jn.isFormData(e)&&jn.isFunction(e.entries)){const n={};return jn.forEachEntry(e,(e,i)=>{t(function(e){return jn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const hi={transitional:ii,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=jn.isObject(e);r&&jn.isHTMLForm(e)&&(e=new FormData(e));if(jn.isFormData(e))return i?JSON.stringify(ui(e)):e;if(jn.isArrayBuffer(e)||jn.isBuffer(e)||jn.isStream(e)||jn.isFile(e)||jn.isBlob(e)||jn.isReadableStream(e))return e;if(jn.isArrayBufferView(e))return e.buffer;if(jn.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 Qn(e,new li.classes.URLSearchParams,{visitor:function(e,t,n,i){return li.isNode&&jn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=jn.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Qn(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(jn.isString(e))try{return(t||JSON.parse)(e),jn.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||hi.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(jn.isResponse(e)||jn.isReadableStream(e))return e;if(e&&jn.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 Kn.from(r,Kn.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:li.classes.FormData,Blob:li.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};jn.forEach(["delete","get","head","post","put","patch"],e=>{hi.headers[e]={}});const pi=jn.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"]),gi=Symbol("internals");function fi(e){return e&&String(e).trim().toLowerCase()}function mi(e){return!1===e||null==e?e:jn.isArray(e)?e.map(mi):String(e)}function yi(e,t,n,i,r){return jn.isFunction(i)?i.call(this,t,n):(r&&(t=n),jn.isString(t)?jn.isString(i)?-1!==t.indexOf(i):jn.isRegExp(i)?i.test(t):void 0:void 0)}let bi=class{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=fi(t);if(!r)throw new Error("header name must be a non-empty string");const s=jn.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=mi(e))}const s=(e,t)=>jn.forEach(e,(e,n)=>r(e,n,t));if(jn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(jn.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]&&pi[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(jn.isObject(e)&&jn.isIterable(e)){let n,i,r={};for(const t of e){if(!jn.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?jn.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=fi(e)){const n=jn.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(jn.isFunction(t))return t.call(this,e,n);if(jn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=fi(e)){const n=jn.findKey(this,e);return!(!n||void 0===this[n]||t&&!yi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=fi(e)){const r=jn.findKey(n,e);!r||t&&!yi(0,n[r],r,t)||(delete n[r],i=!0)}}return jn.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&&!yi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return jn.forEach(this,(i,r)=>{const s=jn.findKey(n,r);if(s)return t[s]=mi(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]=mi(i),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return jn.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&jn.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[gi]=this[gi]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=fi(e);t[i]||(!function(e,t){const n=jn.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 jn.isArray(e)?e.forEach(i):i(e),this}};function wi(e,t){const n=this||hi,i=t||n,r=bi.from(i.headers);let s=i.data;return jn.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function vi(e){return!(!e||!e.__CANCEL__)}function Ii(e,t,n){Kn.call(this,null==e?"canceled":e,Kn.ERR_CANCELED,t,n),this.name="CanceledError"}function Ti(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Kn("Request failed with status code "+n.status,[Kn.ERR_BAD_REQUEST,Kn.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}bi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),jn.reduceDescriptors(bi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),jn.freezeMethods(bi),jn.inherits(Ii,Kn,{__CANCEL__:!0});const Ai=(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 h=d&&c-d;return h?Math.round(1e3*u/h):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)},_i=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Ci=e=>(...t)=>jn.asap(()=>e(...t)),Ei=li.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,li.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(li.origin),li.navigator&&/(msie|trident)/i.test(li.navigator.userAgent)):()=>!0,Ri=li.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const o=[e+"="+encodeURIComponent(t)];jn.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),jn.isString(i)&&o.push("path="+i),jn.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 Si(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 xi=e=>e instanceof bi?{...e}:e;function Oi(e,t){t=t||{};const n={};function i(e,t,n,i){return jn.isPlainObject(e)&&jn.isPlainObject(t)?jn.merge.call({caseless:i},e,t):jn.isPlainObject(t)?jn.merge({},t):jn.isArray(t)?t.slice():t}function r(e,t,n,r){return jn.isUndefined(t)?jn.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!jn.isUndefined(t))return i(void 0,t)}function o(e,t){return jn.isUndefined(t)?jn.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(xi(e),xi(t),0,!0)};return jn.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,o=s(e[i],t[i],i);jn.isUndefined(o)&&s!==a||(n[i]=o)}),n}const Ni=e=>{const t=Oi({},e);let n,{data:i,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=bi.from(a),t.url=ti(Si(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),jn.isFormData(i))if(li.hasStandardBrowserEnv||li.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(li.hasStandardBrowserEnv&&(r&&jn.isFunction(r)&&(r=r(t)),r||!1!==r&&Ei(t.url))){const e=s&&o&&Ri.read(o);e&&a.set(s,e)}return t},ki="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=Ni(e);let r=i.data;const s=bi.from(i.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=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=bi.from("getAllResponseHeaders"in f&&f.getAllResponseHeaders());Ti(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 Kn("Request aborted",Kn.ECONNABORTED,e,f)),f=null)},f.onerror=function(){n(new Kn("Network Error",Kn.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||ii;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new Kn(t,r.clarifyTimeoutError?Kn.ETIMEDOUT:Kn.ECONNABORTED,e,f)),f=null},void 0===r&&s.setContentType(null),"setRequestHeader"in f&&jn.forEach(s.toJSON(),function(e,t){f.setRequestHeader(t,e)}),jn.isUndefined(i.withCredentials)||(f.withCredentials=!!i.withCredentials),u&&"json"!==u&&(f.responseType=i.responseType),p&&([c,l]=Ai(p,!0),f.addEventListener("progress",c)),h&&f.upload&&([a,d]=Ai(h),f.upload.addEventListener("progress",a),f.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(o=t=>{f&&(n(!t||t.type?new Ii(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===li.protocols.indexOf(y)?n(new Kn("Unsupported protocol "+y+":",Kn.ERR_BAD_REQUEST,e)):f.send(r||null)})},$i=(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 Kn?t:new Ii(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new Kn(`timeout ${t} of ms exceeded`,Kn.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=()=>jn.asap(o),a}},Pi=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},Mi=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()}},Fi=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of Mi(e))yield*Pi(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})},qi="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Di=qi&&"function"==typeof ReadableStream,Bi=qi&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Li=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},Ui=Di&&Li(()=>{let e=!1;const t=new Request(li.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),ji=Di&&Li(()=>jn.isReadableStream(new Response("").body)),Ki={stream:ji&&(e=>e.body)};var Hi;qi&&(Hi=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ki[e]&&(Ki[e]=jn.isFunction(Hi[e])?t=>t[e]():(t,n)=>{throw new Kn(`Response type '${e}' is not supported`,Kn.ERR_NOT_SUPPORT,n)})}));const zi=async(e,t)=>{const n=jn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(jn.isBlob(e))return e.size;if(jn.isSpecCompliantForm(e)){const t=new Request(li.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return jn.isArrayBufferView(e)||jn.isArrayBuffer(e)?e.byteLength:(jn.isURLSearchParams(e)&&(e+=""),jn.isString(e)?(await Bi(e)).byteLength:void 0)})(t):n},Zi={http:null,xhr:ki,fetch:qi&&(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:h}=Ni(e);d=d?(d+"").toLowerCase():"text";let p,g=$i([r,s&&s.toAbortSignal()],o);const f=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let m;try{if(c&&Ui&&"get"!==n&&"head"!==n&&0!==(m=await zi(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(jn.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=_i(m,Ai(Ci(c)));i=Fi(n.body,65536,e,t)}}jn.isString(u)||(u=u?"include":"omit");const r="credentials"in Request.prototype;p=new Request(t,{...h,signal:g,method:n.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:r?u:void 0});let s=await fetch(p,h);const o=ji&&("stream"===d||"response"===d);if(ji&&(a||o&&f)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=jn.toFiniteNumber(s.headers.get("content-length")),[n,i]=a&&_i(t,Ai(Ci(a),!0))||[];s=new Response(Fi(s.body,65536,n,()=>{i&&i(),f&&f()}),e)}d=d||"text";let y=await Ki[jn.findKey(Ki,d)||"text"](s,e);return!o&&f&&f(),await new Promise((t,n)=>{Ti(t,n,{data:y,headers:bi.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:p})})}catch(y){if(f&&f(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new Kn("Network Error",Kn.ERR_NETWORK,e,p),{cause:y.cause||y});throw Kn.from(y,y&&y.code,e,p)}})};jn.forEach(Zi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Gi=e=>`- ${e}`,Wi=e=>jn.isFunction(e)||null===e||!1===e,Vi=e=>{e=jn.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,!Wi(n)&&(i=Zi[(t=String(n)).toLowerCase()],void 0===i))throw new Kn(`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 Kn("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Gi).join("\n"):" "+Gi(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Qi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ii(null,e)}function Xi(e){Qi(e),e.headers=bi.from(e.headers),e.data=wi.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Vi(e.adapter||hi.adapter)(e).then(function(t){return Qi(e),t.data=wi.call(e,e.transformResponse,t),t.headers=bi.from(t.headers),t},function(t){return vi(t)||(Qi(e),t&&t.response&&(t.response.data=wi.call(e,e.transformResponse,t.response),t.response.headers=bi.from(t.response.headers))),Promise.reject(t)})}const Ji="1.11.0",Yi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Yi[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const er={};Yi.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 Kn(i(r," has been removed"+(t?" in "+t:"")),Kn.ERR_DEPRECATED);return t&&!er[r]&&(er[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)}},Yi.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const tr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Kn("options must be an object",Kn.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 Kn("option "+s+" must be "+n,Kn.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Kn("Unknown option "+s,Kn.ERR_BAD_OPTION)}},validators:Yi},nr=tr.validators;let ir=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ni,response:new ni}}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=Oi(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&tr.assertOptions(n,{silentJSONParsing:nr.transitional(nr.boolean),forcedJSONParsing:nr.transitional(nr.boolean),clarifyTimeoutError:nr.transitional(nr.boolean)},!1),null!=i&&(jn.isFunction(i)?t.paramsSerializer={serialize:i}:tr.assertOptions(i,{encode:nr.function,serialize:nr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),tr.assertOptions(t,{baseUrl:nr.spelling("baseURL"),withXsrfToken:nr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&jn.merge(r.common,r[t.method]);r&&jn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=bi.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=[Xi.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 h=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{h=e(h)}catch(p){t.call(this,p);break}}try{d=Xi.call(this,h)}catch(p){return Promise.reject(p)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return ti(Si((e=Oi(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};jn.forEach(["delete","get","head","options"],function(e){ir.prototype[e]=function(t,n){return this.request(Oi(n||{},{method:e,url:t,data:(n||{}).data}))}}),jn.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Oi(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}ir.prototype[e]=t(),ir.prototype[e+"Form"]=t(!0)});const rr={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(rr).forEach(([e,t])=>{rr[t]=e});const sr=function e(t){const n=new ir(t),i=Yt(ir.prototype.request,n);return jn.extend(i,ir.prototype,n,{allOwnKeys:!0}),jn.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Oi(t,n))},i}(hi);sr.Axios=ir,sr.CanceledError=Ii,sr.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 Ii(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}}},sr.isCancel=vi,sr.VERSION=Ji,sr.toFormData=Qn,sr.AxiosError=Kn,sr.Cancel=sr.CanceledError,sr.all=function(e){return Promise.all(e)},sr.spread=function(e){return function(t){return e.apply(null,t)}},sr.isAxiosError=function(e){return jn.isObject(e)&&!0===e.isAxiosError},sr.mergeConfig=Oi,sr.AxiosHeaders=bi,sr.formToJSON=e=>ui(jn.isHTMLForm(e)?new FormData(e):e),sr.getAdapter=Vi,sr.HttpStatusCode=rr,sr.default=sr;const{Axios:or,AxiosError:ar,CanceledError:cr,isCancel:dr,CancelToken:lr,VERSION:ur,all:hr,Cancel:pr,isAxiosError:gr,spread:fr,toFormData:mr,AxiosHeaders:yr,HttpStatusCode:br,formToJSON:wr,getAdapter:vr,mergeConfig:Ir}=sr,Tr="ConnectionsManager not initialized";class Ar extends i.BaseServiceBuilder{constructor(e,t,n){super(e),this.useEncryption=!1,this.guardedRegistryBaseUrl="",this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const s=this.hederaKit.signer.getAccountId().toString(),o=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new r.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new r.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:o,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 t=await sr.get(e,{responseType:"arraybuffer"}),i=n.Buffer.from(t.data),r=new URL(e).pathname;return{buffer:i,filename:o.basename(r)||"profile.png"}}{if(!s.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=s.readFileSync(e);return{buffer:t,filename:o.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const t=await sr.get(e.url,{responseType:"arraybuffer"}),i=n.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!s.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=s.readFileSync(e.path);return{buffer:t,filename:e.filename||o.basename(e.path)}}return null}catch(t){return this.logger.error("Failed to load profile picture:",t),null}}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?t.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let t=null;e.profilePicture&&(t=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==t?.buffer&&{pfpBuffer:t.buffer},...void 0!==t?.filename&&{pfpFileName:t.filename}};if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,i,s)}const i=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.state?.agentMetadata?.accountId}}}catch(t){throw this.logger.error("Failed to register agent:",t),t}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const n=t.topicInfo.inboundTopic;let 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 i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(Tr);await i.fetchConnectionData(n.accountId);const s=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const o=s.targetAccountId,a=s.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,i)}const d=await this.getInboundTopicId(),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 r={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:u,status:"established",created:new Date};this.stateManager.addActiveConnection(r),i.markConnectionRequestProcessed(s.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId: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:i=120,hbarFees:s=[],tokenFees:o=[],exemptAccountIds:a=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const d=await this.getInboundTopicId(),l=Date.now()+1e3*i;let u=0,h=0;const p=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 i of e){const e=i.sequence_number;if(!e||p.has(e))continue;const l=i.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 r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,a)}for(const t of o){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,a)}t=e}await this.handleConnectionRequest(d,l,e,t),p.add(e),h++}}}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:h,monitorDurationSeconds:i,processedRequestIds:Array.from(p)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${h}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(Tr);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(Tr),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 _r extends i.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 i.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}class Cr extends i.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 r.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 Er extends i.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().toString():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:t};this.hcs6Client=new r.HCS6Client(n)}return this.hcs6Client}async createRegistry(e={}){const t=await this.getHCS6Client(),n={...e};return"adminKey"in n&&delete n.adminKey,await t.createRegistry(n)}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(),n={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal metadata",type:e.metadata?.type||"json",...e.metadata};return await t.createHashinal({...e,metadata:n})}async register(e){const t=await this.getHCS6Client(),n={name:e.metadata?.name||"Dynamic Hashinal",creator:e.metadata?.creator||this.hederaKit.signer.getAccountId().toString(),description:e.metadata?.description||"Dynamic hashinal registration",type:e.metadata?.type||"json",...e.metadata};return await t.register({...e,metadata:n})}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 Rr extends i.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 r.inscribe(e,n,t)}async inscribeWithSigner(e,t,n){return await r.inscribeWithSigner(e,t,n)}async retrieveInscription(e,t){const n=this.hederaKit.signer.getAccountId().toString(),i=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";return await r.retrieveInscription(e,{...t,accountId:n,privateKey:i})}async close(){this.inscriptionSDK=void 0}}Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>i.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>i.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>i.PluginRegistry}),e.AcceptConnectionRequestTool=At,e.BaseHCS10QueryTool=g,e.BaseHCS10TransactionTool=p,e.BaseHCS2QueryTool=xt,e.BaseHCS2TransactionTool=St,e.BaseHCS6QueryTool=qt,e.BaseHCS6TransactionTool=Ft,e.BaseInscriberQueryTool=Kt,e.BaseInscriberTransactionTool=jt,e.CheckMessagesTool=ft,e.ConnectionMonitorTool=wt,e.CreateDynamicRegistryTool=class extends qt{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return Dt}async executeQuery(e,t){const n=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!n.success)throw new Error(n.error||"Failed to create dynamic registry");return`Successfully created HCS-6 dynamic registry!\n\nTopic ID: ${n.topicId}\nTTL: ${e.ttl} seconds\n\nYou can now register dynamic hashinals to this registry using the topic ID.`}},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 Ot}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=Ar,e.HCS10Client=class{constructor(e,n,i,s){this.standardClient=new r.HCS10Client({network:i,operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:s?.registryUrl,logLevel:s?.logLevel}),this.guardedRegistryBaseUrl=s?.registryUrl||"",this.useEncryption=s?.useEncryption||!1;const o="true"===t.env.DISABLE_LOGGING;this.logger=new r.Logger({level:s?.logLevel||"info",silent:o})}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 r.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),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 r.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HCS2Builder=Cr,e.HCS6Builder=Er,e.HbarPricePlugin=_r,e.InitiateConnectionTool=ut,e.InscribeFromBufferTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Inscribe content that you have already retrieved or displayed. When user says "inscribe it" after you showed search results or other content, use THIS tool. The base64Data field accepts PLAIN TEXT (not just base64) and content reference IDs in format "content-ref:[id]". Pass the EXACT content from your previous response or MCP tool output. DO NOT generate new content or create repetitive text. Content references are automatically resolved to the original content for inscription. Set quoteOnly=true to get cost estimates without executing the inscription.',this.config=Gt()}get specificInputSchema(){return Wt}async executeQuery(e,t){this.validateInput(e);const n=await this.resolveContent(e.base64Data,e.mimeType,e.fileName);this.validateContent(n.buffer);const i=n.buffer,r=n.mimeType||e.mimeType,s=n.fileName||e.fileName,o={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const e=await this.generateInscriptionQuote({type:"buffer",buffer:i,fileName:s,mimeType:r},o);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:s,mimeType:r,sizeBytes:i.length},message:`Quote generated for buffer content: ${s} (${(i.length/1024).toFixed(2)} KB)\nTotal cost: ${e.totalCostHbar} HBAR`}}catch(c){const e=c instanceof Error?c.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}const a=e.timeoutMs||(o.waitForConfirmation?6e4:void 0);try{const e=await this.executeInscription(i,s,r,o,a);return this.formatInscriptionResult(e,o)}catch(c){const e=c instanceof Error?c.message:"Failed to inscribe from buffer";throw new Error(`Inscription failed: ${e}`)}}validateInput(e){if(!e.base64Data||""===e.base64Data.trim())throw new Error("No data provided. Cannot inscribe empty content. Please provide valid content, plain text, base64 encoded data, or a content reference ID.");if(!e.fileName||""===e.fileName.trim())throw new Error("No fileName provided. A valid fileName is required for inscription.")}validateContent(e){if(0===e.length)throw new Error("Buffer is empty after conversion. The provided data appears to be invalid or empty.");if(e.length>this.config.maxInscriptionSize){const t=Math.round(this.config.maxInscriptionSize/1024),n=Math.round(e.length/1024);throw new Error(`Content is too large for inscription (${n}KB, max ${t}KB). Please summarize or extract key information before inscribing.`)}if(e.length<this.config.minContentSize)throw new Error(`Buffer content is too small (${e.length} bytes). This may indicate empty or invalid content. Please verify the source data contains actual content.`);if(""===e.toString("utf8",0,Math.min(e.length,100)).trim())throw new Error("Buffer contains only whitespace or empty content. Cannot inscribe meaningless data.");const t=e.toString("utf8");if(/<a\s+href=["'][^"']+["']\s*>\s*<\/a>/i.test(t)&&t.replace(/<[^>]+>/g,"").trim().length<50)throw new Error("Buffer contains empty HTML with only links and no actual content. When inscribing content from external sources, use the actual article text you retrieved, not empty HTML with links.")}async executeInscription(e,t,n,i,r){const s={type:"buffer",buffer:e,fileName:t,mimeType:n};if(r){const e=new Promise((e,t)=>{setTimeout(()=>t(new Error(`Inscription timed out after ${r}ms`)),r)});return Promise.race([this.inscriberBuilder.inscribe(s,i),e])}return this.inscriberBuilder.inscribe(s,i)}formatInscriptionResult(e,t){if(e.confirmed&&!e.quote){const n=e.inscription?.topic_id||e.result.topicId,i=t.network||"testnet",r=n?`https://kiloscribe.com/api/inscription-cdn/${n}?network=${i}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\nTopic ID: ${n||"N/A"}${r?`\nView inscription: ${r}`:""}\n\nThe inscription is now available.`}return e.quote||e.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${e.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}async resolveContent(e,t,n){const i=e.trim(),s=this.getContentResolver()||r.ContentResolverRegistry.getResolver();if(!s)return this.handleDirectContent(i,t,n);const o=s.extractReferenceId(i);if(o)try{const e=await s.resolveReference(o);return{buffer:e.content,mimeType:e.metadata?.mimeType||t,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(a){const e=a instanceof Error?a.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return this.handleDirectContent(i,t,n)}handleDirectContent(e,t,i){if(/^[A-Za-z0-9+/]*={0,2}$/.test(e))try{return{buffer:n.Buffer.from(e,"base64"),mimeType:t,fileName:i,wasReference:!1}}catch(r){throw new Error("Failed to decode base64 data. Please ensure the data is properly encoded.")}return{buffer:n.Buffer.from(e,"utf8"),mimeType:t||"text/plain",fileName:i,wasReference:!1}}},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. Set quoteOnly=true to get cost estimates without executing the inscription."}get specificInputSchema(){return zt}async executeQuery(e,i){let r;console.log(`[DEBUG] InscribeFromFileTool.executeQuery called with: ${e.filePath}`);try{console.log(`[DEBUG] Checking file: ${e.filePath}`),console.log(`[DEBUG] Current working directory: ${t.cwd()}`);const n=await h.stat(e.filePath);if(!n.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(console.log(`[DEBUG] File size: ${n.size} bytes`),0===n.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(n.size<10)throw new Error(`File "${e.filePath}" is too small (${n.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(n.size>104857600&&console.log(`[InscribeFromFileTool] WARNING: Large file detected (${(n.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),r=await h.readFile(e.filePath),this.logger?.info(`Read ${r.length} bytes from file`),!r||0===r.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(r.length<10)throw new Error(`File "${e.filePath}" content is too small (${r.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const i=u.basename(e.filePath),s=this.getMimeType(i);if(s.startsWith("text/")||"application/json"===s){if(""===r.toString("utf8",0,Math.min(r.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 s=r.toString("base64");this.logger?.info(`Converted to base64: ${s.length} characters`);const o=u.basename(e.filePath),a=this.getMimeType(o);this.logger?.info(`File: ${o}, MIME type: ${a}`);const c={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"buffer",buffer:n.Buffer.from(s,"base64"),fileName:o,mimeType:a},c);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{fileName:o,mimeType:a,sizeBytes:r.length,filePath:e.filePath},message:`Quote generated for file: ${o} (${(r.length/1024).toFixed(2)} KB)\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(d){const e=d instanceof Error?d.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}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:"buffer",buffer:n.Buffer.from(s,"base64"),fileName:o,mimeType:a},c),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:n.Buffer.from(s,"base64"),fileName:o,mimeType:a},c);const i=t;if(i.confirmed&&!i.quote){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${c.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 i.quote||i.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${i.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='ONLY for direct FILE DOWNLOAD URLs ending with file extensions (.pdf, .jpg, .png, .json, .zip). NEVER use for web pages, articles, or ANY HTML content - it WILL FAIL. If you have already retrieved content from any source (including MCP tools), you MUST use inscribeFromBuffer instead. This tool downloads files from URLs - it does NOT inscribe content you already have. When asked to "inscribe it" after retrieving content, ALWAYS use inscribeFromBuffer with the actual content. Set quoteOnly=true to get cost estimates without executing the inscription.'}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){if(i instanceof Error&&i.message.includes("Cannot inscribe content from"))throw 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.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"url",url:e.url},n);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{url:e.url},message:`Quote generated for URL: ${e.url}\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(i){const e=i instanceof Error?i.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}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&&!t.quote){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 t.quote||t.confirmed?"Inscription operation completed.":`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. Set quoteOnly=true to get cost estimates without executing the inscription."}get specificInputSchema(){return Vt}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.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"url",url:e.url},n);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{url:e.url,name:e.name,creator:e.creator,type:e.type},message:`Quote generated for Hashinal NFT: ${e.name}\nCreator: ${e.creator}\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(i){const e=i instanceof Error?i.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}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&&!t.quote){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 t.quote||t.confirmed?"Inscription operation completed.":`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=Rr,e.ListConnectionsTool=pt,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 qt{constructor(e){super(e),this.name="queryDynamicRegistry",this.description="Query a dynamic registry to get the current state of a dynamic hashinal"}get specificInputSchema(){return Ut}async executeQuery(e,t){const n=await this.hcs6Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip}),i=n.latestEntry?{topicId:n.latestEntry.message.t_id,timestamp:n.latestEntry.timestamp,memo:n.latestEntry.message.m,sequence:n.latestEntry.sequence,payer:n.latestEntry.payer}:null;return`Successfully queried dynamic registry!\n\nRegistry Topic: ${n.topicId}\nRegistry Type: NON_INDEXED\nTTL: ${n.ttl} seconds\nTotal Entries: ${n.entries.length}${i?`\n\nLatest Entry:\n- Topic ID: ${i.topicId}\n- Timestamp: ${i.timestamp}\n- Memo: ${i.memo||"N/A"}\n- Sequence: ${i.sequence}`:"\n\nNo entries found in registry."}`}},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 qt{constructor(e){super(e),this.name="registerDynamicHashinal",this.description="Create and register a new dynamic hashinal that can be updated over time"}get specificInputSchema(){return Bt}async executeQuery(e,t){const n=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,ttl:e.ttl,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!n.success)throw new Error(n.error||"Failed to register dynamic hashinal");return`Successfully registered dynamic hashinal!\n\nRegistry Topic ID: ${n.registryTopicId}\nInscription Topic ID: ${n.inscriptionTopicId}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe dynamic hashinal has been created and can be updated using the registry topic ID.`}},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 Qt}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 qt{constructor(e){super(e),this.name="updateDynamicHashinal",this.description="Update an existing dynamic hashinal with new content while maintaining the same registry"}get specificInputSchema(){return Lt}async executeQuery(e,t){const n=await this.hcs6Builder.register({metadata:e.metadata,data:e.data,memo:e.memo,registryTopicId:e.registryTopicId,submitKey:e.submitKey});if(!n.success)throw new Error(n.error||"Failed to update dynamic hashinal");return`Successfully updated dynamic hashinal!\n\nRegistry Topic ID: ${e.registryTopicId}\nInscription Topic ID: ${n.inscriptionTopicId}${e.memo?`\nUpdate Memo: ${e.memo}`:""}\n\nThe dynamic hashinal has been updated with new content.`}},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 kt}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 n=e?.clientConfig||{},s=n.operatorId||t.env.HEDERA_OPERATOR_ID,o=n.operatorKey||t.env.HEDERA_OPERATOR_KEY,a=n.network||t.env.HEDERA_NETWORK||"testnet";let c;if("mainnet"===a?c="mainnet":("testnet"===a||console.warn(`Unsupported network specified: '${a}'. Defaulting to 'testnet'.`),c="testnet"),!s||!o)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const d="true"===t.env.DISABLE_LOGGING,l=r.Logger.getInstance({level:n.logLevel||"info",silent:d}),u=e?.stateManager||new Jt({defaultEnvFilePath:Xt,defaultPrefix:"TODD"});l.info("State manager initialized");const h=new i.ServerSigner(s,o,c),p=new i.HederaAgentKit(h);await p.initialize(),l.info(`HederaAgentKit initialized for ${s} on ${c}`);const g=new Ar(p,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let f,m;if(e?.monitoringClient){const e=new i.ServerSigner(s,o,c);f=new i.HederaAgentKit(e),await f.initialize(),m=new Ar(f,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),l.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new at({hederaKit:p,hcs10Builder:g,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new yt({hederaKit:p,hcs10Builder:g,logger:void 0}),y.retrieveProfileTool=new Ct({hederaKit:p,hcs10Builder:g,logger:void 0}),y.initiateConnectionTool=new ut({hederaKit:p,hcs10Builder:g,logger:void 0}),y.listConnectionsTool=new pt({hederaKit:p,hcs10Builder:g,logger:void 0}),y.sendMessageToConnectionTool=new dt({hederaKit:p,hcs10Builder:g,logger:void 0}),y.checkMessagesTool=new ft({hederaKit:p,hcs10Builder:g,logger:void 0}),y.connectionMonitorTool=new wt({hederaKit:f||p,hcs10Builder:m||g,logger:void 0}),y.manageConnectionRequestsTool=new It({hederaKit:p,hcs10Builder:g,logger:void 0}),y.acceptConnectionRequestTool=new At({hederaKit:p,hcs10Builder:g,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new Rt({hederaKit:p,hcs10Builder:g,logger:void 0}),l.info("All tools initialized")),{hederaKit:p,hcs10Builder:g,monitoringHederaKit:f,monitoringHcs10Builder:m,tools:y,stateManager:u}},e.loadConfig=Gt,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=standards-agent-kit.umd.js.map