@hashgraphonline/standards-agent-kit 0.2.134 → 0.2.136

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 (32) hide show
  1. package/dist/cjs/interfaces/FormValidatable.d.ts +4 -13
  2. package/dist/cjs/standards-agent-kit.cjs +1 -1
  3. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  4. package/dist/cjs/tools/inscriber/InscribeHashinalTool.d.ts +1 -8
  5. package/dist/cjs/tools/inscriber/base-inscriber-tools.d.ts +19 -0
  6. package/dist/es/interfaces/FormValidatable.d.ts +4 -13
  7. package/dist/es/standards-agent-kit.es33.js +12 -0
  8. package/dist/es/standards-agent-kit.es33.js.map +1 -1
  9. package/dist/es/standards-agent-kit.es34.js +2 -2
  10. package/dist/es/standards-agent-kit.es34.js.map +1 -1
  11. package/dist/es/standards-agent-kit.es36.js +2 -2
  12. package/dist/es/standards-agent-kit.es36.js.map +1 -1
  13. package/dist/es/standards-agent-kit.es37.js +25 -26
  14. package/dist/es/standards-agent-kit.es37.js.map +1 -1
  15. package/dist/es/standards-agent-kit.es44.js +1 -1
  16. package/dist/es/standards-agent-kit.es44.js.map +1 -1
  17. package/dist/es/standards-agent-kit.es51.js +2 -2
  18. package/dist/es/standards-agent-kit.es51.js.map +1 -1
  19. package/dist/es/tools/inscriber/InscribeHashinalTool.d.ts +1 -8
  20. package/dist/es/tools/inscriber/base-inscriber-tools.d.ts +19 -0
  21. package/dist/umd/interfaces/FormValidatable.d.ts +4 -13
  22. package/dist/umd/standards-agent-kit.umd.js +1 -1
  23. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  24. package/dist/umd/tools/inscriber/InscribeHashinalTool.d.ts +1 -8
  25. package/dist/umd/tools/inscriber/base-inscriber-tools.d.ts +19 -0
  26. package/package.json +2 -2
  27. package/src/interfaces/FormValidatable.ts +9 -12
  28. package/src/tools/inscriber/InscribeFromBufferTool.ts +2 -2
  29. package/src/tools/inscriber/InscribeFromUrlTool.ts +2 -2
  30. package/src/tools/inscriber/InscribeHashinalTool.ts +43 -50
  31. package/src/tools/inscriber/base-inscriber-tools.ts +26 -0
  32. package/src/types/inscription-response.ts +2 -2
