@hashgraphonline/standards-agent-kit 0.2.152 → 0.2.154

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 (40) hide show
  1. package/dist/cjs/standards-agent-kit.cjs +1 -1
  2. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  3. package/dist/es/standards-agent-kit.es24.js +1 -1
  4. package/dist/es/standards-agent-kit.es25.js +1 -1
  5. package/dist/es/standards-agent-kit.es26.js +1 -1
  6. package/dist/es/standards-agent-kit.es27.js +1 -1
  7. package/dist/es/standards-agent-kit.es28.js +1 -1
  8. package/dist/es/standards-agent-kit.es31.js +1 -1
  9. package/dist/es/standards-agent-kit.es32.js +1 -1
  10. package/dist/es/standards-agent-kit.es33.js +1 -1
  11. package/dist/es/standards-agent-kit.es36.js +1 -1
  12. package/dist/es/standards-agent-kit.es37.js +1 -1
  13. package/dist/es/standards-agent-kit.es38.js +3 -3
  14. package/dist/es/standards-agent-kit.es39.js +8 -8
  15. package/dist/es/standards-agent-kit.es39.js.map +1 -1
  16. package/dist/es/standards-agent-kit.es48.js +7 -3
  17. package/dist/es/standards-agent-kit.es48.js.map +1 -1
  18. package/dist/es/standards-agent-kit.es49.js +3 -7
  19. package/dist/es/standards-agent-kit.es49.js.map +1 -1
  20. package/dist/es/standards-agent-kit.es50.js +3 -20
  21. package/dist/es/standards-agent-kit.es50.js.map +1 -1
  22. package/dist/es/standards-agent-kit.es51.js +17 -50
  23. package/dist/es/standards-agent-kit.es51.js.map +1 -1
  24. package/dist/es/standards-agent-kit.es52.js +54 -3
  25. package/dist/es/standards-agent-kit.es52.js.map +1 -1
  26. package/dist/es/standards-agent-kit.es53.js +2 -39
  27. package/dist/es/standards-agent-kit.es53.js.map +1 -1
  28. package/dist/es/standards-agent-kit.es54.js +38 -17
  29. package/dist/es/standards-agent-kit.es54.js.map +1 -1
  30. package/dist/es/standards-agent-kit.es55.js +16 -71
  31. package/dist/es/standards-agent-kit.es55.js.map +1 -1
  32. package/dist/es/standards-agent-kit.es56.js +73 -3
  33. package/dist/es/standards-agent-kit.es56.js.map +1 -1
  34. package/dist/es/standards-agent-kit.es6.js +1 -1
  35. package/dist/es/standards-agent-kit.es7.js +1 -1
  36. package/dist/es/standards-agent-kit.es9.js +1 -1
  37. package/dist/umd/standards-agent-kit.umd.js +1 -1
  38. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  39. package/package.json +1 -1
  40. package/src/tools/inscriber/InscribeHashinalTool.ts +9 -3