@@ -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,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),p=l(d);class h extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class f extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var g,m,y;(m=g||(g={})).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=g.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=g.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,g.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,g.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${g.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${g.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${g.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}"`:g.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,g.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}),k=e=>"aborted"===e.status,x=e=>"dirty"===e.status,N=e=>"valid"===e.status,O=e=>"undefined"!=typeof Promise&&e instanceof Promise;var $,P;(P=$||($={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},P.toString=e=>"string"==typeof e?e:e?.message;class M{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const F=(e,t)=>{if(N(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new I(e.common.issues);return this._error=t,this._error}}};function 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 N(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>N(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:w(e)},i=this._parse({data:e,path:n.path,parent:n}),r=await(O(i)?i:Promise.resolve(i));return F(n,r)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,i)=>{const r=e(t),s=()=>i.addIssue({code:v.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then(e=>!!e||(s(),!1)):!!r||(s(),!1)})}refinement(e,t){return this._refinement((n,i)=>!!e(n)||(i.addIssue("function"==typeof t?t(n,i):t),!1))}_refinement(e){return new 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 qe.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 Be({...D(this._def),innerType:this,defaultValue:t,typeName:ze.ZodDefault})}brand(){return new He({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 Ke.create(this,e)}readonly(){return Ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const q=/^c[^\s-]{8,}$/i,B=/^[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,H=/^[a-z0-9_-]{21}$/i,K=/^[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]))$/,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])$/,X=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Y=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ee="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",te=new RegExp(`^${ee}$`);function ne(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function ie(e){return new RegExp(`^${ne(e)}$`)}function re(e){let t=`${ee}T${ne(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function se(e,t){return!("v4"!==t&&t||!W.test(e))||!("v6"!==t&&t||!Q.test(e))}function oe(e,t){if(!K.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||!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)H.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)q.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)B.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cuid2",code:v.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"ulid",code:v.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),_(n,{validation:"url",code:v.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"regex",code:v.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){re(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){te.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){ie(i).test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{code:v.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?Z.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"duration",code:v.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?se(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"ip",code:v.invalid_string,message:i.message}),t.dirty()):"jwt"===i.kind?oe(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"jwt",code:v.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?ae(e.data,i.version)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"cidr",code:v.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?X.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"base64",code:v.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Y.test(e.data)||(n=this._getOrReturnCtx(e,n),_(n,{validation:"base64url",code:v.invalid_string,message:i.message}),t.dirty()):g.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)g.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()):g.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&&g.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()):g.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 pe 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)}}pe.create=e=>new pe({typeName:ze.ZodBoolean,coerce:e?.coerce||!1,...D(e)});class he 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()):g.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new he({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}he.create=e=>new he({checks:[],coerce:e?.coerce||!1,typeName:ze.ZodDate,...D(e)});class fe 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)}}fe.create=e=>new fe({typeName:ze.ZodSymbol,...D(e)});class ge 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)}}ge.create=e=>new ge({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 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]=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 qe?qe.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=g.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 g.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 g.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 g.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 g.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(g.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=g.objectKeys(t),i=g.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(k(e)||k(i))return E;const r=Ce(e.value,i.value);return r.valid?((x(e)||x(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 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,...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 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 L?{keyType:e,valueType:t,typeName:ze.ZodRecord,...D(n)}:{keyType:ce.create(),valueType:e,typeName:ze.ZodRecord,...D(t)})}}class ke 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 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}}}}ke.create=(e,t,n)=>new ke({valueType:t,keyType:e,typeName:ze.ZodMap,...D(n)});class xe 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 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 xe({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new xe({...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)}}xe.create=(e,t)=>new xe({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...D(t)});class Ne 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})}}Ne.create=(e,t)=>new Ne({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 Pe({values:e,typeName:ze.ZodEnum,...D(t)})}Oe.create=(e,t)=>new Oe({value:e,typeName:ze.ZodLiteral,...D(t)});class Pe extends L{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return _(t,{expected:g.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 L{_parse(e){const t=g.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const e=g.objectValues(t);return _(n,{expected:g.joinValues(e),received:n.parsedType,code:v.invalid_type}),E}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=g.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,...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(!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)}g.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 qe extends L{_parse(e){return this._getType(e)===b.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:ze.ZodNullable,...D(t)});class Be 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}}Be.create=(e,t)=>new Be({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 He 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 Ke 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 Ke({in:e,out:t,typeName:ze.ZodPipeline})}}class Ze extends L{_parse(e){const t=this._def.innerType._parse(e),n=e=>(N(e)&&(e.value=Object.freeze(e.value)),e);return O(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var ze,Ge;Ze.create=(e,t)=>new Ze({innerType:e,typeName:ze.ZodReadonly,...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,Qe=pe.create,Je=be.create;we.create;const Xe=Ie.create,Ye=Ae.create,et=_e.create;Ee.create,Re.create;const tt=Se.create,nt=Pe.create,it=Me.create;Fe.create,Le.create,qe.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([Xe(it(r.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Agent capabilities - can be capability names (e.g. "ai", "data processing"), capability enum values, or array of either. Common values: "ai"/"text" (TEXT_GENERATION), "data" (DATA_INTEGRATION), "analytics" (TRANSACTION_ANALYTICS)'),tags:et([Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):st.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:We().optional().describe("Creator attribution for the agent"),socials:tt(nt(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),We()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:tt(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:Xe(Ye({amount:Ve().positive(),tokenId:We()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Xe(We()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Qe().optional().describe("Whether to set as current agent (default: true)"),persistence:Ye({prefix:We().optional()}).optional().describe("Optional persistence configuration")});class at extends h{constructor(e){super(e),this.name="register_agent",this.description='Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Supports natural language for capabilities/tags like "ai", "data processing", "analytics". Note: This tool requires multiple transactions and cannot be used in returnBytes mode. If alias is set to "random" or contains "random", a unique alias will be generated.',this.specificInputSchema=ot,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;this.specificArgs=t;const i={name:t.name};if(void 0!==t.description&&(i.bio=t.description),void 0!==t.alias)i.alias=t.alias;else{const e=Date.now().toString(36);i.alias=`${t.name}${e}`}if(void 0!==t.type&&(i.type=t.type),void 0!==t.model&&(i.model=t.model),void 0!==t.tags?i.capabilities=t.tags:void 0!==t.capabilities&&(i.capabilities=t.capabilities),void 0!==t.creator&&(i.creator=t.creator),void 0!==t.socials&&(i.socials=t.socials),void 0!==t.properties&&(i.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)i.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),i.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(i.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(i.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(i.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(i.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(i.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(i.initialBalance=t.initialBalance),await n.registerAgent(i)}async _call(e,t){const n=await super._call(e,t),i=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&i)try{const e=JSON.parse(n);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(r){}return n}_handleRegistrationResult(e){let t=e.accountId||e.metadata?.accountId;if(!t&&e.state?.createdResources){const n=e.state.createdResources.find(e=>e.startsWith("account:"));n&&(t=n.split(":")[1])}const n=e.inboundTopicId||e.metadata?.inboundTopicId||e.state?.inboundTopicId,i=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,r=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,s=e.privateKey||e.metadata?.privateKey;if(t&&n&&i&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:n,outboundTopicId:i,profileTopicId:r,privateKey:s},o=this.getServiceBuilder().getStateManager();if(o&&(o.setCurrentAgent(e),o.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");o.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const ct=new r.Logger({module:"SendMessageToConnectionTool"}),dt=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 lt extends h{constructor(e){super(e),this.name="send_message_to_connection",this.description="Use this to send a message to an agent you already have an active connection with. Provide the target agent's account ID (e.g., 0.0.12345) and your message. If no active connection exists, this will fail - use initiate_connection instead to create a new connection first.",this.specificInputSchema=dt,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){ct.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 ut=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 pt extends h{constructor(e){super(e),this.name="initiate_connection",this.description="ONLY use this to START a BRAND NEW connection to an agent you have NEVER connected to before. If you already have an active connection to this agent, use send_message_to_connection instead. This creates a new connection request and waits for acceptance.",this.specificInputSchema=ut,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 ft extends f{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 mt extends f{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 yt=Ye({accountId:We().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:et([Xe(it(r.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class bt extends f{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=yt}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 wt=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:Xe(Ye({amount:Ve(),collectorAccount:We().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Xe(Ye({amount:Ve(),tokenId:We(),collectorAccount:We().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:Xe(We()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:Ve().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:We().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class vt extends h{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=wt,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 It=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 Tt extends f{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=It}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 At=Ye({requestKey:We().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:Ve().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:Xe(We()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class _t extends h{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=At,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 Ct=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 Et extends f{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=Ct}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 Rt=Ye({});class St extends f{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=Rt}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class kt 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(),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 Ot=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 $t=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 Pt=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 Ft=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 Dt extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Lt extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const qt=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(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 Ut=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 jt=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 Ht 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){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){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 Zt=new r.Logger({module:"InscribeFromUrlTool"}),zt=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:Xe(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 Gt=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:Xe(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")});function Wt(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}}const Vt=We().regex(/^content-ref:[a-zA-Z0-9_-]+$/,'Content reference must be in format "content-ref:[alphanumeric-id]"').describe('Content reference in format "content-ref:[id]"'),Qt={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function Jt(){return{maxInscriptionSize:parseInt(t.env.REF_MAX_SIZE||Qt.maxInscriptionSize.toString(),10),minContentSize:parseInt(t.env.REF_MIN_SIZE||Qt.minContentSize.toString(),10),logLevel:t.env.REF_LOG_LEVEL||Qt.logLevel,enableContentValidation:"false"!==t.env.REF_ENABLE_VALIDATION}}const Xt=Ye({base64Data:et([We(),Vt]).describe("Content to inscribe as base64 data, plain text, or content reference"),fileName:We().min(1).describe("Name for the inscribed content"),mimeType:We().optional().describe("MIME type of the content"),metadata:tt(Je()).optional().describe("Metadata to attach"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Qe().optional().describe("Wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds"),apiKey:We().optional().describe("API key for inscription service"),quoteOnly:Qe().optional().default(!1).describe("Return cost quote only")});const Yt=Ye({uri:We().describe("URI of the file"),checksum:We().optional().describe("SHA-256 checksum of the file"),is_default_file:Qe().optional().describe("Whether this is the default file"),type:We().describe("MIME type of the file")}),en=Ye({trait_type:We().describe("The trait type"),value:et([We(),Ve()]).describe("The trait value"),display_type:We().optional().describe("Display type for the attribute")}),tn=Ye({name:We().describe("Token name (required by HIP-412)"),description:We().describe("Human readable description (required by HIP-412)"),image:We().describe("Preview image URI (required by HIP-412)"),type:We().describe("MIME type (required by HIP-412)"),creator:We().optional().describe("Creator name or comma-separated names"),creatorDID:We().optional().describe("Decentralized identifier for creator"),checksum:We().optional().describe("SHA-256 checksum of the image"),format:We().optional().default("HIP412@2.0.0").describe("Metadata format version"),files:Xe(Yt).optional().describe("Array of files for multi-file NFTs"),attributes:Xe(en).optional().describe("NFT attributes/traits"),properties:tt(Je()).optional().describe("Additional properties")});function nn(e){const t=e.fileName?.replace(/\.[^/.]+$/,"")||"Hashinal NFT";let n="media";return e.mimeType?.startsWith("image/")?n="image":e.mimeType?.startsWith("video/")?n="video":e.mimeType?.startsWith("audio/")&&(n="audio"),{name:e.name||t,creator:e.creator||e.operatorAccount,description:e.description||`${n.charAt(0).toUpperCase()+n.slice(1)} NFT inscribed as Hashinal`,type:e.type||n,image:""}}function rn(e){const t=e;return t.withRender=function(e){const n=Object.create(this),i=this._renderConfig||{},r={...i,...e,ui:{...i.ui||{},...e.ui||{}}};return(i.progressive||e.progressive)&&(r.progressive={...i.progressive||{},...e.progressive||{}}),(i.block||e.block)&&(r.block={...i.block||{},...e.block||{}}),n._renderConfig=r,n.withRender=t.withRender,n.withProgressive=t.withProgressive,n.withBlock=t.withBlock,n},t.withProgressive=function(t,n){const i=this._renderConfig||{fieldType:an(e)};return this.withRender({...i,progressive:{priority:t,group:n}})},t.withBlock=function(t){const n=this._renderConfig||{fieldType:an(e)};return this.withRender({...n,block:{id:t,type:"field",reusable:!0}})},t}function sn(e){return Boolean(e&&"function"==typeof e.withRender)}function on(e){if(sn(e))return e._renderConfig}function an(e){const t=e._def?.typeName;switch(t){case"ZodString":{const t=e._def?.checks||[];for(const e of t){if("email"===e.kind)return"text";if("url"===e.kind)return"text"}return"text"}case"ZodNumber":case"ZodBigInt":return"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":case"ZodUnion":case"ZodDiscriminatedUnion":return"select";case"ZodArray":return"array";case"ZodDate":default:return"text";case"ZodObject":return"object";case"ZodOptional":case"ZodDefault":{const t=e._def?.innerType;return t?an(t):"text"}}}function cn(e){const t=e._def?.typeName;if("ZodEnum"===t){const t=e._def?.values;if(Array.isArray(t))return t.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1).replace(/[_-]/g," ")}))}if("ZodNativeEnum"===t){const t=e._def?.values;if(t)return Object.entries(t).map(([e,t])=>({value:t,label:e.replace(/[_-]/g," ")}))}if("ZodUnion"===t){const t=[],n=e._def?.options;if(Array.isArray(n))for(const e of n)if("ZodLiteral"===e._def?.typeName){const n=e._def?.value;void 0!==n&&t.push({value:n,label:"string"==typeof n?n.charAt(0).toUpperCase()+n.slice(1):String(n)})}return t.length>0?t:void 0}}function dn(e){const t=e._def?.typeName;return"ZodOptional"===t||"ZodDefault"===t}function ln(e){const t=e._def?.typeName;if("ZodOptional"===t||"ZodDefault"===t){const t=e._def?.innerType;return t||e}return e}function un(e){const t=ln(e),n=t._def?.typeName,i={};if("ZodString"===n){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":i.minLength=t.value;break;case"max":i.maxLength=t.value;break;case"email":i.type="email";break;case"url":i.type="url";break;case"regex":i.pattern=t.regex}}if("ZodNumber"===n){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":i.min=t.value;break;case"max":i.max=t.value;break;case"int":i.step=1;break;case"multipleOf":i.step=t.value}}if("ZodArray"===n){const e=t._def,n=e.minLength,r=e.maxLength;void 0!==n&&(i.minItems=n.value),void 0!==r&&(i.maxItems=r.value)}return i}function pn(e){const t=e._def?.typeName;if("ZodDefault"===t){const t=e._def?.defaultValue;return"function"==typeof t?t():t}const n=ln(e),i=n._def?.typeName;switch(i){case"ZodString":return"";case"ZodNumber":case"ZodBigInt":return 0;case"ZodBoolean":return!1;case"ZodArray":return[];case"ZodObject":{const e=n._def?.shape;if(e){const t={};for(const[n,i]of Object.entries(e))t[n]=pn(i);return t}return{}}case"ZodDate":return new Date;case"ZodEnum":{const e=n._def?.values;return Array.isArray(e)&&e.length>0?e[0]:void 0}default:return}}function hn(e){const t=ln(e),n=an(e),i=!dn(e),r=dn(e),s=pn(e),o=cn(t),a=un(e),c=e?.description;return{type:n,required:i,optional:r,default:s,options:o,constraints:a,description:c,validation:{minLength:a.minLength,maxLength:a.maxLength,min:a.min,max:a.max,pattern:a.pattern?new RegExp(a.pattern):void 0}}}const fn={text:(e,t,n="common")=>({fieldType:"text",ui:{label:e,placeholder:t,priority:n},progressive:{priority:n}}),number:(e,t,n,i="common")=>({fieldType:"number",ui:{label:e,priority:i},constraints:{min:t,max:n},progressive:{priority:i}}),select:(e,t,n="common")=>({fieldType:"select",ui:{label:e,priority:n},options:t,progressive:{priority:n}}),textarea:(e,t=3,n="common")=>({fieldType:"textarea",ui:{label:e,priority:n},props:{rows:t},progressive:{priority:n}}),currency:(e,t="HBAR",n="common")=>({fieldType:"currency",ui:{label:e,priority:n},props:{symbol:t},progressive:{priority:n}}),array:(e,t,n="advanced")=>({fieldType:"array",ui:{label:e,priority:n},props:{itemLabel:t},progressive:{priority:n}}),essential:{text:(e,t)=>fn.text(e,t,"essential"),number:(e,t,n)=>fn.number(e,t,n,"essential"),select:(e,t)=>fn.select(e,t,"essential"),textarea:(e,t)=>fn.textarea(e,t,"essential")},advanced:{text:(e,t)=>fn.text(e,t,"advanced"),number:(e,t,n)=>fn.number(e,t,n,"advanced"),select:(e,t)=>fn.select(e,t,"advanced"),textarea:(e,t)=>fn.textarea(e,t,"advanced"),array:(e,t)=>fn.array(e,t,"advanced")},expert:{text:(e,t)=>fn.text(e,t,"expert"),number:(e,t,n)=>fn.number(e,t,n,"expert"),select:(e,t)=>fn.select(e,t,"expert"),textarea:(e,t)=>fn.textarea(e,t,"expert")}};function gn(e){const{hrl:t,topicId:n,standard:i,cdnUrl:r,transactionId:s,metadata:o}=e;return{success:!0,type:"inscription",title:`${i} Hashinal Inscription Complete`,message:`Successfully inscribed "${o.name||"your content"}" as a ${i} Hashinal. The content is now ready for NFT minting.`,inscription:{hrl:t,topicId:n,standard:i,cdnUrl:r,transactionId:s},metadata:o,nextSteps:{primary:"Use the HRL below as metadata when minting your NFT",context:"The HRL (Hedera Resource Locator) is the standardized way to reference your inscribed content in NFT metadata.",mintingMetadata:t}}}function mn(e){const{code:t,details:n,suggestions:i}=e;return{success:!1,type:"error",title:"Inscription Failed",message:`Unable to complete inscription: ${n}`,error:{code:t,details:n,suggestions:i}}}const yn={testnet:{blockId:"0.0.6617393",hashLink:"hcs://12/0.0.6617393",template:"0.0.6617393"},mainnet:{blockId:"0.0.TBD",hashLink:"hcs://12/0.0.TBD",template:"0.0.TBD"}};const bn=rn(Ye({url:We().optional().describe("The URL of the content to inscribe as Hashinal NFT (use this OR contentRef)"),contentRef:Vt.optional().describe('Content reference ID in format "content-ref:[id]" for already stored content (use this OR url)'),base64Data:We().optional().describe("Base64 encoded content data (use this if neither url nor contentRef provided)"),fileName:We().optional().describe("File name for the content (required when using base64Data or contentRef)"),mimeType:We().optional().describe('MIME type of the content (e.g., "image/png", "image/jpeg")'),name:We().optional().describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),creator:We().optional().describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),description:We().optional().describe("Meaningful description of the artwork, story, or concept behind this NFT"),type:We().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card")'),attributes:rn(Xe(Ye({trait_type:We(),value:et([We(),Ve()])}))).withRender(fn.array("NFT Attributes","Attribute")).optional().describe('Collectible traits and characteristics (e.g., "Rarity": "Epic", "Color": "Blue", "Style": "Abstract")'),properties:tt(Je()).optional().describe("Additional properties"),jsonFileURL:We().url().optional().describe("URL to JSON metadata file"),fileStandard:nt(["1","6"]).optional().default("1").describe("HCS file standard: 1 for static Hashinals (HCS-5), 6 for dynamic Hashinals (HCS-6)"),tags:Xe(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)"),quoteOnly:Qe().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription"),withHashLinkBlocks:Qe().optional().default(!0).describe("If true, creates interactive HashLink blocks for the inscribed content and returns block data alongside the inscription response"),renderForm:Qe().optional().default(!0).describe("Whether to show a form to collect metadata. Set to false only if user provided complete metadata including name, description, creator, and attributes.")})).withRender({fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}});const wn=Ye({transactionId:We().describe("The transaction ID of the inscription to retrieve"),apiKey:We().optional().describe("API key for inscription service")});const vn=o.join(t.cwd(),".env");class In{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 Tn(e,t){return function(){return e.apply(t,arguments)}}const{toString:An}=Object.prototype,{getPrototypeOf:_n}=Object,{iterator:Cn,toStringTag:En}=Symbol,Rn=(e=>t=>{const n=An.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Sn=e=>(e=e.toLowerCase(),t=>Rn(t)===e),kn=e=>t=>typeof t===e,{isArray:xn}=Array,Nn=kn("undefined");function On(e){return null!==e&&!Nn(e)&&null!==e.constructor&&!Nn(e.constructor)&&Mn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const $n=Sn("ArrayBuffer");const Pn=kn("string"),Mn=kn("function"),Fn=kn("number"),Dn=e=>null!==e&&"object"==typeof e,Ln=e=>{if("object"!==Rn(e))return!1;const t=_n(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||En in e||Cn in e)},qn=Sn("Date"),Bn=Sn("File"),Un=Sn("Blob"),jn=Sn("FileList"),Hn=Sn("URLSearchParams"),[Kn,Zn,zn,Gn]=["ReadableStream","Request","Response","Headers"].map(Sn);function Wn(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),xn(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(On(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 Vn(e,t){if(On(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 Qn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:a,Jn=e=>!Nn(e)&&e!==Qn;const Xn=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&_n(Uint8Array)),Yn=Sn("HTMLFormElement"),ei=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),ti=Sn("RegExp"),ni=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};Wn(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const ii=Sn("AsyncFunction"),ri=(si="function"==typeof c.setImmediate,oi=Mn(Qn.postMessage),si?c.setImmediate:oi?(ai=`axios@${Math.random()}`,ci=[],Qn.addEventListener("message",({source:e,data:t})=>{e===Qn&&t===ai&&ci.length&&ci.shift()()},!1),e=>{ci.push(e),Qn.postMessage(ai,"*")}):e=>setTimeout(e));var si,oi,ai,ci;const di="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Qn):void 0!==t&&t.nextTick||ri,li={isArray:xn,isArrayBuffer:$n,isBuffer:On,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Mn(e.append)&&("formdata"===(t=Rn(e))||"object"===t&&Mn(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&$n(e.buffer),t},isString:Pn,isNumber:Fn,isBoolean:e=>!0===e||!1===e,isObject:Dn,isPlainObject:Ln,isEmptyObject:e=>{if(!Dn(e)||On(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Kn,isRequest:Zn,isResponse:zn,isHeaders:Gn,isUndefined:Nn,isDate:qn,isFile:Bn,isBlob:Un,isRegExp:ti,isFunction:Mn,isStream:e=>Dn(e)&&Mn(e.pipe),isURLSearchParams:Hn,isTypedArray:Xn,isFileList:jn,forEach:Wn,merge:function e(){const{caseless:t}=Jn(this)&&this||{},n={},i=(i,r)=>{const s=t&&Vn(n,r)||r;Ln(n[s])&&Ln(i)?n[s]=e(n[s],i):Ln(i)?n[s]=e({},i):xn(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&Wn(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(Wn(t,(t,i)=>{n&&Mn(t)?e[i]=Tn(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&&_n(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Rn,kindOfTest:Sn,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(xn(e))return e;let t=e.length;if(!Fn(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Cn]).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:Yn,hasOwnProperty:ei,hasOwnProp:ei,reduceDescriptors:ni,freezeMethods:e=>{ni(e,(t,n)=>{if(Mn(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];Mn(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 xn(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:Vn,global:Qn,isContextDefined:Jn,isSpecCompliantForm:function(e){return!!(e&&Mn(e.append)&&"FormData"===e[En]&&e[Cn])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(Dn(e)){if(t.indexOf(e)>=0)return;if(On(e))return e;if(!("toJSON"in e)){t[i]=e;const r=xn(e)?[]:{};return Wn(e,(e,t)=>{const s=n(e,i+1);!Nn(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:ii,isThenable:e=>e&&(Dn(e)||Mn(e))&&Mn(e.then)&&Mn(e.catch),setImmediate:ri,asap:di,isIterable:e=>null!=e&&Mn(e[Cn])};function ui(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)}li.inherits(ui,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:li.toJSONObject(this.config),code:this.code,status:this.status}}});const pi=ui.prototype,hi={};["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=>{hi[e]={value:e}}),Object.defineProperties(ui,hi),Object.defineProperty(pi,"isAxiosError",{value:!0}),ui.from=(e,t,n,i,r,s)=>{const o=Object.create(pi);return li.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),ui.call(o,e.message,t,n,i,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function fi(e){return li.isPlainObject(e)||li.isArray(e)}function gi(e){return li.endsWith(e,"[]")?e.slice(0,-2):e}function mi(e,t,n){return e?e.concat(t).map(function(e,t){return e=gi(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const yi=li.toFlatObject(li,{},null,function(e){return/^is[A-Z]/.test(e)});function bi(e,t,i){if(!li.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const r=(i=li.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!li.isUndefined(t[e])})).metaTokens,s=i.visitor||l,o=i.dots,a=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&li.isSpecCompliantForm(t);if(!li.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(li.isDate(e))return e.toISOString();if(li.isBoolean(e))return e.toString();if(!c&&li.isBlob(e))throw new ui("Blob is not supported. Use a Buffer instead.");return li.isArrayBuffer(e)||li.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(li.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(li.isArray(e)&&function(e){return li.isArray(e)&&!e.some(fi)}(e)||(li.isFileList(e)||li.endsWith(n,"[]"))&&(s=li.toArray(e)))return n=gi(n),s.forEach(function(e,i){!li.isUndefined(e)&&null!==e&&t.append(!0===a?mi([n],i,o):null===a?n:n+"[]",d(e))}),!1;return!!fi(e)||(t.append(mi(i,n,o),d(e)),!1)}const u=[],p=Object.assign(yi,{defaultVisitor:l,convertValue:d,isVisitable:fi});if(!li.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!li.isUndefined(n)){if(-1!==u.indexOf(n))throw Error("Circular reference detected in "+i.join("."));u.push(n),li.forEach(n,function(n,r){!0===(!(li.isUndefined(n)||null===n)&&s.call(t,n,li.isString(r)?r.trim():r,i,p))&&e(n,i?i.concat(r):[r])}),u.pop()}}(e),t}function wi(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function vi(e,t){this._pairs=[],e&&bi(e,this,t)}const Ii=vi.prototype;function Ti(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ai(e,t,n){if(!t)return e;const i=n&&n.encode||Ti;li.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):li.isURLSearchParams(t)?t.toString():new vi(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Ii.append=function(e,t){this._pairs.push([e,t])},Ii.toString=function(e){const t=e?function(t){return e.call(this,t,wi)}:wi;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class _i{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){li.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Ci={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ei={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:vi,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Ri="undefined"!=typeof window&&"undefined"!=typeof document,Si="object"==typeof navigator&&navigator||void 0,ki=Ri&&(!Si||["ReactNative","NativeScript","NS"].indexOf(Si.product)<0),xi="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ni=Ri&&window.location.href||"http://localhost",Oi={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ri,hasStandardBrowserEnv:ki,hasStandardBrowserWebWorkerEnv:xi,navigator:Si,origin:Ni},Symbol.toStringTag,{value:"Module"})),...Ei};function $i(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&&li.isArray(i)?i.length:s,a)return li.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!o;i[s]&&li.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&li.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(li.isFormData(e)&&li.isFunction(e.entries)){const n={};return li.forEachEntry(e,(e,i)=>{t(function(e){return li.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const Pi={transitional:Ci,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=li.isObject(e);r&&li.isHTMLForm(e)&&(e=new FormData(e));if(li.isFormData(e))return i?JSON.stringify($i(e)):e;if(li.isArrayBuffer(e)||li.isBuffer(e)||li.isStream(e)||li.isFile(e)||li.isBlob(e)||li.isReadableStream(e))return e;if(li.isArrayBufferView(e))return e.buffer;if(li.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 bi(e,new Oi.classes.URLSearchParams,{visitor:function(e,t,n,i){return Oi.isNode&&li.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=li.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return bi(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(li.isString(e))try{return(t||JSON.parse)(e),li.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Pi.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(li.isResponse(e)||li.isReadableStream(e))return e;if(e&&li.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 ui.from(r,ui.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:Oi.classes.FormData,Blob:Oi.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};li.forEach(["delete","get","head","post","put","patch"],e=>{Pi.headers[e]={}});const Mi=li.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"]),Fi=Symbol("internals");function Di(e){return e&&String(e).trim().toLowerCase()}function Li(e){return!1===e||null==e?e:li.isArray(e)?e.map(Li):String(e)}function qi(e,t,n,i,r){return li.isFunction(i)?i.call(this,t,n):(r&&(t=n),li.isString(t)?li.isString(i)?-1!==t.indexOf(i):li.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=Di(t);if(!r)throw new Error("header name must be a non-empty string");const s=li.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=Li(e))}const s=(e,t)=>li.forEach(e,(e,n)=>r(e,n,t));if(li.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(li.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]&&Mi[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(li.isObject(e)&&li.isIterable(e)){let n,i,r={};for(const t of e){if(!li.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?li.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=Di(e)){const n=li.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(li.isFunction(t))return t.call(this,e,n);if(li.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Di(e)){const n=li.findKey(this,e);return!(!n||void 0===this[n]||t&&!qi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=Di(e)){const r=li.findKey(n,e);!r||t&&!qi(0,n[r],r,t)||(delete n[r],i=!0)}}return li.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&&!qi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return li.forEach(this,(i,r)=>{const s=li.findKey(n,r);if(s)return t[s]=Li(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]=Li(i),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return li.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&li.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[Fi]=this[Fi]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=Di(e);t[i]||(!function(e,t){const n=li.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 li.isArray(e)?e.forEach(i):i(e),this}};function Ui(e,t){const n=this||Pi,i=t||n,r=Bi.from(i.headers);let s=i.data;return li.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function ji(e){return!(!e||!e.__CANCEL__)}function Hi(e,t,n){ui.call(this,null==e?"canceled":e,ui.ERR_CANCELED,t,n),this.name="CanceledError"}function Ki(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new ui("Request failed with status code "+n.status,[ui.ERR_BAD_REQUEST,ui.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"]),li.reduceDescriptors(Bi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),li.freezeMethods(Bi),li.inherits(Hi,ui,{__CANCEL__:!0});const Zi=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];r||(r=c),n[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=n[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-r<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const o=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-r;a>=s?o(e,t):(n=e,i||(i=setTimeout(()=>{i=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-i,c=r(a);i=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:n,lengthComputable:null!=o,[t?"download":"upload"]:!0})},n)},zi=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Gi=e=>(...t)=>li.asap(()=>e(...t)),Wi=Oi.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Oi.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Oi.origin),Oi.navigator&&/(msie|trident)/i.test(Oi.navigator.userAgent)):()=>!0,Vi=Oi.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const o=[e+"="+encodeURIComponent(t)];li.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),li.isString(i)&&o.push("path="+i),li.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 Qi(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 Ji=e=>e instanceof Bi?{...e}:e;function Xi(e,t){t=t||{};const n={};function i(e,t,n,i){return li.isPlainObject(e)&&li.isPlainObject(t)?li.merge.call({caseless:i},e,t):li.isPlainObject(t)?li.merge({},t):li.isArray(t)?t.slice():t}function r(e,t,n,r){return li.isUndefined(t)?li.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!li.isUndefined(t))return i(void 0,t)}function o(e,t){return li.isUndefined(t)?li.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(Ji(e),Ji(t),0,!0)};return li.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,o=s(e[i],t[i],i);li.isUndefined(o)&&s!==a||(n[i]=o)}),n}const Yi=e=>{const t=Xi({},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=Ai(Qi(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),li.isFormData(i))if(Oi.hasStandardBrowserEnv||Oi.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(Oi.hasStandardBrowserEnv&&(r&&li.isFunction(r)&&(r=r(t)),r||!1!==r&&Wi(t.url))){const e=s&&o&&Vi.read(o);e&&a.set(s,e)}return t},er="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=Yi(e);let r=i.data;const s=Bi.from(i.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function f(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const i=Bi.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Ki(function(e){t(e),f()},function(e){n(e),f()},{data:u&&"text"!==u&&"json"!==u?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:i,config:e,request:g}),g=null}g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(n(new ui("Request aborted",ui.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new ui("Network Error",ui.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||Ci;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new ui(t,r.clarifyTimeoutError?ui.ETIMEDOUT:ui.ECONNABORTED,e,g)),g=null},void 0===r&&s.setContentType(null),"setRequestHeader"in g&&li.forEach(s.toJSON(),function(e,t){g.setRequestHeader(t,e)}),li.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),u&&"json"!==u&&(g.responseType=i.responseType),h&&([c,l]=Zi(h,!0),g.addEventListener("progress",c)),p&&g.upload&&([a,d]=Zi(p),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(o=t=>{g&&(n(!t||t.type?new Hi(null,e,g):t),g.abort(),g=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===Oi.protocols.indexOf(y)?n(new ui("Unsupported protocol "+y+":",ui.ERR_BAD_REQUEST,e)):g.send(r||null)})},tr=(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 ui?t:new Hi(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new ui(`timeout ${t} of ms exceeded`,ui.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=()=>li.asap(o),a}},nr=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},ir=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()}},rr=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of ir(e))yield*nr(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})},sr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,or=sr&&"function"==typeof ReadableStream,ar=sr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),cr=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},dr=or&&cr(()=>{let e=!1;const t=new Request(Oi.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),lr=or&&cr(()=>li.isReadableStream(new Response("").body)),ur={stream:lr&&(e=>e.body)};var pr;sr&&(pr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!ur[e]&&(ur[e]=li.isFunction(pr[e])?t=>t[e]():(t,n)=>{throw new ui(`Response type '${e}' is not supported`,ui.ERR_NOT_SUPPORT,n)})}));const hr=async(e,t)=>{const n=li.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(li.isBlob(e))return e.size;if(li.isSpecCompliantForm(e)){const t=new Request(Oi.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return li.isArrayBufferView(e)||li.isArrayBuffer(e)?e.byteLength:(li.isURLSearchParams(e)&&(e+=""),li.isString(e)?(await ar(e)).byteLength:void 0)})(t):n},fr={http:null,xhr:er,fetch:sr&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=Yi(e);d=d?(d+"").toLowerCase():"text";let h,f=tr([r,s&&s.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&dr&&"get"!==n&&"head"!==n&&0!==(m=await hr(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(li.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=zi(m,Zi(Gi(c)));i=rr(n.body,65536,e,t)}}li.isString(u)||(u=u?"include":"omit");const r="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:n.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:r?u:void 0});let s=await fetch(h,p);const o=lr&&("stream"===d||"response"===d);if(lr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=li.toFiniteNumber(s.headers.get("content-length")),[n,i]=a&&zi(t,Zi(Gi(a),!0))||[];s=new Response(rr(s.body,65536,n,()=>{i&&i(),g&&g()}),e)}d=d||"text";let y=await ur[li.findKey(ur,d)||"text"](s,e);return!o&&g&&g(),await new Promise((t,n)=>{Ki(t,n,{data:y,headers:Bi.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(y){if(g&&g(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new ui("Network Error",ui.ERR_NETWORK,e,h),{cause:y.cause||y});throw ui.from(y,y&&y.code,e,h)}})};li.forEach(fr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const gr=e=>`- ${e}`,mr=e=>li.isFunction(e)||null===e||!1===e,yr=e=>{e=li.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,!mr(n)&&(i=fr[(t=String(n)).toLowerCase()],void 0===i))throw new ui(`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 ui("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(gr).join("\n"):" "+gr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function br(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Hi(null,e)}function wr(e){br(e),e.headers=Bi.from(e.headers),e.data=Ui.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return yr(e.adapter||Pi.adapter)(e).then(function(t){return br(e),t.data=Ui.call(e,e.transformResponse,t),t.headers=Bi.from(t.headers),t},function(t){return ji(t)||(br(e),t&&t.response&&(t.response.data=Ui.call(e,e.transformResponse,t.response),t.response.headers=Bi.from(t.response.headers))),Promise.reject(t)})}const vr="1.11.0",Ir={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ir[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Tr={};Ir.transitional=function(e,t,n){function i(e,t){return"[Axios v"+vr+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new ui(i(r," has been removed"+(t?" in "+t:"")),ui.ERR_DEPRECATED);return t&&!Tr[r]&&(Tr[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)}},Ir.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const Ar={assertOptions:function(e,t,n){if("object"!=typeof e)throw new ui("options must be an object",ui.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 ui("option "+s+" must be "+n,ui.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new ui("Unknown option "+s,ui.ERR_BAD_OPTION)}},validators:Ir},_r=Ar.validators;let Cr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new _i,response:new _i}}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=Xi(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&Ar.assertOptions(n,{silentJSONParsing:_r.transitional(_r.boolean),forcedJSONParsing:_r.transitional(_r.boolean),clarifyTimeoutError:_r.transitional(_r.boolean)},!1),null!=i&&(li.isFunction(i)?t.paramsSerializer={serialize:i}:Ar.assertOptions(i,{encode:_r.function,serialize:_r.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ar.assertOptions(t,{baseUrl:_r.spelling("baseURL"),withXsrfToken:_r.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&li.merge(r.common,r[t.method]);r&&li.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=[wr.bind(this),void 0];for(e.unshift(...o),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{d=wr.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return Ai(Qi((e=Xi(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};li.forEach(["delete","get","head","options"],function(e){Cr.prototype[e]=function(t,n){return this.request(Xi(n||{},{method:e,url:t,data:(n||{}).data}))}}),li.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Xi(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}Cr.prototype[e]=t(),Cr.prototype[e+"Form"]=t(!0)});const Er={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(Er).forEach(([e,t])=>{Er[t]=e});const Rr=function e(t){const n=new Cr(t),i=Tn(Cr.prototype.request,n);return li.extend(i,Cr.prototype,n,{allOwnKeys:!0}),li.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Xi(t,n))},i}(Pi);Rr.Axios=Cr,Rr.CanceledError=Hi,Rr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const 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 Hi(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}}},Rr.isCancel=ji,Rr.VERSION=vr,Rr.toFormData=bi,Rr.AxiosError=ui,Rr.Cancel=Rr.CanceledError,Rr.all=function(e){return Promise.all(e)},Rr.spread=function(e){return function(t){return e.apply(null,t)}},Rr.isAxiosError=function(e){return li.isObject(e)&&!0===e.isAxiosError},Rr.mergeConfig=Xi,Rr.AxiosHeaders=Bi,Rr.formToJSON=e=>$i(li.isHTMLForm(e)?new FormData(e):e),Rr.getAdapter=yr,Rr.HttpStatusCode=Er,Rr.default=Rr;const{Axios:Sr,AxiosError:kr,CanceledError:xr,isCancel:Nr,CancelToken:Or,VERSION:$r,all:Pr,Cancel:Mr,isAxiosError:Fr,spread:Dr,toFormData:Lr,AxiosHeaders:qr,HttpStatusCode:Br,formToJSON:Ur,getAdapter:jr,mergeConfig:Hr}=Rr,Kr="ConnectionsManager not initialized";class Zr extends i.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t;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 Rr.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 Rr.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(Kr);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,p=0;const h=new Set;for(;Date.now()<l;){try{const e=(await this.getMessages(d)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||h.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),h.add(e),p++}}}catch(f){this.logger.error("Error during connection monitoring:",f)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:u,acceptedConnections:p,monitorDurationSeconds:i,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${p}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(Kr);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(Kr),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 zr 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}}function Gr(e){const t={},n={},i=[],r={};return Wr(e,"",t,n,i,r),{fields:t,groups:Jr(n),order:Xr(i,t),metadata:r}}function Wr(e,t,n,i,r,s){const o=ln(e),a=o._def?.typeName;"ZodObject"===a?function(e,t,n,i,r,s){const o=e.shape;if(sn(e)){const s=on(e);s&&t&&(n[t]=s,Vr(i,s.ui?.group||"default",t),Qr(r,t,s.ui?.order))}for(const[a,c]of Object.entries(o)){Wr(c,t?`${t}.${a}`:a,n,i,r,s)}}(o,t,n,i,r,s):"ZodArray"===a?function(e,t,n,i,r,s){if(sn(e)){const o=on(e);o&&(n[t]=o,Vr(i,o.ui?.group||"default",t),Qr(r,t,o.ui?.order),s[t]=hn(e))}const o=e._def.type;if(o){Wr(o,`${t}[]`,n,i,r,s)}}(o,t,n,i,r,s):function(e,t,n,i,r,s){if(sn(e)){const s=on(e);s&&(n[t]=s,Vr(i,s.ui?.group||"default",t),Qr(r,t,s.ui?.order))}s[t]=hn(e)}(e,t,n,i,r,s)}function Vr(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}function Qr(e,t,n){void 0!==n?e.splice(n,0,t):e.push(t)}function Jr(e){const t={},n=["default","Keys & Security","Token Settings","Custom Fees"];for(const i of n)e[i]&&(t[i]=e[i]);for(const[i,r]of Object.entries(e))n.includes(i)||(t[i]=r);return t}function Xr(e,t){const n={tokenName:1,tokenSymbol:2,maxSupply:3,supplyType:4,treasuryAccountId:5,memo:6};return e.sort((e,i)=>{const r=t[e],s=t[i];if(void 0!==r?.ui?.order&&void 0!==s?.ui?.order)return r.ui.order-s.ui.order;if(void 0!==r?.ui?.order)return-1;if(void 0!==s?.ui?.order)return 1;const o=n[e]||1e3,a=n[i]||1e3;return o!==a?o-a:e.localeCompare(i)})}class Yr 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 es 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 ts 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=_t,e.BaseHCS10QueryTool=f,e.BaseHCS10TransactionTool=h,e.BaseHCS2QueryTool=xt,e.BaseHCS2TransactionTool=kt,e.BaseHCS6QueryTool=Lt,e.BaseHCS6TransactionTool=Dt,e.BaseInscriberQueryTool=Kt,e.BaseInscriberTransactionTool=Ht,e.CheckMessagesTool=mt,e.ConnectionMonitorTool=vt,e.CreateDynamicRegistryTool=class extends Lt{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return qt}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 Pt}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=bt,e.HCS10Builder=Zr,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=Yr,e.HCS6Builder=es,e.HbarPricePlugin=zr,e.InitiateConnectionTool=pt,e.InscribeFromBufferTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Use ONLY for inscribing regular files or content (NOT for NFT/Hashinal inscriptions). When user says "inscribe it" after you showed search results or other content WITHOUT mentioning NFT/hashinal, 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. NEVER use this for Hashinal NFTs - always use InscribeHashinalTool instead when user mentions hashinal, NFT, dynamic, or minting.',this.config=Jt()}get specificInputSchema(){return Xt}async executeQuery(e,t){this.validateInput(e);const n=await async function(e,t,n){const i=e.trim(),s=r.ContentResolverRegistry.getResolver();if(!s)return Wt(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 Wt(i,t,n)}(e.base64Data,e.mimeType,e.fileName);this.validateContent(n.buffer);const i=n.buffer,s=n.mimeType||e.mimeType,o=n.fileName||e.fileName,a={mode:"file",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:o,mimeType:s},a);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:o,mimeType:s,sizeBytes:i.length},message:`Estimated Quote for buffer content: ${o} (${(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}`)}try{const t=await this.executeInscription(i,o,s,a,e.timeoutMs);return this.formatInscriptionResult(t,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&&!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.`}},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 Gt}async executeQuery(e,t){let i;try{const t=await p.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(0===t.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(t.size<10)throw new Error(`File "${e.filePath}" is too small (${t.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(t.size>104857600&&this.logger?.warn(`Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await p.readFile(e.filePath),this.logger?.info(`Read ${i.length} bytes from file`),!i||0===i.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(i.length<10)throw new Error(`File "${e.filePath}" content is too small (${i.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const n=u.basename(e.filePath),r=this.getMimeType(n);if(r.startsWith("text/")||"application/json"===r){if(""===i.toString("utf8",0,Math.min(i.length,1e3)).trim())throw new Error(`File "${e.filePath}" contains only whitespace or empty content. Cannot inscribe meaningless data.`)}}catch(c){if(c instanceof Error){if(c.message.includes("ENOENT"))throw new Error(`File not found: "${e.filePath}"`);throw c}throw new Error(`Failed to read file: ${c}`)}const r=i.toString("base64");this.logger?.info(`Converted to base64: ${r.length} characters`);const s=u.basename(e.filePath),o=this.getMimeType(s);this.logger?.info(`File: ${s}, MIME type: ${o}`);const a={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.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(r,"base64"),fileName:s,mimeType:o},a);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{fileName:s,mimeType:o,sizeBytes:i.length,filePath:e.filePath},message:`Estimated Quote for file: ${s} (${(i.length/1024).toFixed(2)} KB)\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(c){const e=c instanceof Error?c.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(r,"base64"),fileName:s,mimeType:o},a),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:n.Buffer.from(r,"base64"),fileName:s,mimeType:o},a);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=${a.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(c){const e=c instanceof Error?c.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 zt}async executeQuery(e,t){if(Zt.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.`)}Zt.info("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){Zt.info("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;Zt.warn(`Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}Zt.info(`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)Zt.warn("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;Zt.warn(`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:`Estimated Quote 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="Tool for inscribing Hashinal NFTs. CRITICAL: When user provides content (url/contentRef/base64Data), call with ONLY the content parameters - DO NOT auto-generate name, description, creator, or attributes. A form will be automatically shown to collect metadata from the user. Only include metadata parameters if the user explicitly provided them in their message."}get specificInputSchema(){return bn._def?.schema||bn}get schema(){if(!this._schemaWithRenderConfig){const e=this.specificInputSchema,t=e;t._renderConfig||(t._renderConfig={fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}}),this._schemaWithRenderConfig=e}return this._schemaWithRenderConfig}shouldGenerateForm(e){const t=new r.Logger({module:"InscribeHashinalTool"}),n=e;t.info("InscribeHashinalTool: Checking if form should be generated",{inputKeys:Object.keys(n||{}),hasContent:!!(n.url||n.contentRef||n.base64Data),renderFormProvided:"renderForm"in n,renderFormValue:n.renderForm});if(!!!(n.url||n.contentRef||n.base64Data))return t.info("InscribeHashinalTool: No content source provided"),!1;if("renderForm"in n&&!1===n.renderForm)return t.info("InscribeHashinalTool: renderForm=false, skipping form generation"),!1;const i=e=>"string"==typeof e&&0!==e.trim().length;return i(n.name)&&i(n.description)&&i(n.creator)?(t.info("InscribeHashinalTool: Required metadata present, skipping form generation"),!1):(t.info("InscribeHashinalTool: Content provided, showing form for metadata collection"),!0)}getFormSchema(){return rn(Ye({name:We().min(1,"Name is required").describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),description:We().min(1,"Description is required").describe("Meaningful description of the artwork, story, or concept behind this NFT"),creator:We().min(1,"Creator is required").describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),attributes:rn(Xe(Ye({trait_type:We().describe('Trait name (e.g., "Rarity", "Color", "Style")'),value:et([We(),Ve()]).describe('Trait value (e.g., "Epic", "Blue", 85)')}))).withRender(fn.array("NFT Attributes","Attribute")).optional().describe("Collectible traits and characteristics."),type:We().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card)')})).withRender({fieldType:"object",ui:{label:"Complete NFT Metadata",description:"Provide meaningful metadata to create a valuable NFT"}})}validateMetadataQuality(e){const t=e;return!!(t.name&&t.description&&t.creator)?{needsForm:!1,reason:"All required metadata fields present"}:{needsForm:!0,reason:"Missing essential metadata (name, description, creator) for NFT creation"}}async executeQuery(e,t){if(!e.url&&!e.contentRef&&!e.base64Data)return mn({code:"MISSING_CONTENT",details:"No content source provided",suggestions:["Provide a URL to content you want to inscribe","Upload a file and use the content reference","Provide base64-encoded content data"]});const n=this.inscriberBuilder.hederaKit?.client?.operatorAccountId?.toString()||"0.0.unknown",i={...nn({name:e.name,creator:e.creator,description:e.description,type:e.type,fileName:e.fileName,mimeType:e.mimeType,operatorAccount:n}),attributes:Array.isArray(e.attributes)?e.attributes:[],properties:e.properties||{}};let s;try{s=function(e){try{return tn.parse(e)}catch(t){if(t instanceof I){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`).join("; ");throw new Error(`HIP-412 metadata validation failed: ${e}`)}throw t}}(i)}catch(c){return mn({code:"METADATA_VALIDATION_FAILED",details:`Metadata validation error: ${c instanceof Error?c.message:String(c)}`,suggestions:["Ensure all required metadata fields are provided","Check that attribute values are valid","Verify metadata follows HIP-412 standard"]})}const o={mode:"hashinal",metadata:s,jsonFileURL:e.jsonFileURL,fileStandard:e.fileStandard,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:30,waitIntervalMs:5e3,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};let a;if(e.url)a={type:"url",url:e.url};else{if(!e.contentRef&&!e.base64Data)throw new Error("No valid input data provided for inscription");{const t=e.contentRef||e.base64Data||"",{buffer:n,mimeType:i,fileName:r}=await this.resolveContent(t,e.mimeType,e.fileName);a={type:"buffer",buffer:n,fileName:r||e.fileName||"hashinal-content",mimeType:i||e.mimeType}}}if(e.quoteOnly)try{const t=await this.generateInscriptionQuote(a,o);return function(e){const{totalCostHbar:t,validUntil:n,breakdown:i,content:r}=e;return{success:!0,type:"quote",title:"Inscription Cost Quote",message:`Estimated cost to inscribe "${r.name||"your content"}" is ${t} HBAR.`,quote:{totalCostHbar:t,validUntil:n,breakdown:i},content:r}}({totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown,content:{name:e.name,creator:e.creator,type:e.type}})}catch(c){return mn({code:"QUOTE_GENERATION_FAILED",details:`Quote generation failed: ${c instanceof Error?c.message:"Failed to generate inscription quote"}`,suggestions:["Check network connectivity","Verify content is accessible","Try again in a moment"]})}try{let t;if(e.timeoutMs){const n=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe(a,o),n])}else t=await this.inscriberBuilder.inscribe(a,o);if(t.confirmed&&!t.quote){const n=t.inscription?.topic_id,i=t.inscription?.jsonTopicId,s=i?`https://kiloscribe.com/api/inscription-cdn/${i}?network=${o.network||"testnet"}`:null,c=e.fileStandard||"1",l=i?`hcs://${c}/${i}`:null,u="6"===c?"Dynamic":"Static";if(!l)return mn({code:"MISSING_TOPIC_ID",details:"Inscription completed but topic ID is missing",suggestions:["Try the inscription again","Contact support if the issue persists"]});const p=gn({hrl:l,topicId:i||n||"unknown",standard:u,cdnUrl:s||void 0,transactionId:t.result?.transactionId,metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes}});if(e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(p,"buffer"===a.type?a.mimeType:void 0);p.hashLinkBlock=e}catch(d){new r.Logger({module:"InscribeHashinalTool"}).error("Failed to create HashLink block",{error:d})}return p}if(t.quote||t.confirmed)return mn({code:"UNKNOWN_STATE",details:"Inscription completed but result state is unclear",suggestions:["Check if the inscription was successful manually","Try the inscription again"]});{const n=t.inscription?.topic_id,i=t.inscription?.jsonTopicId;if(i||n){const s=i?`https://kiloscribe.com/api/inscription-cdn/${i}?network=${o.network||"testnet"}`:null,c=e.fileStandard||"1",l=i?`hcs://${c}/${i}`:null;if(l){const o=gn({hrl:l,topicId:i||n||"unknown",standard:"6"===c?"Dynamic":"Static",cdnUrl:s||void 0,transactionId:t.result?.transactionId,metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes}});if(e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(o,"buffer"===a.type?a.mimeType:void 0);o.hashLinkBlock=e}catch(d){new r.Logger({module:"InscribeHashinalTool"}).error("Failed to create HashLink block",{error:d})}return o}}return mn({code:"INSCRIPTION_PENDING",details:`Inscription submitted but not yet confirmed. Transaction ID: ${t.result?.transactionId||"unknown"}`,suggestions:["Wait a few moments for confirmation","Check the transaction status on a Hedera explorer","Try the inscription again if it doesn't confirm within 5 minutes"]})}}catch(c){return mn({code:"INSCRIPTION_FAILED",details:`Inscription failed: ${c instanceof Error?c.message:"Failed to inscribe Hashinal NFT"}`,suggestions:["Check network connectivity","Verify you have sufficient HBAR balance","Ensure content is accessible and valid","Try again in a moment"]})}}async createHashLinkBlock(e,t){const n=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",i=e.inscription.cdnUrl?.includes("mainnet")?"mainnet":"testnet";if(n!==i){new r.Logger({module:"InscribeHashinalTool"}).warn(`Network mismatch detected: client=${n}, cdn=${i}. Using client network.`)}const s=n,o=function(e){const t=yn[e];return t&&"0.0.TBD"!==t.blockId?t:yn.testnet}(s);return{blockId:o.blockId,hashLink:o.hashLink,template:o.template,attributes:{name:e.metadata.name||"Untitled Content",creator:e.metadata.creator||"",topicId:e.inscription.topicId,hrl:e.inscription.hrl,network:s}}}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}}getEssentialFields(){return["name","description","creator","attributes"]}isFieldEmpty(e,t){return null==t||""===t||(!(!Array.isArray(t)||0!==t.length)||!("attributes"!==e||!Array.isArray(t))&&t.every(e=>!e||"object"==typeof e&&(!e.trait_type||!e.value)))}},e.InscriberBuilder=ts,e.ListConnectionsTool=ft,e.ListUnapprovedConnectionRequestsTool=St,e.ManageConnectionRequestsTool=Tt,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=In,e.QueryDynamicRegistryTool=class extends Lt{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 jt}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 Ft}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 Lt{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 Ot}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 wn}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"}),i=n;return{inscriptionId:i.inscriptionId,transactionId:n.transactionId||"unknown",topicId:i.topic_id,status:n.status||"unknown",holderId:i.holderId,metadata:n.metadata,tags:i.tags,mode:n.mode,chunks:i.chunks,createdAt:i.createdAt,completedAt:i.completed||i.completedAt,fileUrl:n.fileUrl,mimeType:i.mimeType,fileSize:i.fileSize}}},e.RetrieveProfileTool=Et,e.SendMessageToConnectionTool=lt,e.UpdateDynamicHashinalTool=class extends Lt{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 Ut}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 $t}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.createFieldConfigMap=function(e){const t=Gr(e),n={};for(const[i,r]of Object.entries(t.fields)){const e=t.metadata[i],s=i.split(".");n[i]={renderConfig:r,metadata:e,path:s}}return n},e.createProgressiveSchema=function(e,t){const n=rn(e),i=e._def?.typeName;if("ZodObject"===i){const i=e._def?.shape;if(i){for(const[e,n]of Object.entries(i)){let i,r="common";for(const[n,s]of Object.entries(t))if(s.fields.includes(e)){i=n,r=s.priority;break}rn(n).withProgressive(r,i)}return n}}return n},e.createSimpleConfig=function(e){const t=Gr(e),n=[];for(const i of t.order){const e=t.fields[i],r=t.metadata[i];e&&r&&n.push({name:i,type:r.type,label:e.ui?.label||i,required:r.required,placeholder:e.ui?.placeholder,options:e.options||r.options})}return{fields:n}},e.enhanceRenderConfig=function(e){return{...e,progressive:{priority:e.ui?.priority||"common",group:e.ui?.group}}},e.extendZodSchema=rn,e.extractFieldMetadata=hn,e.extractOptionsFromSchema=cn,e.extractProgressiveInfo=function(e){const t=on(e);return t?.progressive?{priority:t.progressive.priority,group:t.progressive.group}:t?.ui?.priority?{priority:t.ui.priority,group:t.ui.group}:{priority:"common"}},e.extractRenderConfigs=Gr,e.extractValidationConstraints=un,e.generateFieldOrdering=function(e){const t=Gr(e),n={},i={default:0,"Basic Information":1,"Token Settings":2,"Keys & Security":3,"Custom Fees":4,"Advanced Settings":5};for(const[r,s]of Object.entries(t.groups)){const e="default"===r?"Basic Information":r;n[e]={title:e,fields:s,order:i[e]||10}}return{sections:n,fieldOrder:t.order}},e.getDefaultValue=pn,e.getInnerSchema=ln,e.getRenderConfig=on,e.hasRenderConfig=sn,e.inferFieldTypeFromSchema=an,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",c="true"===t.env.DISABLE_LOGGING,d=r.Logger.getInstance({level:n.logLevel||"info",silent:c});let l;if("mainnet"===a?l="mainnet":("testnet"===a||d.warn(`Unsupported network specified: '${a}'. Defaulting to 'testnet'.`),l="testnet"),!s||!o)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const u=e?.stateManager||new In({defaultEnvFilePath:vn,defaultPrefix:"TODD"});d.info("State manager initialized");const p=new i.ServerSigner(s,o,l),h=new i.HederaAgentKit(p);await h.initialize(),d.info(`HederaAgentKit initialized for ${s} on ${l}`);const f=new Zr(h,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let g,m;if(e?.monitoringClient){const e=new i.ServerSigner(s,o,l);g=new i.HederaAgentKit(e),await g.initialize(),m=new Zr(g,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new at({hederaKit:h,hcs10Builder:f,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new bt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.retrieveProfileTool=new Et({hederaKit:h,hcs10Builder:f,logger:void 0}),y.initiateConnectionTool=new pt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listConnectionsTool=new ft({hederaKit:h,hcs10Builder:f,logger:void 0}),y.sendMessageToConnectionTool=new lt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.checkMessagesTool=new mt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.connectionMonitorTool=new vt({hederaKit:g||h,hcs10Builder:m||f,logger:void 0}),y.manageConnectionRequestsTool=new Tt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.acceptConnectionRequestTool=new _t({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new St({hederaKit:h,hcs10Builder:f,logger:void 0}),d.info("All tools initialized")),{hederaKit:h,hcs10Builder:f,monitoringHederaKit:g,monitoringHcs10Builder:m,tools:y,stateManager:u}},e.installZodRenderExtensions=function(){L.prototype.withRender||(L.prototype.withRender=function(e){return rn(this).withRender(e)},L.prototype.withProgressive=function(e,t){return rn(this).withProgressive(e,t)},L.prototype.withBlock=function(e){return rn(this).withBlock(e)})},e.isFormValidatable=function(e){return null!==e&&"object"==typeof e&&"shouldGenerateForm"in e&&"getFormSchema"in e&&"function"==typeof e.shouldGenerateForm&&"function"==typeof e.getFormSchema},e.isOptionalSchema=dn,e.loadConfig=Jt,e.renderConfigs=fn,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),p=l(d);class h extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class f extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var g,m,y;(m=g||(g={})).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=g.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=g.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,g.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,g.jsonStringifyReplacer)}`;break;case v.unrecognized_keys:n=`Unrecognized key(s) in object: ${g.joinValues(e.keys,", ")}`;break;case v.invalid_union:n="Invalid input";break;case v.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${g.joinValues(e.options)}`;break;case v.invalid_enum_value:n=`Invalid enum value. Expected ${g.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}"`:g.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,g.assertNever(e)}return{message:n}};let A=T;function C(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 _{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 _.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}),k=e=>"aborted"===e.status,x=e=>"dirty"===e.status,N=e=>"valid"===e.status,O=e=>"undefined"!=typeof Promise&&e instanceof Promise;var $,P;(P=$||($={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},P.toString=e=>"string"==typeof e?e:e?.message;class M{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const F=(e,t)=>{if(N(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new I(e.common.issues);return this._error=t,this._error}}};function 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 _,ctx:{common:e.parent.common,data:e.data,parsedType:w(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(O(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:w(e)},i=this._parseSync({data:e,path:n.path,parent:n});return F(n,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:w(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return N(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>N(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:w(e)},i=this._parse({data:e,path:n.path,parent:n}),r=await(O(i)?i:Promise.resolve(i));return F(n,r)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,i)=>{const r=e(t),s=()=>i.addIssue({code:v.custom,...n(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then(e=>!!e||(s(),!1)):!!r||(s(),!1)})}refinement(e,t){return this._refinement((n,i)=>!!e(n)||(i.addIssue("function"==typeof t?t(n,i):t),!1))}_refinement(e){return new 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 qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ie.create(this)}promise(){return Fe.create(this,this._def)}or(e){return Ce.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 Be({...D(this._def),innerType:this,defaultValue:t,typeName:ze.ZodDefault})}brand(){return new He({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 Ke.create(this,e)}readonly(){return Ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const q=/^c[^\s-]{8,}$/i,B=/^[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,H=/^[a-z0-9_-]{21}$/i,K=/^[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]))$/,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])$/,X=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Y=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ee="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",te=new RegExp(`^${ee}$`);function ne(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function ie(e){return new RegExp(`^${ne(e)}$`)}function re(e){let t=`${ee}T${ne(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function se(e,t){return!("v4"!==t&&t||!W.test(e))||!("v6"!==t&&t||!Q.test(e))}function oe(e,t){if(!K.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||!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 C(t,{code:v.invalid_type,expected:b.string,received:t.parsedType}),E}const t=new _;let n;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),C(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),C(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?C(n,{code:v.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&C(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),C(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),C(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),C(n,{validation:"uuid",code:v.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)H.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"nanoid",code:v.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)q.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"cuid",code:v.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)B.test(e.data)||(n=this._getOrReturnCtx(e,n),C(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),C(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),C(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),C(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),C(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),C(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),C(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),C(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),C(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),C(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),C(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),C(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),C(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),C(n,{validation:"cidr",code:v.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?X.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"base64",code:v.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?Y.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"base64url",code:v.invalid_string,message:i.message}),t.dirty()):g.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 C(t,{code:v.invalid_type,expected:b.number,received:t.parsedType}),E}let t;const n=new _;for(const i of this._def.checks)if("int"===i.kind)g.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),C(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),C(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),C(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),C(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),C(t,{code:v.not_finite,message:i.message}),n.dirty()):g.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&&g.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 _;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),C(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),C(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),C(t,{code:v.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):g.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return C(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 pe extends L{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==b.boolean){const t=this._getOrReturnCtx(e);return C(t,{code:v.invalid_type,expected:b.boolean,received:t.parsedType}),E}return S(e.data)}}pe.create=e=>new pe({typeName:ze.ZodBoolean,coerce:e?.coerce||!1,...D(e)});class he 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 C(t,{code:v.invalid_type,expected:b.date,received:t.parsedType}),E}if(Number.isNaN(e.data.getTime())){return C(this._getOrReturnCtx(e),{code:v.invalid_date}),E}const t=new _;let n;for(const i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),C(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),C(n,{code:v.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):g.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new he({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}he.create=e=>new he({checks:[],coerce:e?.coerce||!1,typeName:ze.ZodDate,...D(e)});class fe extends L{_parse(e){if(this._getType(e)!==b.symbol){const t=this._getOrReturnCtx(e);return C(t,{code:v.invalid_type,expected:b.symbol,received:t.parsedType}),E}return S(e.data)}}fe.create=e=>new fe({typeName:ze.ZodSymbol,...D(e)});class ge extends L{_parse(e){if(this._getType(e)!==b.undefined){const t=this._getOrReturnCtx(e);return C(t,{code:v.invalid_type,expected:b.undefined,received:t.parsedType}),E}return S(e.data)}}ge.create=e=>new ge({typeName:ze.ZodUndefined,...D(e)});class me extends L{_parse(e){if(this._getType(e)!==b.null){const t=this._getOrReturnCtx(e);return C(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 C(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 C(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 C(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)&&(C(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&&(C(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&&(C(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=>_.mergeArray(n,e));const r=[...t.data].map((e,n)=>i.type._parseSync(new M(t,e,t.path,n)));return _.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 qe?qe.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=g.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 C(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&&(C(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=>_.mergeObjectSync(t,e)):_.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 g.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 g.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 g.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 g.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(g.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 Ce 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 C(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 C(t,{code:v.invalid_union,unionErrors:r}),E}}get options(){return this._def.options}}function _e(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=g.objectKeys(t),i=g.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const s of i){const n=_e(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=_e(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}}Ce.create=(e,t)=>new Ce({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(k(e)||k(i))return E;const r=_e(e.value,i.value);return r.valid?((x(e)||x(i))&&t.dirty(),{status:t.value,value:r.data}):(C(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 C(n,{code:v.invalid_type,expected:b.array,received:n.parsedType}),E;if(n.data.length<this._def.items.length)return C(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&&(C(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=>_.mergeArray(t,e)):_.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 C(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?_.mergeObjectAsync(t,i):_.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 ke 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 C(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}}}}ke.create=(e,t,n)=>new ke({valueType:t,keyType:e,typeName:ze.ZodMap,...D(n)});class xe extends L{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==b.set)return C(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&&(C(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&&(C(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 xe({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new xe({...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)}}xe.create=(e,t)=>new xe({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...D(t)});class Ne 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})}}Ne.create=(e,t)=>new Ne({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 C(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,...D(t)})}Oe.create=(e,t)=>new Oe({value:e,typeName:ze.ZodLiteral,...D(t)});class Pe extends L{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return C(t,{expected:g.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 C(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 L{_parse(e){const t=g.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==b.string&&n.parsedType!==b.number){const e=g.objectValues(t);return C(n,{expected:g.joinValues(e),received:n.parsedType,code:v.invalid_type}),E}if(this._cache||(this._cache=new Set(g.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=g.objectValues(t);return C(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,...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 C(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=>{C(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)}g.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 qe extends L{_parse(e){return this._getType(e)===b.null?S(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:ze.ZodNullable,...D(t)});class Be 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}}Be.create=(e,t)=>new Be({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 C(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 He 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 Ke 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 Ke({in:e,out:t,typeName:ze.ZodPipeline})}}class Ze extends L{_parse(e){const t=this._def.innerType._parse(e),n=e=>(N(e)&&(e.value=Object.freeze(e.value)),e);return O(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var ze,Ge;Ze.create=(e,t)=>new Ze({innerType:e,typeName:ze.ZodReadonly,...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,Qe=pe.create,Je=be.create;we.create;const Xe=Ie.create,Ye=Ae.create,et=Ce.create;Ee.create,Re.create;const tt=Se.create,nt=Pe.create,it=Me.create;Fe.create,Le.create,qe.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([Xe(it(r.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Agent capabilities - can be capability names (e.g. "ai", "data processing"), capability enum values, or array of either. Common values: "ai"/"text" (TEXT_GENERATION), "data" (DATA_INTEGRATION), "analytics" (TRANSACTION_ANALYTICS)'),tags:et([Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):st.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:We().optional().describe("Creator attribution for the agent"),socials:tt(nt(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),We()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:tt(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:Xe(Ye({amount:Ve().positive(),tokenId:We()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Xe(We()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Qe().optional().describe("Whether to set as current agent (default: true)"),persistence:Ye({prefix:We().optional()}).optional().describe("Optional persistence configuration")});class at extends h{constructor(e){super(e),this.name="register_agent",this.description='Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Supports natural language for capabilities/tags like "ai", "data processing", "analytics". Note: This tool requires multiple transactions and cannot be used in returnBytes mode. If alias is set to "random" or contains "random", a unique alias will be generated.',this.specificInputSchema=ot,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;this.specificArgs=t;const i={name:t.name};if(void 0!==t.description&&(i.bio=t.description),void 0!==t.alias)i.alias=t.alias;else{const e=Date.now().toString(36);i.alias=`${t.name}${e}`}if(void 0!==t.type&&(i.type=t.type),void 0!==t.model&&(i.model=t.model),void 0!==t.tags?i.capabilities=t.tags:void 0!==t.capabilities&&(i.capabilities=t.capabilities),void 0!==t.creator&&(i.creator=t.creator),void 0!==t.socials&&(i.socials=t.socials),void 0!==t.properties&&(i.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)i.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),i.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(i.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(i.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(i.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(i.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(i.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(i.initialBalance=t.initialBalance),await n.registerAgent(i)}async _call(e,t){const n=await super._call(e,t),i=!1!==this.specificArgs?.setAsCurrent;if(this.specificArgs&&i)try{const e=JSON.parse(n);e.rawResult?this._handleRegistrationResult(e.rawResult):(e.state||e.accountId||e.metadata)&&this._handleRegistrationResult(e)}catch(r){}return n}_handleRegistrationResult(e){let t=e.accountId||e.metadata?.accountId;if(!t&&e.state?.createdResources){const n=e.state.createdResources.find(e=>e.startsWith("account:"));n&&(t=n.split(":")[1])}const n=e.inboundTopicId||e.metadata?.inboundTopicId||e.state?.inboundTopicId,i=e.outboundTopicId||e.metadata?.outboundTopicId||e.state?.outboundTopicId,r=e.profileTopicId||e.metadata?.profileTopicId||e.state?.profileTopicId,s=e.privateKey||e.metadata?.privateKey;if(t&&n&&i&&this.specificArgs){const e={name:this.specificArgs.name,accountId:t,inboundTopicId:n,outboundTopicId:i,profileTopicId:r,privateKey:s},o=this.getServiceBuilder().getStateManager();if(o&&(o.setCurrentAgent(e),o.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");o.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const ct=new r.Logger({module:"SendMessageToConnectionTool"}),dt=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 lt extends h{constructor(e){super(e),this.name="send_message_to_connection",this.description="Use this to send a message to an agent you already have an active connection with. Provide the target agent's account ID (e.g., 0.0.12345) and your message. If no active connection exists, this will fail - use initiate_connection instead to create a new connection first.",this.specificInputSchema=dt,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){ct.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 ut=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 pt extends h{constructor(e){super(e),this.name="initiate_connection",this.description="ONLY use this to START a BRAND NEW connection to an agent you have NEVER connected to before. If you already have an active connection to this agent, use send_message_to_connection instead. This creates a new connection request and waits for acceptance.",this.specificInputSchema=ut,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 ft extends f{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 mt extends f{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 yt=Ye({accountId:We().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:et([Xe(it(r.AIAgentCapability)),Xe(We()),We()]).optional().transform(e=>{if(e)return"string"==typeof e?st.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?st.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class bt extends f{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=yt}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 wt=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:Xe(Ye({amount:Ve(),collectorAccount:We().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Xe(Ye({amount:Ve(),tokenId:We(),collectorAccount:We().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:Xe(We()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:Ve().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:We().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class vt extends h{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=wt,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 It=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 Tt extends f{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=It}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 At=Ye({requestKey:We().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:Ve().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:Xe(We()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class Ct extends h{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=At,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 Et extends f{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 Rt=Ye({});class St extends f{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=Rt}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class kt 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(),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 Ot=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 $t=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 Pt=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 Ft=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 Dt extends i.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Lt extends i.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const qt=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(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 Ut=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 jt=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 Ht 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}setEntityCreationHandler(e){this.onEntityCreated=e}async generateInscriptionQuote(e,t){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}setEntityCreationHandler(e){this.onEntityCreated=e}async generateInscriptionQuote(e,t){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 Zt=new r.Logger({module:"InscribeFromUrlTool"}),zt=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:Xe(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 Gt=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:Xe(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")});function Wt(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}}const Vt=We().regex(/^content-ref:[a-zA-Z0-9_-]+$/,'Content reference must be in format "content-ref:[alphanumeric-id]"').describe('Content reference in format "content-ref:[id]"'),Qt={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function Jt(){return{maxInscriptionSize:parseInt(t.env.REF_MAX_SIZE||Qt.maxInscriptionSize.toString(),10),minContentSize:parseInt(t.env.REF_MIN_SIZE||Qt.minContentSize.toString(),10),logLevel:t.env.REF_LOG_LEVEL||Qt.logLevel,enableContentValidation:"false"!==t.env.REF_ENABLE_VALIDATION}}const Xt=Ye({base64Data:et([We(),Vt]).describe("Content to inscribe as base64 data, plain text, or content reference"),fileName:We().min(1).describe("Name for the inscribed content"),mimeType:We().optional().describe("MIME type of the content"),metadata:tt(Je()).optional().describe("Metadata to attach"),tags:Xe(We()).optional().describe("Tags to categorize the inscription"),chunkSize:Ve().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Qe().optional().describe("Wait for inscription confirmation"),timeoutMs:Ve().int().positive().optional().describe("Timeout in milliseconds"),apiKey:We().optional().describe("API key for inscription service"),quoteOnly:Qe().optional().default(!1).describe("Return cost quote only")});const Yt=Ye({uri:We().describe("URI of the file"),checksum:We().optional().describe("SHA-256 checksum of the file"),is_default_file:Qe().optional().describe("Whether this is the default file"),type:We().describe("MIME type of the file")}),en=Ye({trait_type:We().describe("The trait type"),value:et([We(),Ve()]).describe("The trait value"),display_type:We().optional().describe("Display type for the attribute")}),tn=Ye({name:We().describe("Token name (required by HIP-412)"),description:We().describe("Human readable description (required by HIP-412)"),image:We().describe("Preview image URI (required by HIP-412)"),type:We().describe("MIME type (required by HIP-412)"),creator:We().optional().describe("Creator name or comma-separated names"),creatorDID:We().optional().describe("Decentralized identifier for creator"),checksum:We().optional().describe("SHA-256 checksum of the image"),format:We().optional().default("HIP412@2.0.0").describe("Metadata format version"),files:Xe(Yt).optional().describe("Array of files for multi-file NFTs"),attributes:Xe(en).optional().describe("NFT attributes/traits"),properties:tt(Je()).optional().describe("Additional properties")});function nn(e){const t=e.fileName?.replace(/\.[^/.]+$/,"")||"Hashinal NFT";let n="media";return e.mimeType?.startsWith("image/")?n="image":e.mimeType?.startsWith("video/")?n="video":e.mimeType?.startsWith("audio/")&&(n="audio"),{name:e.name||t,creator:e.creator||e.operatorAccount,description:e.description||`${n.charAt(0).toUpperCase()+n.slice(1)} NFT inscribed as Hashinal`,type:e.type||n,image:""}}function rn(e){const t=e;return t.withRender=function(e){const n=Object.create(this),i=this._renderConfig||{},r={...i,...e,ui:{...i.ui||{},...e.ui||{}}};return(i.progressive||e.progressive)&&(r.progressive={...i.progressive||{},...e.progressive||{}}),(i.block||e.block)&&(r.block={...i.block||{},...e.block||{}}),n._renderConfig=r,n.withRender=t.withRender,n.withProgressive=t.withProgressive,n.withBlock=t.withBlock,n},t.withProgressive=function(t,n){const i=this._renderConfig||{fieldType:an(e)};return this.withRender({...i,progressive:{priority:t,group:n}})},t.withBlock=function(t){const n=this._renderConfig||{fieldType:an(e)};return this.withRender({...n,block:{id:t,type:"field",reusable:!0}})},t}function sn(e){return Boolean(e&&"function"==typeof e.withRender)}function on(e){if(sn(e))return e._renderConfig}function an(e){const t=e._def?.typeName;switch(t){case"ZodString":{const t=e._def?.checks||[];for(const e of t){if("email"===e.kind)return"text";if("url"===e.kind)return"text"}return"text"}case"ZodNumber":case"ZodBigInt":return"number";case"ZodBoolean":return"checkbox";case"ZodEnum":case"ZodNativeEnum":case"ZodUnion":case"ZodDiscriminatedUnion":return"select";case"ZodArray":return"array";case"ZodDate":default:return"text";case"ZodObject":return"object";case"ZodOptional":case"ZodDefault":{const t=e._def?.innerType;return t?an(t):"text"}}}function cn(e){const t=e._def?.typeName;if("ZodEnum"===t){const t=e._def?.values;if(Array.isArray(t))return t.map(e=>({value:e,label:e.charAt(0).toUpperCase()+e.slice(1).replace(/[_-]/g," ")}))}if("ZodNativeEnum"===t){const t=e._def?.values;if(t)return Object.entries(t).map(([e,t])=>({value:t,label:e.replace(/[_-]/g," ")}))}if("ZodUnion"===t){const t=[],n=e._def?.options;if(Array.isArray(n))for(const e of n)if("ZodLiteral"===e._def?.typeName){const n=e._def?.value;void 0!==n&&t.push({value:n,label:"string"==typeof n?n.charAt(0).toUpperCase()+n.slice(1):String(n)})}return t.length>0?t:void 0}}function dn(e){const t=e._def?.typeName;return"ZodOptional"===t||"ZodDefault"===t}function ln(e){const t=e._def?.typeName;if("ZodOptional"===t||"ZodDefault"===t){const t=e._def?.innerType;return t||e}return e}function un(e){const t=ln(e),n=t._def?.typeName,i={};if("ZodString"===n){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":i.minLength=t.value;break;case"max":i.maxLength=t.value;break;case"email":i.type="email";break;case"url":i.type="url";break;case"regex":i.pattern=t.regex}}if("ZodNumber"===n){const e=t._def.checks;if(e&&Array.isArray(e))for(const t of e)switch(t.kind){case"min":i.min=t.value;break;case"max":i.max=t.value;break;case"int":i.step=1;break;case"multipleOf":i.step=t.value}}if("ZodArray"===n){const e=t._def,n=e.minLength,r=e.maxLength;void 0!==n&&(i.minItems=n.value),void 0!==r&&(i.maxItems=r.value)}return i}function pn(e){const t=e._def?.typeName;if("ZodDefault"===t){const t=e._def?.defaultValue;return"function"==typeof t?t():t}const n=ln(e),i=n._def?.typeName;switch(i){case"ZodString":return"";case"ZodNumber":case"ZodBigInt":return 0;case"ZodBoolean":return!1;case"ZodArray":return[];case"ZodObject":{const e=n._def?.shape;if(e){const t={};for(const[n,i]of Object.entries(e))t[n]=pn(i);return t}return{}}case"ZodDate":return new Date;case"ZodEnum":{const e=n._def?.values;return Array.isArray(e)&&e.length>0?e[0]:void 0}default:return}}function hn(e){const t=ln(e),n=an(e),i=!dn(e),r=dn(e),s=pn(e),o=cn(t),a=un(e),c=e?.description;return{type:n,required:i,optional:r,default:s,options:o,constraints:a,description:c,validation:{minLength:a.minLength,maxLength:a.maxLength,min:a.min,max:a.max,pattern:a.pattern?new RegExp(a.pattern):void 0}}}const fn={text:(e,t,n="common")=>({fieldType:"text",ui:{label:e,placeholder:t,priority:n},progressive:{priority:n}}),number:(e,t,n,i="common")=>({fieldType:"number",ui:{label:e,priority:i},constraints:{min:t,max:n},progressive:{priority:i}}),select:(e,t,n="common")=>({fieldType:"select",ui:{label:e,priority:n},options:t,progressive:{priority:n}}),textarea:(e,t=3,n="common")=>({fieldType:"textarea",ui:{label:e,priority:n},props:{rows:t},progressive:{priority:n}}),currency:(e,t="HBAR",n="common")=>({fieldType:"currency",ui:{label:e,priority:n},props:{symbol:t},progressive:{priority:n}}),array:(e,t,n="advanced")=>({fieldType:"array",ui:{label:e,priority:n},props:{itemLabel:t},progressive:{priority:n}}),essential:{text:(e,t)=>fn.text(e,t,"essential"),number:(e,t,n)=>fn.number(e,t,n,"essential"),select:(e,t)=>fn.select(e,t,"essential"),textarea:(e,t)=>fn.textarea(e,t,"essential")},advanced:{text:(e,t)=>fn.text(e,t,"advanced"),number:(e,t,n)=>fn.number(e,t,n,"advanced"),select:(e,t)=>fn.select(e,t,"advanced"),textarea:(e,t)=>fn.textarea(e,t,"advanced"),array:(e,t)=>fn.array(e,t,"advanced")},expert:{text:(e,t)=>fn.text(e,t,"expert"),number:(e,t,n)=>fn.number(e,t,n,"expert"),select:(e,t)=>fn.select(e,t,"expert"),textarea:(e,t)=>fn.textarea(e,t,"expert")}};function gn(e){const{hrl:t,topicId:n,standard:i,cdnUrl:r,transactionId:s,metadata:o}=e;return{success:!0,type:"inscription",title:`${i} Hashinal Inscription Complete`,message:`Successfully inscribed "${o.name||"your content"}" as a ${i} Hashinal. The content is now ready for NFT minting.`,inscription:{hrl:t,topicId:n,standard:i,cdnUrl:r,transactionId:s},metadata:o,nextSteps:{primary:"CRITICAL: When minting NFTs, use ONLY the mintingMetadata value as a single string in the metadata array. Do NOT create JSON objects.",context:'The metadata parameter for minting should be exactly: ["'+t+'"] - just the HRL string in an array, nothing else.',mintingMetadata:t}}}function mn(e){const{code:t,details:n,suggestions:i}=e;return{success:!1,type:"error",title:"Inscription Failed",message:`Unable to complete inscription: ${n}`,error:{code:t,details:n,suggestions:i}}}const yn={testnet:{blockId:"0.0.6617393",hashLink:"hcs://12/0.0.6617393",template:"0.0.6617393"},mainnet:{blockId:"0.0.TBD",hashLink:"hcs://12/0.0.TBD",template:"0.0.TBD"}};const bn=rn(Ye({url:We().optional().describe("The URL of the content to inscribe as Hashinal NFT (use this OR contentRef)"),contentRef:Vt.optional().describe('Content reference ID in format "content-ref:[id]" for already stored content (use this OR url)'),base64Data:We().optional().describe("Base64 encoded content data (use this if neither url nor contentRef provided)"),fileName:We().optional().describe("File name for the content (required when using base64Data or contentRef)"),mimeType:We().optional().describe('MIME type of the content (e.g., "image/png", "image/jpeg")'),name:We().optional().describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),creator:We().optional().describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),description:We().optional().describe("Meaningful description of the artwork, story, or concept behind this NFT"),type:We().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card")'),attributes:rn(Xe(Ye({trait_type:We(),value:et([We(),Ve()])}))).withRender(fn.array("NFT Attributes","Attribute")).optional().describe('Collectible traits and characteristics (e.g., "Rarity": "Epic", "Color": "Blue", "Style": "Abstract")'),properties:tt(Je()).optional().describe("Additional properties"),jsonFileURL:We().url().optional().describe("URL to JSON metadata file"),fileStandard:nt(["1","6"]).optional().default("1").describe("HCS file standard: 1 for static Hashinals (HCS-5), 6 for dynamic Hashinals (HCS-6)"),tags:Xe(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)"),quoteOnly:Qe().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription"),withHashLinkBlocks:Qe().optional().default(!0).describe("If true, creates interactive HashLink blocks for the inscribed content and returns block data alongside the inscription response"),renderForm:Qe().optional().default(!0).describe("Whether to show a form to collect metadata. Set to false only if user provided complete metadata including name, description, creator, and attributes.")})).withRender({fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}});const wn=Ye({transactionId:We().describe("The transaction ID of the inscription to retrieve"),apiKey:We().optional().describe("API key for inscription service")});const vn=o.join(t.cwd(),".env");class In{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 Tn(e,t){return function(){return e.apply(t,arguments)}}const{toString:An}=Object.prototype,{getPrototypeOf:Cn}=Object,{iterator:_n,toStringTag:En}=Symbol,Rn=(e=>t=>{const n=An.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Sn=e=>(e=e.toLowerCase(),t=>Rn(t)===e),kn=e=>t=>typeof t===e,{isArray:xn}=Array,Nn=kn("undefined");function On(e){return null!==e&&!Nn(e)&&null!==e.constructor&&!Nn(e.constructor)&&Mn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const $n=Sn("ArrayBuffer");const Pn=kn("string"),Mn=kn("function"),Fn=kn("number"),Dn=e=>null!==e&&"object"==typeof e,Ln=e=>{if("object"!==Rn(e))return!1;const t=Cn(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||En in e||_n in e)},qn=Sn("Date"),Bn=Sn("File"),Un=Sn("Blob"),jn=Sn("FileList"),Hn=Sn("URLSearchParams"),[Kn,Zn,zn,Gn]=["ReadableStream","Request","Response","Headers"].map(Sn);function Wn(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),xn(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(On(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 Vn(e,t){if(On(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 Qn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:a,Jn=e=>!Nn(e)&&e!==Qn;const Xn=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Cn(Uint8Array)),Yn=Sn("HTMLFormElement"),ei=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),ti=Sn("RegExp"),ni=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};Wn(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const ii=Sn("AsyncFunction"),ri=(si="function"==typeof c.setImmediate,oi=Mn(Qn.postMessage),si?c.setImmediate:oi?(ai=`axios@${Math.random()}`,ci=[],Qn.addEventListener("message",({source:e,data:t})=>{e===Qn&&t===ai&&ci.length&&ci.shift()()},!1),e=>{ci.push(e),Qn.postMessage(ai,"*")}):e=>setTimeout(e));var si,oi,ai,ci;const di="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Qn):void 0!==t&&t.nextTick||ri,li={isArray:xn,isArrayBuffer:$n,isBuffer:On,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Mn(e.append)&&("formdata"===(t=Rn(e))||"object"===t&&Mn(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&$n(e.buffer),t},isString:Pn,isNumber:Fn,isBoolean:e=>!0===e||!1===e,isObject:Dn,isPlainObject:Ln,isEmptyObject:e=>{if(!Dn(e)||On(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Kn,isRequest:Zn,isResponse:zn,isHeaders:Gn,isUndefined:Nn,isDate:qn,isFile:Bn,isBlob:Un,isRegExp:ti,isFunction:Mn,isStream:e=>Dn(e)&&Mn(e.pipe),isURLSearchParams:Hn,isTypedArray:Xn,isFileList:jn,forEach:Wn,merge:function e(){const{caseless:t}=Jn(this)&&this||{},n={},i=(i,r)=>{const s=t&&Vn(n,r)||r;Ln(n[s])&&Ln(i)?n[s]=e(n[s],i):Ln(i)?n[s]=e({},i):xn(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&Wn(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(Wn(t,(t,i)=>{n&&Mn(t)?e[i]=Tn(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&&Cn(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Rn,kindOfTest:Sn,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(xn(e))return e;let t=e.length;if(!Fn(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[_n]).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:Yn,hasOwnProperty:ei,hasOwnProp:ei,reduceDescriptors:ni,freezeMethods:e=>{ni(e,(t,n)=>{if(Mn(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];Mn(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 xn(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:Vn,global:Qn,isContextDefined:Jn,isSpecCompliantForm:function(e){return!!(e&&Mn(e.append)&&"FormData"===e[En]&&e[_n])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(Dn(e)){if(t.indexOf(e)>=0)return;if(On(e))return e;if(!("toJSON"in e)){t[i]=e;const r=xn(e)?[]:{};return Wn(e,(e,t)=>{const s=n(e,i+1);!Nn(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:ii,isThenable:e=>e&&(Dn(e)||Mn(e))&&Mn(e.then)&&Mn(e.catch),setImmediate:ri,asap:di,isIterable:e=>null!=e&&Mn(e[_n])};function ui(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)}li.inherits(ui,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:li.toJSONObject(this.config),code:this.code,status:this.status}}});const pi=ui.prototype,hi={};["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=>{hi[e]={value:e}}),Object.defineProperties(ui,hi),Object.defineProperty(pi,"isAxiosError",{value:!0}),ui.from=(e,t,n,i,r,s)=>{const o=Object.create(pi);return li.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),ui.call(o,e.message,t,n,i,r),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function fi(e){return li.isPlainObject(e)||li.isArray(e)}function gi(e){return li.endsWith(e,"[]")?e.slice(0,-2):e}function mi(e,t,n){return e?e.concat(t).map(function(e,t){return e=gi(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const yi=li.toFlatObject(li,{},null,function(e){return/^is[A-Z]/.test(e)});function bi(e,t,i){if(!li.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const r=(i=li.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!li.isUndefined(t[e])})).metaTokens,s=i.visitor||l,o=i.dots,a=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&li.isSpecCompliantForm(t);if(!li.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(li.isDate(e))return e.toISOString();if(li.isBoolean(e))return e.toString();if(!c&&li.isBlob(e))throw new ui("Blob is not supported. Use a Buffer instead.");return li.isArrayBuffer(e)||li.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(li.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(li.isArray(e)&&function(e){return li.isArray(e)&&!e.some(fi)}(e)||(li.isFileList(e)||li.endsWith(n,"[]"))&&(s=li.toArray(e)))return n=gi(n),s.forEach(function(e,i){!li.isUndefined(e)&&null!==e&&t.append(!0===a?mi([n],i,o):null===a?n:n+"[]",d(e))}),!1;return!!fi(e)||(t.append(mi(i,n,o),d(e)),!1)}const u=[],p=Object.assign(yi,{defaultVisitor:l,convertValue:d,isVisitable:fi});if(!li.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!li.isUndefined(n)){if(-1!==u.indexOf(n))throw Error("Circular reference detected in "+i.join("."));u.push(n),li.forEach(n,function(n,r){!0===(!(li.isUndefined(n)||null===n)&&s.call(t,n,li.isString(r)?r.trim():r,i,p))&&e(n,i?i.concat(r):[r])}),u.pop()}}(e),t}function wi(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function vi(e,t){this._pairs=[],e&&bi(e,this,t)}const Ii=vi.prototype;function Ti(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ai(e,t,n){if(!t)return e;const i=n&&n.encode||Ti;li.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):li.isURLSearchParams(t)?t.toString():new vi(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Ii.append=function(e,t){this._pairs.push([e,t])},Ii.toString=function(e){const t=e?function(t){return e.call(this,t,wi)}:wi;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Ci{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){li.forEach(this.handlers,function(t){null!==t&&e(t)})}}const _i={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ei={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:vi,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Ri="undefined"!=typeof window&&"undefined"!=typeof document,Si="object"==typeof navigator&&navigator||void 0,ki=Ri&&(!Si||["ReactNative","NativeScript","NS"].indexOf(Si.product)<0),xi="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ni=Ri&&window.location.href||"http://localhost",Oi={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ri,hasStandardBrowserEnv:ki,hasStandardBrowserWebWorkerEnv:xi,navigator:Si,origin:Ni},Symbol.toStringTag,{value:"Module"})),...Ei};function $i(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&&li.isArray(i)?i.length:s,a)return li.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!o;i[s]&&li.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&li.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(li.isFormData(e)&&li.isFunction(e.entries)){const n={};return li.forEachEntry(e,(e,i)=>{t(function(e){return li.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const Pi={transitional:_i,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=li.isObject(e);r&&li.isHTMLForm(e)&&(e=new FormData(e));if(li.isFormData(e))return i?JSON.stringify($i(e)):e;if(li.isArrayBuffer(e)||li.isBuffer(e)||li.isStream(e)||li.isFile(e)||li.isBlob(e)||li.isReadableStream(e))return e;if(li.isArrayBufferView(e))return e.buffer;if(li.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 bi(e,new Oi.classes.URLSearchParams,{visitor:function(e,t,n,i){return Oi.isNode&&li.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=li.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return bi(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(li.isString(e))try{return(t||JSON.parse)(e),li.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Pi.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(li.isResponse(e)||li.isReadableStream(e))return e;if(e&&li.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 ui.from(r,ui.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:Oi.classes.FormData,Blob:Oi.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};li.forEach(["delete","get","head","post","put","patch"],e=>{Pi.headers[e]={}});const Mi=li.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"]),Fi=Symbol("internals");function Di(e){return e&&String(e).trim().toLowerCase()}function Li(e){return!1===e||null==e?e:li.isArray(e)?e.map(Li):String(e)}function qi(e,t,n,i,r){return li.isFunction(i)?i.call(this,t,n):(r&&(t=n),li.isString(t)?li.isString(i)?-1!==t.indexOf(i):li.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=Di(t);if(!r)throw new Error("header name must be a non-empty string");const s=li.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=Li(e))}const s=(e,t)=>li.forEach(e,(e,n)=>r(e,n,t));if(li.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(li.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]&&Mi[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(li.isObject(e)&&li.isIterable(e)){let n,i,r={};for(const t of e){if(!li.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?li.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=Di(e)){const n=li.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(li.isFunction(t))return t.call(this,e,n);if(li.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Di(e)){const n=li.findKey(this,e);return!(!n||void 0===this[n]||t&&!qi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=Di(e)){const r=li.findKey(n,e);!r||t&&!qi(0,n[r],r,t)||(delete n[r],i=!0)}}return li.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&&!qi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return li.forEach(this,(i,r)=>{const s=li.findKey(n,r);if(s)return t[s]=Li(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]=Li(i),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return li.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&li.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[Fi]=this[Fi]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=Di(e);t[i]||(!function(e,t){const n=li.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 li.isArray(e)?e.forEach(i):i(e),this}};function Ui(e,t){const n=this||Pi,i=t||n,r=Bi.from(i.headers);let s=i.data;return li.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function ji(e){return!(!e||!e.__CANCEL__)}function Hi(e,t,n){ui.call(this,null==e?"canceled":e,ui.ERR_CANCELED,t,n),this.name="CanceledError"}function Ki(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new ui("Request failed with status code "+n.status,[ui.ERR_BAD_REQUEST,ui.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"]),li.reduceDescriptors(Bi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),li.freezeMethods(Bi),li.inherits(Hi,ui,{__CANCEL__:!0});const Zi=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[o];r||(r=c),n[s]=a,i[s]=c;let l=o,u=0;for(;l!==s;)u+=n[l++],l%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-r<t)return;const p=d&&c-d;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const o=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-r;a>=s?o(e,t):(n=e,i||(i=setTimeout(()=>{i=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-i,c=r(a);i=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:n,lengthComputable:null!=o,[t?"download":"upload"]:!0})},n)},zi=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Gi=e=>(...t)=>li.asap(()=>e(...t)),Wi=Oi.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Oi.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Oi.origin),Oi.navigator&&/(msie|trident)/i.test(Oi.navigator.userAgent)):()=>!0,Vi=Oi.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const o=[e+"="+encodeURIComponent(t)];li.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),li.isString(i)&&o.push("path="+i),li.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 Qi(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 Ji=e=>e instanceof Bi?{...e}:e;function Xi(e,t){t=t||{};const n={};function i(e,t,n,i){return li.isPlainObject(e)&&li.isPlainObject(t)?li.merge.call({caseless:i},e,t):li.isPlainObject(t)?li.merge({},t):li.isArray(t)?t.slice():t}function r(e,t,n,r){return li.isUndefined(t)?li.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!li.isUndefined(t))return i(void 0,t)}function o(e,t){return li.isUndefined(t)?li.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(Ji(e),Ji(t),0,!0)};return li.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,o=s(e[i],t[i],i);li.isUndefined(o)&&s!==a||(n[i]=o)}),n}const Yi=e=>{const t=Xi({},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=Ai(Qi(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),li.isFormData(i))if(Oi.hasStandardBrowserEnv||Oi.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(Oi.hasStandardBrowserEnv&&(r&&li.isFunction(r)&&(r=r(t)),r||!1!==r&&Wi(t.url))){const e=s&&o&&Vi.read(o);e&&a.set(s,e)}return t},er="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=Yi(e);let r=i.data;const s=Bi.from(i.headers).normalize();let o,a,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function f(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(o),i.signal&&i.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const i=Bi.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Ki(function(e){t(e),f()},function(e){n(e),f()},{data:u&&"text"!==u&&"json"!==u?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:i,config:e,request:g}),g=null}g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(n(new ui("Request aborted",ui.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new ui("Network Error",ui.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||_i;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new ui(t,r.clarifyTimeoutError?ui.ETIMEDOUT:ui.ECONNABORTED,e,g)),g=null},void 0===r&&s.setContentType(null),"setRequestHeader"in g&&li.forEach(s.toJSON(),function(e,t){g.setRequestHeader(t,e)}),li.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),u&&"json"!==u&&(g.responseType=i.responseType),h&&([c,l]=Zi(h,!0),g.addEventListener("progress",c)),p&&g.upload&&([a,d]=Zi(p),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(o=t=>{g&&(n(!t||t.type?new Hi(null,e,g):t),g.abort(),g=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===Oi.protocols.indexOf(y)?n(new ui("Unsupported protocol "+y+":",ui.ERR_BAD_REQUEST,e)):g.send(r||null)})},tr=(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 ui?t:new Hi(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new ui(`timeout ${t} of ms exceeded`,ui.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=()=>li.asap(o),a}},nr=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},ir=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()}},rr=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of ir(e))yield*nr(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})},sr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,or=sr&&"function"==typeof ReadableStream,ar=sr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),cr=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},dr=or&&cr(()=>{let e=!1;const t=new Request(Oi.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),lr=or&&cr(()=>li.isReadableStream(new Response("").body)),ur={stream:lr&&(e=>e.body)};var pr;sr&&(pr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!ur[e]&&(ur[e]=li.isFunction(pr[e])?t=>t[e]():(t,n)=>{throw new ui(`Response type '${e}' is not supported`,ui.ERR_NOT_SUPPORT,n)})}));const hr=async(e,t)=>{const n=li.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(li.isBlob(e))return e.size;if(li.isSpecCompliantForm(e)){const t=new Request(Oi.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return li.isArrayBufferView(e)||li.isArrayBuffer(e)?e.byteLength:(li.isURLSearchParams(e)&&(e+=""),li.isString(e)?(await ar(e)).byteLength:void 0)})(t):n},fr={http:null,xhr:er,fetch:sr&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=Yi(e);d=d?(d+"").toLowerCase():"text";let h,f=tr([r,s&&s.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&dr&&"get"!==n&&"head"!==n&&0!==(m=await hr(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(li.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=zi(m,Zi(Gi(c)));i=rr(n.body,65536,e,t)}}li.isString(u)||(u=u?"include":"omit");const r="credentials"in Request.prototype;h=new Request(t,{...p,signal:f,method:n.toUpperCase(),headers:l.normalize().toJSON(),body:i,duplex:"half",credentials:r?u:void 0});let s=await fetch(h,p);const o=lr&&("stream"===d||"response"===d);if(lr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=li.toFiniteNumber(s.headers.get("content-length")),[n,i]=a&&zi(t,Zi(Gi(a),!0))||[];s=new Response(rr(s.body,65536,n,()=>{i&&i(),g&&g()}),e)}d=d||"text";let y=await ur[li.findKey(ur,d)||"text"](s,e);return!o&&g&&g(),await new Promise((t,n)=>{Ki(t,n,{data:y,headers:Bi.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(y){if(g&&g(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new ui("Network Error",ui.ERR_NETWORK,e,h),{cause:y.cause||y});throw ui.from(y,y&&y.code,e,h)}})};li.forEach(fr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const gr=e=>`- ${e}`,mr=e=>li.isFunction(e)||null===e||!1===e,yr=e=>{e=li.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,!mr(n)&&(i=fr[(t=String(n)).toLowerCase()],void 0===i))throw new ui(`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 ui("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(gr).join("\n"):" "+gr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function br(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Hi(null,e)}function wr(e){br(e),e.headers=Bi.from(e.headers),e.data=Ui.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return yr(e.adapter||Pi.adapter)(e).then(function(t){return br(e),t.data=Ui.call(e,e.transformResponse,t),t.headers=Bi.from(t.headers),t},function(t){return ji(t)||(br(e),t&&t.response&&(t.response.data=Ui.call(e,e.transformResponse,t.response),t.response.headers=Bi.from(t.response.headers))),Promise.reject(t)})}const vr="1.11.0",Ir={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ir[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Tr={};Ir.transitional=function(e,t,n){function i(e,t){return"[Axios v"+vr+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new ui(i(r," has been removed"+(t?" in "+t:"")),ui.ERR_DEPRECATED);return t&&!Tr[r]&&(Tr[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)}},Ir.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const Ar={assertOptions:function(e,t,n){if("object"!=typeof e)throw new ui("options must be an object",ui.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 ui("option "+s+" must be "+n,ui.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new ui("Unknown option "+s,ui.ERR_BAD_OPTION)}},validators:Ir},Cr=Ar.validators;let _r=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ci,response:new Ci}}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=Xi(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&Ar.assertOptions(n,{silentJSONParsing:Cr.transitional(Cr.boolean),forcedJSONParsing:Cr.transitional(Cr.boolean),clarifyTimeoutError:Cr.transitional(Cr.boolean)},!1),null!=i&&(li.isFunction(i)?t.paramsSerializer={serialize:i}:Ar.assertOptions(i,{encode:Cr.function,serialize:Cr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ar.assertOptions(t,{baseUrl:Cr.spelling("baseURL"),withXsrfToken:Cr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&li.merge(r.common,r[t.method]);r&&li.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=[wr.bind(this),void 0];for(e.unshift(...o),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=o.length;let p=t;for(u=0;u<l;){const e=o[u++],t=o[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{d=wr.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(e){return Ai(Qi((e=Xi(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};li.forEach(["delete","get","head","options"],function(e){_r.prototype[e]=function(t,n){return this.request(Xi(n||{},{method:e,url:t,data:(n||{}).data}))}}),li.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(Xi(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}_r.prototype[e]=t(),_r.prototype[e+"Form"]=t(!0)});const Er={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(Er).forEach(([e,t])=>{Er[t]=e});const Rr=function e(t){const n=new _r(t),i=Tn(_r.prototype.request,n);return li.extend(i,_r.prototype,n,{allOwnKeys:!0}),li.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Xi(t,n))},i}(Pi);Rr.Axios=_r,Rr.CanceledError=Hi,Rr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const 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 Hi(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}}},Rr.isCancel=ji,Rr.VERSION=vr,Rr.toFormData=bi,Rr.AxiosError=ui,Rr.Cancel=Rr.CanceledError,Rr.all=function(e){return Promise.all(e)},Rr.spread=function(e){return function(t){return e.apply(null,t)}},Rr.isAxiosError=function(e){return li.isObject(e)&&!0===e.isAxiosError},Rr.mergeConfig=Xi,Rr.AxiosHeaders=Bi,Rr.formToJSON=e=>$i(li.isHTMLForm(e)?new FormData(e):e),Rr.getAdapter=yr,Rr.HttpStatusCode=Er,Rr.default=Rr;const{Axios:Sr,AxiosError:kr,CanceledError:xr,isCancel:Nr,CancelToken:Or,VERSION:$r,all:Pr,Cancel:Mr,isAxiosError:Fr,spread:Dr,toFormData:Lr,AxiosHeaders:qr,HttpStatusCode:Br,formToJSON:Ur,getAdapter:jr,mergeConfig:Hr}=Rr,Kr="ConnectionsManager not initialized";class Zr extends i.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t;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 Rr.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 Rr.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(Kr);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,p=0;const h=new Set;for(;Date.now()<l;){try{const e=(await this.getMessages(d)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||h.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),h.add(e),p++}}}catch(f){this.logger.error("Error during connection monitoring:",f)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:u,acceptedConnections:p,monitorDurationSeconds:i,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${u} requests, accepted ${p}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(Kr);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(Kr),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 zr 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}}function Gr(e){const t={},n={},i=[],r={};return Wr(e,"",t,n,i,r),{fields:t,groups:Jr(n),order:Xr(i,t),metadata:r}}function Wr(e,t,n,i,r,s){const o=ln(e),a=o._def?.typeName;"ZodObject"===a?function(e,t,n,i,r,s){const o=e.shape;if(sn(e)){const s=on(e);s&&t&&(n[t]=s,Vr(i,s.ui?.group||"default",t),Qr(r,t,s.ui?.order))}for(const[a,c]of Object.entries(o)){Wr(c,t?`${t}.${a}`:a,n,i,r,s)}}(o,t,n,i,r,s):"ZodArray"===a?function(e,t,n,i,r,s){if(sn(e)){const o=on(e);o&&(n[t]=o,Vr(i,o.ui?.group||"default",t),Qr(r,t,o.ui?.order),s[t]=hn(e))}const o=e._def.type;if(o){Wr(o,`${t}[]`,n,i,r,s)}}(o,t,n,i,r,s):function(e,t,n,i,r,s){if(sn(e)){const s=on(e);s&&(n[t]=s,Vr(i,s.ui?.group||"default",t),Qr(r,t,s.ui?.order))}s[t]=hn(e)}(e,t,n,i,r,s)}function Vr(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}function Qr(e,t,n){void 0!==n?e.splice(n,0,t):e.push(t)}function Jr(e){const t={},n=["default","Keys & Security","Token Settings","Custom Fees"];for(const i of n)e[i]&&(t[i]=e[i]);for(const[i,r]of Object.entries(e))n.includes(i)||(t[i]=r);return t}function Xr(e,t){const n={tokenName:1,tokenSymbol:2,maxSupply:3,supplyType:4,treasuryAccountId:5,memo:6};return e.sort((e,i)=>{const r=t[e],s=t[i];if(void 0!==r?.ui?.order&&void 0!==s?.ui?.order)return r.ui.order-s.ui.order;if(void 0!==r?.ui?.order)return-1;if(void 0!==s?.ui?.order)return 1;const o=n[e]||1e3,a=n[i]||1e3;return o!==a?o-a:e.localeCompare(i)})}class Yr 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 es 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 ts 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=Ct,e.BaseHCS10QueryTool=f,e.BaseHCS10TransactionTool=h,e.BaseHCS2QueryTool=xt,e.BaseHCS2TransactionTool=kt,e.BaseHCS6QueryTool=Lt,e.BaseHCS6TransactionTool=Dt,e.BaseInscriberQueryTool=Kt,e.BaseInscriberTransactionTool=Ht,e.CheckMessagesTool=mt,e.ConnectionMonitorTool=vt,e.CreateDynamicRegistryTool=class extends Lt{constructor(e){super(e),this.name="createDynamicRegistry",this.description="Create a new HCS-6 dynamic registry for managing evolving content"}get specificInputSchema(){return qt}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 Pt}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=bt,e.HCS10Builder=Zr,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=Yr,e.HCS6Builder=es,e.HbarPricePlugin=zr,e.InitiateConnectionTool=pt,e.InscribeFromBufferTool=class extends Kt{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description='Use ONLY for inscribing regular files or content (NOT for NFT/Hashinal inscriptions). When user says "inscribe it" after you showed search results or other content WITHOUT mentioning NFT/hashinal, 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. NEVER use this for Hashinal NFTs - always use InscribeHashinalTool instead when user mentions hashinal, NFT, dynamic, or minting.',this.config=Jt()}get specificInputSchema(){return Xt}async executeQuery(e,t){this.validateInput(e);const n=await async function(e,t,n){const i=e.trim(),s=r.ContentResolverRegistry.getResolver();if(!s)return Wt(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 Wt(i,t,n)}(e.base64Data,e.mimeType,e.fileName);this.validateContent(n.buffer);const i=n.buffer,s=n.mimeType||e.mimeType,o=n.fileName||e.fileName,a={mode:"file",metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,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:o,mimeType:s},a);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:o,mimeType:s,sizeBytes:i.length},message:`Estimated Quote for buffer content: ${o} (${(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}`)}try{const t=await this.executeInscription(i,o,s,a,e.timeoutMs);return this.formatInscriptionResult(t,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&&!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.`}},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 Gt}async executeQuery(e,t){let i;try{const t=await p.stat(e.filePath);if(!t.isFile())throw new Error(`Path "${e.filePath}" is not a file`);if(0===t.size)throw new Error(`File "${e.filePath}" is empty (0 bytes). Cannot inscribe empty files.`);if(t.size<10)throw new Error(`File "${e.filePath}" is too small (${t.size} bytes). Files must contain at least 10 bytes of meaningful content.`);if(t.size>104857600&&this.logger?.warn(`Large file detected (${(t.size/1048576).toFixed(2)} MB)`),this.logger?.info("Reading file content..."),i=await p.readFile(e.filePath),this.logger?.info(`Read ${i.length} bytes from file`),!i||0===i.length)throw new Error(`File "${e.filePath}" has no content after reading. Cannot inscribe empty files.`);if(i.length<10)throw new Error(`File "${e.filePath}" content is too small (${i.length} bytes). Files must contain at least 10 bytes of meaningful content.`);const n=u.basename(e.filePath),r=this.getMimeType(n);if(r.startsWith("text/")||"application/json"===r){if(""===i.toString("utf8",0,Math.min(i.length,1e3)).trim())throw new Error(`File "${e.filePath}" contains only whitespace or empty content. Cannot inscribe meaningless data.`)}}catch(c){if(c instanceof Error){if(c.message.includes("ENOENT"))throw new Error(`File not found: "${e.filePath}"`);throw c}throw new Error(`Failed to read file: ${c}`)}const r=i.toString("base64");this.logger?.info(`Converted to base64: ${r.length} characters`);const s=u.basename(e.filePath),o=this.getMimeType(s);this.logger?.info(`File: ${s}, MIME type: ${o}`);const a={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.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(r,"base64"),fileName:s,mimeType:o},a);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{fileName:s,mimeType:o,sizeBytes:i.length,filePath:e.filePath},message:`Estimated Quote for file: ${s} (${(i.length/1024).toFixed(2)} KB)\nTotal cost: ${t.totalCostHbar} HBAR`}}catch(c){const e=c instanceof Error?c.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(r,"base64"),fileName:s,mimeType:o},a),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:n.Buffer.from(r,"base64"),fileName:s,mimeType:o},a);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=${a.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(c){const e=c instanceof Error?c.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 zt}async executeQuery(e,t){if(Zt.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.`)}Zt.info("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){Zt.info("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;Zt.warn(`Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}Zt.info(`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)Zt.warn("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;Zt.warn(`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:60,waitIntervalMs:5e3,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:`Estimated Quote 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="Tool for inscribing Hashinal NFTs. CRITICAL: When user provides content (url/contentRef/base64Data), call with ONLY the content parameters - DO NOT auto-generate name, description, creator, or attributes. A form will be automatically shown to collect metadata from the user. Only include metadata parameters if the user explicitly provided them in their message."}getEntityResolutionPreferences(){return{name:"literal",description:"literal",creator:"literal",attributes:"literal",properties:"literal"}}get specificInputSchema(){return bn._def?.schema||bn}get schema(){if(!this._schemaWithRenderConfig){const e=this.specificInputSchema,t=e;t._renderConfig||(t._renderConfig={fieldType:"object",ui:{label:"Inscribe Hashinal NFT",description:"Create a Hashinal inscription for NFT minting"}}),this._schemaWithRenderConfig=e}return this._schemaWithRenderConfig}shouldGenerateForm(e){const t=new r.Logger({module:"InscribeHashinalTool"}),n=e;t.info("InscribeHashinalTool: Checking if form should be generated",{inputKeys:Object.keys(n||{}),hasContent:!!(n.url||n.contentRef||n.base64Data),renderFormProvided:"renderForm"in n,renderFormValue:n.renderForm});if(!!!(n.url||n.contentRef||n.base64Data))return t.info("InscribeHashinalTool: No content source provided"),!1;if("renderForm"in n&&!1===n.renderForm)return t.info("InscribeHashinalTool: renderForm=false, skipping form generation"),!1;const i=e=>"string"==typeof e&&0!==e.trim().length;return i(n.name)&&i(n.description)&&i(n.creator)?(t.info("InscribeHashinalTool: Required metadata present, skipping form generation"),!1):(t.info("InscribeHashinalTool: Content provided, showing form for metadata collection"),!0)}getFormSchema(){return rn(Ye({name:We().min(1,"Name is required").describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),description:We().min(1,"Description is required").describe("Meaningful description of the artwork, story, or concept behind this NFT"),creator:We().min(1,"Creator is required").describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),attributes:rn(Xe(Ye({trait_type:We().describe('Trait name (e.g., "Rarity", "Color", "Style")'),value:et([We(),Ve()]).describe('Trait value (e.g., "Epic", "Blue", 85)')}))).withRender(fn.array("NFT Attributes","Attribute")).optional().describe("Collectible traits and characteristics."),type:We().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card)')})).withRender({fieldType:"object",ui:{label:"Complete NFT Metadata",description:"Provide meaningful metadata to create a valuable NFT"}})}async executeQuery(e,t){if(!e.url&&!e.contentRef&&!e.base64Data)return mn({code:"MISSING_CONTENT",details:"No content source provided",suggestions:["Provide a URL to content you want to inscribe","Upload a file and use the content reference","Provide base64-encoded content data"]});const n=this.inscriberBuilder.hederaKit?.client?.operatorAccountId?.toString()||"0.0.unknown",i={...nn({name:e.name,creator:e.creator,description:e.description,type:e.type,fileName:e.fileName,mimeType:e.mimeType,operatorAccount:n}),attributes:Array.isArray(e.attributes)?e.attributes:[],properties:e.properties||{}};let s;try{s=function(e){try{return tn.parse(e)}catch(t){if(t instanceof I){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`).join("; ");throw new Error(`HIP-412 metadata validation failed: ${e}`)}throw t}}(i)}catch(c){return mn({code:"METADATA_VALIDATION_FAILED",details:`Metadata validation error: ${c instanceof Error?c.message:String(c)}`,suggestions:["Ensure all required metadata fields are provided","Check that attribute values are valid","Verify metadata follows HIP-412 standard"]})}const o={mode:"hashinal",metadata:s,jsonFileURL:e.jsonFileURL,fileStandard:e.fileStandard,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:60,waitIntervalMs:5e3,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};let a;if(e.url)a={type:"url",url:e.url};else{if(!e.contentRef&&!e.base64Data)throw new Error("No valid input data provided for inscription");{const t=e.contentRef||e.base64Data||"",{buffer:n,mimeType:i,fileName:r}=await this.resolveContent(t,e.mimeType,e.fileName);a={type:"buffer",buffer:n,fileName:r||e.fileName||"hashinal-content",mimeType:i||e.mimeType}}}if(e.quoteOnly)try{const t=await this.generateInscriptionQuote(a,o);return function(e){const{totalCostHbar:t,validUntil:n,breakdown:i,content:r}=e;return{success:!0,type:"quote",title:"Inscription Cost Quote",message:`Estimated cost to inscribe "${r.name||"your content"}" is ${t} HBAR.`,quote:{totalCostHbar:t,validUntil:n,breakdown:i},content:r}}({totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown,content:{name:e.name,creator:e.creator,type:e.type}})}catch(c){return mn({code:"QUOTE_GENERATION_FAILED",details:`Quote generation failed: ${c instanceof Error?c.message:"Failed to generate inscription quote"}`,suggestions:["Check network connectivity","Verify content is accessible","Try again in a moment"]})}try{let t;if(e.timeoutMs){const n=new Promise((t,n)=>{setTimeout(()=>n(new Error(`Inscription timed out after ${e.timeoutMs}ms`)),e.timeoutMs)});t=await Promise.race([this.inscriberBuilder.inscribe(a,o),n])}else t=await this.inscriberBuilder.inscribe(a,o);if(t.confirmed&&!t.quote){const n=t.inscription?.topic_id,i=t.inscription?.jsonTopicId,s=i?`https://kiloscribe.com/api/inscription-cdn/${i}?network=${o.network||"testnet"}`:null,c=e.fileStandard||"1",l=i?`hcs://${c}/${i}`:null,u="6"===c?"Dynamic":"Static";if(!l)return mn({code:"MISSING_TOPIC_ID",details:"Inscription completed but topic ID is missing",suggestions:["Try the inscription again","Contact support if the issue persists"]});const p=gn({hrl:l,topicId:i||n||"unknown",standard:u,cdnUrl:s||void 0,transactionId:t.result?.transactionId,metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes}});if(this.onEntityCreated?.({entityId:i||n||"unknown",entityName:e.name||"Unnamed Inscription",entityType:"topicId",transactionId:t.result?.transactionId}),e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(p,"buffer"===a.type?a.mimeType:void 0);p.hashLinkBlock=e}catch(d){new r.Logger({module:"InscribeHashinalTool"}).error("Failed to create HashLink block",{error:d})}return p}if(t.quote||t.confirmed)return mn({code:"UNKNOWN_STATE",details:"Inscription completed but result state is unclear",suggestions:["Check if the inscription was successful manually","Try the inscription again"]});{const n=t.inscription?.topic_id,i=t.inscription?.jsonTopicId;if(i||n){const s=i?`https://kiloscribe.com/api/inscription-cdn/${i}?network=${o.network||"testnet"}`:null,c=e.fileStandard||"1",l=i?`hcs://${c}/${i}`:null;if(l){const o=gn({hrl:l,topicId:i||n||"unknown",standard:"6"===c?"Dynamic":"Static",cdnUrl:s||void 0,transactionId:t.result?.transactionId,metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes}});if(this.onEntityCreated?.({entityId:i||n||"unknown",entityName:e.name||"Unnamed Inscription",entityType:"topicId",transactionId:t.result?.transactionId}),e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(o,"buffer"===a.type?a.mimeType:void 0);o.hashLinkBlock=e}catch(d){new r.Logger({module:"InscribeHashinalTool"}).error("Failed to create HashLink block",{error:d})}return o}}return mn({code:"INSCRIPTION_PENDING",details:`Inscription submitted but not yet confirmed. Transaction ID: ${t.result?.transactionId||"unknown"}`,suggestions:["Wait a few moments for confirmation","Check the transaction status on a Hedera explorer","Try the inscription again if it doesn't confirm within 5 minutes"]})}}catch(c){return mn({code:"INSCRIPTION_FAILED",details:`Inscription failed: ${c instanceof Error?c.message:"Failed to inscribe Hashinal NFT"}`,suggestions:["Check network connectivity","Verify you have sufficient HBAR balance","Ensure content is accessible and valid","Try again in a moment"]})}}async createHashLinkBlock(e,t){const n=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",i=e.inscription.cdnUrl?.includes("mainnet")?"mainnet":"testnet";if(n!==i){new r.Logger({module:"InscribeHashinalTool"}).warn(`Network mismatch detected: client=${n}, cdn=${i}. Using client network.`)}const s=n,o=function(e){const t="mainnet"===e?yn.mainnet:yn.testnet;return t&&"0.0.TBD"!==t.blockId?t:yn.testnet}(s);return{blockId:o.blockId,hashLink:o.hashLink,template:o.template,attributes:{name:e.metadata.name||"Untitled Content",creator:e.metadata.creator||"",topicId:e.inscription.topicId,hrl:e.inscription.hrl,network:s}}}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}}getEssentialFields(){return["name","description","creator","attributes"]}isFieldEmpty(e,t){return null==t||""===t||(!(!Array.isArray(t)||0!==t.length)||!("attributes"!==e||!Array.isArray(t))&&t.every(e=>!e||"object"==typeof e&&(!e.trait_type||!e.value)))}},e.InscriberBuilder=ts,e.ListConnectionsTool=ft,e.ListUnapprovedConnectionRequestsTool=St,e.ManageConnectionRequestsTool=Tt,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=In,e.QueryDynamicRegistryTool=class extends Lt{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 jt}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 Ft}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 Lt{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 Ot}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 wn}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"}),i=n;return{inscriptionId:i.inscriptionId,transactionId:n.transactionId||"unknown",topicId:i.topic_id,status:n.status||"unknown",holderId:i.holderId,metadata:n.metadata,tags:i.tags,mode:n.mode,chunks:i.chunks,createdAt:i.createdAt,completedAt:i.completed||i.completedAt,fileUrl:n.fileUrl,mimeType:i.mimeType,fileSize:i.fileSize}}},e.RetrieveProfileTool=Et,e.SendMessageToConnectionTool=lt,e.UpdateDynamicHashinalTool=class extends Lt{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 Ut}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 $t}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.createFieldConfigMap=function(e){const t=Gr(e),n={};for(const[i,r]of Object.entries(t.fields)){const e=t.metadata[i],s=i.split(".");n[i]={renderConfig:r,metadata:e,path:s}}return n},e.createProgressiveSchema=function(e,t){const n=rn(e),i=e._def?.typeName;if("ZodObject"===i){const i=e._def?.shape;if(i){for(const[e,n]of Object.entries(i)){let i,r="common";for(const[n,s]of Object.entries(t))if(s.fields.includes(e)){i=n,r=s.priority;break}rn(n).withProgressive(r,i)}return n}}return n},e.createSimpleConfig=function(e){const t=Gr(e),n=[];for(const i of t.order){const e=t.fields[i],r=t.metadata[i];e&&r&&n.push({name:i,type:r.type,label:e.ui?.label||i,required:r.required,placeholder:e.ui?.placeholder,options:e.options||r.options})}return{fields:n}},e.enhanceRenderConfig=function(e){return{...e,progressive:{priority:e.ui?.priority||"common",group:e.ui?.group}}},e.extendZodSchema=rn,e.extractFieldMetadata=hn,e.extractOptionsFromSchema=cn,e.extractProgressiveInfo=function(e){const t=on(e);return t?.progressive?{priority:t.progressive.priority,group:t.progressive.group}:t?.ui?.priority?{priority:t.ui.priority,group:t.ui.group}:{priority:"common"}},e.extractRenderConfigs=Gr,e.extractValidationConstraints=un,e.generateFieldOrdering=function(e){const t=Gr(e),n={},i={default:0,"Basic Information":1,"Token Settings":2,"Keys & Security":3,"Custom Fees":4,"Advanced Settings":5};for(const[r,s]of Object.entries(t.groups)){const e="default"===r?"Basic Information":r;n[e]={title:e,fields:s,order:i[e]||10}}return{sections:n,fieldOrder:t.order}},e.getDefaultValue=pn,e.getInnerSchema=ln,e.getRenderConfig=on,e.hasRenderConfig=sn,e.inferFieldTypeFromSchema=an,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",c="true"===t.env.DISABLE_LOGGING,d=r.Logger.getInstance({level:n.logLevel||"info",silent:c});let l;if("mainnet"===a?l="mainnet":("testnet"===a||d.warn(`Unsupported network specified: '${a}'. Defaulting to 'testnet'.`),l="testnet"),!s||!o)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const u=e?.stateManager||new In({defaultEnvFilePath:vn,defaultPrefix:"TODD"});d.info("State manager initialized");const p=new i.ServerSigner(s,o,l),h=new i.HederaAgentKit(p);await h.initialize(),d.info(`HederaAgentKit initialized for ${s} on ${l}`);const f=new Zr(h,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let g,m;if(e?.monitoringClient){const e=new i.ServerSigner(s,o,l);g=new i.HederaAgentKit(e),await g.initialize(),m=new Zr(g,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new at({hederaKit:h,hcs10Builder:f,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new bt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.retrieveProfileTool=new Et({hederaKit:h,hcs10Builder:f,logger:void 0}),y.initiateConnectionTool=new pt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listConnectionsTool=new ft({hederaKit:h,hcs10Builder:f,logger:void 0}),y.sendMessageToConnectionTool=new lt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.checkMessagesTool=new mt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.connectionMonitorTool=new vt({hederaKit:g||h,hcs10Builder:m||f,logger:void 0}),y.manageConnectionRequestsTool=new Tt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.acceptConnectionRequestTool=new Ct({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new St({hederaKit:h,hcs10Builder:f,logger:void 0}),d.info("All tools initialized")),{hederaKit:h,hcs10Builder:f,monitoringHederaKit:g,monitoringHcs10Builder:m,tools:y,stateManager:u}},e.installZodRenderExtensions=function(){L.prototype.withRender||(L.prototype.withRender=function(e){return rn(this).withRender(e)},L.prototype.withProgressive=function(e,t){return rn(this).withProgressive(e,t)},L.prototype.withBlock=function(e){return rn(this).withBlock(e)})},e.isFormValidatable=function(e){return null!==e&&"object"==typeof e&&"shouldGenerateForm"in e&&"getFormSchema"in e&&"getEssentialFields"in e&&"isFieldEmpty"in e&&"function"==typeof e.shouldGenerateForm&&"function"==typeof e.getFormSchema&&"function"==typeof e.getEssentialFields&&"function"==typeof e.isFieldEmpty},e.isOptionalSchema=dn,e.loadConfig=Jt,e.renderConfigs=fn,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=standards-agent-kit.umd.js.map