@@ -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("@hashgraph/sdk"),require("@hashgraphonline/standards-sdk"),require("hedera-agent-kit"),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","@hashgraph/sdk","@hashgraphonline/standards-sdk","hedera-agent-kit","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.HederaSDK,e.StandardsSDK,e.HederaAgentKit,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],e["unenv/node/fs/promises"])}(this,function(e,t,n,i,r,s,a,o,c,d,l){"use strict";function u(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 p=u(o),h=u(l);class f extends s.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class g extends s.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var m,y,b;(y=m||(m={})).assertEqual=e=>{},y.assertIs=function(e){},y.assertNever=function(e){throw new Error},y.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},y.getValidEnumValues=e=>{const t=y.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const i of t)n[i]=e[i];return y.objectValues(n)},y.objectValues=e=>y.objectKeys(e).map(function(t){return e[t]}),y.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},y.find=(e,t)=>{for(const n of e)if(t(n))return n},y.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,y.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},y.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(b||(b={})).mergeShapes=(e,t)=>({...e,...t});const w=m.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),v=e=>{switch(typeof e){case"undefined":return w.undefined;case"string":return w.string;case"number":return Number.isNaN(e)?w.nan:w.number;case"boolean":return w.boolean;case"function":return w.function;case"bigint":return w.bigint;case"symbol":return w.symbol;case"object":return Array.isArray(e)?w.array:null===e?w.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?w.promise:"undefined"!=typeof Map&&e instanceof Map?w.map:"undefined"!=typeof Set&&e instanceof Set?w.set:"undefined"!=typeof Date&&e instanceof Date?w.date:w.object;default:return w.unknown}},I=m.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 T 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 T))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,m.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()}}T.create=e=>new T(e);const A=(e,t)=>{let n;switch(e.code){case I.invalid_type:n=e.received===w.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,m.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${m.joinValues(e.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${m.joinValues(e.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${m.joinValues(e.options)}, received '${e.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.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}"`:m.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case I.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 I.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 I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=t.defaultError,m.assertNever(e)}return{message:n}};let _=A;function C(e,t){const n=_,i=(e=>{const{data:t,path:n,errorMaps:i,issueData:r}=e,s=[...n,...r.path||[]],a={...r,path:s};if(void 0!==r.message)return{...r,path:s,message:r.message};let o="";const c=i.filter(e=>!!e).slice().reverse();for(const d of c)o=d(a,{data:t,defaultError:o}).message;return{...r,path:s,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===A?void 0:A].filter(e=>!!e)});e.common.issues.push(i)}class E{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 S;"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 E.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 S;if("aborted"===r.status)return S;"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 S=Object.freeze({status:"aborted"}),R=e=>({status:"dirty",value:e}),x=e=>({status:"valid",value:e}),k=e=>"aborted"===e.status,O=e=>"dirty"===e.status,N=e=>"valid"===e.status,B=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 q=(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 T(e.common.issues);return this._error=t,this._error}}};function F(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:i,description:r}=e;if(t&&(n||i))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(t,r)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??r.defaultError}:void 0===r.data?{message:s??i??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:s??n??r.defaultError}},description:r}}class D{get description(){return this._def.description}_getType(e){return v(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:v(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new E,ctx:{common:e.parent.common,data:e.data,parsedType:v(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(B(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:v(e)},i=this._parseSync({data:e,path:n.path,parent:n});return q(n,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:v(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:v(e)},i=this._parse({data:e,path:n.path,parent:n}),r=await(B(i)?i:Promise.resolve(i));return q(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:I.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 Fe({schema:this,typeName:We.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return De.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Te.create(this)}promise(){return qe.create(this,this._def)}or(e){return Ce.create([this,e],this._def)}and(e){return Se.create(this,e,this._def)}transform(e){return new Fe({...F(this._def),schema:this,typeName:We.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new He({...F(this._def),innerType:this,defaultValue:t,typeName:We.ZodDefault})}brand(){return new Ke({typeName:We.ZodBranded,type:this,...F(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...F(this._def),innerType:this,catchValue:t,typeName:We.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ze.create(this,e)}readonly(){return ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const L=/^c[^\s-]{8,}$/i,H=/^[0-9a-z]+$/,U=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,K=/^[a-z0-9_-]{21}$/i,Z=/^[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)?)??$/,W=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let G;const 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])$/,Q=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,J=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,X=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Y=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ee=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,te="((\\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])))",ne=new RegExp(`^${te}$`);function ie(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 re(e){return new RegExp(`^${ie(e)}$`)}function se(e){let t=`${te}T${ie(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 ae(e,t){return!("v4"!==t&&t||!V.test(e))||!("v6"!==t&&t||!J.test(e))}function oe(e,t){if(!Z.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 ce(e,t){return!("v4"!==t&&t||!Q.test(e))||!("v6"!==t&&t||!X.test(e))}class de extends D{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==w.string){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.string,received:t.parsedType}),S}const t=new E;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:I.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:I.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:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&C(n,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)W.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"email",code:I.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:I.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:I.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)K.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"nanoid",code:I.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)L.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"cuid",code:I.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)H.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"cuid2",code:I.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:I.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:I.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:I.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:I.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:I.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:I.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){se(i).test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:I.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){ne.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:I.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){re(i).test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:I.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:I.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?ae(e.data,i.version)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"ip",code:I.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:I.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?ce(e.data,i.version)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"cidr",code:I.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Y.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"base64",code:I.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?ee.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"base64url",code:I.invalid_string,message:i.message}),t.dirty()):m.assertNever(i);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:I.invalid_string,...$.errToObj(n)})}_addCheck(e){return new de({...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 de({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new de({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new de({...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 le(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}de.create=e=>new de({checks:[],typeName:We.ZodString,coerce:e?.coerce??!1,...F(e)});class ue extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==w.number){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.number,received:t.parsedType}),S}let t;const n=new E;for(const i of this._def.checks)if("int"===i.kind)m.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),C(t,{code:I.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:I.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:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty())}else"multipleOf"===i.kind?0!==le(e.data,i.value)&&(t=this._getOrReturnCtx(e,t),C(t,{code:I.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:I.not_finite,message:i.message}),n.dirty()):m.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 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]})}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&&m.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)}}ue.create=e=>new ue({checks:[],typeName:We.ZodNumber,coerce:e?.coerce||!1,...F(e)});class pe extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==w.bigint)return this._getInvalidInput(e);let t;const n=new E;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:I.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:I.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:I.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):m.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.bigint,received:t.parsedType}),S}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 pe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$.toString(i)}]})}_addCheck(e){return new pe({...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}}pe.create=e=>new pe({checks:[],typeName:We.ZodBigInt,coerce:e?.coerce??!1,...F(e)});class he extends D{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==w.boolean){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.boolean,received:t.parsedType}),S}return x(e.data)}}he.create=e=>new he({typeName:We.ZodBoolean,coerce:e?.coerce||!1,...F(e)});class fe extends D{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==w.date){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.date,received:t.parsedType}),S}if(Number.isNaN(e.data.getTime())){return C(this._getOrReturnCtx(e),{code:I.invalid_date}),S}const t=new E;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:I.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:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):m.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new fe({...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}}fe.create=e=>new fe({checks:[],coerce:e?.coerce||!1,typeName:We.ZodDate,...F(e)});class ge extends D{_parse(e){if(this._getType(e)!==w.symbol){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.symbol,received:t.parsedType}),S}return x(e.data)}}ge.create=e=>new ge({typeName:We.ZodSymbol,...F(e)});class me extends D{_parse(e){if(this._getType(e)!==w.undefined){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.undefined,received:t.parsedType}),S}return x(e.data)}}me.create=e=>new me({typeName:We.ZodUndefined,...F(e)});class ye extends D{_parse(e){if(this._getType(e)!==w.null){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.null,received:t.parsedType}),S}return x(e.data)}}ye.create=e=>new ye({typeName:We.ZodNull,...F(e)});class be extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return x(e.data)}}be.create=e=>new be({typeName:We.ZodAny,...F(e)});class we extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return x(e.data)}}we.create=e=>new we({typeName:We.ZodUnknown,...F(e)});class ve extends D{_parse(e){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.never,received:t.parsedType}),S}}ve.create=e=>new ve({typeName:We.ZodNever,...F(e)});class Ie extends D{_parse(e){if(this._getType(e)!==w.undefined){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.void,received:t.parsedType}),S}return x(e.data)}}Ie.create=e=>new Ie({typeName:We.ZodVoid,...F(e)});class Te extends D{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==w.array)return C(t,{code:I.invalid_type,expected:w.array,received:t.parsedType}),S;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?I.too_big:I.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:I.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:I.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=>E.mergeArray(n,e));const r=[...t.data].map((e,n)=>i.type._parseSync(new M(t,e,t.path,n)));return E.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new Te({...this._def,minLength:{value:e,message:$.toString(t)}})}max(e,t){return new Te({...this._def,maxLength:{value:e,message:$.toString(t)}})}length(e,t){return new Te({...this._def,exactLength:{value:e,message:$.toString(t)}})}nonempty(e){return this.min(1,e)}}function Ae(e){if(e instanceof _e){const t={};for(const n in e.shape){const i=e.shape[n];t[n]=De.create(Ae(i))}return new _e({...e._def,shape:()=>t})}return e instanceof Te?new Te({...e._def,type:Ae(e.element)}):e instanceof De?De.create(Ae(e.unwrap())):e instanceof Le?Le.create(Ae(e.unwrap())):e instanceof Re?Re.create(e.items.map(e=>Ae(e))):e}Te.create=(e,t)=>new Te({type:e,minLength:null,maxLength:null,exactLength:null,typeName:We.ZodArray,...F(t)});class _e extends D{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=m.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==w.object){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.object,received:t.parsedType}),S}const{status:t,ctx:n}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),s=[];if(!(this._def.catchall instanceof ve&&"strip"===this._def.unknownKeys))for(const o in n.data)r.includes(o)||s.push(o);const a=[];for(const o of r){const e=i[o],t=n.data[o];a.push({key:{status:"valid",value:o},value:e._parse(new M(n,t,n.path,o)),alwaysSet:o in n.data})}if(this._def.catchall instanceof ve){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of s)a.push({key:{status:"valid",value:t},value:{status:"valid",value:n.data[t]}});else if("strict"===e)s.length>0&&(C(n,{code:I.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const i=n.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new 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 a){const n=await t.key,i=await t.value;e.push({key:n,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>E.mergeObjectSync(t,e)):E.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return $.errToObj,new _e({...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 _e({...this._def,unknownKeys:"strip"})}passthrough(){return new _e({...this._def,unknownKeys:"passthrough"})}extend(e){return new _e({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new _e({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:We.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new _e({...this._def,catchall:e})}pick(e){const t={};for(const n of m.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new _e({...this._def,shape:()=>t})}omit(e){const t={};for(const n of m.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new _e({...this._def,shape:()=>t})}deepPartial(){return Ae(this)}partial(e){const t={};for(const n of m.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new _e({...this._def,shape:()=>t})}required(e){const t={};for(const n of m.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof De;)e=e._def.innerType;t[n]=e}return new _e({...this._def,shape:()=>t})}keyof(){return $e(m.objectKeys(this.shape))}}_e.create=(e,t)=>new _e({shape:()=>e,unknownKeys:"strip",catchall:ve.create(),typeName:We.ZodObject,...F(t)}),_e.strictCreate=(e,t)=>new _e({shape:()=>e,unknownKeys:"strict",catchall:ve.create(),typeName:We.ZodObject,...F(t)}),_e.lazycreate=(e,t)=>new _e({shape:e,unknownKeys:"strip",catchall:ve.create(),typeName:We.ZodObject,...F(t)});class Ce extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const i of e)if("dirty"===i.result.status)return t.common.issues.push(...i.ctx.common.issues),i.result;const n=e.map(e=>new T(e.ctx.common.issues));return C(t,{code:I.invalid_union,unionErrors:n}),S});{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 T(e));return C(t,{code:I.invalid_union,unionErrors:r}),S}}get options(){return this._def.options}}function Ee(e,t){const n=v(e),i=v(t);if(e===t)return{valid:!0,data:e};if(n===w.object&&i===w.object){const n=m.objectKeys(t),i=m.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const s of i){const n=Ee(e[s],t[s]);if(!n.valid)return{valid:!1};r[s]=n.data}return{valid:!0,data:r}}if(n===w.array&&i===w.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let i=0;i<e.length;i++){const r=Ee(e[i],t[i]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===w.date&&i===w.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Ce.create=(e,t)=>new Ce({options:e,typeName:We.ZodUnion,...F(t)});class Se extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=(e,i)=>{if(k(e)||k(i))return S;const r=Ee(e.value,i.value);return r.valid?((O(e)||O(i))&&t.dirty(),{status:t.value,value:r.data}):(C(n,{code:I.invalid_intersection_types}),S)};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}))}}Se.create=(e,t,n)=>new Se({left:e,right:t,typeName:We.ZodIntersection,...F(n)});class Re extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.array)return C(n,{code:I.invalid_type,expected:w.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return C(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(C(n,{code:I.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=>E.mergeArray(t,e)):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:We.ZodTuple,rest:null,...F(t)})};class xe extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.object)return C(n,{code:I.invalid_type,expected:w.object,received:n.parsedType}),S;const i=[],r=this._def.keyType,s=this._def.valueType;for(const a in n.data)i.push({key:r._parse(new M(n,a,n.path,a)),value:s._parse(new M(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?E.mergeObjectAsync(t,i):E.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return new xe(t instanceof D?{keyType:e,valueType:t,typeName:We.ZodRecord,...F(n)}:{keyType:de.create(),valueType:e,typeName:We.ZodRecord,...F(t)})}}class ke extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.map)return C(n,{code:I.invalid_type,expected:w.map,received:n.parsedType}),S;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 S;"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 S;"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:We.ZodMap,...F(n)});class Oe extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.set)return C(n,{code:I.invalid_type,expected:w.set,received:n.parsedType}),S;const i=this._def;null!==i.minSize&&n.data.size<i.minSize.value&&(C(n,{code:I.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:I.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 S;"dirty"===i.status&&t.dirty(),n.add(i.value)}return{status:t.value,value:n}}const a=[...n.data.values()].map((e,t)=>r._parse(new M(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>s(e)):s(a)}min(e,t){return new Oe({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new Oe({...this._def,maxSize:{value:e,message:$.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Oe.create=(e,t)=>new Oe({valueType:e,minSize:null,maxSize:null,typeName:We.ZodSet,...F(t)});class Ne extends D{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ne.create=(e,t)=>new Ne({getter:e,typeName:We.ZodLazy,...F(t)});class Be extends D{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return C(t,{received:t.data,code:I.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}function $e(e,t){return new Pe({values:e,typeName:We.ZodEnum,...F(t)})}Be.create=(e,t)=>new Be({value:e,typeName:We.ZodLiteral,...F(t)});class Pe extends D{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return C(t,{expected:m.joinValues(n),received:t.parsedType,code:I.invalid_type}),S}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:I.invalid_enum_value,options:n}),S}return x(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Pe.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Pe.create=$e;class Me extends D{_parse(e){const t=m.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==w.string&&n.parsedType!==w.number){const e=m.objectValues(t);return C(n,{expected:m.joinValues(e),received:n.parsedType,code:I.invalid_type}),S}if(this._cache||(this._cache=new Set(m.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=m.objectValues(t);return C(n,{received:n.data,code:I.invalid_enum_value,options:e}),S}return x(e.data)}get enum(){return this._def.values}}Me.create=(e,t)=>new Me({values:e,typeName:We.ZodNativeEnum,...F(t)});class qe extends D{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.promise&&!1===t.common.async)return C(t,{code:I.invalid_type,expected:w.promise,received:t.parsedType}),S;const n=t.parsedType===w.promise?t.data:Promise.resolve(t.data);return x(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}qe.create=(e,t)=>new qe({type:e,typeName:We.ZodPromise,...F(t)});class Fe extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===We.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 S;const i=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===i.status?S:"dirty"===i.status||"dirty"===t.value?R(i.value):i});{if("aborted"===t.value)return S;const i=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===i.status?S:"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?S:("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?S:("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 S;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})):S)}m.assertNever(i)}}Fe.create=(e,t,n)=>new Fe({schema:e,typeName:We.ZodEffects,effect:t,...F(n)}),Fe.createWithPreprocess=(e,t,n)=>new Fe({schema:t,effect:{type:"preprocess",transform:e},typeName:We.ZodEffects,...F(n)});class De extends D{_parse(e){return this._getType(e)===w.undefined?x(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:We.ZodOptional,...F(t)});class Le extends D{_parse(e){return this._getType(e)===w.null?x(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(e,t)=>new Le({innerType:e,typeName:We.ZodNullable,...F(t)});class He extends D{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===w.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}He.create=(e,t)=>new He({innerType:e,typeName:We.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...F(t)});class Ue extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return B(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new T(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new T(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ue.create=(e,t)=>new Ue({innerType:e,typeName:We.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...F(t)});class je extends D{_parse(e){if(this._getType(e)!==w.nan){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.nan,received:t.parsedType}),S}return{status:"valid",value:e.data}}}je.create=e=>new je({typeName:We.ZodNaN,...F(e)});class Ke extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ze extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?S:"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?S:"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 Ze({in:e,out:t,typeName:We.ZodPipeline})}}class ze extends D{_parse(e){const t=this._def.innerType._parse(e),n=e=>(N(e)&&(e.value=Object.freeze(e.value)),e);return B(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var We,Ge;ze.create=(e,t)=>new ze({innerType:e,typeName:We.ZodReadonly,...F(t)}),(Ge=We||(We={})).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 Ve=de.create,Qe=ue.create,Je=he.create,Xe=we.create;ve.create;const Ye=Te.create,et=_e.create,tt=Ce.create;Se.create,Re.create;const nt=xe.create,it=Pe.create,rt=Me.create;qe.create,De.create,Le.create;const st=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"}};st.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 at=st;const ot=et({name:Ve().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:Ve().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:Ve().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:it(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:Ve().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:tt([Ye(rt(r.AIAgentCapability)),Ye(Ve()),Ve()]).optional().transform(e=>{if(e)return"string"==typeof e?at.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?at.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:tt([Ye(Ve()),Ve()]).optional().transform(e=>{if(e)return"string"==typeof e?at.parseCapabilities(e):at.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:Ve().optional().describe("Creator attribution for the agent"),socials:nt(it(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),Ve()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:nt(Xe()).optional().describe("Custom metadata properties for the agent"),profilePicture:tt([Ve().describe("URL or local file path to profile picture"),et({url:Ve().optional(),path:Ve().optional(),filename:Ve().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:Ve().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:Qe().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:Ve().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:Qe().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:Ye(et({amount:Qe().positive(),tokenId:Ve()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Ye(Ve()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Je().optional().describe("Whether to set as current agent (default: true)"),persistence:et({prefix:Ve().optional()}).optional().describe("Optional persistence configuration")});class ct extends f{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},a=this.getServiceBuilder().getStateManager();if(a&&(a.setCurrentAgent(e),a.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");a.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const dt=new r.Logger({module:"SendMessageToConnectionTool"}),lt=et({targetIdentifier:Ve().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:Ve().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:Ve().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:Ve().describe("The text message content to send."),disableMonitoring:Je().optional().default(!1)});class ut extends f{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=lt,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){dt.debug("Could not refresh connections:",s)}if(i.match(/^\d+$/)){const e=r.listConnections(),s=parseInt(i)-1,a=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(s>=0&&s<a.length){const e=a[s];if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}if(i.match(/^\d+\.\d+\.\d+$/)){const e=r.listConnections().find(e=>!(e.targetAccountId!==i&&e.targetAccountId!==`0.0.${i}`||"established"!==e.status||e.isPending||e.needsConfirmation));if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}await n.sendMessageToConnection({targetIdentifier:i,message:t.message,disableMonitoring:t.disableMonitoring})}}const pt=et({targetAccountId:Ve().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:Je().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:Ve().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 ht extends f{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=pt,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 ft=et({includeDetails:Je().optional().describe("Whether to include detailed information about each connection"),showPending:Je().optional().describe("Whether to include pending connection requests")});class gt extends g{constructor(e){super(e),this.name="list_connections",this.description="Lists all active HCS-10 connections. Use this FIRST before sending messages to check if you already have an active connection to a target agent. Shows connection details and agent information for each active connection.",this.specificInputSchema=ft}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 mt=et({targetIdentifier:Ve().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:Je().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:Qe().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class yt extends g{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=mt}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 bt=et({accountId:Ve().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:tt([Ye(rt(r.AIAgentCapability)),Ye(Ve()),Ve()]).optional().transform(e=>{if(e)return"string"==typeof e?at.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?at.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class wt extends g{constructor(e){super(e),this.name="find_registrations",this.description='Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=bt}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 vt=et({acceptAll:Je().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:Ve().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:Ye(et({amount:Qe(),collectorAccount:Ve().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Ye(et({amount:Qe(),tokenId:Ve(),collectorAccount:Ve().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:Ye(Ve()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:Qe().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:Ve().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class It extends f{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=vt,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 Tt=et({action:it(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:Ve().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class At extends g{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=Tt}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 _t=et({requestKey:Ve().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:Qe().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:Ye(Ve()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class Ct extends f{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=_t,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 Et=et({accountId:Ve().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:Je().optional().describe("Optional: Force refresh from the network instead of using cache.")});class St extends g{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=Et}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=et({});class xt extends g{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=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 s.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class Ot extends s.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}function Nt(e){return!!e&&"string"==typeof e.transactionBytes}const Bt=et({registryType:rt(r.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:Qe().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:tt([Ve(),Je()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:tt([Ve(),Je()]).optional().describe("Submit key: public key string or true to use operator key")});const $t=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:Ve().optional().describe("Optional metadata URI (HIP-412 format)"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const Pt=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:Ve().describe("The unique ID of the entry to update"),metadata:Ve().optional().describe("Optional metadata URI (HIP-412 format)"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const Mt=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:Ve().describe("The unique ID of the entry to delete"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const qt=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:Ve().optional().describe("Optional metadata URI for migration details"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const Ft=et({topicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:Qe().int().positive().optional().describe("Maximum number of entries to return"),order:it(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:Qe().int().min(0).optional().describe("Number of entries to skip")});class Dt extends s.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Lt extends s.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const Ht=et({ttl:Qe().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),submitKey:tt([Je(),Ve()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Ut=et({metadata:nt(Xe()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:et({base64:Ve().optional().describe("Base64 encoded data for the hashinal"),url:Ve().optional().describe("URL to fetch data from"),mimeType:Ve().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:Ve().optional().describe("Optional memo for the registration"),ttl:Qe().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:Ve().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:Ve().optional().describe("Submit key for the registry (required if registry has a submit key)")});const jt=et({registryTopicId:Ve().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:nt(Xe()).describe("Updated metadata object for the hashinal"),data:et({base64:Ve().optional().describe("Base64 encoded data for the updated hashinal"),url:Ve().optional().describe("URL to fetch updated data from"),mimeType:Ve().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:Ve().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:Ve().describe("Submit key for the registry (required to update)")});const Kt=et({topicId:Ve().describe("The registry topic ID to query"),limit:Qe().optional().default(100).describe("Maximum number of entries to retrieve"),order:it(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:Qe().optional().describe("Number of entries to skip")});class Zt extends s.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 zt extends s.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}}function Wt(e,t){if(!e||"object"!=typeof e)return;const n=e[t];return"string"==typeof n&&n.trim()?n:void 0}function Gt(e,t){return{jsonTopicId:e.jsonTopicId||Wt(e,"json_topic_id"),topicId:Wt(e,"topic_id")||Wt(e,"topicId")||Wt(t,"topicId")||Wt(t,"topic_id")}}function Vt(e,t,n="1"){const i=e.jsonTopicId||e.topicId;return{hrl:i?`hcs://${n}/${i}`:void 0,cdnUrl:e.jsonTopicId?`https://kiloscribe.com/api/inscription-cdn/${e.jsonTopicId}?network=${t}`:void 0,topicId:i}}const Qt=new r.Logger({module:"InscribeFromUrlTool"}),Jt=et({url:Ve().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:it(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:nt(Xe()).optional().describe("Metadata to attach to the inscription"),tags:Ye(Ve()).optional().describe("Tags to categorize the inscription"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:Ve().optional().describe("API key for inscription service"),quoteOnly:Je().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const Xt=et({filePath:Ve().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:it(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:nt(Xe()).optional().describe("Metadata to attach to the inscription"),tags:Ye(Ve()).optional().describe("Tags to categorize the inscription"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:Ve().optional().describe("API key for inscription service"),quoteOnly:Je().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});function Yt(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 en=Ve().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]"'),tn={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function nn(){return{maxInscriptionSize:parseInt(t.env.REF_MAX_SIZE||tn.maxInscriptionSize.toString(),10),minContentSize:parseInt(t.env.REF_MIN_SIZE||tn.minContentSize.toString(),10),logLevel:t.env.REF_LOG_LEVEL||tn.logLevel,enableContentValidation:"false"!==t.env.REF_ENABLE_VALIDATION}}const rn=et({base64Data:tt([Ve(),en]).describe("Content to inscribe as base64 data, plain text, or content reference"),fileName:Ve().min(1).describe("Name for the inscribed content"),mimeType:Ve().optional().describe("MIME type of the content"),metadata:nt(Xe()).optional().describe("Metadata to attach"),tags:Ye(Ve()).optional().describe("Tags to categorize the inscription"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Wait for inscription confirmation"),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds"),apiKey:Ve().optional().describe("API key for inscription service"),quoteOnly:Je().optional().default(!1).describe("Return cost quote only")});const sn=et({uri:Ve().describe("URI of the file"),checksum:Ve().optional().describe("SHA-256 checksum of the file"),is_default_file:Je().optional().describe("Whether this is the default file"),type:Ve().describe("MIME type of the file")}),an=et({trait_type:Ve().describe("The trait type"),value:tt([Ve(),Qe()]).describe("The trait value"),display_type:Ve().optional().describe("Display type for the attribute")}),on=et({name:Ve().describe("Token name (required by HIP-412)"),description:Ve().describe("Human readable description (required by HIP-412)"),image:Ve().describe("Preview image URI (required by HIP-412)"),type:Ve().describe("MIME type (required by HIP-412)"),creator:Ve().optional().describe("Creator name or comma-separated names"),creatorDID:Ve().optional().describe("Decentralized identifier for creator"),checksum:Ve().optional().describe("SHA-256 checksum of the image"),format:Ve().optional().default("HIP412@2.0.0").describe("Metadata format version"),files:Ye(sn).optional().describe("Array of files for multi-file NFTs"),attributes:Ye(an).optional().describe("NFT attributes/traits"),properties:nt(Xe()).optional().describe("Additional properties")});function cn(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 dn(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:pn(e)};return this.withRender({...i,progressive:{priority:t,group:n}})},t.withBlock=function(t){const n=this._renderConfig||{fieldType:pn(e)};return this.withRender({...n,block:{id:t,type:"field",reusable:!0}})},t}function ln(e){return Boolean(e&&"function"==typeof e.withRender)}function un(e){if(ln(e))return e._renderConfig}function pn(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?pn(t):"text"}}}function hn(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 fn(e){const t=e._def?.typeName;return"ZodOptional"===t||"ZodDefault"===t}function gn(e){const t=e._def?.typeName;if("ZodOptional"===t||"ZodDefault"===t){const t=e._def?.innerType;return t||e}return e}function mn(e){const t=gn(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 yn(e){const t=e._def?.typeName;if("ZodDefault"===t){const t=e._def?.defaultValue;return"function"==typeof t?t():t}const n=gn(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]=yn(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 bn(e){const t=gn(e),n=pn(e),i=!fn(e),r=fn(e),s=yn(e),a=hn(t),o=mn(e),c=e?.description;return{type:n,required:i,optional:r,default:s,options:a,constraints:o,description:c,validation:{minLength:o.minLength,maxLength:o.maxLength,min:o.min,max:o.max,pattern:o.pattern?new RegExp(o.pattern):void 0}}}const wn={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)=>wn.text(e,t,"essential"),number:(e,t,n)=>wn.number(e,t,n,"essential"),select:(e,t)=>wn.select(e,t,"essential"),textarea:(e,t)=>wn.textarea(e,t,"essential")},advanced:{text:(e,t)=>wn.text(e,t,"advanced"),number:(e,t,n)=>wn.number(e,t,n,"advanced"),select:(e,t)=>wn.select(e,t,"advanced"),textarea:(e,t)=>wn.textarea(e,t,"advanced"),array:(e,t)=>wn.array(e,t,"advanced")},expert:{text:(e,t)=>wn.text(e,t,"expert"),number:(e,t,n)=>wn.number(e,t,n,"expert"),select:(e,t)=>wn.select(e,t,"expert"),textarea:(e,t)=>wn.textarea(e,t,"expert")}};function vn(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 In={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 Tn=dn(et({url:Ve().optional().describe("The URL of the content to inscribe as Hashinal NFT (use this OR contentRef)"),contentRef:en.optional().describe('Content reference ID in format "content-ref:[id]" for already stored content (use this OR url)'),base64Data:Ve().optional().describe("Base64 encoded content data (use this if neither url nor contentRef provided)"),fileName:Ve().optional().describe("File name for the content (required when using base64Data or contentRef)"),mimeType:Ve().optional().describe('MIME type of the content (e.g., "image/png", "image/jpeg")'),name:Ve().optional().describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),creator:Ve().optional().describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),description:Ve().optional().describe("Meaningful description of the artwork, story, or concept behind this NFT"),type:Ve().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card")'),attributes:dn(Ye(et({trait_type:Ve(),value:tt([Ve(),Qe()])}))).withRender(wn.array("NFT Attributes","Attribute")).optional().describe('Collectible traits and characteristics (e.g., "Rarity": "Epic", "Color": "Blue", "Style": "Abstract")'),properties:nt(Xe()).optional().describe("Additional properties"),jsonFileURL:Ve().url().optional().describe("URL to JSON metadata file"),fileStandard:it(["1","6"]).optional().default("1").describe("HCS file standard: 1 for static Hashinals (HCS-5), 6 for dynamic Hashinals (HCS-6)"),tags:Ye(Ve()).optional().describe("Tags to categorize the NFT"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),quoteOnly:Je().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription"),withHashLinkBlocks:Je().optional().default(!0).describe("If true, creates interactive HashLink blocks for the inscribed content and returns block data alongside the inscription response"),renderForm:Je().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 An=et({transactionId:Ve().describe("The transaction ID of the inscription to retrieve"),apiKey:Ve().optional().describe("API key for inscription service")});const _n=o.join(t.cwd(),".env");class Cn{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 s={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";a.existsSync(e)&&(n=a.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}`)}a.writeFileSync(e,i.join("\n"))}(i,s)}}const En=class{static setSignerProvider(e){this._signerProvider=e}static async getSigner(){const e=this._signerProvider;if(!e)return null;try{if("function"==typeof e){const t=e();return t&&"function"==typeof t.then?await t:t}return e}catch{return null}}static setWalletInfoResolver(e){this._walletInfoResolver=e||null}static async getWalletInfo(){const e=this._walletInfoResolver;if(!e)return null;try{const t=e();return t&&"function"==typeof t.then?await t:t}catch{return null}}static setWalletExecutor(e){this._walletExecutor=e||null}static get walletExecutor(){return this._walletExecutor||null}static setStartHCSDelegate(e){this._startHCSDelegate=e||null}static get startHCSDelegate(){return this._startHCSDelegate||null}static setPreferWalletOnly(e){this._preferWalletOnly=!!e}static setBrowserHCSClientFactory(e){this._browserHCSClientFactory=e||null}static getBrowserHCSClient(e){return this._browserHCSClientFactory?this._browserHCSClientFactory(e):null}static get preferWalletOnly(){return this._preferWalletOnly}};En._preferWalletOnly=!1;let Sn=En;function Rn(e,t){return function(){return e.apply(t,arguments)}}const{toString:xn}=Object.prototype,{getPrototypeOf:kn}=Object,{iterator:On,toStringTag:Nn}=Symbol,Bn=(e=>t=>{const n=xn.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),$n=e=>(e=e.toLowerCase(),t=>Bn(t)===e),Pn=e=>t=>typeof t===e,{isArray:Mn}=Array,qn=Pn("undefined");function Fn(e){return null!==e&&!qn(e)&&null!==e.constructor&&!qn(e.constructor)&&Hn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Dn=$n("ArrayBuffer");const Ln=Pn("string"),Hn=Pn("function"),Un=Pn("number"),jn=e=>null!==e&&"object"==typeof e,Kn=e=>{if("object"!==Bn(e))return!1;const t=kn(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Nn in e||On in e)},Zn=$n("Date"),zn=$n("File"),Wn=$n("Blob"),Gn=$n("FileList"),Vn=$n("URLSearchParams"),[Qn,Jn,Xn,Yn]=["ReadableStream","Request","Response","Headers"].map($n);function ei(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),Mn(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(Fn(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let a;for(i=0;i<s;i++)a=r[i],t.call(null,e[a],a,e)}}function ti(e,t){if(Fn(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 ni="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:c,ii=e=>!qn(e)&&e!==ni;const ri=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&kn(Uint8Array)),si=$n("HTMLFormElement"),ai=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),oi=$n("RegExp"),ci=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};ei(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const di=$n("AsyncFunction"),li=(ui="function"==typeof d.setImmediate,pi=Hn(ni.postMessage),ui?d.setImmediate:pi?(hi=`axios@${Math.random()}`,fi=[],ni.addEventListener("message",({source:e,data:t})=>{e===ni&&t===hi&&fi.length&&fi.shift()()},!1),e=>{fi.push(e),ni.postMessage(hi,"*")}):e=>setTimeout(e));var ui,pi,hi,fi;const gi="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ni):void 0!==t&&t.nextTick||li,mi={isArray:Mn,isArrayBuffer:Dn,isBuffer:Fn,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Hn(e.append)&&("formdata"===(t=Bn(e))||"object"===t&&Hn(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Dn(e.buffer),t},isString:Ln,isNumber:Un,isBoolean:e=>!0===e||!1===e,isObject:jn,isPlainObject:Kn,isEmptyObject:e=>{if(!jn(e)||Fn(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Qn,isRequest:Jn,isResponse:Xn,isHeaders:Yn,isUndefined:qn,isDate:Zn,isFile:zn,isBlob:Wn,isRegExp:oi,isFunction:Hn,isStream:e=>jn(e)&&Hn(e.pipe),isURLSearchParams:Vn,isTypedArray:ri,isFileList:Gn,forEach:ei,merge:function e(){const{caseless:t}=ii(this)&&this||{},n={},i=(i,r)=>{const s=t&&ti(n,r)||r;Kn(n[s])&&Kn(i)?n[s]=e(n[s],i):Kn(i)?n[s]=e({},i):Mn(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&ei(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(ei(t,(t,i)=>{n&&Hn(t)?e[i]=Rn(t,n):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,s,a;const o={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)a=r[s],i&&!i(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==n&&kn(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Bn,kindOfTest:$n,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(Mn(e))return e;let t=e.length;if(!Un(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[On]).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:si,hasOwnProperty:ai,hasOwnProp:ai,reduceDescriptors:ci,freezeMethods:e=>{ci(e,(t,n)=>{if(Hn(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];Hn(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 Mn(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:ti,global:ni,isContextDefined:ii,isSpecCompliantForm:function(e){return!!(e&&Hn(e.append)&&"FormData"===e[Nn]&&e[On])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(jn(e)){if(t.indexOf(e)>=0)return;if(Fn(e))return e;if(!("toJSON"in e)){t[i]=e;const r=Mn(e)?[]:{};return ei(e,(e,t)=>{const s=n(e,i+1);!qn(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:di,isThenable:e=>e&&(jn(e)||Hn(e))&&Hn(e.then)&&Hn(e.catch),setImmediate:li,asap:gi,isIterable:e=>null!=e&&Hn(e[On])};function yi(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)}mi.inherits(yi,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:mi.toJSONObject(this.config),code:this.code,status:this.status}}});const bi=yi.prototype,wi={};["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=>{wi[e]={value:e}}),Object.defineProperties(yi,wi),Object.defineProperty(bi,"isAxiosError",{value:!0}),yi.from=(e,t,n,i,r,s)=>{const a=Object.create(bi);return mi.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),yi.call(a,e.message,t,n,i,r),a.cause=e,a.name=e.name,s&&Object.assign(a,s),a};function vi(e){return mi.isPlainObject(e)||mi.isArray(e)}function Ii(e){return mi.endsWith(e,"[]")?e.slice(0,-2):e}function Ti(e,t,n){return e?e.concat(t).map(function(e,t){return e=Ii(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Ai=mi.toFlatObject(mi,{},null,function(e){return/^is[A-Z]/.test(e)});function _i(e,t,i){if(!mi.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const r=(i=mi.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!mi.isUndefined(t[e])})).metaTokens,s=i.visitor||l,a=i.dots,o=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&mi.isSpecCompliantForm(t);if(!mi.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(mi.isDate(e))return e.toISOString();if(mi.isBoolean(e))return e.toString();if(!c&&mi.isBlob(e))throw new yi("Blob is not supported. Use a Buffer instead.");return mi.isArrayBuffer(e)||mi.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(mi.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(mi.isArray(e)&&function(e){return mi.isArray(e)&&!e.some(vi)}(e)||(mi.isFileList(e)||mi.endsWith(n,"[]"))&&(s=mi.toArray(e)))return n=Ii(n),s.forEach(function(e,i){!mi.isUndefined(e)&&null!==e&&t.append(!0===o?Ti([n],i,a):null===o?n:n+"[]",d(e))}),!1;return!!vi(e)||(t.append(Ti(i,n,a),d(e)),!1)}const u=[],p=Object.assign(Ai,{defaultVisitor:l,convertValue:d,isVisitable:vi});if(!mi.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!mi.isUndefined(n)){if(-1!==u.indexOf(n))throw Error("Circular reference detected in "+i.join("."));u.push(n),mi.forEach(n,function(n,r){!0===(!(mi.isUndefined(n)||null===n)&&s.call(t,n,mi.isString(r)?r.trim():r,i,p))&&e(n,i?i.concat(r):[r])}),u.pop()}}(e),t}function Ci(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Ei(e,t){this._pairs=[],e&&_i(e,this,t)}const Si=Ei.prototype;function Ri(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xi(e,t,n){if(!t)return e;const i=n&&n.encode||Ri;mi.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):mi.isURLSearchParams(t)?t.toString():new Ei(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Si.append=function(e,t){this._pairs.push([e,t])},Si.toString=function(e){const t=e?function(t){return e.call(this,t,Ci)}:Ci;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class ki{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){mi.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Oi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ni={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ei,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Bi="undefined"!=typeof window&&"undefined"!=typeof document,$i="object"==typeof navigator&&navigator||void 0,Pi=Bi&&(!$i||["ReactNative","NativeScript","NS"].indexOf($i.product)<0),Mi="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,qi=Bi&&window.location.href||"http://localhost",Fi={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Bi,hasStandardBrowserEnv:Pi,hasStandardBrowserWebWorkerEnv:Mi,navigator:$i,origin:qi},Symbol.toStringTag,{value:"Module"})),...Ni};function Di(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=e.length;if(s=!s&&mi.isArray(i)?i.length:s,o)return mi.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a;i[s]&&mi.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&mi.isArray(i[s])&&(i[s]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],t[s]=e[s];return t}(i[s])),!a}if(mi.isFormData(e)&&mi.isFunction(e.entries)){const n={};return mi.forEachEntry(e,(e,i)=>{t(function(e){return mi.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const Li={transitional:Oi,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=mi.isObject(e);r&&mi.isHTMLForm(e)&&(e=new FormData(e));if(mi.isFormData(e))return i?JSON.stringify(Di(e)):e;if(mi.isArrayBuffer(e)||mi.isBuffer(e)||mi.isStream(e)||mi.isFile(e)||mi.isBlob(e)||mi.isReadableStream(e))return e;if(mi.isArrayBufferView(e))return e.buffer;if(mi.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 _i(e,new Fi.classes.URLSearchParams,{visitor:function(e,t,n,i){return Fi.isNode&&mi.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=mi.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return _i(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(mi.isString(e))try{return(t||JSON.parse)(e),mi.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Li.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(mi.isResponse(e)||mi.isReadableStream(e))return e;if(e&&mi.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 yi.from(r,yi.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:Fi.classes.FormData,Blob:Fi.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};mi.forEach(["delete","get","head","post","put","patch"],e=>{Li.headers[e]={}});const Hi=mi.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"]),Ui=Symbol("internals");function ji(e){return e&&String(e).trim().toLowerCase()}function Ki(e){return!1===e||null==e?e:mi.isArray(e)?e.map(Ki):String(e)}function Zi(e,t,n,i,r){return mi.isFunction(i)?i.call(this,t,n):(r&&(t=n),mi.isString(t)?mi.isString(i)?-1!==t.indexOf(i):mi.isRegExp(i)?i.test(t):void 0:void 0)}let zi=class{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=ji(t);if(!r)throw new Error("header name must be a non-empty string");const s=mi.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=Ki(e))}const s=(e,t)=>mi.forEach(e,(e,n)=>r(e,n,t));if(mi.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(mi.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]&&Hi[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(mi.isObject(e)&&mi.isIterable(e)){let n,i,r={};for(const t of e){if(!mi.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?mi.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=ji(e)){const n=mi.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(mi.isFunction(t))return t.call(this,e,n);if(mi.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=ji(e)){const n=mi.findKey(this,e);return!(!n||void 0===this[n]||t&&!Zi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=ji(e)){const r=mi.findKey(n,e);!r||t&&!Zi(0,n[r],r,t)||(delete n[r],i=!0)}}return mi.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&&!Zi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return mi.forEach(this,(i,r)=>{const s=mi.findKey(n,r);if(s)return t[s]=Ki(i),void delete t[r];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();a!==r&&delete t[r],t[a]=Ki(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return mi.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&mi.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[Ui]=this[Ui]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=ji(e);t[i]||(!function(e,t){const n=mi.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 mi.isArray(e)?e.forEach(i):i(e),this}};function Wi(e,t){const n=this||Li,i=t||n,r=zi.from(i.headers);let s=i.data;return mi.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function Gi(e){return!(!e||!e.__CANCEL__)}function Vi(e,t,n){yi.call(this,null==e?"canceled":e,yi.ERR_CANCELED,t,n),this.name="CanceledError"}function Qi(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new yi("Request failed with status code "+n.status,[yi.ERR_BAD_REQUEST,yi.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}zi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),mi.reduceDescriptors(zi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),mi.freezeMethods(zi),mi.inherits(Vi,yi,{__CANCEL__:!0});const Ji=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,a=0;return t=void 0!==t?t:1e3,function(o){const c=Date.now(),d=i[a];r||(r=c),n[s]=o,i[s]=c;let l=a,u=0;for(;l!==s;)u+=n[l++],l%=e;if(s=(s+1)%e,s===a&&(a=(a+1)%e),c-r<t)return;const 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 a=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),o=t-r;o>=s?a(e,t):(n=e,i||(i=setTimeout(()=>{i=null,a(n)},s-o)))},()=>n&&a(n)]}(n=>{const s=n.loaded,a=n.lengthComputable?n.total:void 0,o=s-i,c=r(o);i=s;e({loaded:s,total:a,progress:a?s/a:void 0,bytes:o,rate:c||void 0,estimated:c&&a&&s<=a?(a-s)/c:void 0,event:n,lengthComputable:null!=a,[t?"download":"upload"]:!0})},n)},Xi=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Yi=e=>(...t)=>mi.asap(()=>e(...t)),er=Fi.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Fi.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Fi.origin),Fi.navigator&&/(msie|trident)/i.test(Fi.navigator.userAgent)):()=>!0,tr=Fi.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const a=[e+"="+encodeURIComponent(t)];mi.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),mi.isString(i)&&a.push("path="+i),mi.isString(r)&&a.push("domain="+r),!0===s&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function nr(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 ir=e=>e instanceof zi?{...e}:e;function rr(e,t){t=t||{};const n={};function i(e,t,n,i){return mi.isPlainObject(e)&&mi.isPlainObject(t)?mi.merge.call({caseless:i},e,t):mi.isPlainObject(t)?mi.merge({},t):mi.isArray(t)?t.slice():t}function r(e,t,n,r){return mi.isUndefined(t)?mi.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!mi.isUndefined(t))return i(void 0,t)}function a(e,t){return mi.isUndefined(t)?mi.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function o(n,r,s){return s in t?i(n,r):s in e?i(void 0,n):void 0}const c={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t,n)=>r(ir(e),ir(t),0,!0)};return mi.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,a=s(e[i],t[i],i);mi.isUndefined(a)&&s!==o||(n[i]=a)}),n}const sr=e=>{const t=rr({},e);let n,{data:i,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=zi.from(o),t.url=xi(nr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),mi.isFormData(i))if(Fi.hasStandardBrowserEnv||Fi.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(!1!==(n=o.getContentType())){const[e,...t]=n?n.split(";").map(e=>e.trim()).filter(Boolean):[];o.setContentType([e||"multipart/form-data",...t].join("; "))}if(Fi.hasStandardBrowserEnv&&(r&&mi.isFunction(r)&&(r=r(t)),r||!1!==r&&er(t.url))){const e=s&&a&&tr.read(a);e&&o.set(s,e)}return t},ar="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=sr(e);let r=i.data;const s=zi.from(i.headers).normalize();let a,o,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function f(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let g=new XMLHttpRequest;function m(){if(!g)return;const i=zi.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Qi(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 yi("Request aborted",yi.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new yi("Network Error",yi.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||Oi;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new yi(t,r.clarifyTimeoutError?yi.ETIMEDOUT:yi.ECONNABORTED,e,g)),g=null},void 0===r&&s.setContentType(null),"setRequestHeader"in g&&mi.forEach(s.toJSON(),function(e,t){g.setRequestHeader(t,e)}),mi.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),u&&"json"!==u&&(g.responseType=i.responseType),h&&([c,l]=Ji(h,!0),g.addEventListener("progress",c)),p&&g.upload&&([o,d]=Ji(p),g.upload.addEventListener("progress",o),g.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(a=t=>{g&&(n(!t||t.type?new Vi(null,e,g):t),g.abort(),g=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===Fi.protocols.indexOf(y)?n(new yi("Unsupported protocol "+y+":",yi.ERR_BAD_REQUEST,e)):g.send(r||null)})},or=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof yi?t:new Vi(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new yi(`timeout ${t} of ms exceeded`,yi.ETIMEDOUT))},t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:o}=i;return o.unsubscribe=()=>mi.asap(a),o}},cr=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},dr=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()}},lr=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of dr(e))yield*cr(n,t)}(e,t);let s,a=0,o=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return o(),void e.close();let s=i.byteLength;if(n){let e=a+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(t){throw o(t),t}},cancel:e=>(o(e),r.return())},{highWaterMark:2})},ur="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,pr=ur&&"function"==typeof ReadableStream,hr=ur&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),fr=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},gr=pr&&fr(()=>{let e=!1;const t=new Request(Fi.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),mr=pr&&fr(()=>mi.isReadableStream(new Response("").body)),yr={stream:mr&&(e=>e.body)};var br;ur&&(br=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!yr[e]&&(yr[e]=mi.isFunction(br[e])?t=>t[e]():(t,n)=>{throw new yi(`Response type '${e}' is not supported`,yi.ERR_NOT_SUPPORT,n)})}));const wr=async(e,t)=>{const n=mi.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(mi.isBlob(e))return e.size;if(mi.isSpecCompliantForm(e)){const t=new Request(Fi.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return mi.isArrayBufferView(e)||mi.isArrayBuffer(e)?e.byteLength:(mi.isURLSearchParams(e)&&(e+=""),mi.isString(e)?(await hr(e)).byteLength:void 0)})(t):n},vr={http:null,xhr:ar,fetch:ur&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:a,onDownloadProgress:o,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=sr(e);d=d?(d+"").toLowerCase():"text";let h,f=or([r,s&&s.toAbortSignal()],a);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&gr&&"get"!==n&&"head"!==n&&0!==(m=await wr(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(mi.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=Xi(m,Ji(Yi(c)));i=lr(n.body,65536,e,t)}}mi.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 a=mr&&("stream"===d||"response"===d);if(mr&&(o||a&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=mi.toFiniteNumber(s.headers.get("content-length")),[n,i]=o&&Xi(t,Ji(Yi(o),!0))||[];s=new Response(lr(s.body,65536,n,()=>{i&&i(),g&&g()}),e)}d=d||"text";let y=await yr[mi.findKey(yr,d)||"text"](s,e);return!a&&g&&g(),await new Promise((t,n)=>{Qi(t,n,{data:y,headers:zi.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 yi("Network Error",yi.ERR_NETWORK,e,h),{cause:y.cause||y});throw yi.from(y,y&&y.code,e,h)}})};mi.forEach(vr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Ir=e=>`- ${e}`,Tr=e=>mi.isFunction(e)||null===e||!1===e,Ar=e=>{e=mi.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,!Tr(n)&&(i=vr[(t=String(n)).toLowerCase()],void 0===i))throw new yi(`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 yi("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Ir).join("\n"):" "+Ir(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function _r(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Vi(null,e)}function Cr(e){_r(e),e.headers=zi.from(e.headers),e.data=Wi.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Ar(e.adapter||Li.adapter)(e).then(function(t){return _r(e),t.data=Wi.call(e,e.transformResponse,t),t.headers=zi.from(t.headers),t},function(t){return Gi(t)||(_r(e),t&&t.response&&(t.response.data=Wi.call(e,e.transformResponse,t.response),t.response.headers=zi.from(t.response.headers))),Promise.reject(t)})}const Er="1.11.0",Sr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Sr[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Rr={};Sr.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Er+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new yi(i(r," has been removed"+(t?" in "+t:"")),yi.ERR_DEPRECATED);return t&&!Rr[r]&&(Rr[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)}},Sr.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const xr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new yi("options must be an object",yi.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],a=t[s];if(a){const t=e[s],n=void 0===t||a(t,s,e);if(!0!==n)throw new yi("option "+s+" must be "+n,yi.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new yi("Unknown option "+s,yi.ERR_BAD_OPTION)}},validators:Sr},kr=xr.validators;let Or=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ki,response:new ki}}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=rr(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&xr.assertOptions(n,{silentJSONParsing:kr.transitional(kr.boolean),forcedJSONParsing:kr.transitional(kr.boolean),clarifyTimeoutError:kr.transitional(kr.boolean)},!1),null!=i&&(mi.isFunction(i)?t.paramsSerializer={serialize:i}:xr.assertOptions(i,{encode:kr.function,serialize:kr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xr.assertOptions(t,{baseUrl:kr.spelling("baseURL"),withXsrfToken:kr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&mi.merge(r.common,r[t.method]);r&&mi.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=zi.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.unshift(e.fulfilled,e.rejected))});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0;if(!o){const e=[Cr.bind(this),void 0];for(e.unshift(...a),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=a.length;let p=t;for(u=0;u<l;){const e=a[u++],t=a[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{d=Cr.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 xi(nr((e=rr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};mi.forEach(["delete","get","head","options"],function(e){Or.prototype[e]=function(t,n){return this.request(rr(n||{},{method:e,url:t,data:(n||{}).data}))}}),mi.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(rr(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}Or.prototype[e]=t(),Or.prototype[e+"Form"]=t(!0)});const Nr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Nr).forEach(([e,t])=>{Nr[t]=e});const Br=function e(t){const n=new Or(t),i=Rn(Or.prototype.request,n);return mi.extend(i,Or.prototype,n,{allOwnKeys:!0}),mi.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(rr(t,n))},i}(Li);Br.Axios=Or,Br.CanceledError=Vi,Br.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 Vi(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}}},Br.isCancel=Gi,Br.VERSION=Er,Br.toFormData=_i,Br.AxiosError=yi,Br.Cancel=Br.CanceledError,Br.all=function(e){return Promise.all(e)},Br.spread=function(e){return function(t){return e.apply(null,t)}},Br.isAxiosError=function(e){return mi.isObject(e)&&!0===e.isAxiosError},Br.mergeConfig=rr,Br.AxiosHeaders=zi,Br.formToJSON=e=>Di(mi.isHTMLForm(e)?new FormData(e):e),Br.getAdapter=Ar,Br.HttpStatusCode=Nr,Br.default=Br;const{Axios:$r,AxiosError:Pr,CanceledError:Mr,isCancel:qr,CancelToken:Fr,VERSION:Dr,all:Lr,Cancel:Hr,isAxiosError:Ur,spread:jr,toFormData:Kr,AxiosHeaders:Zr,HttpStatusCode:zr,formToJSON:Wr,getAdapter:Gr,mergeConfig:Vr}=Br,Qr="ConnectionsManager not initialized";class Jr extends s.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(),a=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=(()=>{try{if("function"==typeof r.Logger)return new r.Logger({module:"HCS10Builder",level:n?.logLevel||"info"})}catch{}return{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},trace:()=>{},setLogLevel:()=>{},getLevel:()=>"info",setSilent:()=>{},setModule:()=>{}}})(),this.standardClient=new r.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:a,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getStateManager(){return this.stateManager}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){const n=Sn.startHCSDelegate,i=Sn.walletExecutor,r=Sn.preferWalletOnly,s=this.network;try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>ys);if(i&&n.has("submitConnectionRequest")){const r=await n.build("submitConnectionRequest",this.hederaKit,{inboundTopicId:e,memo:t});if(r&&r.transactionBytes){const{transactionId:e}=await i(r.transactionBytes,s);return{transactionId:e}}}}catch{}if(n&&i)try{const r={inboundTopicId:e,memo:t},{transactionBytes:a}=await n("submitConnectionRequest",r,s),{transactionId:o}=await i(a,s);return{transactionId:o}}catch(a){if(r){const e=new Error(`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`);throw e.code="wallet_submit_failed",e}}else if(r){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,n,i){try{const s=Sn.startHCSDelegate,a=Sn.walletExecutor,o=Sn.preferWalletOnly,c=this.network;if(s&&a)try{const r={inboundTopicId:e,requestingAccountId:t,connectionRequestId:n,feeConfig:i?"configured":void 0},{transactionBytes:o}=await s("handleConnectionRequest",r,c),{transactionId:d}=await a(o,c);return{success:!0,transactionId:d}}catch(r){if(o){const e=new Error(`wallet_submit_failed: ${r instanceof Error?r.message:String(r)}`);throw e.code="wallet_submit_failed",e}}else if(o){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const d=await this.standardClient.handleConnectionRequest(e,t,n,i);return d&&d.connectionTopicId&&"object"==typeof d.connectionTopicId&&"toString"in d.connectionTopicId&&(d.connectionTopicId=d.connectionTopicId.toString()),d}catch(s){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,s),new Error(`Failed to handle connection request: ${s instanceof Error?s.message:String(s)}`)}}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{let r=0;try{r=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const s=Sn.startHCSDelegate,a=Sn.walletExecutor,o=Sn.preferWalletOnly,c=this.network;try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(a&&i.has("sendMessage")){const s=await i.build("sendMessage",this.hederaKit,{topicId:e,data:t,memo:n});if(s&&s.transactionBytes){const{transactionId:t}=await a(s.transactionBytes,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:t},transactionId:t}}}}catch{}if(s&&a)try{const i={topicId:e,data:t,memo:n},{transactionBytes:o}=await s("sendMessage",i,c),{transactionId:d}=await a(o,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:d},transactionId:d}}catch(i){if(o){const e=new Error(`wallet_submit_failed: ${i instanceof Error?i.message:String(i)}`);throw e.code="wallet_submit_failed",e}}else if(o){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const d=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:d.topicSequenceNumber?.toNumber(),receipt:d,transactionId:"transactionId"in d?d.transactionId?.toString():void 0}}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const t=await Br.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(!a.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=a.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 Br.get(e.url,{responseType:"arraybuffer"}),i=n.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!a.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=a.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 pollForNewSequence(e,t){for(let n=0;n<10;n++){try{const n=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),t);if(n>t)return n}catch{}await new Promise(e=>setTimeout(e,1e3))}}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 n=null;e.profilePicture&&(n=await this.loadProfilePicture(e.profilePicture));const i={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!==n?.buffer&&{pfpBuffer:n.buffer},...void 0!==n?.filename&&{pfpFileName:n.filename}};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 s=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];i.feeConfig=t.addHbarFee(e.hbarFee,n,s)}const s=Sn.preferWalletOnly,a=Sn.getBrowserHCSClient(this.network);if(a)try{const e=(new r.AgentBuilder).setNetwork(this.network).setName(i.name).setAlias(i.alias||`${i.name}-${Date.now()}`).setBio(i.bio||"").setType(i.type||"autonomous").setModel(i.model||"agent-model-2024");i.capabilities?.length&&e.setCapabilities(i.capabilities),i.creator&&e.setCreator(i.creator),i.existingProfilePictureTopicId&&e.setExistingProfilePicture(i.existingProfilePictureTopicId),i.socials&&Object.entries(i.socials).forEach(([t,n])=>{n&&"string"==typeof n&&e.addSocial(t,n)}),i.properties&&Object.entries(i.properties).forEach(([t,n])=>{null!=n&&e.addProperty(t,n)});const t=await a.create(e,{progressCallback:e=>{},updateAccountMemo:!0});return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{result:t,name:i.name}},this}catch(t){if(s)throw new Error(`wallet_registration_failed: ${t instanceof Error?t.message:String(t)}`)}else if(s)throw new Error("wallet_unavailable: BrowserHCSClient factory not provided");const o=await this.createAndRegisterAgent(i);this.executeResult={success:!0,transactionId:o.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...o,name:e.name,accountId:o?.metadata?.accountId||o.state?.agentMetadata?.accountId}}}catch(n){throw this.logger.error("Failed to register agent:",n),n}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 i=this.stateManager?.getCurrentAgent();if(!i)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const s=this.stateManager?.getConnectionsManager();if(!s)throw new Error(Qr);await s.fetchConnectionData(i.accountId);const a=[...s.getPendingRequests(),...s.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!a)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!a.needsConfirmation||!a.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const o=a.targetAccountId,c=a.inboundRequestId;let d;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"))||[];d=t.addHbarFee(e.hbarFee,n,i)}const l=await this.getInboundTopicId(),u=await this.handleConnectionRequest(l,o,c,d);let p=u?.connectionTopicId;if(p&&"object"==typeof p&&"toString"in p&&(p=p?.toString()),!p||"string"!=typeof p)try{const e=(await(this.stateManager?.getConnectionsManager()?.fetchConnectionData(i.accountId))||[]).find(e=>e.targetAccountId===o&&"established"===e.status);e?.connectionTopicId&&(p=e.connectionTopicId)}catch(t){this.logger.debug("Could not refresh connections after acceptance to derive topic id:",t)}if(!p||"string"!=typeof p)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(p)}`);if(this.stateManager){const e=a.targetAgentName||`Agent ${o}`;a.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${o}'.`);let t=a.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(o);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(n){this.logger.warn(`Could not fetch profile for ${o}:`,n)}const i={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:p,status:"established",created:new Date};this.stateManager.addActiveConnection(i),s.markConnectionRequestProcessed(a.targetInboundTopicId||"",c)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId:p,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:u}}}catch(i){throw this.logger.error("Failed to accept connection:",i),i}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let n;const i=e.targetIdentifier;if(i.includes("@")){const e=i.split("@");if(2===e.length){const t=e[1];n=this.stateManager.getConnectionByIdentifier(t),n||this.addNote(`Could not find connection using request key '${i}', extracted account ID '${t}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(i)),!n&&!i.startsWith("0.0.")&&/^\d+$/.test(i)){const e=`0.0.${i}`;n=this.stateManager.getConnectionByIdentifier(e),n&&this.addNote(`Found connection using account ID with prefix: ${e}`)}if(!n&&/^[1-9]\d*$/.test(i)){const e=this.stateManager.listConnections(),t=parseInt(i)-1;t>=0&&t<e.length&&(n=e[t],n&&this.addNote(`Found connection by index ${i}: ${n.targetAccountId}`))}if(!n){const e=this.stateManager.listConnections().map((e,t)=>`${t+1}. ${e.targetAccountId} (Topic: ${e.connectionTopicId})`);let t=`Connection not found for identifier: "${i}"\n`;throw t+=`Available connections:\n${e.join("\n")||"No active connections"}`,t+="\n\nYou can use:\n",t+='- Connection number (e.g., "1", "2")\n',t+='- Account ID (e.g., "0.0.6412936")\n',t+="- Connection topic ID\n",t+="Use 'list_connections' to see all active connections.",new Error(t)}let r=n.connectionTopicId;if(r&&"object"==typeof r&&"toString"in r&&(r=r?.toString()),!r||"string"!=typeof r)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(r)} (type: ${typeof r})`);const s=n.targetAgentName,a=`${t.inboundTopicId}@${t.accountId}`;let o=0;try{o=(await this.getMessages(r)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const c=await this.sendMessage(r,e.message,`Agent message from ${t.name}`),d=c.sequenceNumber??o;if(0===d)throw new Error("Failed to send message");let l=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):l=await this.monitorResponses(r,a,d),this.executeResult={success:!0,transactionId:c.transactionId,receipt:c.receipt,scheduleId:void 0,rawResult:{targetAgentName:s,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:c.sequenceNumber,reply:l,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:c}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let i=0;for(;i<30;){try{const i=await this.getMessageStream(e);for(const e of i.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(r){this.logger.error(`Error monitoring responses: ${r}`)}await new Promise(e=>setTimeout(e,4e3)),i++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:t=!1,targetAccountId:n,monitorDurationSeconds:i=120,hbarFees:s=[],tokenFees:a=[],exemptAccountIds:o=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const d=await this.getInboundTopicId(),l=Date.now()+1e3*i;let u=0,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||a.length>0){const e=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,o)}for(const t of a){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,o)}t=e}await this.handleConnectionRequest(d,l,e,t),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(Qr);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const i=t.getPendingRequests(),r=t.getConnectionsNeedingConfirmation(),s=[...i,...r];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:s.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const n=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,n=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const i=e.filter(e=>"established"===e.status),r=e.filter(e=>e.isPending),s=e.filter(e=>e.needsConfirmation);let a="";i.length>0&&(a+=`🟢 Active Connections (${i.length}):\n`,i.forEach((e,n)=>{a+=this.formatConnection(e,n,t)}),a+="\n"),n&&s.length>0&&(a+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach((e,n)=>{a+=this.formatConnection(e,n,t)}),a+="\n"),n&&r.length>0&&(a+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach((e,n)=>{a+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:a.trim(),activeCount:i.length,pendingCount:r.length,needsConfirmationCount:s.length}}}catch(i){this.logger.error("Failed to list connections:",i),this.executeResult={success:!1,error:`Failed to list connections: ${i instanceof Error?i.message:String(i)}`}}return this}formatConnection(e,t,n){const i=e;let r=`${t+1}. ${i.profileInfo?.display_name||i.targetAgentName||"Unknown Agent"} (${i.targetAccountId})\n`;r+=` Topic: ${i.isPending?"(Pending Request)":i.connectionTopicId}\n`;if(r+=` Status: ${i.status||"unknown"}\n`,n){if(i.profileInfo?.bio&&(r+=` Bio: ${i.profileInfo.bio.substring(0,100)}${i.profileInfo.bio.length>100?"...":""}\n`),i.created){r+=` ${i.isPending?"Request sent":"Connection established"}: ${i.created.toLocaleString()}\n`}i.lastActivity&&(r+=` Last activity: ${i.lastActivity.toLocaleString()}\n`)}return r}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(Qr),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const i of n)this.stateManager.addActiveConnection(i);return n}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const i=t.targetAgentName,r=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${i} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${r})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let a=[],o=r;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;a=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${r}`),a=t.filter(e=>1e6*e.timestamp>r),a.length>0&&(o=a.reduce((e,t)=>Math.max(e,1e6*t.timestamp),r));if(0===a.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${i} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${a.length} message(s).`);let d=c?`Latest message(s) from ${i}:\n`:`New messages from ${i}:\n`;const l=[];for(const e of a){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}d+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,l.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(s){const t=`Error processing message (Seq: ${e.sequence_number}): ${s instanceof Error?s.message:String(s)}`;this.logger.error(t),d+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&o>r&&(this.logger.debug(`Updating timestamp for topic ${n} to ${o}`),this.stateManager.updateTimestamp(n,o)),this.executeResult={success:!0,rawResult:{messages:l,formattedOutput:d.trim(),targetAgentName:i,connectionTopicId:n}}}catch(s){this.logger.error(`Failed to check messages for topic ${n}: ${s}`),this.executeResult={success:!1,error:`Error checking messages for ${i}: ${s instanceof Error?s.message:String(s)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const i=n.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${i}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const n=t.profile,i=t.topicInfo;let r=`Profile for ${e.accountId}:\n`;r+=`Name: ${n.name||"Unknown"}\n`,r+=`Bio: ${n.bio||"No bio provided"}\n`,r+=`Type: ${n.type||"Unknown"}\n`,r+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?r+=`Capabilities: ${n.capabilities.join(", ")}\n`:r+="Capabilities: None listed\n",i&&(r+=`Inbound Topic: ${i.inboundTopic||"Unknown"}\n`,r+=`Outbound Topic: ${i.outboundTopic||"Unknown"}\n`,r+=`Profile Topic: ${i.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(r+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(r+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:r,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class Xr extends s.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 s.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}function Yr(e){const t={},n={},i=[],r={};return es(e,"",t,n,i,r),{fields:t,groups:is(n),order:rs(i,t),metadata:r}}function es(e,t,n,i,r,s){const a=gn(e),o=a._def?.typeName;"ZodObject"===o?function(e,t,n,i,r,s){const a=e.shape;if(ln(e)){const s=un(e);s&&t&&(n[t]=s,ts(i,s.ui?.group||"default",t),ns(r,t,s.ui?.order))}for(const[o,c]of Object.entries(a)){es(c,t?`${t}.${o}`:o,n,i,r,s)}}(a,t,n,i,r,s):"ZodArray"===o?function(e,t,n,i,r,s){if(ln(e)){const a=un(e);a&&(n[t]=a,ts(i,a.ui?.group||"default",t),ns(r,t,a.ui?.order),s[t]=bn(e))}const a=e._def.type;if(a){es(a,`${t}[]`,n,i,r,s)}}(a,t,n,i,r,s):function(e,t,n,i,r,s){if(ln(e)){const s=un(e);s&&(n[t]=s,ts(i,s.ui?.group||"default",t),ns(r,t,s.ui?.order))}s[t]=bn(e)}(e,t,n,i,r,s)}function ts(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}function ns(e,t,n){void 0!==n?e.splice(n,0,t):e.push(t)}function is(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 rs(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 a=n[e]||1e3,o=n[i]||1e3;return a!==o?a-o:e.localeCompare(i)})}class ss extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,ss.prototype)}}class as extends s.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().toString():"",n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";let i;try{const t=new r.HederaMirrorNode(n),s=await t.requestAccount(e),a=s?.key?._type;if(a){const e=a.toUpperCase();e.includes("ED25519")?i="ed25519":e.includes("ECDSA")&&(i="ecdsa")}}catch{}const s={network:n,operatorId:e,operatorKey:t,...i?{keyType:i}:{}};this.hcs2Client=new r.HCS2Client(s)}return this.hcs2Client}async createRegistry(e={}){const t=Sn.walletExecutor,n=Sn.preferWalletOnly,i=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());if(t){const t=Sn.startHCSDelegate;if(t)try{const n={options:e},i=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:r}=await t("hcs2.createRegistry",n,i);if(r)return{success:!0,transactionBytes:r}}catch(s){if(n)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(n)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.createRegistry")}if(!i)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const r=await this.getHCS2Client();return await r.createRegistry(e)}async registerEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.registerEntry")){const r=await i.build("hcs2.registerEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={registryTopicId:e,options:t},{transactionBytes:o}=await a("hcs2.registerEntry",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.registerEntry");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.registerEntry(e,t)}async updateEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.updateEntry")){const r=await i.build("hcs2.updateEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={registryTopicId:e,options:t},{transactionBytes:o}=await a("hcs2.updateEntry",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.updateEntry");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.updateEntry(e,t)}async deleteEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.deleteEntry")){const r=await i.build("hcs2.deleteEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={registryTopicId:e,options:t},{transactionBytes:o}=await a("hcs2.deleteEntry",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.deleteEntry");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.deleteEntry(e,t)}async migrateRegistry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.migrateRegistry")){const s=await i.build("hcs2.migrateRegistry",this.hederaKit,{registryTopicId:e,options:t});if(s&&s.transactionBytes){if(n)return{success:!0,transactionBytes:s.transactionBytes};if(!r)return{success:!0,transactionBytes:s.transactionBytes}}}}catch{}const s=Sn.startHCSDelegate;if(s)try{const i={registryTopicId:e,options:t},a=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:o}=await s("hcs2.migrateRegistry",i,a);if(o){if(n)return{success:!0,transactionBytes:o};if(!r)return{success:!0,transactionBytes:o}}}catch(o){if(i){const e=`wallet_submit_failed: ${o instanceof Error?o.message:String(o)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.migrateRegistry");if(!r)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.migrateRegistry(e,t)}async getRegistry(e,t={}){const n=await this.getHCS2Client();return await n.getRegistry(e,t)}async submitMessage(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.submitMessage")){const r=await i.build("hcs2.submitMessage",this.hederaKit,{topicId:e,payload:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={topicId:e,payload:t},{transactionBytes:o}=await a("hcs2.submitMessage",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.submitMessage");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.submitMessage(e,t),{success:!0}}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 os extends s.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=Sn.walletExecutor,n=Sn.preferWalletOnly,i=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(t){const t=Sn.startHCSDelegate;if(t)try{const n={options:e},{transactionBytes:r}=await t("hcs6.createRegistry",n,i);if(r)return{success:!0,transactionBytes:r}}catch(a){if(n)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`)}if(n)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs6.createRegistry")}const r=await this.getHCS6Client(),s={...e};return"adminKey"in s&&delete s.adminKey,await r.createRegistry(s)}async registerEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(n){const n=Sn.startHCSDelegate;if(n)try{const i={registryTopicId:e,options:t},{transactionBytes:s}=await n("hcs6.registerEntry",i,r);if(s)return{success:!0,transactionBytes:s}}catch(a){if(i)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`)}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs6.registerEntry")}const s=await this.getHCS6Client();return await s.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=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(n){const n=Sn.startHCSDelegate;if(n)try{const i={topicId:e,payload:t},{transactionBytes:s}=await n("hcs6.submitMessage",i,r);if(s)return{success:!0,transactionBytes:s}}catch(a){if(i)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`)}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs6.submitMessage")}const s=await this.getHCS6Client();return await s.submitMessage(e,t)}async getTopicInfo(e){const t=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",n=new r.HederaMirrorNode(t);return await n.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}const cs=class e extends s.BaseServiceBuilder{constructor(e){super(e)}getOperationalMode(){return this.hederaKit.operationalMode}static setSignerProvider(t){e.signerProvider=t}static setWalletInfoResolver(t){e.walletInfoResolver=t}static setStartInscriptionDelegate(t){e.startInscriptionDelegate=t}static setWalletExecutor(t){e.walletExecutor=t}static setPreferWalletOnly(t){e.preferWalletOnly=!!t}async getSigner(){const t=e.signerProvider;if(!t)return null;try{const e=t();return e&&"function"==typeof e.then?await e:e}catch{return null}}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 inscribeAuto(t,i){const s=await this.getSigner();if(s)return this.inscribeWithSigner(t,s,i);const a=e.walletInfoResolver?await e.walletInfoResolver():null;if(e.preferWalletOnly&&!a){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}if(a&&e.startInscriptionDelegate&&e.walletExecutor){const s=a.accountId,o=a.network,c=i,d={holderId:s,metadata:c.metadata||{},tags:i.tags||[],mode:i.mode||"file"};void 0!==c.fileStandard&&(d.fileStandard=c.fileStandard),void 0!==c.chunkSize&&(d.chunkSize=c.chunkSize);let l={...d};switch(t.type){case"url":l={...d,file:{type:"url",url:t.url}};break;case"file":l={...d,file:{type:"path",path:t.path}};break;case"buffer":l={...d,file:{type:"base64",base64:n.Buffer.from(t.buffer).toString("base64"),fileName:t.fileName,mimeType:t.mimeType}}}"hashinal"===i.mode&&(l.metadataObject=c.metadata,l.creator=c.metadata?.creator||s,l.description=c.metadata?.description,"string"==typeof c.jsonFileURL&&c.jsonFileURL.length>0&&(l.jsonFileURL=c.jsonFileURL));const u=await e.startInscriptionDelegate(l,o),p=u;if(Boolean(p?.inscription)&&p?.confirmed){const e=u;return this.logger.info("inscription already completed, short circuiting",u),{quote:!1,confirmed:!0===e.confirmed,result:e.result,inscription:e.inscription}}const h=u;if(!h||!h.transactionBytes)throw new Error("Failed to start inscription (no transaction bytes)");const f=await e.walletExecutor(h.transactionBytes,o),g=f?.transactionId||"";if(!i.quoteOnly&&(i.waitForConfirmation??!0)){this.logger.debug("Will be retrieving inscription");const e=i.waitMaxAttempts??60,t=i.waitIntervalMs??5e3;for(let n=0;n<e;n++){try{const e=await this.retrieveInscription(g,i),t=r.getTopicId(e)??h.topic_id,n=e.status;if("completed"===n||!!t){const n={quote:!1,confirmed:!0,result:{jobId:h.tx_id||"",transactionId:g,topicId:t},inscription:e};return this.logger.debug("retrieved inscription",n,e),n}}catch{}await new Promise(e=>setTimeout(e,t))}}return{quote:!1,confirmed:!1,result:{jobId:h.tx_id||"",transactionId:g,status:h.status,completed:h.completed},inscription:h.topic_id?{topic_id:h.topic_id}:void 0}}if(e.preferWalletOnly){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}return this.inscribe(t,i)}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}};cs.preferWalletOnly=!1;let ds=cs;const ls=new class{constructor(){this.handlers=new Map}register(e,t){this.handlers.set(e,t)}has(e){return this.handlers.has(e)}async build(e,t,n){const i=this.handlers.get(e);return i?await i({hederaKit:t,request:n}):null}};async function us(e,t){const r="mainnet"===(e.client.network.toString().includes("mainnet")?"mainnet":"testnet")?i.Client.forMainnet():i.Client.forTestnet(),s=e.signer.getAccountId().toString(),a=i.AccountId.fromString(s);if("function"==typeof t.setTransactionId&&t.setTransactionId(i.TransactionId.generate(a)),"function"==typeof t.setAutoRenewAccountId)try{t.setAutoRenewAccountId(s)}catch{}const o=await t.freezeWith(r);return{transactionBytes:n.Buffer.from(o.toBytes()).toString("base64")}}async function ps(e,t,r,s){const a="mainnet"===(e.client.network.toString().includes("mainnet")?"mainnet":"testnet")?i.Client.forMainnet():i.Client.forTestnet(),o=e.signer.getAccountId().toString(),c=i.AccountId.fromString(o),d=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(t)).setTransactionId(i.TransactionId.generate(c)).setMessage(r),l=await d.freezeWith(a);return{transactionBytes:n.Buffer.from(l.toBytes()).toString("base64")}}function hs(e){return"object"==typeof e&&null!==e}function fs(e,t){const n=e[t];return"string"==typeof n?n:void 0}function gs(e,t){const n=e[t];return"number"==typeof n&&Number.isFinite(n)?n:void 0}function ms(e,t){const n=e[t];return hs(n)?n:void 0}ls.register("hcs2.createRegistry",async({hederaKit:e,request:t})=>{const n=t?.options||{};let i;try{const t=e?.signer?.getOperatorPrivateKey?.();i=t?.publicKey}catch{}const s=r.buildHcs2CreateRegistryTx({registryType:n.registryType??r.HCS2RegistryType.INDEXED,ttl:n.ttl??86400,adminKey:n.adminKey,submitKey:n.submitKey,operatorPublicKey:i});return await us(e,s)}),ls.register("hcs2.migrateRegistry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.migrateRegistry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.migrateRegistry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"metadata"),o=fs(i,"memo"),c=r.buildHcs2MigrateTx({registryTopicId:n,targetTopicId:s,metadata:a,memo:o});return await us(e,c)}),ls.register("hcs2.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.submitMessage: invalid request payload");const n=fs(t,"topicId")||fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.submitMessage: topicId is required");const i=t.payload,r="string"==typeof i?i:JSON.stringify(i??{});return await ps(e,n,r)}),ls.register("hcs2.registerEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.registerEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.registerEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"metadata"),o=fs(i,"memo"),c=r.buildHcs2RegisterTx({registryTopicId:n,targetTopicId:s,metadata:a,memo:o});return await us(e,c)}),ls.register("hcs2.updateEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.updateEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.updateEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"uid")||"",o=fs(i,"metadata"),c=fs(i,"memo"),d=r.buildHcs2UpdateTx({registryTopicId:n,uid:a,targetTopicId:s,metadata:o,memo:c});return await us(e,d)}),ls.register("hcs2.deleteEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.deleteEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.deleteEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"uid")||"",a=fs(i,"memo"),o=r.buildHcs2DeleteTx({registryTopicId:n,uid:s,memo:a});return await us(e,o)}),ls.register("hcs6.createRegistry",async({hederaKit:e,request:t})=>{const n=hs(t)?ms(t,"options"):void 0,i=n?gs(n,"ttl"):void 0;let s;try{const t=e?.signer?.getOperatorPrivateKey?.();s=t?.publicKey}catch{}const a=r.buildHcs6CreateRegistryTx({ttl:i??86400,operatorPublicKey:s});return await us(e,a)}),ls.register("hcs6.registerEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs6.registerEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs6.registerEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"memo"),o=r.buildHcs6RegisterEntryTx({registryTopicId:n,targetTopicId:s,memo:a});return await us(e,o)}),ls.register("hcs6.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs6.submitMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs6.submitMessage: topicId is required");const i=t.payload,r="string"==typeof i?i:JSON.stringify(i??{});return await ps(e,n,r)}),ls.register("sendMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("sendMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("sendMessage: topicId is required");const i=t.data,s=fs(t,"memo")||"",a=e.signer.getAccountId().toString(),o="string"==typeof i?i:JSON.stringify(i??{}),c=r.buildHcs10SendMessageTx({connectionTopicId:n,operatorId:a,data:o,memo:s});return await us(e,c)}),ls.register("submitConnectionRequest",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("submitConnectionRequest: invalid request payload");const n=fs(t,"inboundTopicId")||"";if(!n)throw new Error("submitConnectionRequest: inboundTopicId is required");const i=fs(t,"memo")||"",s=e.signer.getAccountId().toString(),a=r.buildHcs10SubmitConnectionRequestTx({inboundTopicId:n,operatorId:s,memo:i});return await us(e,a)}),ls.register("hcs20.deploy",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.deploy: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.deploy: topicId is required");const i=fs(t,"name")||"",s=fs(t,"tick")||"",a=fs(t,"max")||"",o=fs(t,"lim"),c=fs(t,"metadata"),d=fs(t,"memo"),l=r.buildHcs20DeployTx({topicId:n,name:i,tick:s,max:a,lim:o,metadata:c,memo:d});return await us(e,l)}),ls.register("hcs20.mint",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.mint: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.mint: topicId is required");const i=fs(t,"tick")||"",s=fs(t,"amt")||"",a=fs(t,"to")||"",o=fs(t,"memo"),c=r.buildHcs20MintTx({topicId:n,tick:i,amt:s,to:a,memo:o});return await us(e,c)}),ls.register("hcs20.transfer",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.transfer: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.transfer: topicId is required");const i=fs(t,"tick")||"",s=fs(t,"amt")||"",a=fs(t,"from")||"",o=fs(t,"to")||"",c=fs(t,"memo"),d=r.buildHcs20TransferTx({topicId:n,tick:i,amt:s,from:a,to:o,memo:c});return await us(e,d)}),ls.register("hcs20.burn",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.burn: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.burn: topicId is required");const i=fs(t,"tick")||"",s=fs(t,"amt")||"",a=fs(t,"from")||"",o=fs(t,"memo"),c=r.buildHcs20BurnTx({topicId:n,tick:i,amt:s,from:a,memo:o});return await us(e,c)}),ls.register("hcs20.register",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.register: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs20.register: registryTopicId is required");const i=fs(t,"topicId")||"",s=fs(t,"name")||"",a=t.isPrivate,o="boolean"==typeof a&&a,c=fs(t,"metadata"),d=fs(t,"memo"),l=r.buildHcs20RegisterTx({registryTopicId:n,name:s,topicId:i,isPrivate:o,metadata:c,memo:d});return await us(e,l)}),ls.register("hcs12.createRegistry",async({hederaKit:e,request:t})=>{const n=hs(t)?ms(t,"options"):void 0,i=(n?gs(n,"ttl"):void 0)??60,s=n&&fs(n,"registry")||"hashlinks";let a;try{const t=e?.signer?.getOperatorPrivateKey?.();a=t?.publicKey}catch{}const o=r.buildHcs12CreateRegistryTopicTx({registry:s,ttl:i,operatorPublicKey:a});return await us(e,o)}),ls.register("hcs12.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.submitMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs12.submitMessage: topicId is required");const i=t.payload,s=r.buildHcs12SubmitMessageTx({topicId:n,payload:i});return await us(e,s)}),ls.register("hcs12.registerAssembly",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.registerAssembly: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.registerAssembly: assemblyTopicId is required");const i=ms(t,"registration")||{},s=r.buildHcs12RegisterAssemblyTx({assemblyTopicId:n,registration:i});return await us(e,s)}),ls.register("hcs12.addBlock",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.addBlock: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addBlock: assemblyTopicId is required");const i=ms(t,"operation")||{},s=r.buildHcs12AddBlockToAssemblyTx({assemblyTopicId:n,operation:i});return await us(e,s)}),ls.register("hcs12.addAction",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.addAction: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addAction: assemblyTopicId is required");const i=ms(t,"operation")||{},s=r.buildHcs12AddActionToAssemblyTx({assemblyTopicId:n,operation:i});return await us(e,s)}),ls.register("hcs12.updateAssembly",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.updateAssembly: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.updateAssembly: assemblyTopicId is required");const i=ms(t,"operation")||{},s=r.buildHcs12UpdateAssemblyTx({assemblyTopicId:n,operation:i});return await us(e,s)}),ls.register("hcs7.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs7.submitMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs7.submitMessage: topicId is required");const i=ms(t,"message")||{},s=r.buildHcs7SubmitMessageTx({topicId:n,message:i});return await us(e,s)}),ls.register("hcs7.evm",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs7.evm: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs7.evm: topicId is required");const i=ms(t,"config")||{},s=r.buildHcs7EvmMessageTx({topicId:n,config:i});return await us(e,s)}),ls.register("hcs7.wasm",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs7.wasm: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs7.wasm: topicId is required");const i=ms(t,"config")||{},s=r.buildHcs7WasmMessageTx({topicId:n,config:i});return await us(e,s)});const ys=Object.freeze(Object.defineProperty({__proto__:null,ByteBuildRegistry:ls},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>s.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>s.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>s.PluginRegistry}),e.AcceptConnectionRequestTool=Ct,e.BaseHCS10QueryTool=g,e.BaseHCS10TransactionTool=f,e.BaseHCS2QueryTool=Ot,e.BaseHCS2TransactionTool=kt,e.BaseHCS6QueryTool=Lt,e.BaseHCS6TransactionTool=Dt,e.BaseInscriberQueryTool=zt,e.BaseInscriberTransactionTool=Zt,e.ByteBuildRegistry=ls,e.CheckMessagesTool=yt,e.ConnectionMonitorTool=It,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 Ht}async executeQuery(e,t){const n=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!("success"in n)||!n.success)throw new Error(n.error||"Failed to create dynamic registry");if(Nt(n)){const t=n.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-6 dynamic registry. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Create HCS-6 dynamic registry (TTL: ${e.ttl}s)`}}}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 Ot{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create an HCS-2 registry (standard HCS-2). Use when the user asks to create an HCS-2 registry, not a generic HCS topic. Builds a standards-compliant registry topic and returns the result or transaction bytes."}get specificInputSchema(){return Bt}async executeQuery(e,t){const n=e=>{if("string"==typeof e){const t=e.trim().toLowerCase();return"true"===t||"false"!==t&&e}return e};try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:n(e.adminKey),submitKey:n(e.submitKey)});if(!t.success)throw new Error(t.error||"Failed to create registry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-2 registry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Create HCS-2 registry (${1===e.registryType?"Non-Indexed":"Indexed"}; TTL: ${e.ttl||86400}s)`}}}return`Successfully created HCS-2 registry!\n\nTopic ID: ${t?.topicId||"unknown"}\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(i){const e=i instanceof Error?i.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},e.DeleteEntryTool=class extends Ot{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return Mt}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to delete entry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to delete the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Delete HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid})`}}}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=wt,e.HCS10Builder=Jr,e.HCS10Client=class{constructor(e,n,i,s){this.standardClient=new r.HCS10Client({network:i,operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:s?.registryUrl,logLevel:s?.logLevel}),this.guardedRegistryBaseUrl=s?.registryUrl||"",this.useEncryption=s?.useEncryption||!1;const a="true"===t.env.DISABLE_LOGGING;this.logger=new r.Logger({level:s?.logLevel||"info",silent:a})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,i){try{return await this.standardClient.handleConnectionRequest(e,t,n,i)}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,i=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,i)}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),i=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return i?.metadata?.inboundTopicId&&i?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:i.metadata.inboundTopicId,outboundTopicId:i.metadata.outboundTopicId}),i}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,n,i){this.useEncryption;try{const r=await this.standardClient.sendMessage(e,t,n,i);return r.topicSequenceNumber?.toNumber()}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,t){return this.standardClient=new r.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HCS2Builder=as,e.HCS6Builder=os,e.HbarPricePlugin=Xr,e.InitiateConnectionTool=ht,e.InscribeFromBufferTool=class extends zt{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=nn()}get specificInputSchema(){return rn}async _call(e,t){try{const t="string"==typeof e.base64Data?e.base64Data:"",i=/^[A-Za-z0-9+/]*={0,2}$/.test(t)?n.Buffer.from(t,"base64"):n.Buffer.from(t,"utf8"),r=e.fileName,s=e.mimeType,a=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o={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:a,quoteOnly:e.quoteOnly},c=await this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:r,mimeType:s},o);if(c.confirmed&&!c.quote){const e=Gt(c.inscription,c.result),{topicId:t,cdnUrl:n}=Vt(e,a,"1");return JSON.stringify({success:!0,data:`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${c.result?.transactionId??"unknown"}\nTopic ID: ${t||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe inscription is now available.`})}return JSON.stringify({success:!0,data:`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${c.result?.transactionId??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`})}catch(i){const e=i instanceof Error?i.message:String(i);return JSON.stringify({success:!1,error:`Inscription failed: ${e}`})}}async executeQuery(e,t){const n=await async function(e,t,n){const i=e.trim(),s=r.ContentResolverRegistry.getResolver();if(!s)return Yt(i,t,n);const a=s.extractReferenceId(i);if(a)try{const e=await s.resolveReference(a);return{buffer:e.content,mimeType:e.metadata?.mimeType||t,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(o){const e=o instanceof Error?o.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return Yt(i,t,n)}(e.base64Data,e.mimeType,e.fileName);this.logger?.debug(`[InscribeFromBufferTool] Resolved content bytes: ${n.buffer?.length??-1}`);try{this.validateContent(n.buffer)}catch(c){this.logger?.warn(`Content validation warning: ${c instanceof Error?c.message:String(c)}`)}const i=n.buffer,s=n.mimeType||e.mimeType,a=n.fileName||e.fileName,o={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:a,mimeType:s},o);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:a,mimeType:s,sizeBytes:i.length},message:`Estimated Quote for buffer content: ${a} (${(i.length/1024).toFixed(2)} KB)\nTotal cost: ${e.totalCostHbar} HBAR`}}catch(d){const e=d instanceof Error?d.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{this.logger?.debug(`[InscribeFromBufferTool] Calling inscribe with fileName: ${a}, mime: ${s}`);const t=await this.executeInscription(i,a,s,o,e.timeoutMs);return this.logger?.debug(`[InscribeFromBufferTool] Inscribe result (confirmed): ${Boolean(t?.confirmed)}`),this.formatInscriptionResult(t,o)}catch(d){this.logger?.warn(`[InscribeFromBufferTool] Error during inscription: ${d instanceof Error?d.message:String(d)}`);const e=d instanceof Error?d.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){const n=e;if(n.confirmed&&!n.quote){const e=Gt(n.inscription,n.result),i=t.network||"testnet",{topicId:r,cdnUrl:s}=Vt(e,i,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${s?`\nView inscription: ${s}`:""}\n\nThe inscription is now available.`}return n.quote||n.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`}},e.InscribeFromFileTool=class extends zt{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 Xt}async executeQuery(e,t){let i;try{const t=await h.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 h.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=p.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=p.basename(e.filePath),a=this.getMimeType(s);this.logger?.info(`File: ${s}, MIME type: ${a}`);const o={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"buffer",buffer:n.Buffer.from(r,"base64"),fileName:s,mimeType:a},o);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{fileName:s,mimeType:a,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:a},o),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:n.Buffer.from(r,"base64"),fileName:s,mimeType:a},o);const i=t;if(i.confirmed&&!i.quote){const e=Gt(i.inscription,i.result),t=o.network||"testnet",{topicId:n,cdnUrl:r}=Vt(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${n||"N/A"}${r?`\nView inscription: ${r}`:""}\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??"unknown"}\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"}[p.extname(e).toLowerCase()]||"application/octet-stream"}},e.InscribeFromUrlTool=class extends zt{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 Jt}async executeQuery(e,t){if(Qt.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.`)}Qt.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")||"",a=i.headers.get("content-length");if(["text/html","application/xhtml+xml","text/xml"].some(e=>s.toLowerCase().includes(e)))throw new Error(`URL returns HTML/web page content (Content-Type: ${s}). This tool only works with direct file URLs (PDFs, images, JSON, etc.). For web page content, first retrieve the content using the appropriate MCP tool or web scraper, then use inscribeFromBuffer to inscribe it.`);if(a&&0===parseInt(a))throw new Error("URL returns empty content (Content-Length: 0). Cannot inscribe empty content.");if(a&&parseInt(a)<10)throw new Error(`URL content is too small (${a} bytes). Content must be at least 10 bytes.`);if(!s||"application/octet-stream"===s){Qt.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;Qt.warn(`Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}Qt.info(`URL validation passed. Content-Type: ${s}, Content-Length: ${a||"unknown"}`)}catch(s){throw clearTimeout(n),s}}catch(i){if(i instanceof Error)if("AbortError"===i.name)Qt.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;Qt.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);const i=t;if(i.confirmed&&!i.quote){const e=Gt(i.inscription,i.result),t=n.network||"testnet",{topicId:r,cdnUrl:s}=Vt(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${s?`\nView inscription: ${s}`:""}\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??"unknown"}\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 zt{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 Tn._def?.schema||Tn}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 dn(et({name:Ve().min(1,"Name is required").describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),description:Ve().min(1,"Description is required").describe("Meaningful description of the artwork, story, or concept behind this NFT"),creator:Ve().min(1,"Creator is required").describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),attributes:dn(Ye(et({trait_type:Ve().describe('Trait name (e.g., "Rarity", "Color", "Style")'),value:tt([Ve(),Qe()]).describe('Trait value (e.g., "Epic", "Blue", 85)')}))).withRender(wn.array("NFT Attributes","Attribute")).optional().describe("Collectible traits and characteristics."),type:Ve().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 vn({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={...cn({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 on.parse(e)}catch(t){if(t instanceof T){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 vn({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 a={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 o;if(e.url)o={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);o={type:"buffer",buffer:n,fileName:r||e.fileName||"hashinal-content",mimeType:i||e.mimeType}}}if(e.quoteOnly)try{const t=await this.generateInscriptionQuote(o,a);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 vn({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.inscribeAuto?this.inscriberBuilder.inscribeAuto(o,a):this.inscriberBuilder.inscribe(o,a),n])}else t=this.inscriberBuilder.inscribeAuto?await this.inscriberBuilder.inscribeAuto(o,a):await this.inscriberBuilder.inscribe(o,a);if(t.confirmed&&!t.quote){const n=Gt(t.inscription,t.result),i=a.network||"testnet",s=e.fileStandard||"1",{hrl:o,topicId:c,cdnUrl:l}=Vt(n,i,s),u=function(e){const{hrl:t,topicId:n,standard:i,cdnUrl:r,transactionId:s,metadata:a}=e;return{success:!0,type:"inscription",title:`${i} Hashinal Inscription Complete`,message:`Successfully inscribed "${a.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:a,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}}}({hrl:o||"hcs://1/unknown",topicId:c||"unknown",standard:"6"===s?"Dynamic":"Static",cdnUrl:l,transactionId:t?.inscription?.tx_id??"unknown",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:Array.isArray(e.attributes)?e.attributes:[]}});if(!1!==e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(u);u.hashLinkBlock=e}catch(d){new r.Logger({module:"InscribeHashinalTool"}).warn("Failed to create HashLink block",d)}return u}if(t.quote||t.confirmed)return vn({code:"UNEXPECTED_RESULT",details:"Received an unexpected inscription result state",suggestions:["Try again or verify network status"]});return function(e){const{transactionId:t,details:n,suggestions:i}=e,r=n||`Inscription submitted but not yet confirmed. Transaction ID: ${t}`;return{success:!1,type:"error",title:"Inscription Submitted (Pending)",message:r,error:{code:"INSCRIPTION_PENDING",details:r,suggestions:i||["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"]}}}({transactionId:t.result?.transactionId??"unknown",details:"Successfully submitted Hashinal inscription. Waiting for network confirmation..."})}catch(c){const e=c instanceof Error?c.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}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,a=function(e){const t="mainnet"===e?In.mainnet:In.testnet;return t&&"0.0.TBD"!==t.blockId?t:In.testnet}(s);return{blockId:a.blockId,hashLink:a.hashLink,template:a.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 a=s.extractReferenceId(i);if(a)try{const e=await s.resolveReference(a);return{buffer:e.content,mimeType:e.metadata?.mimeType||t,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(o){const e=o instanceof Error?o.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return this.handleDirectContent(i,t,n)}handleDirectContent(e,t,i){if(/^[A-Za-z0-9+/]*={0,2}$/.test(e))try{return{buffer:n.Buffer.from(e,"base64"),mimeType:t,fileName:i,wasReference:!1}}catch(r){throw new Error("Failed to decode base64 data. Please ensure the data is properly encoded.")}return{buffer:n.Buffer.from(e,"utf8"),mimeType:t||"text/plain",fileName:i,wasReference:!1}}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=ds,e.ListConnectionsTool=gt,e.ListUnapprovedConnectionRequestsTool=xt,e.ManageConnectionRequestsTool=At,e.MigrateRegistryTool=class extends Ot{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return qt}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to migrate registry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to migrate the HCS-2 registry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Migrate HCS-2 registry (from ${e.registryTopicId} to ${e.targetTopicId})`}}}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=at,e.OpenConvaiState=Cn,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 Kt}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 Ot{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry (standard HCS-2). Retrieves indexed or latest entries and returns a structured summary."}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}),i=n.registryType,r=0===i||"0"===i||"indexed"===String(i).toLowerCase()||"index"===String(i).toLowerCase()||"index_topic"===String(i).toLowerCase()||"indexed_registry"===String(i).toLowerCase();return{topicId:n.topicId,registryType:r?"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=ct,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 Ut}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(!("success"in n)||!n.success)throw new Error(n.error||"Failed to register dynamic hashinal");if(Nt(n)){const t=n.transactionBytes;return{message:"I prepared an unsigned transaction to register a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:"Register dynamic hashinal"+(e.memo?` (Memo: ${e.memo})`:"")}}}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 Ot{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register an entry in an HCS-2 registry (standard HCS-2). Use this to add a target topic to an existing HCS-2 registry."}get specificInputSchema(){return $t}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to register entry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to register the entry in the HCS-2 registry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Register HCS-2 entry (registry ${e.registryTopicId} -> target ${e.targetTopicId})`}}}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 zt{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return An}async executeQuery(e,t){const n=await this.inscriberBuilder.retrieveInscription(e.transactionId,{apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"});return{inscriptionId:n.inscriptionId,transactionId:n.transactionId||"unknown",topicId:n.topic_id||n.topicId,status:n.status||"unknown",holderId:n.holderId,metadata:n.metadata,tags:n.tags,mode:n.mode,chunks:n.chunks,createdAt:n.createdAt,completedAt:n.completed||n.completedAt,fileUrl:n.fileUrl,mimeType:n.mimeType,fileSize:n.fileSize}}},e.RetrieveProfileTool=St,e.SendMessageToConnectionTool=ut,e.SignerProviderRegistry=Sn,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 jt}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(!("success"in n)||!n.success)throw new Error(n.error||"Failed to update dynamic hashinal");if(Nt(n)){const t=n.transactionBytes;return{message:"I prepared an unsigned transaction to update a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Update dynamic hashinal (registry ${e.registryTopicId})${e.memo?` (Memo: ${e.memo})`:""}`}}}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 Ot{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return Pt}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(!("success"in t)||!t.success)throw new Error(t.error||"Failed to update entry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to update the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Update HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid} -> ${e.targetTopicId})`}}}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=Yr(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=dn(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}dn(n).withProgressive(r,i)}return n}}return n},e.createSimpleConfig=function(e){const t=Yr(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=dn,e.extractFieldMetadata=bn,e.extractOptionsFromSchema=hn,e.extractProgressiveInfo=function(e){const t=un(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=Yr,e.extractValidationConstraints=mn,e.generateFieldOrdering=function(e){const t=Yr(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=yn,e.getInnerSchema=gn,e.getRenderConfig=un,e.hasRenderConfig=ln,e.inferFieldTypeFromSchema=pn,e.initializeStandardsAgentKit=async e=>{const n=e?.clientConfig||{},i=n.operatorId||t.env.HEDERA_OPERATOR_ID,a=n.operatorKey||t.env.HEDERA_OPERATOR_KEY,o=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"===o?l="mainnet":("testnet"===o||d.warn(`Unsupported network specified: '${o}'. Defaulting to 'testnet'.`),l="testnet"),!i||!a)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const u=e?.stateManager||new Cn({defaultEnvFilePath:_n,defaultPrefix:"TODD"});d.info("State manager initialized");const p=new s.ServerSigner(i,a,l),h=new s.HederaAgentKit(p);await h.initialize(),d.info(`HederaAgentKit initialized for ${i} on ${l}`);const f=new Jr(h,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let g,m;if(e?.monitoringClient){const e=new s.ServerSigner(i,a,l);g=new s.HederaAgentKit(e),await g.initialize(),m=new Jr(g,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new ct({hederaKit:h,hcs10Builder:f,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new wt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.retrieveProfileTool=new St({hederaKit:h,hcs10Builder:f,logger:void 0}),y.initiateConnectionTool=new ht({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listConnectionsTool=new gt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.sendMessageToConnectionTool=new ut({hederaKit:h,hcs10Builder:f,logger:void 0}),y.checkMessagesTool=new yt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.connectionMonitorTool=new It({hederaKit:g||h,hcs10Builder:m||f,logger:void 0}),y.manageConnectionRequestsTool=new At({hederaKit:h,hcs10Builder:f,logger:void 0}),y.acceptConnectionRequestTool=new Ct({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new xt({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(){D.prototype.withRender||(D.prototype.withRender=function(e){return dn(this).withRender(e)},D.prototype.withProgressive=function(e,t){return dn(this).withProgressive(e,t)},D.prototype.withBlock=function(e){return dn(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=fn,e.loadConfig=nn,e.renderConfigs=wn,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("@hashgraph/sdk"),require("@hashgraphonline/standards-sdk"),require("hedera-agent-kit"),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","@hashgraph/sdk","@hashgraphonline/standards-sdk","hedera-agent-kit","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.HederaSDK,e.StandardsSDK,e.HederaAgentKit,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],e["unenv/node/fs/promises"])}(this,function(e,t,n,i,r,s,a,o,c,d,l){"use strict";function u(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 p=u(o),h=u(l);class f extends s.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class g extends s.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var m,y,b;(y=m||(m={})).assertEqual=e=>{},y.assertIs=function(e){},y.assertNever=function(e){throw new Error},y.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},y.getValidEnumValues=e=>{const t=y.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const i of t)n[i]=e[i];return y.objectValues(n)},y.objectValues=e=>y.objectKeys(e).map(function(t){return e[t]}),y.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},y.find=(e,t)=>{for(const n of e)if(t(n))return n},y.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,y.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},y.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(b||(b={})).mergeShapes=(e,t)=>({...e,...t});const w=m.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),v=e=>{switch(typeof e){case"undefined":return w.undefined;case"string":return w.string;case"number":return Number.isNaN(e)?w.nan:w.number;case"boolean":return w.boolean;case"function":return w.function;case"bigint":return w.bigint;case"symbol":return w.symbol;case"object":return Array.isArray(e)?w.array:null===e?w.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?w.promise:"undefined"!=typeof Map&&e instanceof Map?w.map:"undefined"!=typeof Set&&e instanceof Set?w.set:"undefined"!=typeof Date&&e instanceof Date?w.date:w.object;default:return w.unknown}},I=m.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 T 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 T))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,m.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()}}T.create=e=>new T(e);const A=(e,t)=>{let n;switch(e.code){case I.invalid_type:n=e.received===w.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case I.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,m.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:n=`Unrecognized key(s) in object: ${m.joinValues(e.keys,", ")}`;break;case I.invalid_union:n="Invalid input";break;case I.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${m.joinValues(e.options)}`;break;case I.invalid_enum_value:n=`Invalid enum value. Expected ${m.joinValues(e.options)}, received '${e.received}'`;break;case I.invalid_arguments:n="Invalid function arguments";break;case I.invalid_return_type:n="Invalid function return type";break;case I.invalid_date:n="Invalid date";break;case I.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}"`:m.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case I.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 I.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 I.custom:n="Invalid input";break;case I.invalid_intersection_types:n="Intersection results could not be merged";break;case I.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case I.not_finite:n="Number must be finite";break;default:n=t.defaultError,m.assertNever(e)}return{message:n}};let _=A;function C(e,t){const n=_,i=(e=>{const{data:t,path:n,errorMaps:i,issueData:r}=e,s=[...n,...r.path||[]],a={...r,path:s};if(void 0!==r.message)return{...r,path:s,message:r.message};let o="";const c=i.filter(e=>!!e).slice().reverse();for(const d of c)o=d(a,{data:t,defaultError:o}).message;return{...r,path:s,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===A?void 0:A].filter(e=>!!e)});e.common.issues.push(i)}class E{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 S;"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 E.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 S;if("aborted"===r.status)return S;"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 S=Object.freeze({status:"aborted"}),R=e=>({status:"dirty",value:e}),x=e=>({status:"valid",value:e}),k=e=>"aborted"===e.status,O=e=>"dirty"===e.status,N=e=>"valid"===e.status,B=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 q=(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 T(e.common.issues);return this._error=t,this._error}}};function F(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:i,description:r}=e;if(t&&(n||i))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:r};return{errorMap:(t,r)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??r.defaultError}:void 0===r.data?{message:s??i??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:s??n??r.defaultError}},description:r}}class D{get description(){return this._def.description}_getType(e){return v(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:v(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new E,ctx:{common:e.parent.common,data:e.data,parsedType:v(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(B(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:v(e)},i=this._parseSync({data:e,path:n.path,parent:n});return q(n,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:v(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:v(e)},i=this._parse({data:e,path:n.path,parent:n}),r=await(B(i)?i:Promise.resolve(i));return q(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:I.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 Fe({schema:this,typeName:We.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return De.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Te.create(this)}promise(){return qe.create(this,this._def)}or(e){return Ce.create([this,e],this._def)}and(e){return Se.create(this,e,this._def)}transform(e){return new Fe({...F(this._def),schema:this,typeName:We.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new He({...F(this._def),innerType:this,defaultValue:t,typeName:We.ZodDefault})}brand(){return new Ke({typeName:We.ZodBranded,type:this,...F(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...F(this._def),innerType:this,catchValue:t,typeName:We.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ze.create(this,e)}readonly(){return ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const L=/^c[^\s-]{8,}$/i,H=/^[0-9a-z]+$/,U=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,K=/^[a-z0-9_-]{21}$/i,Z=/^[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)?)??$/,W=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let G;const 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])$/,Q=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,J=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,X=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Y=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ee=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,te="((\\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])))",ne=new RegExp(`^${te}$`);function ie(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 re(e){return new RegExp(`^${ie(e)}$`)}function se(e){let t=`${te}T${ie(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 ae(e,t){return!("v4"!==t&&t||!V.test(e))||!("v6"!==t&&t||!J.test(e))}function oe(e,t){if(!Z.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 ce(e,t){return!("v4"!==t&&t||!Q.test(e))||!("v6"!==t&&t||!X.test(e))}class de extends D{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==w.string){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.string,received:t.parsedType}),S}const t=new E;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:I.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:I.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:I.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&C(n,{code:I.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)W.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"email",code:I.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:I.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:I.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)K.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"nanoid",code:I.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)L.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"cuid",code:I.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)H.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"cuid2",code:I.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:I.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:I.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:I.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:I.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:I.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:I.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){se(i).test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:I.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){ne.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:I.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){re(i).test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{code:I.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:I.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?ae(e.data,i.version)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"ip",code:I.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:I.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?ce(e.data,i.version)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"cidr",code:I.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?Y.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"base64",code:I.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?ee.test(e.data)||(n=this._getOrReturnCtx(e,n),C(n,{validation:"base64url",code:I.invalid_string,message:i.message}),t.dirty()):m.assertNever(i);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:I.invalid_string,...$.errToObj(n)})}_addCheck(e){return new de({...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 de({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new de({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new de({...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 le(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}de.create=e=>new de({checks:[],typeName:We.ZodString,coerce:e?.coerce??!1,...F(e)});class ue extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==w.number){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.number,received:t.parsedType}),S}let t;const n=new E;for(const i of this._def.checks)if("int"===i.kind)m.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),C(t,{code:I.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:I.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:I.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty())}else"multipleOf"===i.kind?0!==le(e.data,i.value)&&(t=this._getOrReturnCtx(e,t),C(t,{code:I.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:I.not_finite,message:i.message}),n.dirty()):m.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 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]})}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&&m.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)}}ue.create=e=>new ue({checks:[],typeName:We.ZodNumber,coerce:e?.coerce||!1,...F(e)});class pe extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==w.bigint)return this._getInvalidInput(e);let t;const n=new E;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:I.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:I.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:I.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):m.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.bigint,received:t.parsedType}),S}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 pe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$.toString(i)}]})}_addCheck(e){return new pe({...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}}pe.create=e=>new pe({checks:[],typeName:We.ZodBigInt,coerce:e?.coerce??!1,...F(e)});class he extends D{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==w.boolean){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.boolean,received:t.parsedType}),S}return x(e.data)}}he.create=e=>new he({typeName:We.ZodBoolean,coerce:e?.coerce||!1,...F(e)});class fe extends D{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==w.date){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.date,received:t.parsedType}),S}if(Number.isNaN(e.data.getTime())){return C(this._getOrReturnCtx(e),{code:I.invalid_date}),S}const t=new E;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:I.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:I.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):m.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new fe({...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}}fe.create=e=>new fe({checks:[],coerce:e?.coerce||!1,typeName:We.ZodDate,...F(e)});class ge extends D{_parse(e){if(this._getType(e)!==w.symbol){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.symbol,received:t.parsedType}),S}return x(e.data)}}ge.create=e=>new ge({typeName:We.ZodSymbol,...F(e)});class me extends D{_parse(e){if(this._getType(e)!==w.undefined){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.undefined,received:t.parsedType}),S}return x(e.data)}}me.create=e=>new me({typeName:We.ZodUndefined,...F(e)});class ye extends D{_parse(e){if(this._getType(e)!==w.null){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.null,received:t.parsedType}),S}return x(e.data)}}ye.create=e=>new ye({typeName:We.ZodNull,...F(e)});class be extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return x(e.data)}}be.create=e=>new be({typeName:We.ZodAny,...F(e)});class we extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return x(e.data)}}we.create=e=>new we({typeName:We.ZodUnknown,...F(e)});class ve extends D{_parse(e){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.never,received:t.parsedType}),S}}ve.create=e=>new ve({typeName:We.ZodNever,...F(e)});class Ie extends D{_parse(e){if(this._getType(e)!==w.undefined){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.void,received:t.parsedType}),S}return x(e.data)}}Ie.create=e=>new Ie({typeName:We.ZodVoid,...F(e)});class Te extends D{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==w.array)return C(t,{code:I.invalid_type,expected:w.array,received:t.parsedType}),S;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?I.too_big:I.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:I.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:I.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=>E.mergeArray(n,e));const r=[...t.data].map((e,n)=>i.type._parseSync(new M(t,e,t.path,n)));return E.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new Te({...this._def,minLength:{value:e,message:$.toString(t)}})}max(e,t){return new Te({...this._def,maxLength:{value:e,message:$.toString(t)}})}length(e,t){return new Te({...this._def,exactLength:{value:e,message:$.toString(t)}})}nonempty(e){return this.min(1,e)}}function Ae(e){if(e instanceof _e){const t={};for(const n in e.shape){const i=e.shape[n];t[n]=De.create(Ae(i))}return new _e({...e._def,shape:()=>t})}return e instanceof Te?new Te({...e._def,type:Ae(e.element)}):e instanceof De?De.create(Ae(e.unwrap())):e instanceof Le?Le.create(Ae(e.unwrap())):e instanceof Re?Re.create(e.items.map(e=>Ae(e))):e}Te.create=(e,t)=>new Te({type:e,minLength:null,maxLength:null,exactLength:null,typeName:We.ZodArray,...F(t)});class _e extends D{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=m.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==w.object){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.object,received:t.parsedType}),S}const{status:t,ctx:n}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),s=[];if(!(this._def.catchall instanceof ve&&"strip"===this._def.unknownKeys))for(const o in n.data)r.includes(o)||s.push(o);const a=[];for(const o of r){const e=i[o],t=n.data[o];a.push({key:{status:"valid",value:o},value:e._parse(new M(n,t,n.path,o)),alwaysSet:o in n.data})}if(this._def.catchall instanceof ve){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of s)a.push({key:{status:"valid",value:t},value:{status:"valid",value:n.data[t]}});else if("strict"===e)s.length>0&&(C(n,{code:I.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const i=n.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new 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 a){const n=await t.key,i=await t.value;e.push({key:n,value:i,alwaysSet:t.alwaysSet})}return e}).then(e=>E.mergeObjectSync(t,e)):E.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return $.errToObj,new _e({...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 _e({...this._def,unknownKeys:"strip"})}passthrough(){return new _e({...this._def,unknownKeys:"passthrough"})}extend(e){return new _e({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new _e({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:We.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new _e({...this._def,catchall:e})}pick(e){const t={};for(const n of m.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new _e({...this._def,shape:()=>t})}omit(e){const t={};for(const n of m.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new _e({...this._def,shape:()=>t})}deepPartial(){return Ae(this)}partial(e){const t={};for(const n of m.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new _e({...this._def,shape:()=>t})}required(e){const t={};for(const n of m.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof De;)e=e._def.innerType;t[n]=e}return new _e({...this._def,shape:()=>t})}keyof(){return $e(m.objectKeys(this.shape))}}_e.create=(e,t)=>new _e({shape:()=>e,unknownKeys:"strip",catchall:ve.create(),typeName:We.ZodObject,...F(t)}),_e.strictCreate=(e,t)=>new _e({shape:()=>e,unknownKeys:"strict",catchall:ve.create(),typeName:We.ZodObject,...F(t)}),_e.lazycreate=(e,t)=>new _e({shape:e,unknownKeys:"strip",catchall:ve.create(),typeName:We.ZodObject,...F(t)});class Ce extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const i of e)if("dirty"===i.result.status)return t.common.issues.push(...i.ctx.common.issues),i.result;const n=e.map(e=>new T(e.ctx.common.issues));return C(t,{code:I.invalid_union,unionErrors:n}),S});{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 T(e));return C(t,{code:I.invalid_union,unionErrors:r}),S}}get options(){return this._def.options}}function Ee(e,t){const n=v(e),i=v(t);if(e===t)return{valid:!0,data:e};if(n===w.object&&i===w.object){const n=m.objectKeys(t),i=m.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const s of i){const n=Ee(e[s],t[s]);if(!n.valid)return{valid:!1};r[s]=n.data}return{valid:!0,data:r}}if(n===w.array&&i===w.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let i=0;i<e.length;i++){const r=Ee(e[i],t[i]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===w.date&&i===w.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}Ce.create=(e,t)=>new Ce({options:e,typeName:We.ZodUnion,...F(t)});class Se extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=(e,i)=>{if(k(e)||k(i))return S;const r=Ee(e.value,i.value);return r.valid?((O(e)||O(i))&&t.dirty(),{status:t.value,value:r.data}):(C(n,{code:I.invalid_intersection_types}),S)};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}))}}Se.create=(e,t,n)=>new Se({left:e,right:t,typeName:We.ZodIntersection,...F(n)});class Re extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.array)return C(n,{code:I.invalid_type,expected:w.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return C(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(C(n,{code:I.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=>E.mergeArray(t,e)):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:We.ZodTuple,rest:null,...F(t)})};class xe extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.object)return C(n,{code:I.invalid_type,expected:w.object,received:n.parsedType}),S;const i=[],r=this._def.keyType,s=this._def.valueType;for(const a in n.data)i.push({key:r._parse(new M(n,a,n.path,a)),value:s._parse(new M(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?E.mergeObjectAsync(t,i):E.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return new xe(t instanceof D?{keyType:e,valueType:t,typeName:We.ZodRecord,...F(n)}:{keyType:de.create(),valueType:e,typeName:We.ZodRecord,...F(t)})}}class ke extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.map)return C(n,{code:I.invalid_type,expected:w.map,received:n.parsedType}),S;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 S;"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 S;"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:We.ZodMap,...F(n)});class Oe extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==w.set)return C(n,{code:I.invalid_type,expected:w.set,received:n.parsedType}),S;const i=this._def;null!==i.minSize&&n.data.size<i.minSize.value&&(C(n,{code:I.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:I.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 S;"dirty"===i.status&&t.dirty(),n.add(i.value)}return{status:t.value,value:n}}const a=[...n.data.values()].map((e,t)=>r._parse(new M(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>s(e)):s(a)}min(e,t){return new Oe({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new Oe({...this._def,maxSize:{value:e,message:$.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Oe.create=(e,t)=>new Oe({valueType:e,minSize:null,maxSize:null,typeName:We.ZodSet,...F(t)});class Ne extends D{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ne.create=(e,t)=>new Ne({getter:e,typeName:We.ZodLazy,...F(t)});class Be extends D{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return C(t,{received:t.data,code:I.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}function $e(e,t){return new Pe({values:e,typeName:We.ZodEnum,...F(t)})}Be.create=(e,t)=>new Be({value:e,typeName:We.ZodLiteral,...F(t)});class Pe extends D{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return C(t,{expected:m.joinValues(n),received:t.parsedType,code:I.invalid_type}),S}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:I.invalid_enum_value,options:n}),S}return x(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return Pe.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Pe.create=$e;class Me extends D{_parse(e){const t=m.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==w.string&&n.parsedType!==w.number){const e=m.objectValues(t);return C(n,{expected:m.joinValues(e),received:n.parsedType,code:I.invalid_type}),S}if(this._cache||(this._cache=new Set(m.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=m.objectValues(t);return C(n,{received:n.data,code:I.invalid_enum_value,options:e}),S}return x(e.data)}get enum(){return this._def.values}}Me.create=(e,t)=>new Me({values:e,typeName:We.ZodNativeEnum,...F(t)});class qe extends D{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==w.promise&&!1===t.common.async)return C(t,{code:I.invalid_type,expected:w.promise,received:t.parsedType}),S;const n=t.parsedType===w.promise?t.data:Promise.resolve(t.data);return x(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}qe.create=(e,t)=>new qe({type:e,typeName:We.ZodPromise,...F(t)});class Fe extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===We.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 S;const i=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===i.status?S:"dirty"===i.status||"dirty"===t.value?R(i.value):i});{if("aborted"===t.value)return S;const i=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===i.status?S:"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?S:("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?S:("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 S;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})):S)}m.assertNever(i)}}Fe.create=(e,t,n)=>new Fe({schema:e,typeName:We.ZodEffects,effect:t,...F(n)}),Fe.createWithPreprocess=(e,t,n)=>new Fe({schema:t,effect:{type:"preprocess",transform:e},typeName:We.ZodEffects,...F(n)});class De extends D{_parse(e){return this._getType(e)===w.undefined?x(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}De.create=(e,t)=>new De({innerType:e,typeName:We.ZodOptional,...F(t)});class Le extends D{_parse(e){return this._getType(e)===w.null?x(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(e,t)=>new Le({innerType:e,typeName:We.ZodNullable,...F(t)});class He extends D{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===w.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}He.create=(e,t)=>new He({innerType:e,typeName:We.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...F(t)});class Ue extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return B(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new T(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new T(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Ue.create=(e,t)=>new Ue({innerType:e,typeName:We.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...F(t)});class je extends D{_parse(e){if(this._getType(e)!==w.nan){const t=this._getOrReturnCtx(e);return C(t,{code:I.invalid_type,expected:w.nan,received:t.parsedType}),S}return{status:"valid",value:e.data}}}je.create=e=>new je({typeName:We.ZodNaN,...F(e)});class Ke extends D{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ze extends D{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?S:"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?S:"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 Ze({in:e,out:t,typeName:We.ZodPipeline})}}class ze extends D{_parse(e){const t=this._def.innerType._parse(e),n=e=>(N(e)&&(e.value=Object.freeze(e.value)),e);return B(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var We,Ge;ze.create=(e,t)=>new ze({innerType:e,typeName:We.ZodReadonly,...F(t)}),(Ge=We||(We={})).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 Ve=de.create,Qe=ue.create,Je=he.create,Xe=we.create;ve.create;const Ye=Te.create,et=_e.create,tt=Ce.create;Se.create,Re.create;const nt=xe.create,it=Pe.create,rt=Me.create;qe.create,De.create,Le.create;const st=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"}};st.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 at=st;const ot=et({name:Ve().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:Ve().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:Ve().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:it(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:Ve().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:tt([Ye(rt(r.AIAgentCapability)),Ye(Ve()),Ve()]).optional().transform(e=>{if(e)return"string"==typeof e?at.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?at.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:tt([Ye(Ve()),Ve()]).optional().transform(e=>{if(e)return"string"==typeof e?at.parseCapabilities(e):at.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:Ve().optional().describe("Creator attribution for the agent"),socials:nt(it(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),Ve()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:nt(Xe()).optional().describe("Custom metadata properties for the agent"),profilePicture:tt([Ve().describe("URL or local file path to profile picture"),et({url:Ve().optional(),path:Ve().optional(),filename:Ve().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:Ve().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:Qe().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:Ve().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:Qe().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:Ye(et({amount:Qe().positive(),tokenId:Ve()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Ye(Ve()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:Je().optional().describe("Whether to set as current agent (default: true)"),persistence:et({prefix:Ve().optional()}).optional().describe("Optional persistence configuration")});class ct extends f{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},a=this.getServiceBuilder().getStateManager();if(a&&(a.setCurrentAgent(e),a.persistAgentData)){const t=this.specificArgs.persistence?.prefix||this.specificArgs.name.toUpperCase().replace(/[^A-Z0-9]/g,"_");a.persistAgentData(e,{type:"env-file",prefix:t}).catch(()=>{})}}}}const dt=new r.Logger({module:"SendMessageToConnectionTool"}),lt=et({targetIdentifier:Ve().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:Ve().optional().describe("The connection number (e.g., '1', '2') from the 'list_connections' tool."),agentId:Ve().optional().describe("The account ID (e.g., 0.0.12345) of the target agent."),message:Ve().describe("The text message content to send."),disableMonitoring:Je().optional().default(!1)});class ut extends f{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=lt,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){dt.debug("Could not refresh connections:",s)}if(i.match(/^\d+$/)){const e=r.listConnections(),s=parseInt(i)-1,a=e.filter(e=>"established"===e.status&&!e.isPending&&!e.needsConfirmation);if(s>=0&&s<a.length){const e=a[s];if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}if(i.match(/^\d+\.\d+\.\d+$/)){const e=r.listConnections().find(e=>!(e.targetAccountId!==i&&e.targetAccountId!==`0.0.${i}`||"established"!==e.status||e.isPending||e.needsConfirmation));if(e&&e.connectionTopicId)return void(await n.sendMessageToConnection({targetIdentifier:e.connectionTopicId,message:t.message,disableMonitoring:t.disableMonitoring}))}}await n.sendMessageToConnection({targetIdentifier:i,message:t.message,disableMonitoring:t.disableMonitoring})}}const pt=et({targetAccountId:Ve().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:Je().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:Ve().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 ht extends f{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=pt,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 ft=et({includeDetails:Je().optional().describe("Whether to include detailed information about each connection"),showPending:Je().optional().describe("Whether to include pending connection requests")});class gt extends g{constructor(e){super(e),this.name="list_connections",this.description="Lists all active HCS-10 connections. Use this FIRST before sending messages to check if you already have an active connection to a target agent. Shows connection details and agent information for each active connection.",this.specificInputSchema=ft}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 mt=et({targetIdentifier:Ve().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:Je().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:Qe().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class yt extends g{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=mt}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 bt=et({accountId:Ve().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:tt([Ye(rt(r.AIAgentCapability)),Ye(Ve()),Ve()]).optional().transform(e=>{if(e)return"string"==typeof e?at.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?at.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class wt extends g{constructor(e){super(e),this.name="find_registrations",this.description='Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=bt}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 vt=et({acceptAll:Je().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:Ve().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:Ye(et({amount:Qe(),collectorAccount:Ve().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Ye(et({amount:Qe(),tokenId:Ve(),collectorAccount:Ve().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:Ye(Ve()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:Qe().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:Ve().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class It extends f{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=vt,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 Tt=et({action:it(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:Ve().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class At extends g{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=Tt}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 _t=et({requestKey:Ve().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:Qe().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:Ye(Ve()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class Ct extends f{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=_t,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 Et=et({accountId:Ve().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:Je().optional().describe("Optional: Force refresh from the network instead of using cache.")});class St extends g{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=Et}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=et({});class xt extends g{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=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 s.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class Ot extends s.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}function Nt(e){return!!e&&"string"==typeof e.transactionBytes}const Bt=et({registryType:rt(r.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:Qe().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:tt([Ve(),Je()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:tt([Ve(),Je()]).optional().describe("Submit key: public key string or true to use operator key")});const $t=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:Ve().optional().describe("Optional metadata URI (HIP-412 format)"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const Pt=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:Ve().describe("The unique ID of the entry to update"),metadata:Ve().optional().describe("Optional metadata URI (HIP-412 format)"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const Mt=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:Ve().describe("The unique ID of the entry to delete"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const qt=et({registryTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:Ve().optional().describe("Optional metadata URI for migration details"),memo:Ve().max(500).optional().describe("Optional memo (max 500 characters)")});const Ft=et({topicId:Ve().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:Qe().int().positive().optional().describe("Maximum number of entries to return"),order:it(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:Qe().int().min(0).optional().describe("Number of entries to skip")});class Dt extends s.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}class Lt extends s.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs6",this.hcs6Builder=e.hcs6Builder}getServiceBuilder(){return this.hcs6Builder}}const Ht=et({ttl:Qe().min(3600).default(86400).describe("Time-to-live in seconds (minimum 3600 seconds/1 hour)"),submitKey:tt([Je(),Ve()]).optional().describe("Submit key for the registry topic. Can be boolean (use operator key) or a public key string")});const Ut=et({metadata:nt(Xe()).describe("Metadata object for the hashinal (e.g., name, description, attributes)"),data:et({base64:Ve().optional().describe("Base64 encoded data for the hashinal"),url:Ve().optional().describe("URL to fetch data from"),mimeType:Ve().optional().describe("MIME type of the data")}).optional().describe("Data to inscribe with the hashinal"),memo:Ve().optional().describe("Optional memo for the registration"),ttl:Qe().min(3600).default(86400).describe("Time-to-live in seconds for the inscription"),registryTopicId:Ve().optional().describe("Registry topic ID to use. If not provided, a new registry will be created"),submitKey:Ve().optional().describe("Submit key for the registry (required if registry has a submit key)")});const jt=et({registryTopicId:Ve().describe("The registry topic ID that tracks this dynamic hashinal"),metadata:nt(Xe()).describe("Updated metadata object for the hashinal"),data:et({base64:Ve().optional().describe("Base64 encoded data for the updated hashinal"),url:Ve().optional().describe("URL to fetch updated data from"),mimeType:Ve().optional().describe("MIME type of the data")}).optional().describe("Updated data to inscribe"),memo:Ve().optional().describe('Optional memo for the update (e.g., "Level up", "Version 2.0")'),submitKey:Ve().describe("Submit key for the registry (required to update)")});const Kt=et({topicId:Ve().describe("The registry topic ID to query"),limit:Qe().optional().default(100).describe("Maximum number of entries to retrieve"),order:it(["asc","desc"]).optional().default("desc").describe("Order of entries (desc shows latest first)"),skip:Qe().optional().describe("Number of entries to skip")});class Zt extends s.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 zt extends s.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}}function Wt(e,t){if(!e||"object"!=typeof e)return;const n=e[t];return"string"==typeof n&&n.trim()?n:void 0}function Gt(e,t){return{jsonTopicId:e.jsonTopicId||Wt(e,"json_topic_id"),topicId:Wt(e,"topic_id")||Wt(e,"topicId")||Wt(t,"topicId")||Wt(t,"topic_id")}}function Vt(e,t,n="1"){const i=e.jsonTopicId||e.topicId;return{hrl:i?`hcs://${n}/${i}`:void 0,cdnUrl:e.jsonTopicId?`https://kiloscribe.com/api/inscription-cdn/${e.jsonTopicId}?network=${t}`:void 0,topicId:i}}const Qt=new r.Logger({module:"InscribeFromUrlTool"}),Jt=et({url:Ve().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:it(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:nt(Xe()).optional().describe("Metadata to attach to the inscription"),tags:Ye(Ve()).optional().describe("Tags to categorize the inscription"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),apiKey:Ve().optional().describe("API key for inscription service"),quoteOnly:Je().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});const Xt=et({filePath:Ve().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:it(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:nt(Xe()).optional().describe("Metadata to attach to the inscription"),tags:Ye(Ve()).optional().describe("Tags to categorize the inscription"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation"),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout)"),apiKey:Ve().optional().describe("API key for inscription service"),quoteOnly:Je().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription")});function Yt(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 en=Ve().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]"'),tn={maxInscriptionSize:51200,minContentSize:10,logLevel:"warn"};function nn(){return{maxInscriptionSize:parseInt(t.env.REF_MAX_SIZE||tn.maxInscriptionSize.toString(),10),minContentSize:parseInt(t.env.REF_MIN_SIZE||tn.minContentSize.toString(),10),logLevel:t.env.REF_LOG_LEVEL||tn.logLevel,enableContentValidation:"false"!==t.env.REF_ENABLE_VALIDATION}}const rn=et({base64Data:tt([Ve(),en]).describe("Content to inscribe as base64 data, plain text, or content reference"),fileName:Ve().min(1).describe("Name for the inscribed content"),mimeType:Ve().optional().describe("MIME type of the content"),metadata:nt(Xe()).optional().describe("Metadata to attach"),tags:Ye(Ve()).optional().describe("Tags to categorize the inscription"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Wait for inscription confirmation"),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds"),apiKey:Ve().optional().describe("API key for inscription service"),quoteOnly:Je().optional().default(!1).describe("Return cost quote only")});const sn=et({uri:Ve().describe("URI of the file"),checksum:Ve().optional().describe("SHA-256 checksum of the file"),is_default_file:Je().optional().describe("Whether this is the default file"),type:Ve().describe("MIME type of the file")}),an=et({trait_type:Ve().describe("The trait type"),value:tt([Ve(),Qe()]).describe("The trait value"),display_type:Ve().optional().describe("Display type for the attribute")}),on=et({name:Ve().describe("Token name (required by HIP-412)"),description:Ve().describe("Human readable description (required by HIP-412)"),image:Ve().describe("Preview image URI (required by HIP-412)"),type:Ve().describe("MIME type (required by HIP-412)"),creator:Ve().optional().describe("Creator name or comma-separated names"),creatorDID:Ve().optional().describe("Decentralized identifier for creator"),checksum:Ve().optional().describe("SHA-256 checksum of the image"),format:Ve().optional().default("HIP412@2.0.0").describe("Metadata format version"),files:Ye(sn).optional().describe("Array of files for multi-file NFTs"),attributes:Ye(an).optional().describe("NFT attributes/traits"),properties:nt(Xe()).optional().describe("Additional properties")});function cn(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 dn(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:pn(e)};return this.withRender({...i,progressive:{priority:t,group:n}})},t.withBlock=function(t){const n=this._renderConfig||{fieldType:pn(e)};return this.withRender({...n,block:{id:t,type:"field",reusable:!0}})},t}function ln(e){return Boolean(e&&"function"==typeof e.withRender)}function un(e){if(ln(e))return e._renderConfig}function pn(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?pn(t):"text"}}}function hn(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 fn(e){const t=e._def?.typeName;return"ZodOptional"===t||"ZodDefault"===t}function gn(e){const t=e._def?.typeName;if("ZodOptional"===t||"ZodDefault"===t){const t=e._def?.innerType;return t||e}return e}function mn(e){const t=gn(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 yn(e){const t=e._def?.typeName;if("ZodDefault"===t){const t=e._def?.defaultValue;return"function"==typeof t?t():t}const n=gn(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]=yn(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 bn(e){const t=gn(e),n=pn(e),i=!fn(e),r=fn(e),s=yn(e),a=hn(t),o=mn(e),c=e?.description;return{type:n,required:i,optional:r,default:s,options:a,constraints:o,description:c,validation:{minLength:o.minLength,maxLength:o.maxLength,min:o.min,max:o.max,pattern:o.pattern?new RegExp(o.pattern):void 0}}}const wn={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)=>wn.text(e,t,"essential"),number:(e,t,n)=>wn.number(e,t,n,"essential"),select:(e,t)=>wn.select(e,t,"essential"),textarea:(e,t)=>wn.textarea(e,t,"essential")},advanced:{text:(e,t)=>wn.text(e,t,"advanced"),number:(e,t,n)=>wn.number(e,t,n,"advanced"),select:(e,t)=>wn.select(e,t,"advanced"),textarea:(e,t)=>wn.textarea(e,t,"advanced"),array:(e,t)=>wn.array(e,t,"advanced")},expert:{text:(e,t)=>wn.text(e,t,"expert"),number:(e,t,n)=>wn.number(e,t,n,"expert"),select:(e,t)=>wn.select(e,t,"expert"),textarea:(e,t)=>wn.textarea(e,t,"expert")}};function vn(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 In={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 Tn=dn(et({url:Ve().optional().describe("The URL of the content to inscribe as Hashinal NFT (use this OR contentRef)"),contentRef:en.optional().describe('Content reference ID in format "content-ref:[id]" for already stored content (use this OR url)'),base64Data:Ve().optional().describe("Base64 encoded content data (use this if neither url nor contentRef provided)"),fileName:Ve().optional().describe("File name for the content (required when using base64Data or contentRef)"),mimeType:Ve().optional().describe('MIME type of the content (e.g., "image/png", "image/jpeg")'),name:Ve().optional().describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),creator:Ve().optional().describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),description:Ve().optional().describe("Meaningful description of the artwork, story, or concept behind this NFT"),type:Ve().optional().describe('Category or genre of the NFT (e.g., "Digital Art", "Photography", "Collectible Card")'),attributes:dn(Ye(et({trait_type:Ve(),value:tt([Ve(),Qe()])}))).withRender(wn.array("NFT Attributes","Attribute")).optional().describe('Collectible traits and characteristics (e.g., "Rarity": "Epic", "Color": "Blue", "Style": "Abstract")'),properties:nt(Xe()).optional().describe("Additional properties"),jsonFileURL:Ve().url().optional().describe("URL to JSON metadata file"),fileStandard:it(["1","6"]).optional().default("1").describe("HCS file standard: 1 for static Hashinals (HCS-5), 6 for dynamic Hashinals (HCS-6)"),tags:Ye(Ve()).optional().describe("Tags to categorize the NFT"),chunkSize:Qe().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:Je().optional().describe("Whether to wait for inscription confirmation").default(!0),timeoutMs:Qe().int().positive().optional().describe("Timeout in milliseconds for inscription (default: no timeout - waits until completion)"),quoteOnly:Je().optional().default(!1).describe("If true, returns a cost quote instead of executing the inscription"),withHashLinkBlocks:Je().optional().default(!0).describe("If true, creates interactive HashLink blocks for the inscribed content and returns block data alongside the inscription response"),renderForm:Je().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 An=et({transactionId:Ve().describe("The transaction ID of the inscription to retrieve"),apiKey:Ve().optional().describe("API key for inscription service")});const _n=o.join(t.cwd(),".env");class Cn{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 s={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";a.existsSync(e)&&(n=a.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}`)}a.writeFileSync(e,i.join("\n"))}(i,s)}}const En=class{static setSignerProvider(e){this._signerProvider=e}static async getSigner(){const e=this._signerProvider;if(!e)return null;try{if("function"==typeof e){const t=e();return t&&"function"==typeof t.then?await t:t}return e}catch{return null}}static setWalletInfoResolver(e){this._walletInfoResolver=e||null}static async getWalletInfo(){const e=this._walletInfoResolver;if(!e)return null;try{const t=e();return t&&"function"==typeof t.then?await t:t}catch{return null}}static setWalletExecutor(e){this._walletExecutor=e||null}static get walletExecutor(){return this._walletExecutor||null}static setStartHCSDelegate(e){this._startHCSDelegate=e||null}static get startHCSDelegate(){return this._startHCSDelegate||null}static setPreferWalletOnly(e){this._preferWalletOnly=!!e}static setBrowserHCSClientFactory(e){this._browserHCSClientFactory=e||null}static getBrowserHCSClient(e){return this._browserHCSClientFactory?this._browserHCSClientFactory(e):null}static get preferWalletOnly(){return this._preferWalletOnly}};En._preferWalletOnly=!1;let Sn=En;function Rn(e,t){return function(){return e.apply(t,arguments)}}const{toString:xn}=Object.prototype,{getPrototypeOf:kn}=Object,{iterator:On,toStringTag:Nn}=Symbol,Bn=(e=>t=>{const n=xn.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),$n=e=>(e=e.toLowerCase(),t=>Bn(t)===e),Pn=e=>t=>typeof t===e,{isArray:Mn}=Array,qn=Pn("undefined");function Fn(e){return null!==e&&!qn(e)&&null!==e.constructor&&!qn(e.constructor)&&Hn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Dn=$n("ArrayBuffer");const Ln=Pn("string"),Hn=Pn("function"),Un=Pn("number"),jn=e=>null!==e&&"object"==typeof e,Kn=e=>{if("object"!==Bn(e))return!1;const t=kn(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Nn in e||On in e)},Zn=$n("Date"),zn=$n("File"),Wn=$n("Blob"),Gn=$n("FileList"),Vn=$n("URLSearchParams"),[Qn,Jn,Xn,Yn]=["ReadableStream","Request","Response","Headers"].map($n);function ei(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),Mn(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(Fn(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let a;for(i=0;i<s;i++)a=r[i],t.call(null,e[a],a,e)}}function ti(e,t){if(Fn(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 ni="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:c,ii=e=>!qn(e)&&e!==ni;const ri=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&kn(Uint8Array)),si=$n("HTMLFormElement"),ai=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),oi=$n("RegExp"),ci=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};ei(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const di=$n("AsyncFunction"),li=(ui="function"==typeof d.setImmediate,pi=Hn(ni.postMessage),ui?d.setImmediate:pi?(hi=`axios@${Math.random()}`,fi=[],ni.addEventListener("message",({source:e,data:t})=>{e===ni&&t===hi&&fi.length&&fi.shift()()},!1),e=>{fi.push(e),ni.postMessage(hi,"*")}):e=>setTimeout(e));var ui,pi,hi,fi;const gi="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ni):void 0!==t&&t.nextTick||li,mi={isArray:Mn,isArrayBuffer:Dn,isBuffer:Fn,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Hn(e.append)&&("formdata"===(t=Bn(e))||"object"===t&&Hn(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Dn(e.buffer),t},isString:Ln,isNumber:Un,isBoolean:e=>!0===e||!1===e,isObject:jn,isPlainObject:Kn,isEmptyObject:e=>{if(!jn(e)||Fn(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Qn,isRequest:Jn,isResponse:Xn,isHeaders:Yn,isUndefined:qn,isDate:Zn,isFile:zn,isBlob:Wn,isRegExp:oi,isFunction:Hn,isStream:e=>jn(e)&&Hn(e.pipe),isURLSearchParams:Vn,isTypedArray:ri,isFileList:Gn,forEach:ei,merge:function e(){const{caseless:t}=ii(this)&&this||{},n={},i=(i,r)=>{const s=t&&ti(n,r)||r;Kn(n[s])&&Kn(i)?n[s]=e(n[s],i):Kn(i)?n[s]=e({},i):Mn(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&ei(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(ei(t,(t,i)=>{n&&Hn(t)?e[i]=Rn(t,n):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,s,a;const o={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)a=r[s],i&&!i(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==n&&kn(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Bn,kindOfTest:$n,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(Mn(e))return e;let t=e.length;if(!Un(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[On]).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:si,hasOwnProperty:ai,hasOwnProp:ai,reduceDescriptors:ci,freezeMethods:e=>{ci(e,(t,n)=>{if(Hn(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];Hn(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 Mn(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:ti,global:ni,isContextDefined:ii,isSpecCompliantForm:function(e){return!!(e&&Hn(e.append)&&"FormData"===e[Nn]&&e[On])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(jn(e)){if(t.indexOf(e)>=0)return;if(Fn(e))return e;if(!("toJSON"in e)){t[i]=e;const r=Mn(e)?[]:{};return ei(e,(e,t)=>{const s=n(e,i+1);!qn(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:di,isThenable:e=>e&&(jn(e)||Hn(e))&&Hn(e.then)&&Hn(e.catch),setImmediate:li,asap:gi,isIterable:e=>null!=e&&Hn(e[On])};function yi(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)}mi.inherits(yi,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:mi.toJSONObject(this.config),code:this.code,status:this.status}}});const bi=yi.prototype,wi={};["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=>{wi[e]={value:e}}),Object.defineProperties(yi,wi),Object.defineProperty(bi,"isAxiosError",{value:!0}),yi.from=(e,t,n,i,r,s)=>{const a=Object.create(bi);return mi.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),yi.call(a,e.message,t,n,i,r),a.cause=e,a.name=e.name,s&&Object.assign(a,s),a};function vi(e){return mi.isPlainObject(e)||mi.isArray(e)}function Ii(e){return mi.endsWith(e,"[]")?e.slice(0,-2):e}function Ti(e,t,n){return e?e.concat(t).map(function(e,t){return e=Ii(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Ai=mi.toFlatObject(mi,{},null,function(e){return/^is[A-Z]/.test(e)});function _i(e,t,i){if(!mi.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const r=(i=mi.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!mi.isUndefined(t[e])})).metaTokens,s=i.visitor||l,a=i.dots,o=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&mi.isSpecCompliantForm(t);if(!mi.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(mi.isDate(e))return e.toISOString();if(mi.isBoolean(e))return e.toString();if(!c&&mi.isBlob(e))throw new yi("Blob is not supported. Use a Buffer instead.");return mi.isArrayBuffer(e)||mi.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(mi.endsWith(n,"{}"))n=r?n:n.slice(0,-2),e=JSON.stringify(e);else if(mi.isArray(e)&&function(e){return mi.isArray(e)&&!e.some(vi)}(e)||(mi.isFileList(e)||mi.endsWith(n,"[]"))&&(s=mi.toArray(e)))return n=Ii(n),s.forEach(function(e,i){!mi.isUndefined(e)&&null!==e&&t.append(!0===o?Ti([n],i,a):null===o?n:n+"[]",d(e))}),!1;return!!vi(e)||(t.append(Ti(i,n,a),d(e)),!1)}const u=[],p=Object.assign(Ai,{defaultVisitor:l,convertValue:d,isVisitable:vi});if(!mi.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!mi.isUndefined(n)){if(-1!==u.indexOf(n))throw Error("Circular reference detected in "+i.join("."));u.push(n),mi.forEach(n,function(n,r){!0===(!(mi.isUndefined(n)||null===n)&&s.call(t,n,mi.isString(r)?r.trim():r,i,p))&&e(n,i?i.concat(r):[r])}),u.pop()}}(e),t}function Ci(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Ei(e,t){this._pairs=[],e&&_i(e,this,t)}const Si=Ei.prototype;function Ri(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xi(e,t,n){if(!t)return e;const i=n&&n.encode||Ri;mi.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):mi.isURLSearchParams(t)?t.toString():new Ei(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Si.append=function(e,t){this._pairs.push([e,t])},Si.toString=function(e){const t=e?function(t){return e.call(this,t,Ci)}:Ci;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class ki{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){mi.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Oi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ni={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ei,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Bi="undefined"!=typeof window&&"undefined"!=typeof document,$i="object"==typeof navigator&&navigator||void 0,Pi=Bi&&(!$i||["ReactNative","NativeScript","NS"].indexOf($i.product)<0),Mi="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,qi=Bi&&window.location.href||"http://localhost",Fi={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Bi,hasStandardBrowserEnv:Pi,hasStandardBrowserWebWorkerEnv:Mi,navigator:$i,origin:qi},Symbol.toStringTag,{value:"Module"})),...Ni};function Di(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=e.length;if(s=!s&&mi.isArray(i)?i.length:s,o)return mi.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a;i[s]&&mi.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&mi.isArray(i[s])&&(i[s]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],t[s]=e[s];return t}(i[s])),!a}if(mi.isFormData(e)&&mi.isFunction(e.entries)){const n={};return mi.forEachEntry(e,(e,i)=>{t(function(e){return mi.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const Li={transitional:Oi,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=mi.isObject(e);r&&mi.isHTMLForm(e)&&(e=new FormData(e));if(mi.isFormData(e))return i?JSON.stringify(Di(e)):e;if(mi.isArrayBuffer(e)||mi.isBuffer(e)||mi.isStream(e)||mi.isFile(e)||mi.isBlob(e)||mi.isReadableStream(e))return e;if(mi.isArrayBufferView(e))return e.buffer;if(mi.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 _i(e,new Fi.classes.URLSearchParams,{visitor:function(e,t,n,i){return Fi.isNode&&mi.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=mi.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return _i(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(mi.isString(e))try{return(t||JSON.parse)(e),mi.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Li.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(mi.isResponse(e)||mi.isReadableStream(e))return e;if(e&&mi.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 yi.from(r,yi.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:Fi.classes.FormData,Blob:Fi.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};mi.forEach(["delete","get","head","post","put","patch"],e=>{Li.headers[e]={}});const Hi=mi.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"]),Ui=Symbol("internals");function ji(e){return e&&String(e).trim().toLowerCase()}function Ki(e){return!1===e||null==e?e:mi.isArray(e)?e.map(Ki):String(e)}function Zi(e,t,n,i,r){return mi.isFunction(i)?i.call(this,t,n):(r&&(t=n),mi.isString(t)?mi.isString(i)?-1!==t.indexOf(i):mi.isRegExp(i)?i.test(t):void 0:void 0)}let zi=class{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=ji(t);if(!r)throw new Error("header name must be a non-empty string");const s=mi.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=Ki(e))}const s=(e,t)=>mi.forEach(e,(e,n)=>r(e,n,t));if(mi.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(mi.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]&&Hi[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(mi.isObject(e)&&mi.isIterable(e)){let n,i,r={};for(const t of e){if(!mi.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?mi.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=ji(e)){const n=mi.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(mi.isFunction(t))return t.call(this,e,n);if(mi.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=ji(e)){const n=mi.findKey(this,e);return!(!n||void 0===this[n]||t&&!Zi(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=ji(e)){const r=mi.findKey(n,e);!r||t&&!Zi(0,n[r],r,t)||(delete n[r],i=!0)}}return mi.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&&!Zi(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return mi.forEach(this,(i,r)=>{const s=mi.findKey(n,r);if(s)return t[s]=Ki(i),void delete t[r];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();a!==r&&delete t[r],t[a]=Ki(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return mi.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&mi.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[Ui]=this[Ui]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=ji(e);t[i]||(!function(e,t){const n=mi.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 mi.isArray(e)?e.forEach(i):i(e),this}};function Wi(e,t){const n=this||Li,i=t||n,r=zi.from(i.headers);let s=i.data;return mi.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function Gi(e){return!(!e||!e.__CANCEL__)}function Vi(e,t,n){yi.call(this,null==e?"canceled":e,yi.ERR_CANCELED,t,n),this.name="CanceledError"}function Qi(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new yi("Request failed with status code "+n.status,[yi.ERR_BAD_REQUEST,yi.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}zi.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),mi.reduceDescriptors(zi.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),mi.freezeMethods(zi),mi.inherits(Vi,yi,{__CANCEL__:!0});const Ji=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,a=0;return t=void 0!==t?t:1e3,function(o){const c=Date.now(),d=i[a];r||(r=c),n[s]=o,i[s]=c;let l=a,u=0;for(;l!==s;)u+=n[l++],l%=e;if(s=(s+1)%e,s===a&&(a=(a+1)%e),c-r<t)return;const 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 a=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),o=t-r;o>=s?a(e,t):(n=e,i||(i=setTimeout(()=>{i=null,a(n)},s-o)))},()=>n&&a(n)]}(n=>{const s=n.loaded,a=n.lengthComputable?n.total:void 0,o=s-i,c=r(o);i=s;e({loaded:s,total:a,progress:a?s/a:void 0,bytes:o,rate:c||void 0,estimated:c&&a&&s<=a?(a-s)/c:void 0,event:n,lengthComputable:null!=a,[t?"download":"upload"]:!0})},n)},Xi=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Yi=e=>(...t)=>mi.asap(()=>e(...t)),er=Fi.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Fi.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Fi.origin),Fi.navigator&&/(msie|trident)/i.test(Fi.navigator.userAgent)):()=>!0,tr=Fi.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const a=[e+"="+encodeURIComponent(t)];mi.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),mi.isString(i)&&a.push("path="+i),mi.isString(r)&&a.push("domain="+r),!0===s&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function nr(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 ir=e=>e instanceof zi?{...e}:e;function rr(e,t){t=t||{};const n={};function i(e,t,n,i){return mi.isPlainObject(e)&&mi.isPlainObject(t)?mi.merge.call({caseless:i},e,t):mi.isPlainObject(t)?mi.merge({},t):mi.isArray(t)?t.slice():t}function r(e,t,n,r){return mi.isUndefined(t)?mi.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!mi.isUndefined(t))return i(void 0,t)}function a(e,t){return mi.isUndefined(t)?mi.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function o(n,r,s){return s in t?i(n,r):s in e?i(void 0,n):void 0}const c={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t,n)=>r(ir(e),ir(t),0,!0)};return mi.forEach(Object.keys({...e,...t}),function(i){const s=c[i]||r,a=s(e[i],t[i],i);mi.isUndefined(a)&&s!==o||(n[i]=a)}),n}const sr=e=>{const t=rr({},e);let n,{data:i,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=zi.from(o),t.url=xi(nr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),mi.isFormData(i))if(Fi.hasStandardBrowserEnv||Fi.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(!1!==(n=o.getContentType())){const[e,...t]=n?n.split(";").map(e=>e.trim()).filter(Boolean):[];o.setContentType([e||"multipart/form-data",...t].join("; "))}if(Fi.hasStandardBrowserEnv&&(r&&mi.isFunction(r)&&(r=r(t)),r||!1!==r&&er(t.url))){const e=s&&a&&tr.read(a);e&&o.set(s,e)}return t},ar="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=sr(e);let r=i.data;const s=zi.from(i.headers).normalize();let a,o,c,d,l,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function f(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let g=new XMLHttpRequest;function m(){if(!g)return;const i=zi.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Qi(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 yi("Request aborted",yi.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new yi("Network Error",yi.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||Oi;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new yi(t,r.clarifyTimeoutError?yi.ETIMEDOUT:yi.ECONNABORTED,e,g)),g=null},void 0===r&&s.setContentType(null),"setRequestHeader"in g&&mi.forEach(s.toJSON(),function(e,t){g.setRequestHeader(t,e)}),mi.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),u&&"json"!==u&&(g.responseType=i.responseType),h&&([c,l]=Ji(h,!0),g.addEventListener("progress",c)),p&&g.upload&&([o,d]=Ji(p),g.upload.addEventListener("progress",o),g.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(a=t=>{g&&(n(!t||t.type?new Vi(null,e,g):t),g.abort(),g=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===Fi.protocols.indexOf(y)?n(new yi("Unsupported protocol "+y+":",yi.ERR_BAD_REQUEST,e)):g.send(r||null)})},or=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof yi?t:new Vi(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new yi(`timeout ${t} of ms exceeded`,yi.ETIMEDOUT))},t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:o}=i;return o.unsubscribe=()=>mi.asap(a),o}},cr=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},dr=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()}},lr=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of dr(e))yield*cr(n,t)}(e,t);let s,a=0,o=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return o(),void e.close();let s=i.byteLength;if(n){let e=a+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(t){throw o(t),t}},cancel:e=>(o(e),r.return())},{highWaterMark:2})},ur="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,pr=ur&&"function"==typeof ReadableStream,hr=ur&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),fr=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},gr=pr&&fr(()=>{let e=!1;const t=new Request(Fi.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),mr=pr&&fr(()=>mi.isReadableStream(new Response("").body)),yr={stream:mr&&(e=>e.body)};var br;ur&&(br=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!yr[e]&&(yr[e]=mi.isFunction(br[e])?t=>t[e]():(t,n)=>{throw new yi(`Response type '${e}' is not supported`,yi.ERR_NOT_SUPPORT,n)})}));const wr=async(e,t)=>{const n=mi.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(mi.isBlob(e))return e.size;if(mi.isSpecCompliantForm(e)){const t=new Request(Fi.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return mi.isArrayBufferView(e)||mi.isArrayBuffer(e)?e.byteLength:(mi.isURLSearchParams(e)&&(e+=""),mi.isString(e)?(await hr(e)).byteLength:void 0)})(t):n},vr={http:null,xhr:ar,fetch:ur&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:a,onDownloadProgress:o,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:p}=sr(e);d=d?(d+"").toLowerCase():"text";let h,f=or([r,s&&s.toAbortSignal()],a);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&gr&&"get"!==n&&"head"!==n&&0!==(m=await wr(l,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(mi.isFormData(i)&&(e=n.headers.get("content-type"))&&l.setContentType(e),n.body){const[e,t]=Xi(m,Ji(Yi(c)));i=lr(n.body,65536,e,t)}}mi.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 a=mr&&("stream"===d||"response"===d);if(mr&&(o||a&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=mi.toFiniteNumber(s.headers.get("content-length")),[n,i]=o&&Xi(t,Ji(Yi(o),!0))||[];s=new Response(lr(s.body,65536,n,()=>{i&&i(),g&&g()}),e)}d=d||"text";let y=await yr[mi.findKey(yr,d)||"text"](s,e);return!a&&g&&g(),await new Promise((t,n)=>{Qi(t,n,{data:y,headers:zi.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 yi("Network Error",yi.ERR_NETWORK,e,h),{cause:y.cause||y});throw yi.from(y,y&&y.code,e,h)}})};mi.forEach(vr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Ir=e=>`- ${e}`,Tr=e=>mi.isFunction(e)||null===e||!1===e,Ar=e=>{e=mi.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,!Tr(n)&&(i=vr[(t=String(n)).toLowerCase()],void 0===i))throw new yi(`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 yi("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Ir).join("\n"):" "+Ir(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function _r(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Vi(null,e)}function Cr(e){_r(e),e.headers=zi.from(e.headers),e.data=Wi.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Ar(e.adapter||Li.adapter)(e).then(function(t){return _r(e),t.data=Wi.call(e,e.transformResponse,t),t.headers=zi.from(t.headers),t},function(t){return Gi(t)||(_r(e),t&&t.response&&(t.response.data=Wi.call(e,e.transformResponse,t.response),t.response.headers=zi.from(t.response.headers))),Promise.reject(t)})}const Er="1.11.0",Sr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Sr[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Rr={};Sr.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Er+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new yi(i(r," has been removed"+(t?" in "+t:"")),yi.ERR_DEPRECATED);return t&&!Rr[r]&&(Rr[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)}},Sr.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const xr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new yi("options must be an object",yi.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],a=t[s];if(a){const t=e[s],n=void 0===t||a(t,s,e);if(!0!==n)throw new yi("option "+s+" must be "+n,yi.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new yi("Unknown option "+s,yi.ERR_BAD_OPTION)}},validators:Sr},kr=xr.validators;let Or=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ki,response:new ki}}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=rr(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&xr.assertOptions(n,{silentJSONParsing:kr.transitional(kr.boolean),forcedJSONParsing:kr.transitional(kr.boolean),clarifyTimeoutError:kr.transitional(kr.boolean)},!1),null!=i&&(mi.isFunction(i)?t.paramsSerializer={serialize:i}:xr.assertOptions(i,{encode:kr.function,serialize:kr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xr.assertOptions(t,{baseUrl:kr.spelling("baseURL"),withXsrfToken:kr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&mi.merge(r.common,r[t.method]);r&&mi.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=zi.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.unshift(e.fulfilled,e.rejected))});const c=[];let d;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let l,u=0;if(!o){const e=[Cr.bind(this),void 0];for(e.unshift(...a),e.push(...c),l=e.length,d=Promise.resolve(t);u<l;)d=d.then(e[u++],e[u++]);return d}l=a.length;let p=t;for(u=0;u<l;){const e=a[u++],t=a[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{d=Cr.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 xi(nr((e=rr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};mi.forEach(["delete","get","head","options"],function(e){Or.prototype[e]=function(t,n){return this.request(rr(n||{},{method:e,url:t,data:(n||{}).data}))}}),mi.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(rr(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}Or.prototype[e]=t(),Or.prototype[e+"Form"]=t(!0)});const Nr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Nr).forEach(([e,t])=>{Nr[t]=e});const Br=function e(t){const n=new Or(t),i=Rn(Or.prototype.request,n);return mi.extend(i,Or.prototype,n,{allOwnKeys:!0}),mi.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(rr(t,n))},i}(Li);Br.Axios=Or,Br.CanceledError=Vi,Br.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 Vi(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}}},Br.isCancel=Gi,Br.VERSION=Er,Br.toFormData=_i,Br.AxiosError=yi,Br.Cancel=Br.CanceledError,Br.all=function(e){return Promise.all(e)},Br.spread=function(e){return function(t){return e.apply(null,t)}},Br.isAxiosError=function(e){return mi.isObject(e)&&!0===e.isAxiosError},Br.mergeConfig=rr,Br.AxiosHeaders=zi,Br.formToJSON=e=>Di(mi.isHTMLForm(e)?new FormData(e):e),Br.getAdapter=Ar,Br.HttpStatusCode=Nr,Br.default=Br;const{Axios:$r,AxiosError:Pr,CanceledError:Mr,isCancel:qr,CancelToken:Fr,VERSION:Dr,all:Lr,Cancel:Hr,isAxiosError:Ur,spread:jr,toFormData:Kr,AxiosHeaders:Zr,HttpStatusCode:zr,formToJSON:Wr,getAdapter:Gr,mergeConfig:Vr}=Br,Qr="ConnectionsManager not initialized";class Jr extends s.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(),a=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=(()=>{try{if("function"==typeof r.Logger)return new r.Logger({module:"HCS10Builder",level:n?.logLevel||"info"})}catch{}return{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{},trace:()=>{},setLogLevel:()=>{},getLevel:()=>"info",setSilent:()=>{},setModule:()=>{}}})(),this.standardClient=new r.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:a,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getStateManager(){return this.stateManager}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){const n=Sn.startHCSDelegate,i=Sn.walletExecutor,r=Sn.preferWalletOnly,s=this.network;try{const{ByteBuildRegistry:n}=await Promise.resolve().then(()=>ys);if(i&&n.has("submitConnectionRequest")){const r=await n.build("submitConnectionRequest",this.hederaKit,{inboundTopicId:e,memo:t});if(r&&r.transactionBytes){const{transactionId:e}=await i(r.transactionBytes,s);return{transactionId:e}}}}catch{}if(n&&i)try{const r={inboundTopicId:e,memo:t},{transactionBytes:a}=await n("submitConnectionRequest",r,s),{transactionId:o}=await i(a,s);return{transactionId:o}}catch(a){if(r){const e=new Error(`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`);throw e.code="wallet_submit_failed",e}}else if(r){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,n,i){try{const s=Sn.startHCSDelegate,a=Sn.walletExecutor,o=Sn.preferWalletOnly,c=this.network;if(s&&a)try{const r={inboundTopicId:e,requestingAccountId:t,connectionRequestId:n,feeConfig:i?"configured":void 0},{transactionBytes:o}=await s("handleConnectionRequest",r,c),{transactionId:d}=await a(o,c);return{success:!0,transactionId:d}}catch(r){if(o){const e=new Error(`wallet_submit_failed: ${r instanceof Error?r.message:String(r)}`);throw e.code="wallet_submit_failed",e}}else if(o){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const d=await this.standardClient.handleConnectionRequest(e,t,n,i);return d&&d.connectionTopicId&&"object"==typeof d.connectionTopicId&&"toString"in d.connectionTopicId&&(d.connectionTopicId=d.connectionTopicId.toString()),d}catch(s){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,s),new Error(`Failed to handle connection request: ${s instanceof Error?s.message:String(s)}`)}}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{let r=0;try{r=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const s=Sn.startHCSDelegate,a=Sn.walletExecutor,o=Sn.preferWalletOnly,c=this.network;try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(a&&i.has("sendMessage")){const s=await i.build("sendMessage",this.hederaKit,{topicId:e,data:t,memo:n});if(s&&s.transactionBytes){const{transactionId:t}=await a(s.transactionBytes,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:t},transactionId:t}}}}catch{}if(s&&a)try{const i={topicId:e,data:t,memo:n},{transactionBytes:o}=await s("sendMessage",i,c),{transactionId:d}=await a(o,c);return{sequenceNumber:await this.pollForNewSequence(e,r),receipt:{transactionId:d},transactionId:d}}catch(i){if(o){const e=new Error(`wallet_submit_failed: ${i instanceof Error?i.message:String(i)}`);throw e.code="wallet_submit_failed",e}}else if(o){const e=new Error("wallet_unavailable: connect a wallet or configure StartHCSDelegate and WalletExecutor");throw e.code="wallet_unavailable",e}const d=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:d.topicSequenceNumber?.toNumber(),receipt:d,transactionId:"transactionId"in d?d.transactionId?.toString():void 0}}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const t=await Br.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(!a.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=a.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 Br.get(e.url,{responseType:"arraybuffer"}),i=n.Buffer.from(t.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!a.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=a.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 pollForNewSequence(e,t){for(let n=0;n<10;n++){try{const n=(await this.getMessages(e)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),t);if(n>t)return n}catch{}await new Promise(e=>setTimeout(e,1e3))}}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 n=null;e.profilePicture&&(n=await this.loadProfilePicture(e.profilePicture));const i={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!==n?.buffer&&{pfpBuffer:n.buffer},...void 0!==n?.filename&&{pfpFileName:n.filename}};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 s=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];i.feeConfig=t.addHbarFee(e.hbarFee,n,s)}const s=Sn.preferWalletOnly,a=Sn.getBrowserHCSClient(this.network);if(a)try{const e=(new r.AgentBuilder).setNetwork(this.network).setName(i.name).setAlias(i.alias||`${i.name}-${Date.now()}`).setBio(i.bio||"").setType(i.type||"autonomous").setModel(i.model||"agent-model-2024");i.capabilities?.length&&e.setCapabilities(i.capabilities),i.creator&&e.setCreator(i.creator),i.existingProfilePictureTopicId&&e.setExistingProfilePicture(i.existingProfilePictureTopicId),i.socials&&Object.entries(i.socials).forEach(([t,n])=>{n&&"string"==typeof n&&e.addSocial(t,n)}),i.properties&&Object.entries(i.properties).forEach(([t,n])=>{null!=n&&e.addProperty(t,n)});const t=await a.create(e,{progressCallback:e=>{},updateAccountMemo:!0});return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{result:t,name:i.name}},this}catch(t){if(s)throw new Error(`wallet_registration_failed: ${t instanceof Error?t.message:String(t)}`)}else if(s)throw new Error("wallet_unavailable: BrowserHCSClient factory not provided");const o=await this.createAndRegisterAgent(i);this.executeResult={success:!0,transactionId:o.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...o,name:e.name,accountId:o?.metadata?.accountId||o.state?.agentMetadata?.accountId}}}catch(n){throw this.logger.error("Failed to register agent:",n),n}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 i=this.stateManager?.getCurrentAgent();if(!i)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const s=this.stateManager?.getConnectionsManager();if(!s)throw new Error(Qr);await s.fetchConnectionData(i.accountId);const a=[...s.getPendingRequests(),...s.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!a)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!a.needsConfirmation||!a.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const o=a.targetAccountId,c=a.inboundRequestId;let d;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"))||[];d=t.addHbarFee(e.hbarFee,n,i)}const l=await this.getInboundTopicId(),u=await this.handleConnectionRequest(l,o,c,d);let p=u?.connectionTopicId;if(p&&"object"==typeof p&&"toString"in p&&(p=p?.toString()),!p||"string"!=typeof p)try{const e=(await(this.stateManager?.getConnectionsManager()?.fetchConnectionData(i.accountId))||[]).find(e=>e.targetAccountId===o&&"established"===e.status);e?.connectionTopicId&&(p=e.connectionTopicId)}catch(t){this.logger.debug("Could not refresh connections after acceptance to derive topic id:",t)}if(!p||"string"!=typeof p)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(p)}`);if(this.stateManager){const e=a.targetAgentName||`Agent ${o}`;a.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${o}'.`);let t=a.targetInboundTopicId||"";if(!t)try{const e=await this.getAgentProfile(o);e.success&&e.topicInfo?.inboundTopic&&(t=e.topicInfo.inboundTopic)}catch(n){this.logger.warn(`Could not fetch profile for ${o}:`,n)}const i={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:t,connectionTopicId:p,status:"established",created:new Date};this.stateManager.addActiveConnection(i),s.markConnectionRequestProcessed(a.targetInboundTopicId||"",c)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId:p,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:u}}}catch(i){throw this.logger.error("Failed to accept connection:",i),i}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let n;const i=e.targetIdentifier;if(i.includes("@")){const e=i.split("@");if(2===e.length){const t=e[1];n=this.stateManager.getConnectionByIdentifier(t),n||this.addNote(`Could not find connection using request key '${i}', extracted account ID '${t}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(i)),!n&&!i.startsWith("0.0.")&&/^\d+$/.test(i)){const e=`0.0.${i}`;n=this.stateManager.getConnectionByIdentifier(e),n&&this.addNote(`Found connection using account ID with prefix: ${e}`)}if(!n&&/^[1-9]\d*$/.test(i)){const e=this.stateManager.listConnections(),t=parseInt(i)-1;t>=0&&t<e.length&&(n=e[t],n&&this.addNote(`Found connection by index ${i}: ${n.targetAccountId}`))}if(!n){const e=this.stateManager.listConnections().map((e,t)=>`${t+1}. ${e.targetAccountId} (Topic: ${e.connectionTopicId})`);let t=`Connection not found for identifier: "${i}"\n`;throw t+=`Available connections:\n${e.join("\n")||"No active connections"}`,t+="\n\nYou can use:\n",t+='- Connection number (e.g., "1", "2")\n',t+='- Account ID (e.g., "0.0.6412936")\n',t+="- Connection topic ID\n",t+="Use 'list_connections' to see all active connections.",new Error(t)}let r=n.connectionTopicId;if(r&&"object"==typeof r&&"toString"in r&&(r=r?.toString()),!r||"string"!=typeof r)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(r)} (type: ${typeof r})`);const s=n.targetAgentName,a=`${t.inboundTopicId}@${t.accountId}`;let o=0;try{o=(await this.getMessages(r)).messages.reduce((e,t)=>Math.max(e,t.sequence_number||0),0)}catch{}const c=await this.sendMessage(r,e.message,`Agent message from ${t.name}`),d=c.sequenceNumber??o;if(0===d)throw new Error("Failed to send message");let l=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):l=await this.monitorResponses(r,a,d),this.executeResult={success:!0,transactionId:c.transactionId,receipt:c.receipt,scheduleId:void 0,rawResult:{targetAgentName:s,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:c.sequenceNumber,reply:l,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:c}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let i=0;for(;i<30;){try{const i=await this.getMessageStream(e);for(const e of i.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(r){this.logger.error(`Error monitoring responses: ${r}`)}await new Promise(e=>setTimeout(e,4e3)),i++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:t=!1,targetAccountId:n,monitorDurationSeconds:i=120,hbarFees:s=[],tokenFees:a=[],exemptAccountIds:o=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const d=await this.getInboundTopicId(),l=Date.now()+1e3*i;let u=0,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||a.length>0){const e=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,o)}for(const t of a){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,o)}t=e}await this.handleConnectionRequest(d,l,e,t),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(Qr);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const i=t.getPendingRequests(),r=t.getConnectionsNeedingConfirmation(),s=[...i,...r];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:s.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const n=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,n=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const i=e.filter(e=>"established"===e.status),r=e.filter(e=>e.isPending),s=e.filter(e=>e.needsConfirmation);let a="";i.length>0&&(a+=`🟢 Active Connections (${i.length}):\n`,i.forEach((e,n)=>{a+=this.formatConnection(e,n,t)}),a+="\n"),n&&s.length>0&&(a+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach((e,n)=>{a+=this.formatConnection(e,n,t)}),a+="\n"),n&&r.length>0&&(a+=`⚪ Pending Connection Requests (${r.length}):\n`,r.forEach((e,n)=>{a+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:a.trim(),activeCount:i.length,pendingCount:r.length,needsConfirmationCount:s.length}}}catch(i){this.logger.error("Failed to list connections:",i),this.executeResult={success:!1,error:`Failed to list connections: ${i instanceof Error?i.message:String(i)}`}}return this}formatConnection(e,t,n){const i=e;let r=`${t+1}. ${i.profileInfo?.display_name||i.targetAgentName||"Unknown Agent"} (${i.targetAccountId})\n`;r+=` Topic: ${i.isPending?"(Pending Request)":i.connectionTopicId}\n`;if(r+=` Status: ${i.status||"unknown"}\n`,n){if(i.profileInfo?.bio&&(r+=` Bio: ${i.profileInfo.bio.substring(0,100)}${i.profileInfo.bio.length>100?"...":""}\n`),i.created){r+=` ${i.isPending?"Request sent":"Connection established"}: ${i.created.toLocaleString()}\n`}i.lastActivity&&(r+=` Last activity: ${i.lastActivity.toLocaleString()}\n`)}return r}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(Qr),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const i of n)this.stateManager.addActiveConnection(i);return n}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const i=t.targetAgentName,r=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${i} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${r})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let a=[],o=r;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;a=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${r}`),a=t.filter(e=>1e6*e.timestamp>r),a.length>0&&(o=a.reduce((e,t)=>Math.max(e,1e6*t.timestamp),r));if(0===a.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${i} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${a.length} message(s).`);let d=c?`Latest message(s) from ${i}:\n`:`New messages from ${i}:\n`;const l=[];for(const e of a){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}d+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,l.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(s){const t=`Error processing message (Seq: ${e.sequence_number}): ${s instanceof Error?s.message:String(s)}`;this.logger.error(t),d+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&o>r&&(this.logger.debug(`Updating timestamp for topic ${n} to ${o}`),this.stateManager.updateTimestamp(n,o)),this.executeResult={success:!0,rawResult:{messages:l,formattedOutput:d.trim(),targetAgentName:i,connectionTopicId:n}}}catch(s){this.logger.error(`Failed to check messages for topic ${n}: ${s}`),this.executeResult={success:!1,error:`Error checking messages for ${i}: ${s instanceof Error?s.message:String(s)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const i=n.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${i}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const n=t.profile,i=t.topicInfo;let r=`Profile for ${e.accountId}:\n`;r+=`Name: ${n.name||"Unknown"}\n`,r+=`Bio: ${n.bio||"No bio provided"}\n`,r+=`Type: ${n.type||"Unknown"}\n`,r+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?r+=`Capabilities: ${n.capabilities.join(", ")}\n`:r+="Capabilities: None listed\n",i&&(r+=`Inbound Topic: ${i.inboundTopic||"Unknown"}\n`,r+=`Outbound Topic: ${i.outboundTopic||"Unknown"}\n`,r+=`Profile Topic: ${i.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(r+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(r+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:r,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class Xr extends s.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 s.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}function Yr(e){const t={},n={},i=[],r={};return es(e,"",t,n,i,r),{fields:t,groups:is(n),order:rs(i,t),metadata:r}}function es(e,t,n,i,r,s){const a=gn(e),o=a._def?.typeName;"ZodObject"===o?function(e,t,n,i,r,s){const a=e.shape;if(ln(e)){const s=un(e);s&&t&&(n[t]=s,ts(i,s.ui?.group||"default",t),ns(r,t,s.ui?.order))}for(const[o,c]of Object.entries(a)){es(c,t?`${t}.${o}`:o,n,i,r,s)}}(a,t,n,i,r,s):"ZodArray"===o?function(e,t,n,i,r,s){if(ln(e)){const a=un(e);a&&(n[t]=a,ts(i,a.ui?.group||"default",t),ns(r,t,a.ui?.order),s[t]=bn(e))}const a=e._def.type;if(a){es(a,`${t}[]`,n,i,r,s)}}(a,t,n,i,r,s):function(e,t,n,i,r,s){if(ln(e)){const s=un(e);s&&(n[t]=s,ts(i,s.ui?.group||"default",t),ns(r,t,s.ui?.order))}s[t]=bn(e)}(e,t,n,i,r,s)}function ts(e,t,n){e[t]||(e[t]=[]),e[t].push(n)}function ns(e,t,n){void 0!==n?e.splice(n,0,t):e.push(t)}function is(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 rs(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 a=n[e]||1e3,o=n[i]||1e3;return a!==o?a-o:e.localeCompare(i)})}class ss extends Error{constructor(e,t){super(t),this.code=e,Object.setPrototypeOf(this,ss.prototype)}}class as extends s.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().toString():"",n=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";let i;try{const t=new r.HederaMirrorNode(n),s=await t.requestAccount(e),a=s?.key?._type;if(a){const e=a.toUpperCase();e.includes("ED25519")?i="ed25519":e.includes("ECDSA")&&(i="ecdsa")}}catch{}const s={network:n,operatorId:e,operatorKey:t,...i?{keyType:i}:{}};this.hcs2Client=new r.HCS2Client(s)}return this.hcs2Client}async createRegistry(e={}){const t=Sn.walletExecutor,n=Sn.preferWalletOnly,i=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());if(t){const t=Sn.startHCSDelegate;if(t)try{const n={options:e},i=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:r}=await t("hcs2.createRegistry",n,i);if(r)return{success:!0,transactionBytes:r}}catch(s){if(n)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${s instanceof Error?s.message:String(s)}`)}if(n)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.createRegistry")}if(!i)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const r=await this.getHCS2Client();return await r.createRegistry(e)}async registerEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.registerEntry")){const r=await i.build("hcs2.registerEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={registryTopicId:e,options:t},{transactionBytes:o}=await a("hcs2.registerEntry",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.registerEntry");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.registerEntry(e,t)}async updateEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.updateEntry")){const r=await i.build("hcs2.updateEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={registryTopicId:e,options:t},{transactionBytes:o}=await a("hcs2.updateEntry",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.updateEntry");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.updateEntry(e,t)}async deleteEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.deleteEntry")){const r=await i.build("hcs2.deleteEntry",this.hederaKit,{registryTopicId:e,options:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={registryTopicId:e,options:t},{transactionBytes:o}=await a("hcs2.deleteEntry",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.deleteEntry");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.deleteEntry(e,t)}async migrateRegistry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.migrateRegistry")){const s=await i.build("hcs2.migrateRegistry",this.hederaKit,{registryTopicId:e,options:t});if(s&&s.transactionBytes){if(n)return{success:!0,transactionBytes:s.transactionBytes};if(!r)return{success:!0,transactionBytes:s.transactionBytes}}}}catch{}const s=Sn.startHCSDelegate;if(s)try{const i={registryTopicId:e,options:t},a=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",{transactionBytes:o}=await s("hcs2.migrateRegistry",i,a);if(o){if(n)return{success:!0,transactionBytes:o};if(!r)return{success:!0,transactionBytes:o}}}catch(o){if(i){const e=`wallet_submit_failed: ${o instanceof Error?o.message:String(o)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.migrateRegistry");if(!r)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const a=await this.getHCS2Client();return await a.migrateRegistry(e,t)}async getRegistry(e,t={}){const n=await this.getHCS2Client();return await n.getRegistry(e,t)}async submitMessage(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",s=!(!this.hederaKit?.signer?.getOperatorPrivateKey||!this.hederaKit.signer.getOperatorPrivateKey());try{const{ByteBuildRegistry:i}=await Promise.resolve().then(()=>ys);if(i.has("hcs2.submitMessage")){const r=await i.build("hcs2.submitMessage",this.hederaKit,{topicId:e,payload:t});if(r&&r.transactionBytes){if(n)return{success:!0,transactionBytes:r.transactionBytes};if(!s)return{success:!0,transactionBytes:r.transactionBytes}}}}catch{}const a=Sn.startHCSDelegate;if(a)try{const i={topicId:e,payload:t},{transactionBytes:o}=await a("hcs2.submitMessage",i,r);if(o){if(n)return{success:!0,transactionBytes:o};if(!s)return{success:!0,transactionBytes:o}}}catch(c){if(i){const e=`wallet_submit_failed: ${c instanceof Error?c.message:String(c)}`;throw new ss("wallet_submit_failed",e)}}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs2.submitMessage");if(!s)throw new ss("wallet_unavailable","No wallet executor and no operator private key available for server execution");const o=await this.getHCS2Client();return await o.submitMessage(e,t),{success:!0}}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 os extends s.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=Sn.walletExecutor,n=Sn.preferWalletOnly,i=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(t){const t=Sn.startHCSDelegate;if(t)try{const n={options:e},{transactionBytes:r}=await t("hcs6.createRegistry",n,i);if(r)return{success:!0,transactionBytes:r}}catch(a){if(n)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`)}if(n)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs6.createRegistry")}const r=await this.getHCS6Client(),s={...e};return"adminKey"in s&&delete s.adminKey,await r.createRegistry(s)}async registerEntry(e,t){const n=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(n){const n=Sn.startHCSDelegate;if(n)try{const i={registryTopicId:e,options:t},{transactionBytes:s}=await n("hcs6.registerEntry",i,r);if(s)return{success:!0,transactionBytes:s}}catch(a){if(i)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`)}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs6.registerEntry")}const s=await this.getHCS6Client();return await s.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=Sn.walletExecutor,i=Sn.preferWalletOnly,r=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet";if(n){const n=Sn.startHCSDelegate;if(n)try{const i={topicId:e,payload:t},{transactionBytes:s}=await n("hcs6.submitMessage",i,r);if(s)return{success:!0,transactionBytes:s}}catch(a){if(i)throw new ss("wallet_submit_failed",`wallet_submit_failed: ${a instanceof Error?a.message:String(a)}`)}if(i)throw new ss("wallet_unavailable","WalletExecutor not configured for hcs6.submitMessage")}const s=await this.getHCS6Client();return await s.submitMessage(e,t)}async getTopicInfo(e){const t=this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",n=new r.HederaMirrorNode(t);return await n.getTopicInfo(e)}async close(){this.hcs6Client&&(this.hcs6Client.close(),this.hcs6Client=void 0)}}const cs=class e extends s.BaseServiceBuilder{constructor(e){super(e)}getOperationalMode(){return this.hederaKit.operationalMode}static setSignerProvider(t){e.signerProvider=t}static setWalletInfoResolver(t){e.walletInfoResolver=t}static setStartInscriptionDelegate(t){e.startInscriptionDelegate=t}static setWalletExecutor(t){e.walletExecutor=t}static setPreferWalletOnly(t){e.preferWalletOnly=!!t}async getSigner(){const t=e.signerProvider;if(!t)return null;try{const e=t();return e&&"function"==typeof e.then?await e:e}catch{return null}}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 inscribeAuto(t,i){const s=await this.getSigner();if(s)return this.inscribeWithSigner(t,s,i);const a=e.walletInfoResolver?await e.walletInfoResolver():null;if(e.preferWalletOnly&&!a){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}if(a&&e.startInscriptionDelegate&&e.walletExecutor){const s=a.accountId,o=a.network,c=i,d={holderId:s,metadata:c.metadata||{},tags:i.tags||[],mode:i.mode||"file"};void 0!==c.fileStandard&&(d.fileStandard=c.fileStandard),void 0!==c.chunkSize&&(d.chunkSize=c.chunkSize);let l={...d};switch(t.type){case"url":l={...d,file:{type:"url",url:t.url}};break;case"file":l={...d,file:{type:"path",path:t.path}};break;case"buffer":l={...d,file:{type:"base64",base64:n.Buffer.from(t.buffer).toString("base64"),fileName:t.fileName,mimeType:t.mimeType}}}"hashinal"===i.mode&&(l.metadataObject=c.metadata,l.creator=c.metadata?.creator||s,l.description=c.metadata?.description,"string"==typeof c.jsonFileURL&&c.jsonFileURL.length>0&&(l.jsonFileURL=c.jsonFileURL));const u=await e.startInscriptionDelegate(l,o),p=u;if(Boolean(p?.inscription)&&p?.confirmed){const e=u;return this.logger.info("inscription already completed, short circuiting",u),{quote:!1,confirmed:!0===e.confirmed,result:e.result,inscription:e.inscription}}const h=u;if(!h||!h.transactionBytes)throw new Error("Failed to start inscription (no transaction bytes)");const f=await e.walletExecutor(h.transactionBytes,o),g=f?.transactionId||"";if(!i.quoteOnly&&(i.waitForConfirmation??!0)){this.logger.debug("Will be retrieving inscription");const e=i.waitMaxAttempts??60,t=i.waitIntervalMs??5e3;for(let n=0;n<e;n++){try{const e=await this.retrieveInscription(g,i),t=r.getTopicId(e)??h.topic_id,n=e.status;if("completed"===n||!!t){const n={quote:!1,confirmed:!0,result:{jobId:h.tx_id||"",transactionId:g,topicId:t},inscription:e};return this.logger.debug("retrieved inscription",n,e),n}}catch{}await new Promise(e=>setTimeout(e,t))}}return{quote:!1,confirmed:!1,result:{jobId:h.tx_id||"",transactionId:g,status:h.status,completed:h.completed},inscription:h.topic_id?{topic_id:h.topic_id}:void 0}}if(e.preferWalletOnly){const e=new Error("Wallet unavailable: connect a wallet or switch to autonomous mode");throw e.code="wallet_unavailable",e}return this.inscribe(t,i)}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}};cs.preferWalletOnly=!1;let ds=cs;const ls=new class{constructor(){this.handlers=new Map}register(e,t){this.handlers.set(e,t)}has(e){return this.handlers.has(e)}async build(e,t,n){const i=this.handlers.get(e);return i?await i({hederaKit:t,request:n}):null}};async function us(e,t){const r="mainnet"===(e.client.network.toString().includes("mainnet")?"mainnet":"testnet")?i.Client.forMainnet():i.Client.forTestnet(),s=e.signer.getAccountId().toString(),a=i.AccountId.fromString(s);if("function"==typeof t.setTransactionId&&t.setTransactionId(i.TransactionId.generate(a)),"function"==typeof t.setAutoRenewAccountId)try{t.setAutoRenewAccountId(s)}catch{}const o=await t.freezeWith(r);return{transactionBytes:n.Buffer.from(o.toBytes()).toString("base64")}}async function ps(e,t,r,s){const a="mainnet"===(e.client.network.toString().includes("mainnet")?"mainnet":"testnet")?i.Client.forMainnet():i.Client.forTestnet(),o=e.signer.getAccountId().toString(),c=i.AccountId.fromString(o),d=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(t)).setTransactionId(i.TransactionId.generate(c)).setMessage(r),l=await d.freezeWith(a);return{transactionBytes:n.Buffer.from(l.toBytes()).toString("base64")}}function hs(e){return"object"==typeof e&&null!==e}function fs(e,t){const n=e[t];return"string"==typeof n?n:void 0}function gs(e,t){const n=e[t];return"number"==typeof n&&Number.isFinite(n)?n:void 0}function ms(e,t){const n=e[t];return hs(n)?n:void 0}ls.register("hcs2.createRegistry",async({hederaKit:e,request:t})=>{const n=t?.options||{};let i;try{const t=e?.signer?.getOperatorPrivateKey?.();i=t?.publicKey}catch{}const s=r.buildHcs2CreateRegistryTx({registryType:n.registryType??r.HCS2RegistryType.INDEXED,ttl:n.ttl??86400,adminKey:n.adminKey,submitKey:n.submitKey,operatorPublicKey:i});return await us(e,s)}),ls.register("hcs2.migrateRegistry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.migrateRegistry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.migrateRegistry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"metadata"),o=fs(i,"memo"),c=r.buildHcs2MigrateTx({registryTopicId:n,targetTopicId:s,metadata:a,memo:o});return await us(e,c)}),ls.register("hcs2.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.submitMessage: invalid request payload");const n=fs(t,"topicId")||fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.submitMessage: topicId is required");const i=t.payload,r="string"==typeof i?i:JSON.stringify(i??{});return await ps(e,n,r)}),ls.register("hcs2.registerEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.registerEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.registerEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"metadata"),o=fs(i,"memo"),c=r.buildHcs2RegisterTx({registryTopicId:n,targetTopicId:s,metadata:a,memo:o});return await us(e,c)}),ls.register("hcs2.updateEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.updateEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.updateEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"uid")||"",o=fs(i,"metadata"),c=fs(i,"memo"),d=r.buildHcs2UpdateTx({registryTopicId:n,uid:a,targetTopicId:s,metadata:o,memo:c});return await us(e,d)}),ls.register("hcs2.deleteEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs2.deleteEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs2.deleteEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"uid")||"",a=fs(i,"memo"),o=r.buildHcs2DeleteTx({registryTopicId:n,uid:s,memo:a});return await us(e,o)}),ls.register("hcs6.createRegistry",async({hederaKit:e,request:t})=>{const n=hs(t)?ms(t,"options"):void 0,i=n?gs(n,"ttl"):void 0;let s;try{const t=e?.signer?.getOperatorPrivateKey?.();s=t?.publicKey}catch{}const a=r.buildHcs6CreateRegistryTx({ttl:i??86400,operatorPublicKey:s});return await us(e,a)}),ls.register("hcs6.registerEntry",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs6.registerEntry: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs6.registerEntry: registryTopicId is required");const i=ms(t,"options")||{},s=fs(i,"targetTopicId")||"",a=fs(i,"memo"),o=r.buildHcs6RegisterEntryTx({registryTopicId:n,targetTopicId:s,memo:a});return await us(e,o)}),ls.register("hcs6.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs6.submitMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs6.submitMessage: topicId is required");const i=t.payload,r="string"==typeof i?i:JSON.stringify(i??{});return await ps(e,n,r)}),ls.register("sendMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("sendMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("sendMessage: topicId is required");const i=t.data,s=fs(t,"memo")||"",a=e.signer.getAccountId().toString(),o="string"==typeof i?i:JSON.stringify(i??{}),c=r.buildHcs10SendMessageTx({connectionTopicId:n,operatorId:a,data:o,memo:s});return await us(e,c)}),ls.register("submitConnectionRequest",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("submitConnectionRequest: invalid request payload");const n=fs(t,"inboundTopicId")||"";if(!n)throw new Error("submitConnectionRequest: inboundTopicId is required");const i=fs(t,"memo")||"",s=e.signer.getAccountId().toString(),a=r.buildHcs10SubmitConnectionRequestTx({inboundTopicId:n,operatorId:s,memo:i});return await us(e,a)}),ls.register("hcs20.deploy",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.deploy: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.deploy: topicId is required");const i=fs(t,"name")||"",s=fs(t,"tick")||"",a=fs(t,"max")||"",o=fs(t,"lim"),c=fs(t,"metadata"),d=fs(t,"memo"),l=r.buildHcs20DeployTx({topicId:n,name:i,tick:s,max:a,lim:o,metadata:c,memo:d});return await us(e,l)}),ls.register("hcs20.mint",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.mint: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.mint: topicId is required");const i=fs(t,"tick")||"",s=fs(t,"amt")||"",a=fs(t,"to")||"",o=fs(t,"memo"),c=r.buildHcs20MintTx({topicId:n,tick:i,amt:s,to:a,memo:o});return await us(e,c)}),ls.register("hcs20.transfer",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.transfer: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.transfer: topicId is required");const i=fs(t,"tick")||"",s=fs(t,"amt")||"",a=fs(t,"from")||"",o=fs(t,"to")||"",c=fs(t,"memo"),d=r.buildHcs20TransferTx({topicId:n,tick:i,amt:s,from:a,to:o,memo:c});return await us(e,d)}),ls.register("hcs20.burn",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.burn: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs20.burn: topicId is required");const i=fs(t,"tick")||"",s=fs(t,"amt")||"",a=fs(t,"from")||"",o=fs(t,"memo"),c=r.buildHcs20BurnTx({topicId:n,tick:i,amt:s,from:a,memo:o});return await us(e,c)}),ls.register("hcs20.register",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs20.register: invalid request payload");const n=fs(t,"registryTopicId")||"";if(!n)throw new Error("hcs20.register: registryTopicId is required");const i=fs(t,"topicId")||"",s=fs(t,"name")||"",a=t.isPrivate,o="boolean"==typeof a&&a,c=fs(t,"metadata"),d=fs(t,"memo"),l=r.buildHcs20RegisterTx({registryTopicId:n,name:s,topicId:i,isPrivate:o,metadata:c,memo:d});return await us(e,l)}),ls.register("hcs12.createRegistry",async({hederaKit:e,request:t})=>{const n=hs(t)?ms(t,"options"):void 0,i=(n?gs(n,"ttl"):void 0)??60,s=n&&fs(n,"registry")||"hashlinks";let a;try{const t=e?.signer?.getOperatorPrivateKey?.();a=t?.publicKey}catch{}const o=r.buildHcs12CreateRegistryTopicTx({registry:s,ttl:i,operatorPublicKey:a});return await us(e,o)}),ls.register("hcs12.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.submitMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs12.submitMessage: topicId is required");const i=t.payload,s=r.buildHcs12SubmitMessageTx({topicId:n,payload:i});return await us(e,s)}),ls.register("hcs12.registerAssembly",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.registerAssembly: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.registerAssembly: assemblyTopicId is required");const i=ms(t,"registration")||{},s=r.buildHcs12RegisterAssemblyTx({assemblyTopicId:n,registration:i});return await us(e,s)}),ls.register("hcs12.addBlock",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.addBlock: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addBlock: assemblyTopicId is required");const i=ms(t,"operation")||{},s=r.buildHcs12AddBlockToAssemblyTx({assemblyTopicId:n,operation:i});return await us(e,s)}),ls.register("hcs12.addAction",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.addAction: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.addAction: assemblyTopicId is required");const i=ms(t,"operation")||{},s=r.buildHcs12AddActionToAssemblyTx({assemblyTopicId:n,operation:i});return await us(e,s)}),ls.register("hcs12.updateAssembly",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs12.updateAssembly: invalid request payload");const n=fs(t,"assemblyTopicId")||"";if(!n)throw new Error("hcs12.updateAssembly: assemblyTopicId is required");const i=ms(t,"operation")||{},s=r.buildHcs12UpdateAssemblyTx({assemblyTopicId:n,operation:i});return await us(e,s)}),ls.register("hcs7.submitMessage",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs7.submitMessage: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs7.submitMessage: topicId is required");const i=ms(t,"message")||{},s=r.buildHcs7SubmitMessageTx({topicId:n,message:i});return await us(e,s)}),ls.register("hcs7.evm",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs7.evm: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs7.evm: topicId is required");const i=ms(t,"config")||{},s=r.buildHcs7EvmMessageTx({topicId:n,config:i});return await us(e,s)}),ls.register("hcs7.wasm",async({hederaKit:e,request:t})=>{if(!hs(t))throw new Error("hcs7.wasm: invalid request payload");const n=fs(t,"topicId")||"";if(!n)throw new Error("hcs7.wasm: topicId is required");const i=ms(t,"config")||{},s=r.buildHcs7WasmMessageTx({topicId:n,config:i});return await us(e,s)});const ys=Object.freeze(Object.defineProperty({__proto__:null,ByteBuildRegistry:ls},Symbol.toStringTag,{value:"Module"}));Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>s.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>s.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>s.PluginRegistry}),e.AcceptConnectionRequestTool=Ct,e.BaseHCS10QueryTool=g,e.BaseHCS10TransactionTool=f,e.BaseHCS2QueryTool=Ot,e.BaseHCS2TransactionTool=kt,e.BaseHCS6QueryTool=Lt,e.BaseHCS6TransactionTool=Dt,e.BaseInscriberQueryTool=zt,e.BaseInscriberTransactionTool=Zt,e.ByteBuildRegistry=ls,e.CheckMessagesTool=yt,e.ConnectionMonitorTool=It,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 Ht}async executeQuery(e,t){const n=await this.hcs6Builder.createRegistry({ttl:e.ttl,submitKey:e.submitKey});if(!("success"in n)||!n.success)throw new Error(n.error||"Failed to create dynamic registry");if(Nt(n)){const t=n.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-6 dynamic registry. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Create HCS-6 dynamic registry (TTL: ${e.ttl}s)`}}}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 Ot{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create an HCS-2 registry (standard HCS-2). Use when the user asks to create an HCS-2 registry, not a generic HCS topic. Builds a standards-compliant registry topic and returns the result or transaction bytes."}get specificInputSchema(){return Bt}async executeQuery(e,t){const n=e=>{if("string"==typeof e){const t=e.trim().toLowerCase();return"true"===t||"false"!==t&&e}return e};try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:n(e.adminKey),submitKey:n(e.submitKey)});if(!t.success)throw new Error(t.error||"Failed to create registry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to create your HCS-2 registry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Create HCS-2 registry (${1===e.registryType?"Non-Indexed":"Indexed"}; TTL: ${e.ttl||86400}s)`}}}return`Successfully created HCS-2 registry!\n\nTopic ID: ${t?.topicId||"unknown"}\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(i){const e=i instanceof Error?i.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},e.DeleteEntryTool=class extends Ot{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return Mt}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to delete entry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to delete the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Delete HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid})`}}}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=wt,e.HCS10Builder=Jr,e.HCS10Client=class{constructor(e,n,i,s){this.standardClient=new r.HCS10Client({network:i,operatorId:e,operatorPrivateKey:n,guardedRegistryBaseUrl:s?.registryUrl,logLevel:s?.logLevel}),this.guardedRegistryBaseUrl=s?.registryUrl||"",this.useEncryption=s?.useEncryption||!1;const a="true"===t.env.DISABLE_LOGGING;this.logger=new r.Logger({level:s?.logLevel||"info",silent:a})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,i){try{return await this.standardClient.handleConnectionRequest(e,t,n,i)}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,i=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,i)}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),i=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return i?.metadata?.inboundTopicId&&i?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:i.metadata.inboundTopicId,outboundTopicId:i.metadata.outboundTopicId}),i}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,n,i){this.useEncryption;try{const r=await this.standardClient.sendMessage(e,t,n,i);return r.topicSequenceNumber?.toNumber()}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,t){return this.standardClient=new r.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HCS2Builder=as,e.HCS6Builder=os,e.HbarPricePlugin=Xr,e.InitiateConnectionTool=ht,e.InscribeFromBufferTool=class extends zt{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=nn()}get specificInputSchema(){return rn}async _call(e,t){try{const t="string"==typeof e.base64Data?e.base64Data:"",i=/^[A-Za-z0-9+/]*={0,2}$/.test(t)?n.Buffer.from(t,"base64"):n.Buffer.from(t,"utf8"),r=e.fileName,s=e.mimeType,a=this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",o={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:a,quoteOnly:e.quoteOnly},c=await this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:r,mimeType:s},o);if(c.confirmed&&!c.quote){const e=Gt(c.inscription,c.result),{topicId:t,cdnUrl:n}=Vt(e,a,"1");return JSON.stringify({success:!0,data:`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${c.result?.transactionId??"unknown"}\nTopic ID: ${t||"N/A"}${n?`\nView inscription: ${n}`:""}\n\nThe inscription is now available.`})}return JSON.stringify({success:!0,data:`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${c.result?.transactionId??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`})}catch(i){const e=i instanceof Error?i.message:String(i);return JSON.stringify({success:!1,error:`Inscription failed: ${e}`})}}async executeQuery(e,t){const n=await async function(e,t,n){const i=e.trim(),s=r.ContentResolverRegistry.getResolver();if(!s)return Yt(i,t,n);const a=s.extractReferenceId(i);if(a)try{const e=await s.resolveReference(a);return{buffer:e.content,mimeType:e.metadata?.mimeType||t,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(o){const e=o instanceof Error?o.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return Yt(i,t,n)}(e.base64Data,e.mimeType,e.fileName);this.logger?.debug(`[InscribeFromBufferTool] Resolved content bytes: ${n.buffer?.length??-1}`);try{this.validateContent(n.buffer)}catch(c){this.logger?.warn(`Content validation warning: ${c instanceof Error?c.message:String(c)}`)}const i=n.buffer,s=n.mimeType||e.mimeType,a=n.fileName||e.fileName,o={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:a,mimeType:s},o);return{success:!0,quote:{totalCostHbar:e.totalCostHbar,validUntil:e.validUntil,breakdown:e.breakdown},contentInfo:{fileName:a,mimeType:s,sizeBytes:i.length},message:`Estimated Quote for buffer content: ${a} (${(i.length/1024).toFixed(2)} KB)\nTotal cost: ${e.totalCostHbar} HBAR`}}catch(d){const e=d instanceof Error?d.message:"Failed to generate inscription quote";throw new Error(`Quote generation failed: ${e}`)}try{this.logger?.debug(`[InscribeFromBufferTool] Calling inscribe with fileName: ${a}, mime: ${s}`);const t=await this.executeInscription(i,a,s,o,e.timeoutMs);return this.logger?.debug(`[InscribeFromBufferTool] Inscribe result (confirmed): ${Boolean(t?.confirmed)}`),this.formatInscriptionResult(t,o)}catch(d){this.logger?.warn(`[InscribeFromBufferTool] Error during inscription: ${d instanceof Error?d.message:String(d)}`);const e=d instanceof Error?d.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){const n=e;if(n.confirmed&&!n.quote){const e=Gt(n.inscription,n.result),i=t.network||"testnet",{topicId:r,cdnUrl:s}=Vt(e,i,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${s?`\nView inscription: ${s}`:""}\n\nThe inscription is now available.`}return n.quote||n.confirmed?"Inscription operation completed.":`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${n.result?.transactionId??"unknown"}\n\nThe inscription is processing and will be confirmed shortly.`}},e.InscribeFromFileTool=class extends zt{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 Xt}async executeQuery(e,t){let i;try{const t=await h.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 h.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=p.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=p.basename(e.filePath),a=this.getMimeType(s);this.logger?.info(`File: ${s}, MIME type: ${a}`);const o={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:!e.quoteOnly&&(e.waitForConfirmation??!0),waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",quoteOnly:e.quoteOnly};if(e.quoteOnly)try{const t=await this.generateInscriptionQuote({type:"buffer",buffer:n.Buffer.from(r,"base64"),fileName:s,mimeType:a},o);return{success:!0,quote:{totalCostHbar:t.totalCostHbar,validUntil:t.validUntil,breakdown:t.breakdown},contentInfo:{fileName:s,mimeType:a,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:a},o),i])}else t=await this.inscriberBuilder.inscribe({type:"buffer",buffer:n.Buffer.from(r,"base64"),fileName:s,mimeType:a},o);const i=t;if(i.confirmed&&!i.quote){const e=Gt(i.inscription,i.result),t=o.network||"testnet",{topicId:n,cdnUrl:r}=Vt(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${n||"N/A"}${r?`\nView inscription: ${r}`:""}\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??"unknown"}\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"}[p.extname(e).toLowerCase()]||"application/octet-stream"}},e.InscribeFromUrlTool=class extends zt{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 Jt}async executeQuery(e,t){if(Qt.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.`)}Qt.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")||"",a=i.headers.get("content-length");if(["text/html","application/xhtml+xml","text/xml"].some(e=>s.toLowerCase().includes(e)))throw new Error(`URL returns HTML/web page content (Content-Type: ${s}). This tool only works with direct file URLs (PDFs, images, JSON, etc.). For web page content, first retrieve the content using the appropriate MCP tool or web scraper, then use inscribeFromBuffer to inscribe it.`);if(a&&0===parseInt(a))throw new Error("URL returns empty content (Content-Length: 0). Cannot inscribe empty content.");if(a&&parseInt(a)<10)throw new Error(`URL content is too small (${a} bytes). Content must be at least 10 bytes.`);if(!s||"application/octet-stream"===s){Qt.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;Qt.warn(`Could not perform partial GET validation: ${r instanceof Error?r.message:"Unknown error"}`)}}Qt.info(`URL validation passed. Content-Type: ${s}, Content-Length: ${a||"unknown"}`)}catch(s){throw clearTimeout(n),s}}catch(i){if(i instanceof Error)if("AbortError"===i.name)Qt.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;Qt.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);const i=t;if(i.confirmed&&!i.quote){const e=Gt(i.inscription,i.result),t=n.network||"testnet",{topicId:r,cdnUrl:s}=Vt(e,t,"1");return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result?.transactionId??"unknown"}\nTopic ID: ${r||"N/A"}${s?`\nView inscription: ${s}`:""}\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??"unknown"}\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 zt{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 Tn._def?.schema||Tn}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 dn(et({name:Ve().min(1,"Name is required").describe('Display name for the NFT (e.g., "Sunset Landscape #42", "Digital Abstract Art")'),description:Ve().min(1,"Description is required").describe("Meaningful description of the artwork, story, or concept behind this NFT"),creator:Ve().min(1,"Creator is required").describe('Creator account ID, artist name, or brand (e.g., "0.0.123456", "ArtistName", "StudioBrand")'),attributes:dn(Ye(et({trait_type:Ve().describe('Trait name (e.g., "Rarity", "Color", "Style")'),value:tt([Ve(),Qe()]).describe('Trait value (e.g., "Epic", "Blue", 85)')}))).withRender(wn.array("NFT Attributes","Attribute")).optional().describe("Collectible traits and characteristics."),type:Ve().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 vn({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={...cn({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 on.parse(e)}catch(t){if(t instanceof T){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 vn({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 a={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 o;if(e.url)o={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);o={type:"buffer",buffer:n,fileName:r||e.fileName||"hashinal-content",mimeType:i||e.mimeType}}}if(e.quoteOnly)try{const t=await this.generateInscriptionQuote(o,a);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 vn({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.inscribeAuto?this.inscriberBuilder.inscribeAuto(o,a):this.inscriberBuilder.inscribe(o,a),n])}else t=this.inscriberBuilder.inscribeAuto?await this.inscriberBuilder.inscribeAuto(o,a):await this.inscriberBuilder.inscribe(o,a);if(t.confirmed&&!t.quote){const n=Gt(t.inscription,t.result),i=a.network||"testnet",s=e.fileStandard||"1",{hrl:o,topicId:c,cdnUrl:l}=Vt(n,i,s),u=function(e){const{hrl:t,topicId:n,standard:i,cdnUrl:r,transactionId:s,metadata:a}=e;return{success:!0,type:"inscription",title:`${i} Hashinal Inscription Complete`,message:`Successfully inscribed "${a.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:a,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}}}({hrl:o||"hcs://1/unknown",topicId:c||"unknown",standard:"6"===s?"Dynamic":"Static",cdnUrl:l,transactionId:t?.inscription?.tx_id||t?.result?.transactionId||"unknown",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:Array.isArray(e.attributes)?e.attributes:[]}});if(!1!==e.withHashLinkBlocks)try{const e=await this.createHashLinkBlock(u);u.hashLinkBlock=e}catch(d){new r.Logger({module:"InscribeHashinalTool"}).warn("Failed to create HashLink block",d)}return u}if(t.quote||t.confirmed)return vn({code:"UNEXPECTED_RESULT",details:"Received an unexpected inscription result state",suggestions:["Try again or verify network status"]});return function(e){const{transactionId:t,details:n,suggestions:i}=e,r=n||`Inscription submitted but not yet confirmed. Transaction ID: ${t}`;return{success:!1,type:"error",title:"Inscription Submitted (Pending)",message:r,error:{code:"INSCRIPTION_PENDING",details:r,suggestions:i||["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"]}}}({transactionId:t.result?.transactionId||t?.inscription?.transactionId||"unknown",details:"Successfully submitted Hashinal inscription. Waiting for network confirmation..."})}catch(c){const e=c instanceof Error?c.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}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,a=function(e){const t="mainnet"===e?In.mainnet:In.testnet;return t&&"0.0.TBD"!==t.blockId?t:In.testnet}(s);return{blockId:a.blockId,hashLink:a.hashLink,template:a.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 a=s.extractReferenceId(i);if(a)try{const e=await s.resolveReference(a);return{buffer:e.content,mimeType:e.metadata?.mimeType||t,fileName:e.metadata?.fileName||n,wasReference:!0}}catch(o){const e=o instanceof Error?o.message:"Unknown error resolving reference";throw new Error(`Reference resolution failed: ${e}`)}return this.handleDirectContent(i,t,n)}handleDirectContent(e,t,i){if(/^[A-Za-z0-9+/]*={0,2}$/.test(e))try{return{buffer:n.Buffer.from(e,"base64"),mimeType:t,fileName:i,wasReference:!1}}catch(r){throw new Error("Failed to decode base64 data. Please ensure the data is properly encoded.")}return{buffer:n.Buffer.from(e,"utf8"),mimeType:t||"text/plain",fileName:i,wasReference:!1}}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=ds,e.ListConnectionsTool=gt,e.ListUnapprovedConnectionRequestsTool=xt,e.ManageConnectionRequestsTool=At,e.MigrateRegistryTool=class extends Ot{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return qt}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to migrate registry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to migrate the HCS-2 registry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Migrate HCS-2 registry (from ${e.registryTopicId} to ${e.targetTopicId})`}}}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=at,e.OpenConvaiState=Cn,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 Kt}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 Ot{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry (standard HCS-2). Retrieves indexed or latest entries and returns a structured summary."}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}),i=n.registryType,r=0===i||"0"===i||"indexed"===String(i).toLowerCase()||"index"===String(i).toLowerCase()||"index_topic"===String(i).toLowerCase()||"indexed_registry"===String(i).toLowerCase();return{topicId:n.topicId,registryType:r?"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=ct,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 Ut}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(!("success"in n)||!n.success)throw new Error(n.error||"Failed to register dynamic hashinal");if(Nt(n)){const t=n.transactionBytes;return{message:"I prepared an unsigned transaction to register a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:"Register dynamic hashinal"+(e.memo?` (Memo: ${e.memo})`:"")}}}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 Ot{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register an entry in an HCS-2 registry (standard HCS-2). Use this to add a target topic to an existing HCS-2 registry."}get specificInputSchema(){return $t}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!("success"in t)||!t.success)throw new Error(t.error||"Failed to register entry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to register the entry in the HCS-2 registry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Register HCS-2 entry (registry ${e.registryTopicId} -> target ${e.targetTopicId})`}}}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 zt{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return An}async executeQuery(e,t){const n=await this.inscriberBuilder.retrieveInscription(e.transactionId,{apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"});return{inscriptionId:n.inscriptionId,transactionId:n.transactionId||"unknown",topicId:n.topic_id||n.topicId,status:n.status||"unknown",holderId:n.holderId,metadata:n.metadata,tags:n.tags,mode:n.mode,chunks:n.chunks,createdAt:n.createdAt,completedAt:n.completed||n.completedAt,fileUrl:n.fileUrl,mimeType:n.mimeType,fileSize:n.fileSize}}},e.RetrieveProfileTool=St,e.SendMessageToConnectionTool=ut,e.SignerProviderRegistry=Sn,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 jt}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(!("success"in n)||!n.success)throw new Error(n.error||"Failed to update dynamic hashinal");if(Nt(n)){const t=n.transactionBytes;return{message:"I prepared an unsigned transaction to update a dynamic hashinal. Please review and approve to submit.",transactionBytes:t,metadata:{transactionBytes:t,pendingApproval:!0,description:`Update dynamic hashinal (registry ${e.registryTopicId})${e.memo?` (Memo: ${e.memo})`:""}`}}}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 Ot{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return Pt}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(!("success"in t)||!t.success)throw new Error(t.error||"Failed to update entry");if(Nt(t)){const n=t.transactionBytes;return{message:"I prepared an unsigned transaction to update the HCS-2 registry entry. Please review and approve to submit.",transactionBytes:n,metadata:{transactionBytes:n,pendingApproval:!0,description:`Update HCS-2 entry (registry ${e.registryTopicId}, uid ${e.uid} -> ${e.targetTopicId})`}}}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=Yr(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=dn(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}dn(n).withProgressive(r,i)}return n}}return n},e.createSimpleConfig=function(e){const t=Yr(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=dn,e.extractFieldMetadata=bn,e.extractOptionsFromSchema=hn,e.extractProgressiveInfo=function(e){const t=un(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=Yr,e.extractValidationConstraints=mn,e.generateFieldOrdering=function(e){const t=Yr(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=yn,e.getInnerSchema=gn,e.getRenderConfig=un,e.hasRenderConfig=ln,e.inferFieldTypeFromSchema=pn,e.initializeStandardsAgentKit=async e=>{const n=e?.clientConfig||{},i=n.operatorId||t.env.HEDERA_OPERATOR_ID,a=n.operatorKey||t.env.HEDERA_OPERATOR_KEY,o=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"===o?l="mainnet":("testnet"===o||d.warn(`Unsupported network specified: '${o}'. Defaulting to 'testnet'.`),l="testnet"),!i||!a)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const u=e?.stateManager||new Cn({defaultEnvFilePath:_n,defaultPrefix:"TODD"});d.info("State manager initialized");const p=new s.ServerSigner(i,a,l),h=new s.HederaAgentKit(p);await h.initialize(),d.info(`HederaAgentKit initialized for ${i} on ${l}`);const f=new Jr(h,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:n.logLevel});let g,m;if(e?.monitoringClient){const e=new s.ServerSigner(i,a,l);g=new s.HederaAgentKit(e),await g.initialize(),m=new Jr(g,u,{useEncryption:n.useEncryption,registryUrl:n.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new ct({hederaKit:h,hcs10Builder:f,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new wt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.retrieveProfileTool=new St({hederaKit:h,hcs10Builder:f,logger:void 0}),y.initiateConnectionTool=new ht({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listConnectionsTool=new gt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.sendMessageToConnectionTool=new ut({hederaKit:h,hcs10Builder:f,logger:void 0}),y.checkMessagesTool=new yt({hederaKit:h,hcs10Builder:f,logger:void 0}),y.connectionMonitorTool=new It({hederaKit:g||h,hcs10Builder:m||f,logger:void 0}),y.manageConnectionRequestsTool=new At({hederaKit:h,hcs10Builder:f,logger:void 0}),y.acceptConnectionRequestTool=new Ct({hederaKit:h,hcs10Builder:f,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new xt({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(){D.prototype.withRender||(D.prototype.withRender=function(e){return dn(this).withRender(e)},D.prototype.withProgressive=function(e,t){return dn(this).withProgressive(e,t)},D.prototype.withBlock=function(e){return dn(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=fn,e.loadConfig=nn,e.renderConfigs=wn,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=standards-agent-kit.umd.js.map