@hashgraphonline/standards-agent-kit 0.2.1 → 0.2.102

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 (193) hide show
  1. package/dist/cjs/builders/hcs10/hcs10-builder.d.ts +4 -0
  2. package/dist/cjs/builders/hcs2/hcs2-builder.d.ts +50 -0
  3. package/dist/cjs/builders/hcs2/index.d.ts +1 -0
  4. package/dist/cjs/builders/index.d.ts +2 -0
  5. package/dist/cjs/builders/inscriber/index.d.ts +1 -0
  6. package/dist/cjs/builders/inscriber/inscriber-builder.d.ts +46 -0
  7. package/dist/cjs/index.d.ts +1 -1
  8. package/dist/cjs/standards-agent-kit.cjs +1 -1
  9. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  10. package/dist/cjs/tools/hcs10/FindRegistrationsTool.d.ts +4 -4
  11. package/dist/cjs/tools/hcs10/RegisterAgentTool.d.ts +24 -8
  12. package/dist/cjs/tools/hcs10/index.d.ts +1 -0
  13. package/dist/cjs/tools/hcs10/natural-language-mapper.d.ts +19 -0
  14. package/dist/cjs/tools/hcs2/CreateRegistryTool.d.ts +48 -0
  15. package/dist/cjs/tools/hcs2/DeleteEntryTool.d.ts +41 -0
  16. package/dist/cjs/tools/hcs2/MigrateRegistryTool.d.ts +47 -0
  17. package/dist/cjs/tools/hcs2/QueryRegistryTool.d.ts +47 -0
  18. package/dist/cjs/tools/hcs2/RegisterEntryTool.d.ts +47 -0
  19. package/dist/cjs/tools/hcs2/UpdateEntryTool.d.ts +53 -0
  20. package/dist/cjs/tools/hcs2/base-hcs2-tools.d.ts +28 -0
  21. package/dist/cjs/tools/hcs2/hcs2-tool-params.d.ts +18 -0
  22. package/dist/cjs/tools/hcs2/index.d.ts +8 -0
  23. package/dist/cjs/tools/index.d.ts +2 -0
  24. package/dist/cjs/tools/inscriber/InscribeFromBufferTool.d.ts +77 -0
  25. package/dist/cjs/tools/inscriber/InscribeFromFileTool.d.ts +65 -0
  26. package/dist/cjs/tools/inscriber/InscribeFromUrlTool.d.ts +65 -0
  27. package/dist/cjs/tools/inscriber/InscribeHashinalTool.d.ts +125 -0
  28. package/dist/cjs/tools/inscriber/RetrieveInscriptionTool.d.ts +35 -0
  29. package/dist/cjs/tools/inscriber/base-inscriber-tools.d.ts +28 -0
  30. package/dist/cjs/tools/inscriber/index.d.ts +7 -0
  31. package/dist/cjs/tools/inscriber/inscriber-tool-params.d.ts +18 -0
  32. package/dist/es/builders/hcs10/hcs10-builder.d.ts +4 -0
  33. package/dist/es/builders/hcs2/hcs2-builder.d.ts +50 -0
  34. package/dist/es/builders/hcs2/index.d.ts +1 -0
  35. package/dist/es/builders/index.d.ts +2 -0
  36. package/dist/es/builders/inscriber/index.d.ts +1 -0
  37. package/dist/es/builders/inscriber/inscriber-builder.d.ts +46 -0
  38. package/dist/es/index.d.ts +1 -1
  39. package/dist/es/standards-agent-kit.es.js +50 -16
  40. package/dist/es/standards-agent-kit.es.js.map +1 -1
  41. package/dist/es/standards-agent-kit.es10.js +17 -23
  42. package/dist/es/standards-agent-kit.es10.js.map +1 -1
  43. package/dist/es/standards-agent-kit.es11.js +36 -58
  44. package/dist/es/standards-agent-kit.es11.js.map +1 -1
  45. package/dist/es/standards-agent-kit.es12.js +43 -18
  46. package/dist/es/standards-agent-kit.es12.js.map +1 -1
  47. package/dist/es/standards-agent-kit.es13.js +53 -16
  48. package/dist/es/standards-agent-kit.es13.js.map +1 -1
  49. package/dist/es/standards-agent-kit.es14.js +18 -28
  50. package/dist/es/standards-agent-kit.es14.js.map +1 -1
  51. package/dist/es/standards-agent-kit.es15.js +26 -12
  52. package/dist/es/standards-agent-kit.es15.js.map +1 -1
  53. package/dist/es/standards-agent-kit.es16.js +37 -241
  54. package/dist/es/standards-agent-kit.es16.js.map +1 -1
  55. package/dist/es/standards-agent-kit.es17.js +16 -136
  56. package/dist/es/standards-agent-kit.es17.js.map +1 -1
  57. package/dist/es/standards-agent-kit.es18.js +154 -27
  58. package/dist/es/standards-agent-kit.es18.js.map +1 -1
  59. package/dist/es/standards-agent-kit.es19.js +26 -22
  60. package/dist/es/standards-agent-kit.es19.js.map +1 -1
  61. package/dist/es/standards-agent-kit.es2.js +27 -13
  62. package/dist/es/standards-agent-kit.es2.js.map +1 -1
  63. package/dist/es/standards-agent-kit.es20.js +42 -3
  64. package/dist/es/standards-agent-kit.es20.js.map +1 -1
  65. package/dist/es/standards-agent-kit.es21.js +48 -0
  66. package/dist/es/standards-agent-kit.es21.js.map +1 -0
  67. package/dist/es/standards-agent-kit.es22.js +51 -0
  68. package/dist/es/standards-agent-kit.es22.js.map +1 -0
  69. package/dist/es/standards-agent-kit.es23.js +45 -0
  70. package/dist/es/standards-agent-kit.es23.js.map +1 -0
  71. package/dist/es/standards-agent-kit.es24.js +48 -0
  72. package/dist/es/standards-agent-kit.es24.js.map +1 -0
  73. package/dist/es/standards-agent-kit.es25.js +45 -0
  74. package/dist/es/standards-agent-kit.es25.js.map +1 -0
  75. package/dist/es/standards-agent-kit.es26.js +32 -0
  76. package/dist/es/standards-agent-kit.es26.js.map +1 -0
  77. package/dist/es/standards-agent-kit.es27.js +71 -0
  78. package/dist/es/standards-agent-kit.es27.js.map +1 -0
  79. package/dist/es/standards-agent-kit.es28.js +71 -0
  80. package/dist/es/standards-agent-kit.es28.js.map +1 -0
  81. package/dist/es/standards-agent-kit.es29.js +79 -0
  82. package/dist/es/standards-agent-kit.es29.js.map +1 -0
  83. package/dist/es/standards-agent-kit.es3.js +59 -296
  84. package/dist/es/standards-agent-kit.es3.js.map +1 -1
  85. package/dist/es/standards-agent-kit.es30.js +90 -0
  86. package/dist/es/standards-agent-kit.es30.js.map +1 -0
  87. package/dist/es/standards-agent-kit.es31.js +45 -0
  88. package/dist/es/standards-agent-kit.es31.js.map +1 -0
  89. package/dist/es/standards-agent-kit.es32.js +249 -0
  90. package/dist/es/standards-agent-kit.es32.js.map +1 -0
  91. package/dist/es/standards-agent-kit.es33.js +141 -0
  92. package/dist/es/standards-agent-kit.es33.js.map +1 -0
  93. package/dist/es/standards-agent-kit.es34.js +33 -0
  94. package/dist/es/standards-agent-kit.es34.js.map +1 -0
  95. package/dist/es/standards-agent-kit.es35.js +28 -0
  96. package/dist/es/standards-agent-kit.es35.js.map +1 -0
  97. package/dist/es/standards-agent-kit.es36.js +7 -0
  98. package/dist/es/standards-agent-kit.es36.js.map +1 -0
  99. package/dist/es/standards-agent-kit.es4.js +44 -20
  100. package/dist/es/standards-agent-kit.es4.js.map +1 -1
  101. package/dist/es/standards-agent-kit.es5.js +312 -121
  102. package/dist/es/standards-agent-kit.es5.js.map +1 -1
  103. package/dist/es/standards-agent-kit.es6.js +24 -23
  104. package/dist/es/standards-agent-kit.es6.js.map +1 -1
  105. package/dist/es/standards-agent-kit.es7.js +220 -20
  106. package/dist/es/standards-agent-kit.es7.js.map +1 -1
  107. package/dist/es/standards-agent-kit.es8.js +20 -29
  108. package/dist/es/standards-agent-kit.es8.js.map +1 -1
  109. package/dist/es/standards-agent-kit.es9.js +26 -36
  110. package/dist/es/standards-agent-kit.es9.js.map +1 -1
  111. package/dist/es/tools/hcs10/FindRegistrationsTool.d.ts +4 -4
  112. package/dist/es/tools/hcs10/RegisterAgentTool.d.ts +24 -8
  113. package/dist/es/tools/hcs10/index.d.ts +1 -0
  114. package/dist/es/tools/hcs10/natural-language-mapper.d.ts +19 -0
  115. package/dist/es/tools/hcs2/CreateRegistryTool.d.ts +48 -0
  116. package/dist/es/tools/hcs2/DeleteEntryTool.d.ts +41 -0
  117. package/dist/es/tools/hcs2/MigrateRegistryTool.d.ts +47 -0
  118. package/dist/es/tools/hcs2/QueryRegistryTool.d.ts +47 -0
  119. package/dist/es/tools/hcs2/RegisterEntryTool.d.ts +47 -0
  120. package/dist/es/tools/hcs2/UpdateEntryTool.d.ts +53 -0
  121. package/dist/es/tools/hcs2/base-hcs2-tools.d.ts +28 -0
  122. package/dist/es/tools/hcs2/hcs2-tool-params.d.ts +18 -0
  123. package/dist/es/tools/hcs2/index.d.ts +8 -0
  124. package/dist/es/tools/index.d.ts +2 -0
  125. package/dist/es/tools/inscriber/InscribeFromBufferTool.d.ts +77 -0
  126. package/dist/es/tools/inscriber/InscribeFromFileTool.d.ts +65 -0
  127. package/dist/es/tools/inscriber/InscribeFromUrlTool.d.ts +65 -0
  128. package/dist/es/tools/inscriber/InscribeHashinalTool.d.ts +125 -0
  129. package/dist/es/tools/inscriber/RetrieveInscriptionTool.d.ts +35 -0
  130. package/dist/es/tools/inscriber/base-inscriber-tools.d.ts +28 -0
  131. package/dist/es/tools/inscriber/index.d.ts +7 -0
  132. package/dist/es/tools/inscriber/inscriber-tool-params.d.ts +18 -0
  133. package/dist/umd/builders/hcs10/hcs10-builder.d.ts +4 -0
  134. package/dist/umd/builders/hcs2/hcs2-builder.d.ts +50 -0
  135. package/dist/umd/builders/hcs2/index.d.ts +1 -0
  136. package/dist/umd/builders/index.d.ts +2 -0
  137. package/dist/umd/builders/inscriber/index.d.ts +1 -0
  138. package/dist/umd/builders/inscriber/inscriber-builder.d.ts +46 -0
  139. package/dist/umd/index.d.ts +1 -1
  140. package/dist/umd/standards-agent-kit.umd.js +1 -1
  141. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  142. package/dist/umd/tools/hcs10/FindRegistrationsTool.d.ts +4 -4
  143. package/dist/umd/tools/hcs10/RegisterAgentTool.d.ts +24 -8
  144. package/dist/umd/tools/hcs10/index.d.ts +1 -0
  145. package/dist/umd/tools/hcs10/natural-language-mapper.d.ts +19 -0
  146. package/dist/umd/tools/hcs2/CreateRegistryTool.d.ts +48 -0
  147. package/dist/umd/tools/hcs2/DeleteEntryTool.d.ts +41 -0
  148. package/dist/umd/tools/hcs2/MigrateRegistryTool.d.ts +47 -0
  149. package/dist/umd/tools/hcs2/QueryRegistryTool.d.ts +47 -0
  150. package/dist/umd/tools/hcs2/RegisterEntryTool.d.ts +47 -0
  151. package/dist/umd/tools/hcs2/UpdateEntryTool.d.ts +53 -0
  152. package/dist/umd/tools/hcs2/base-hcs2-tools.d.ts +28 -0
  153. package/dist/umd/tools/hcs2/hcs2-tool-params.d.ts +18 -0
  154. package/dist/umd/tools/hcs2/index.d.ts +8 -0
  155. package/dist/umd/tools/index.d.ts +2 -0
  156. package/dist/umd/tools/inscriber/InscribeFromBufferTool.d.ts +77 -0
  157. package/dist/umd/tools/inscriber/InscribeFromFileTool.d.ts +65 -0
  158. package/dist/umd/tools/inscriber/InscribeFromUrlTool.d.ts +65 -0
  159. package/dist/umd/tools/inscriber/InscribeHashinalTool.d.ts +125 -0
  160. package/dist/umd/tools/inscriber/RetrieveInscriptionTool.d.ts +35 -0
  161. package/dist/umd/tools/inscriber/base-inscriber-tools.d.ts +28 -0
  162. package/dist/umd/tools/inscriber/index.d.ts +7 -0
  163. package/dist/umd/tools/inscriber/inscriber-tool-params.d.ts +18 -0
  164. package/package.json +32 -30
  165. package/src/builders/hcs10/hcs10-builder.ts +37 -16
  166. package/src/builders/hcs2/hcs2-builder.ts +148 -0
  167. package/src/builders/hcs2/index.ts +1 -0
  168. package/src/builders/index.ts +3 -1
  169. package/src/builders/inscriber/index.ts +1 -0
  170. package/src/builders/inscriber/inscriber-builder.ts +112 -0
  171. package/src/index.ts +1 -1
  172. package/src/tools/hcs10/FindRegistrationsTool.ts +19 -4
  173. package/src/tools/hcs10/RegisterAgentTool.ts +147 -9
  174. package/src/tools/hcs10/index.ts +2 -1
  175. package/src/tools/hcs10/natural-language-mapper.ts +194 -0
  176. package/src/tools/hcs2/CreateRegistryTool.ts +63 -0
  177. package/src/tools/hcs2/DeleteEntryTool.ts +58 -0
  178. package/src/tools/hcs2/MigrateRegistryTool.ts +64 -0
  179. package/src/tools/hcs2/QueryRegistryTool.ts +70 -0
  180. package/src/tools/hcs2/RegisterEntryTool.ts +63 -0
  181. package/src/tools/hcs2/UpdateEntryTool.ts +68 -0
  182. package/src/tools/hcs2/base-hcs2-tools.ts +65 -0
  183. package/src/tools/hcs2/hcs2-tool-params.ts +21 -0
  184. package/src/tools/hcs2/index.ts +8 -0
  185. package/src/tools/index.ts +3 -2
  186. package/src/tools/inscriber/InscribeFromBufferTool.ts +105 -0
  187. package/src/tools/inscriber/InscribeFromFileTool.ts +93 -0
  188. package/src/tools/inscriber/InscribeFromUrlTool.ts +93 -0
  189. package/src/tools/inscriber/InscribeHashinalTool.ts +117 -0
  190. package/src/tools/inscriber/RetrieveInscriptionTool.ts +59 -0
  191. package/src/tools/inscriber/base-inscriber-tools.ts +65 -0
  192. package/src/tools/inscriber/index.ts +7 -0
  193. package/src/tools/inscriber/inscriber-tool-params.ts +21 -0
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("unenv/node/buffer"),require("hedera-agent-kit"),require("@hashgraphonline/standards-sdk"),require("unenv/node/fs"),require("unenv/node/path"),require("unenv/polyfill/globalthis"),require("unenv/node/timers"),require("unenv/node/process")):"function"==typeof define&&define.amd?define(["exports","unenv/node/buffer","hedera-agent-kit","@hashgraphonline/standards-sdk","unenv/node/fs","unenv/node/path","unenv/polyfill/globalthis","unenv/node/timers","unenv/node/process"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsAgentKit={},e["unenv/node/buffer"],e.HederaAgentKit,e.StandardsSDK,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],e.process)}(this,function(e,t,n,r,i,s,o,a,c){"use strict";class u extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class d extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var l,h,p;(h=l||(l={})).assertEqual=e=>{},h.assertIs=function(e){},h.assertNever=function(e){throw new Error},h.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},h.getValidEnumValues=e=>{const t=h.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const r of t)n[r]=e[r];return h.objectValues(n)},h.objectValues=e=>h.objectKeys(e).map(function(t){return e[t]}),h.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},h.find=(e,t)=>{for(const n of e)if(t(n))return n},h.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,h.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},h.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(p||(p={})).mergeShapes=(e,t)=>({...e,...t});const f=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),g=e=>{switch(typeof e){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(e)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(e)?f.array:null===e?f.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?f.promise:"undefined"!=typeof Map&&e instanceof Map?f.map:"undefined"!=typeof Set&&e instanceof Set?f.set:"undefined"!=typeof Date&&e instanceof Date?f.date:f.object;default:return f.unknown}},m=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class y extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(r);else if("invalid_return_type"===i.code)r(i.returnTypeError);else if("invalid_arguments"===i.code)r(i.argumentsError);else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof y))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}y.create=e=>new y(e);const v=(e,t)=>{let n;switch(e.code){case m.invalid_type:n=e.received===f.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,l.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:n=`Unrecognized key(s) in object: ${l.joinValues(e.keys,", ")}`;break;case m.invalid_union:n="Invalid input";break;case m.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${l.joinValues(e.options)}`;break;case m.invalid_enum_value:n=`Invalid enum value. Expected ${l.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:n="Invalid function arguments";break;case m.invalid_return_type:n="Invalid function return type";break;case m.invalid_date:n="Invalid date";break;case m.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:l.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case m.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case m.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case m.custom:n="Invalid input";break;case m.invalid_intersection_types:n="Intersection results could not be merged";break;case m.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:n="Number must be finite";break;default:n=t.defaultError,l.assertNever(e)}return{message:n}};let b=v;function w(e,t){const n=b,r=(e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(void 0!==i.message)return{...i,path:s,message:i.message};let a="";const c=r.filter(e=>!!e).slice().reverse();for(const u of c)a=u(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===v?void 0:v].filter(e=>!!e)});e.common.issues.push(r)}class _{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return I;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const r of t){const e=await r.key,t=await r.value;n.push({key:e,value:t})}return _.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:i}=r;if("aborted"===t.status)return I;if("aborted"===i.status)return I;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!r.alwaysSet||(n[t.value]=i.value)}return{status:e.value,value:n}}}const I=Object.freeze({status:"aborted"}),C=e=>({status:"dirty",value:e}),T=e=>({status:"valid",value:e}),x=e=>"aborted"===e.status,A=e=>"dirty"===e.status,k=e=>"valid"===e.status,S=e=>"undefined"!=typeof Promise&&e instanceof Promise;var R,E;(E=R||(R={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},E.toString=e=>"string"==typeof e?e:e?.message;class O{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const N=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new y(e.common.issues);return this._error=t,this._error}}};function P(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:i};return{errorMap:(t,i)=>{const{message:s}=e;return"invalid_enum_value"===t.code?{message:s??i.defaultError}:void 0===i.data?{message:s??r??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:s??n??i.defaultError}},description:i}}class q{get description(){return this._def.description}_getType(e){return g(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _,ctx:{common:e.parent.common,data:e.data,parsedType:g(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(S(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)},r=this._parseSync({data:e,path:n.path,parent:n});return N(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return k(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>k(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:g(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(S(r)?r:Promise.resolve(r));return N(n,i)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const i=e(t),s=()=>r.addIssue({code:m.custom,...n(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then(e=>!!e||(s(),!1)):!!i||(s(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new Pe({schema:this,typeName:Ue.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return qe.create(this,this._def)}nullable(){return $e.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ye.create(this)}promise(){return Ne.create(this,this._def)}or(e){return we.create([this,e],this._def)}and(e){return Ie.create(this,e,this._def)}transform(e){return new Pe({...P(this._def),schema:this,typeName:Ue.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Me({...P(this._def),innerType:this,defaultValue:t,typeName:Ue.ZodDefault})}brand(){return new Be({typeName:Ue.ZodBranded,type:this,...P(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Fe({...P(this._def),innerType:this,catchValue:t,typeName:Ue.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return De.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const $=/^c[^\s-]{8,}$/i,M=/^[0-9a-z]+$/,F=/^[0-9A-HJKMNP-TV-Z]{26}$/i,j=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,B=/^[a-z0-9_-]{21}$/i,D=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,U=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let Z;const K=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,z=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,H=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,V=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,W=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,J=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,G="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",X=new RegExp(`^${G}$`);function Q(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Y(e){return new RegExp(`^${Q(e)}$`)}function ee(e){let t=`${G}T${Q(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function te(e,t){return!("v4"!==t&&t||!K.test(e))||!("v6"!==t&&t||!H.test(e))}function ne(e,t){if(!D.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return"object"==typeof i&&null!==i&&((!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||i.alg===t)))}catch{return!1}}function re(e,t){return!("v4"!==t&&t||!z.test(e))||!("v6"!==t&&t||!V.test(e))}class ie extends q{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==f.string){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.string,received:t.parsedType}),I}const t=new _;let n;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const i=e.data.length>r.value,s=e.data.length<r.value;(i||s)&&(n=this._getOrReturnCtx(e,n),i?w(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):s&&w(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"email",code:m.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)Z||(Z=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Z.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"emoji",code:m.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"uuid",code:m.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)B.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"nanoid",code:m.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)$.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid",code:m.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)M.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid2",code:m.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)F.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ulid",code:m.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),w(n,{validation:"url",code:m.invalid_string,message:r.message}),t.dirty()}else if("regex"===r.kind){r.regex.lastIndex=0;r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"regex",code:m.invalid_string,message:r.message}),t.dirty())}else if("trim"===r.kind)e.data=e.data.trim();else if("includes"===r.kind)e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty());else if("toLowerCase"===r.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===r.kind)e.data=e.data.toUpperCase();else if("startsWith"===r.kind)e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty());else if("endsWith"===r.kind)e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty());else if("datetime"===r.kind){ee(r).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"datetime",message:r.message}),t.dirty())}else if("date"===r.kind){X.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"date",message:r.message}),t.dirty())}else if("time"===r.kind){Y(r).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"time",message:r.message}),t.dirty())}else"duration"===r.kind?L.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"duration",code:m.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?te(e.data,r.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ip",code:m.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?ne(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"jwt",code:m.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?re(e.data,r.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cidr",code:m.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?W.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64",code:m.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?J.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64url",code:m.invalid_string,message:r.message}),t.dirty()):l.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:m.invalid_string,...R.errToObj(n)})}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...R.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...R.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...R.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...R.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...R.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...R.errToObj(t)})}nonempty(e){return this.min(1,R.errToObj(e))}trim(){return new ie({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function se(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}ie.create=e=>new ie({checks:[],typeName:Ue.ZodString,coerce:e?.coerce??!1,...P(e)});class oe extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==f.number){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.number,received:t.parsedType}),I}let t;const n=new _;for(const r of this._def.checks)if("int"===r.kind)l.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty());else if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty())}else"multipleOf"===r.kind?0!==se(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_finite,message:r.message}),n.dirty()):l.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,r){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(r)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&l.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}oe.create=e=>new oe({checks:[],typeName:Ue.ZodNumber,coerce:e?.coerce||!1,...P(e)});class ae extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let t;const n=new _;for(const r of this._def.checks)if("min"===r.kind){(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else if("max"===r.kind){(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty())}else"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):l.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.bigint,received:t.parsedType}),I}gte(e,t){return this.setLimit("min",e,!0,R.toString(t))}gt(e,t){return this.setLimit("min",e,!1,R.toString(t))}lte(e,t){return this.setLimit("max",e,!0,R.toString(t))}lt(e,t){return this.setLimit("max",e,!1,R.toString(t))}setLimit(e,t,n,r){return new ae({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:R.toString(r)}]})}_addCheck(e){return new ae({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ae.create=e=>new ae({checks:[],typeName:Ue.ZodBigInt,coerce:e?.coerce??!1,...P(e)});class ce extends q{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==f.boolean){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.boolean,received:t.parsedType}),I}return T(e.data)}}ce.create=e=>new ce({typeName:Ue.ZodBoolean,coerce:e?.coerce||!1,...P(e)});class ue extends q{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==f.date){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.date,received:t.parsedType}),I}if(Number.isNaN(e.data.getTime())){return w(this._getOrReturnCtx(e),{code:m.invalid_date}),I}const t=new _;let n;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):l.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:R.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:R.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ue.create=e=>new ue({checks:[],coerce:e?.coerce||!1,typeName:Ue.ZodDate,...P(e)});class de extends q{_parse(e){if(this._getType(e)!==f.symbol){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.symbol,received:t.parsedType}),I}return T(e.data)}}de.create=e=>new de({typeName:Ue.ZodSymbol,...P(e)});class le extends q{_parse(e){if(this._getType(e)!==f.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.undefined,received:t.parsedType}),I}return T(e.data)}}le.create=e=>new le({typeName:Ue.ZodUndefined,...P(e)});class he extends q{_parse(e){if(this._getType(e)!==f.null){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.null,received:t.parsedType}),I}return T(e.data)}}he.create=e=>new he({typeName:Ue.ZodNull,...P(e)});class pe extends q{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}}pe.create=e=>new pe({typeName:Ue.ZodAny,...P(e)});class fe extends q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}}fe.create=e=>new fe({typeName:Ue.ZodUnknown,...P(e)});class ge extends q{_parse(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.never,received:t.parsedType}),I}}ge.create=e=>new ge({typeName:Ue.ZodNever,...P(e)});class me extends q{_parse(e){if(this._getType(e)!==f.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.void,received:t.parsedType}),I}return T(e.data)}}me.create=e=>new me({typeName:Ue.ZodVoid,...P(e)});class ye extends q{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==f.array)return w(t,{code:m.invalid_type,expected:f.array,received:t.parsedType}),I;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(w(t,{code:e?m.too_big:m.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(w(t,{code:m.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(w(t,{code:m.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new O(t,e,t.path,n)))).then(e=>_.mergeArray(n,e));const i=[...t.data].map((e,n)=>r.type._parseSync(new O(t,e,t.path,n)));return _.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ye({...this._def,minLength:{value:e,message:R.toString(t)}})}max(e,t){return new ye({...this._def,maxLength:{value:e,message:R.toString(t)}})}length(e,t){return new ye({...this._def,exactLength:{value:e,message:R.toString(t)}})}nonempty(e){return this.min(1,e)}}function ve(e){if(e instanceof be){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=qe.create(ve(r))}return new be({...e._def,shape:()=>t})}return e instanceof ye?new ye({...e._def,type:ve(e.element)}):e instanceof qe?qe.create(ve(e.unwrap())):e instanceof $e?$e.create(ve(e.unwrap())):e instanceof Ce?Ce.create(e.items.map(e=>ve(e))):e}ye.create=(e,t)=>new ye({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ue.ZodArray,...P(t)});class be extends q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=l.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.object,received:t.parsedType}),I}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ge&&"strip"===this._def.unknownKeys))for(const a in n.data)i.includes(a)||s.push(a);const o=[];for(const a of i){const e=r[a],t=n.data[a];o.push({key:{status:"valid",value:a},value:e._parse(new O(n,t,n.path,a)),alwaysSet:a in n.data})}if(this._def.catchall instanceof ge){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of s)o.push({key:{status:"valid",value:t},value:{status:"valid",value:n.data[t]}});else if("strict"===e)s.length>0&&(w(n,{code:m.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const r=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new O(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>_.mergeObjectSync(t,e)):_.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new be({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:R.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new be({...this._def,unknownKeys:"strip"})}passthrough(){return new be({...this._def,unknownKeys:"passthrough"})}extend(e){return new be({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new be({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ue.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new be({...this._def,catchall:e})}pick(e){const t={};for(const n of l.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new be({...this._def,shape:()=>t})}omit(e){const t={};for(const n of l.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new be({...this._def,shape:()=>t})}deepPartial(){return ve(this)}partial(e){const t={};for(const n of l.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new be({...this._def,shape:()=>t})}required(e){const t={};for(const n of l.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof qe;)e=e._def.innerType;t[n]=e}return new be({...this._def,shape:()=>t})}keyof(){return Re(l.objectKeys(this.shape))}}be.create=(e,t)=>new be({shape:()=>e,unknownKeys:"strip",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)}),be.strictCreate=(e,t)=>new be({shape:()=>e,unknownKeys:"strict",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)}),be.lazycreate=(e,t)=>new be({shape:e,unknownKeys:"strip",catchall:ge.create(),typeName:Ue.ZodObject,...P(t)});class we extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const n=e.map(e=>new y(e.ctx.common.issues));return w(t,{code:m.invalid_union,unionErrors:n}),I});{let e;const r=[];for(const s of n){const n={...t,common:{...t.common,issues:[]},parent:null},i=s._parseSync({data:t.data,path:t.path,parent:n});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const i=r.map(e=>new y(e));return w(t,{code:m.invalid_union,unionErrors:i}),I}}get options(){return this._def.options}}function _e(e,t){const n=g(e),r=g(t);if(e===t)return{valid:!0,data:e};if(n===f.object&&r===f.object){const n=l.objectKeys(t),r=l.objectKeys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const s of r){const n=_e(e[s],t[s]);if(!n.valid)return{valid:!1};i[s]=n.data}return{valid:!0,data:i}}if(n===f.array&&r===f.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const i=_e(e[r],t[r]);if(!i.valid)return{valid:!1};n.push(i.data)}return{valid:!0,data:n}}return n===f.date&&r===f.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}we.create=(e,t)=>new we({options:e,typeName:Ue.ZodUnion,...P(t)});class Ie extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(x(e)||x(r))return I;const i=_e(e.value,r.value);return i.valid?((A(e)||A(r))&&t.dirty(),{status:t.value,value:i.data}):(w(n,{code:m.invalid_intersection_types}),I)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ie.create=(e,t,n)=>new Ie({left:e,right:t,typeName:Ue.ZodIntersection,...P(n)});class Ce extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return w(n,{code:m.invalid_type,expected:f.array,received:n.parsedType}),I;if(n.data.length<this._def.items.length)return w(n,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;!this._def.rest&&n.data.length>this._def.items.length&&(w(n,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new O(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>_.mergeArray(t,e)):_.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Ce({...this._def,rest:e})}}Ce.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ce({items:e,typeName:Ue.ZodTuple,rest:null,...P(t)})};class Te extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return w(n,{code:m.invalid_type,expected:f.object,received:n.parsedType}),I;const r=[],i=this._def.keyType,s=this._def.valueType;for(const o in n.data)r.push({key:i._parse(new O(n,o,n.path,o)),value:s._parse(new O(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?_.mergeObjectAsync(t,r):_.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new Te(t instanceof q?{keyType:e,valueType:t,typeName:Ue.ZodRecord,...P(n)}:{keyType:ie.create(),valueType:e,typeName:Ue.ZodRecord,...P(t)})}}class xe extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return w(n,{code:m.invalid_type,expected:f.map,received:n.parsedType}),I;const r=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([e,t],s)=>({key:r._parse(new O(n,e,n.path,[s,"key"])),value:i._parse(new O(n,t,n.path,[s,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of s){const r=await n.key,i=await n.value;if("aborted"===r.status||"aborted"===i.status)return I;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of s){const r=n.key,i=n.value;if("aborted"===r.status||"aborted"===i.status)return I;"dirty"!==r.status&&"dirty"!==i.status||t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}}xe.create=(e,t,n)=>new xe({valueType:t,keyType:e,typeName:Ue.ZodMap,...P(n)});class Ae extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return w(n,{code:m.invalid_type,expected:f.set,received:n.parsedType}),I;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(w(n,{code:m.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(w(n,{code:m.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function s(e){const n=new Set;for(const r of e){if("aborted"===r.status)return I;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>i._parse(new O(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>s(e)):s(o)}min(e,t){return new Ae({...this._def,minSize:{value:e,message:R.toString(t)}})}max(e,t){return new Ae({...this._def,maxSize:{value:e,message:R.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ae.create=(e,t)=>new Ae({valueType:e,minSize:null,maxSize:null,typeName:Ue.ZodSet,...P(t)});class ke extends q{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ke.create=(e,t)=>new ke({getter:e,typeName:Ue.ZodLazy,...P(t)});class Se extends q{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return w(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Re(e,t){return new Ee({values:e,typeName:Ue.ZodEnum,...P(t)})}Se.create=(e,t)=>new Se({value:e,typeName:Ue.ZodLiteral,...P(t)});class Ee extends q{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{expected:l.joinValues(n),received:t.parsedType,code:m.invalid_type}),I}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{received:t.data,code:m.invalid_enum_value,options:n}),I}return T(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ee.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ee.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ee.create=Re;class Oe extends q{_parse(e){const t=l.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){const e=l.objectValues(t);return w(n,{expected:l.joinValues(e),received:n.parsedType,code:m.invalid_type}),I}if(this._cache||(this._cache=new Set(l.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=l.objectValues(t);return w(n,{received:n.data,code:m.invalid_enum_value,options:e}),I}return T(e.data)}get enum(){return this._def.values}}Oe.create=(e,t)=>new Oe({values:e,typeName:Ue.ZodNativeEnum,...P(t)});class Ne extends q{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&!1===t.common.async)return w(t,{code:m.invalid_type,expected:f.promise,received:t.parsedType}),I;const n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return T(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:Ue.ZodPromise,...P(t)});class Pe extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ue.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{w(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===r.type){const e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return I;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?I:"dirty"===r.status||"dirty"===t.value?C(r.value):r});{if("aborted"===t.value)return I;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?I:"dirty"===r.status||"dirty"===t.value?C(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?I:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?I:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===r.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!k(e))return I;const s=r.transform(e.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>k(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):I)}l.assertNever(r)}}Pe.create=(e,t,n)=>new Pe({schema:e,typeName:Ue.ZodEffects,effect:t,...P(n)}),Pe.createWithPreprocess=(e,t,n)=>new Pe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ue.ZodEffects,...P(n)});class qe extends q{_parse(e){return this._getType(e)===f.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:Ue.ZodOptional,...P(t)});class $e extends q{_parse(e){return this._getType(e)===f.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}$e.create=(e,t)=>new $e({innerType:e,typeName:Ue.ZodNullable,...P(t)});class Me extends q{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:Ue.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...P(t)});class Fe extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return S(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Fe.create=(e,t)=>new Fe({innerType:e,typeName:Ue.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...P(t)});class je extends q{_parse(e){if(this._getType(e)!==f.nan){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:f.nan,received:t.parsedType}),I}return{status:"valid",value:e.data}}}je.create=e=>new je({typeName:Ue.ZodNaN,...P(e)});class Be extends q{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class De extends q{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?I:"dirty"===e.status?(t.dirty(),C(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})()}{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?I:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new De({in:e,out:t,typeName:Ue.ZodPipeline})}}class Le extends q{_parse(e){const t=this._def.innerType._parse(e),n=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return S(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var Ue,Ze;Le.create=(e,t)=>new Le({innerType:e,typeName:Ue.ZodReadonly,...P(t)}),(Ze=Ue||(Ue={})).ZodString="ZodString",Ze.ZodNumber="ZodNumber",Ze.ZodNaN="ZodNaN",Ze.ZodBigInt="ZodBigInt",Ze.ZodBoolean="ZodBoolean",Ze.ZodDate="ZodDate",Ze.ZodSymbol="ZodSymbol",Ze.ZodUndefined="ZodUndefined",Ze.ZodNull="ZodNull",Ze.ZodAny="ZodAny",Ze.ZodUnknown="ZodUnknown",Ze.ZodNever="ZodNever",Ze.ZodVoid="ZodVoid",Ze.ZodArray="ZodArray",Ze.ZodObject="ZodObject",Ze.ZodUnion="ZodUnion",Ze.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ze.ZodIntersection="ZodIntersection",Ze.ZodTuple="ZodTuple",Ze.ZodRecord="ZodRecord",Ze.ZodMap="ZodMap",Ze.ZodSet="ZodSet",Ze.ZodFunction="ZodFunction",Ze.ZodLazy="ZodLazy",Ze.ZodLiteral="ZodLiteral",Ze.ZodEnum="ZodEnum",Ze.ZodEffects="ZodEffects",Ze.ZodNativeEnum="ZodNativeEnum",Ze.ZodOptional="ZodOptional",Ze.ZodNullable="ZodNullable",Ze.ZodDefault="ZodDefault",Ze.ZodCatch="ZodCatch",Ze.ZodPromise="ZodPromise",Ze.ZodBranded="ZodBranded",Ze.ZodPipeline="ZodPipeline",Ze.ZodReadonly="ZodReadonly";const Ke=ie.create,ze=oe.create,He=ce.create,Ve=fe.create;ge.create;const We=ye.create,Je=be.create,Ge=we.create;Ie.create,Ce.create;const Xe=Te.create,Qe=Ee.create,Ye=Oe.create;Ne.create,qe.create,$e.create;const et=Je({name:Ke().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:Ke().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:Ke().optional().describe("Optional custom username/alias for the agent"),type:Qe(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:Ke().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:We(Ye(r.AIAgentCapability)).optional().describe("Array of agent capabilities (default: [TEXT_GENERATION])"),creator:Ke().optional().describe("Creator attribution for the agent"),socials:Xe(Qe(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),Ke()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:Xe(Ve()).optional().describe("Custom metadata properties for the agent"),profilePicture:Ge([Ke().describe("URL or local file path to profile picture"),Je({url:Ke().optional(),path:Ke().optional(),filename:Ke().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:Ke().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:ze().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:Ke().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:ze().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:We(Je({amount:ze().positive(),tokenId:Ke()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:We(Ke()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:He().optional().describe("Whether to set as current agent (default: true)"),persistence:Je({prefix:Ke().optional()}).optional().describe("Optional persistence configuration")});class tt extends u{constructor(e){super(e),this.name="register_agent",this.description="Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. Note: This tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=et,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,r={name:t.name};if(void 0!==t.description&&(r.bio=t.description),void 0!==t.alias&&(r.alias=t.alias),void 0!==t.type&&(r.type=t.type),void 0!==t.model&&(r.model=t.model),void 0!==t.capabilities&&(r.capabilities=t.capabilities),void 0!==t.creator&&(r.creator=t.creator),void 0!==t.socials&&(r.socials=t.socials),void 0!==t.properties&&(r.properties=t.properties),void 0!==t.profilePicture)if("string"==typeof t.profilePicture)r.profilePicture=t.profilePicture;else{const e={};void 0!==t.profilePicture.url&&(e.url=t.profilePicture.url),void 0!==t.profilePicture.path&&(e.path=t.profilePicture.path),void 0!==t.profilePicture.filename&&(e.filename=t.profilePicture.filename),r.profilePicture=e}void 0!==t.existingProfilePictureTopicId&&(r.existingProfilePictureTopicId=t.existingProfilePictureTopicId),void 0!==t.userAccountId&&(r.userAccountId=t.userAccountId),void 0!==t.hbarFee&&(r.hbarFee=t.hbarFee),void 0!==t.tokenFees&&(r.tokenFees=t.tokenFees),void 0!==t.exemptAccountIds&&(r.exemptAccountIds=t.exemptAccountIds),void 0!==t.initialBalance&&(r.initialBalance=t.initialBalance),await n.registerAgent(r)}}const nt=Je({targetIdentifier:Ke().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),message:Ke().describe("The text message content to send."),disableMonitoring:He().optional().default(!1)});class rt extends u{constructor(e){super(e),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.specificInputSchema=nt,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e;await n.sendMessageToConnection({targetIdentifier:t.targetIdentifier,message:t.message,disableMonitoring:t.disableMonitoring})}}const it=Je({targetAccountId:Ke().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:He().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:Ke().optional().describe('Optional memo to include with the connection request (e.g., "Hello from Alice"). If not provided, defaults to "true" or "false" based on monitoring preference.')});class st extends u{constructor(e){super(e),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.specificInputSchema=it,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e,r={targetAccountId:t.targetAccountId};void 0!==t.disableMonitor&&(r.disableMonitor=t.disableMonitor),void 0!==t.memo&&(r.memo=t.memo),await n.initiateConnection(r)}}const ot=Je({includeDetails:He().optional().describe("Whether to include detailed information about each connection"),showPending:He().optional().describe("Whether to include pending connection requests")});class at extends d{constructor(e){super(e),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.specificInputSchema=ot}async executeQuery(e){const t=this.hcs10Builder,n={};void 0!==e.includeDetails&&(n.includeDetails=e.includeDetails),void 0!==e.showPending&&(n.showPending=e.showPending),await t.listConnections(n);const r=await t.execute();if(r.success&&"rawResult"in r&&r.rawResult){const e=r.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Connections listed"}}return r}}const ct=Je({targetIdentifier:Ke().describe("The account ID (e.g., 0.0.12345) of the target agent OR the connection number (e.g., '1', '2') from the 'list_connections' tool to check messages for."),fetchLatest:He().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:ze().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class ut extends d{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=ct}async executeQuery({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n}){const r=this.hcs10Builder;await r.checkMessages({targetIdentifier:e,fetchLatest:t,lastMessagesCount:n||1});const i=await r.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Messages checked"}}return i}}const dt=Je({accountId:Ke().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:We(Ye(r.AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")});class lt extends d{constructor(e){super(e),this.name="find_registrations",this.description="Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags. Returns basic registration info.",this.specificInputSchema=dt}async executeQuery({accountId:e,tags:t}){const n=this.hcs10Builder,r={};e&&(r.accountId=e),t&&(r.tags=t),await n.findRegistrations(r);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.formattedOutput||e.message||"Registrations searched"}}return i}}const ht=Je({acceptAll:He().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:Ke().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:We(Je({amount:ze(),collectorAccount:Ke().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:We(Je({amount:ze(),tokenId:Ke(),collectorAccount:Ke().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:We(Ke()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:ze().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:Ke().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class pt extends u{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=ht,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.monitorConnections({...void 0!==t.acceptAll&&{acceptAll:t.acceptAll},...void 0!==t.targetAccountId&&{targetAccountId:t.targetAccountId},...void 0!==t.monitorDurationSeconds&&{monitorDurationSeconds:t.monitorDurationSeconds},hbarFees:t.hbarFees||[],tokenFees:t.tokenFees||[],...void 0!==t.exemptAccountIds&&{exemptAccountIds:t.exemptAccountIds},...void 0!==t.defaultCollectorAccount&&{defaultCollectorAccount:t.defaultCollectorAccount}})}}const ft=Je({action:Qe(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:Ke().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class gt extends d{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=ft}async executeQuery({action:e,requestKey:t}){const n=this.hcs10Builder,r={action:e};void 0!==t&&(r.requestKey=t),await n.manageConnectionRequests(r);const i=await n.execute();return"rawResult"in i?i.rawResult:i}}const mt=Je({requestKey:Ke().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:ze().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:We(Ke()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class yt extends u{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=mt,this.neverScheduleThisTool=!0,this.requiresMultipleTransactions=!0}async callBuilderMethod(e,t){const n=e;await n.acceptConnection({requestKey:t.requestKey,hbarFee:t.hbarFee,exemptAccountIds:t.exemptAccountIds})}}const vt=Je({accountId:Ke().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:He().optional().describe("Optional: Force refresh from the network instead of using cache.")});class bt extends d{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=vt}async executeQuery({accountId:e,disableCache:t}){const n=this.hcs10Builder,r={accountId:e};void 0!==t&&(r.disableCache=t),await n.retrieveProfile(r);const i=await n.execute();if(i.success&&"rawResult"in i&&i.rawResult){const e=i.rawResult;return{success:!0,data:e.profileDetails||"Profile retrieved",rawProfile:e.rawProfile}}return i}}const wt=Je({});class _t extends d{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=wt}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}const It=s.join(c.cwd(),".env");class Ct{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const t=e?.disableLogging||"true"===c.env.DISABLE_LOGGING;this.logger=new r.Logger({module:"OpenConvaiState",silent:t}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new r.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const r=this.connectionsManager.getConnectionByTopicId(e);if(r)return this.convertToActiveConnection(r);const i=this.connectionsManager.getConnectionByAccountId(e);return i?this.convertToActiveConnection(i):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||c.env.ENV_FILE_PATH||".env",r=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const s={[`${r}_ACCOUNT_ID`]:e.accountId,[`${r}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${r}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${r}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${r}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";i.existsSync(e)&&(n=i.readFileSync(e,"utf8"));const r=[...n.split("\n")];for(const[i,s]of Object.entries(t)){const e=r.findIndex(e=>e.startsWith(`${i}=`));-1!==e?r[e]=`${i}=${s}`:r.push(`${i}=${s}`)}i.writeFileSync(e,r.join("\n"))}(n,s)}}function Tt(e,t){return function(){return e.apply(t,arguments)}}const{toString:xt}=Object.prototype,{getPrototypeOf:At}=Object,{iterator:kt,toStringTag:St}=Symbol,Rt=(e=>t=>{const n=xt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Et=e=>(e=e.toLowerCase(),t=>Rt(t)===e),Ot=e=>t=>typeof t===e,{isArray:Nt}=Array,Pt=Ot("undefined");const qt=Et("ArrayBuffer");const $t=Ot("string"),Mt=Ot("function"),Ft=Ot("number"),jt=e=>null!==e&&"object"==typeof e,Bt=e=>{if("object"!==Rt(e))return!1;const t=At(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||St in e||kt in e)},Dt=Et("Date"),Lt=Et("File"),Ut=Et("Blob"),Zt=Et("FileList"),Kt=Et("URLSearchParams"),[zt,Ht,Vt,Wt]=["ReadableStream","Request","Response","Headers"].map(Et);function Jt(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let r,i;if("object"!=typeof e&&(e=[e]),Nt(e))for(r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else{const i=n?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length;let o;for(r=0;r<s;r++)o=i[r],t.call(null,e[o],o,e)}}function Gt(e,t){t=t.toLowerCase();const n=Object.keys(e);let r,i=n.length;for(;i-- >0;)if(r=n[i],t===r.toLowerCase())return r;return null}const Xt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:o,Qt=e=>!Pt(e)&&e!==Xt;const Yt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&At(Uint8Array)),en=Et("HTMLFormElement"),tn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),nn=Et("RegExp"),rn=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Jt(n,(n,i)=>{let s;!1!==(s=t(n,i,e))&&(r[i]=s||n)}),Object.defineProperties(e,r)};const sn=Et("AsyncFunction"),on=(an="function"==typeof a.setImmediate,cn=Mt(Xt.postMessage),an?a.setImmediate:cn?(un=`axios@${Math.random()}`,dn=[],Xt.addEventListener("message",({source:e,data:t})=>{e===Xt&&t===un&&dn.length&&dn.shift()()},!1),e=>{dn.push(e),Xt.postMessage(un,"*")}):e=>setTimeout(e));var an,cn,un,dn;const ln="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Xt):void 0!==c&&c.nextTick||on,hn={isArray:Nt,isArrayBuffer:qt,isBuffer:function(e){return null!==e&&!Pt(e)&&null!==e.constructor&&!Pt(e.constructor)&&Mt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Mt(e.append)&&("formdata"===(t=Rt(e))||"object"===t&&Mt(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&qt(e.buffer),t},isString:$t,isNumber:Ft,isBoolean:e=>!0===e||!1===e,isObject:jt,isPlainObject:Bt,isReadableStream:zt,isRequest:Ht,isResponse:Vt,isHeaders:Wt,isUndefined:Pt,isDate:Dt,isFile:Lt,isBlob:Ut,isRegExp:nn,isFunction:Mt,isStream:e=>jt(e)&&Mt(e.pipe),isURLSearchParams:Kt,isTypedArray:Yt,isFileList:Zt,forEach:Jt,merge:function e(){const{caseless:t}=Qt(this)&&this||{},n={},r=(r,i)=>{const s=t&&Gt(n,i)||i;Bt(n[s])&&Bt(r)?n[s]=e(n[s],r):Bt(r)?n[s]=e({},r):Nt(r)?n[s]=r.slice():n[s]=r};for(let i=0,s=arguments.length;i<s;i++)arguments[i]&&Jt(arguments[i],r);return n},extend:(e,t,n,{allOwnKeys:r}={})=>(Jt(t,(t,r)=>{n&&Mt(t)?e[r]=Tt(t,n):e[r]=t},{allOwnKeys:r}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,r)=>{let i,s,o;const a={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],r&&!r(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==n&&At(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Rt,kindOfTest:Et,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return-1!==r&&r===n},toArray:e=>{if(!e)return null;if(Nt(e))return e;let t=e.length;if(!Ft(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[kt]).call(e);let r;for(;(r=n.next())&&!r.done;){const n=r.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const r=[];for(;null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:en,hasOwnProperty:tn,hasOwnProp:tn,reduceDescriptors:rn,freezeMethods:e=>{rn(e,(t,n)=>{if(Mt(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=e[n];Mt(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},r=e=>{e.forEach(e=>{n[e]=!0})};return Nt(e)?r(e):r(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Gt,global:Xt,isContextDefined:Qt,isSpecCompliantForm:function(e){return!!(e&&Mt(e.append)&&"FormData"===e[St]&&e[kt])},toJSONObject:e=>{const t=new Array(10),n=(e,r)=>{if(jt(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[r]=e;const i=Nt(e)?[]:{};return Jt(e,(e,t)=>{const s=n(e,r+1);!Pt(s)&&(i[t]=s)}),t[r]=void 0,i}}return e};return n(e,0)},isAsyncFn:sn,isThenable:e=>e&&(jt(e)||Mt(e))&&Mt(e.then)&&Mt(e.catch),setImmediate:on,asap:ln,isIterable:e=>null!=e&&Mt(e[kt])};function pn(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}hn.inherits(pn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:hn.toJSONObject(this.config),code:this.code,status:this.status}}});const fn=pn.prototype,gn={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{gn[e]={value:e}}),Object.defineProperties(pn,gn),Object.defineProperty(fn,"isAxiosError",{value:!0}),pn.from=(e,t,n,r,i,s)=>{const o=Object.create(fn);return hn.toFlatObject(e,o,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),pn.call(o,e.message,t,n,r,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};function mn(e){return hn.isPlainObject(e)||hn.isArray(e)}function yn(e){return hn.endsWith(e,"[]")?e.slice(0,-2):e}function vn(e,t,n){return e?e.concat(t).map(function(e,t){return e=yn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const bn=hn.toFlatObject(hn,{},null,function(e){return/^is[A-Z]/.test(e)});function wn(e,n,r){if(!hn.isObject(e))throw new TypeError("target must be an object");n=n||new FormData;const i=(r=hn.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!hn.isUndefined(t[e])})).metaTokens,s=r.visitor||d,o=r.dots,a=r.indexes,c=(r.Blob||"undefined"!=typeof Blob&&Blob)&&hn.isSpecCompliantForm(n);if(!hn.isFunction(s))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(hn.isDate(e))return e.toISOString();if(hn.isBoolean(e))return e.toString();if(!c&&hn.isBlob(e))throw new pn("Blob is not supported. Use a Buffer instead.");return hn.isArrayBuffer(e)||hn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):t.Buffer.from(e):e}function d(e,t,r){let s=e;if(e&&!r&&"object"==typeof e)if(hn.endsWith(t,"{}"))t=i?t:t.slice(0,-2),e=JSON.stringify(e);else if(hn.isArray(e)&&function(e){return hn.isArray(e)&&!e.some(mn)}(e)||(hn.isFileList(e)||hn.endsWith(t,"[]"))&&(s=hn.toArray(e)))return t=yn(t),s.forEach(function(e,r){!hn.isUndefined(e)&&null!==e&&n.append(!0===a?vn([t],r,o):null===a?t:t+"[]",u(e))}),!1;return!!mn(e)||(n.append(vn(r,t,o),u(e)),!1)}const l=[],h=Object.assign(bn,{defaultVisitor:d,convertValue:u,isVisitable:mn});if(!hn.isObject(e))throw new TypeError("data must be an object");return function e(t,r){if(!hn.isUndefined(t)){if(-1!==l.indexOf(t))throw Error("Circular reference detected in "+r.join("."));l.push(t),hn.forEach(t,function(t,i){!0===(!(hn.isUndefined(t)||null===t)&&s.call(n,t,hn.isString(i)?i.trim():i,r,h))&&e(t,r?r.concat(i):[i])}),l.pop()}}(e),n}function _n(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function In(e,t){this._pairs=[],e&&wn(e,this,t)}const Cn=In.prototype;function Tn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xn(e,t,n){if(!t)return e;const r=n&&n.encode||Tn;hn.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let s;if(s=i?i(t,n):hn.isURLSearchParams(t)?t.toString():new In(t,n).toString(r),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Cn.append=function(e,t){this._pairs.push([e,t])},Cn.toString=function(e){const t=e?function(t){return e.call(this,t,_n)}:_n;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class An{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){hn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const kn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Sn={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:In,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Rn="undefined"!=typeof window&&"undefined"!=typeof document,En="object"==typeof navigator&&navigator||void 0,On=Rn&&(!En||["ReactNative","NativeScript","NS"].indexOf(En.product)<0),Nn="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Pn=Rn&&window.location.href||"http://localhost",qn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Rn,hasStandardBrowserEnv:On,hasStandardBrowserWebWorkerEnv:Nn,navigator:En,origin:Pn},Symbol.toStringTag,{value:"Module"})),...Sn};function $n(e){function t(e,n,r,i){let s=e[i++];if("__proto__"===s)return!0;const o=Number.isFinite(+s),a=i>=e.length;if(s=!s&&hn.isArray(r)?r.length:s,a)return hn.hasOwnProp(r,s)?r[s]=[r[s],n]:r[s]=n,!o;r[s]&&hn.isObject(r[s])||(r[s]=[]);return t(e,n,r[s],i)&&hn.isArray(r[s])&&(r[s]=function(e){const t={},n=Object.keys(e);let r;const i=n.length;let s;for(r=0;r<i;r++)s=n[r],t[s]=e[s];return t}(r[s])),!o}if(hn.isFormData(e)&&hn.isFunction(e.entries)){const n={};return hn.forEachEntry(e,(e,r)=>{t(function(e){return hn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),r,n,0)}),n}return null}const Mn={transitional:kn,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",r=n.indexOf("application/json")>-1,i=hn.isObject(e);i&&hn.isHTMLForm(e)&&(e=new FormData(e));if(hn.isFormData(e))return r?JSON.stringify($n(e)):e;if(hn.isArrayBuffer(e)||hn.isBuffer(e)||hn.isStream(e)||hn.isFile(e)||hn.isBlob(e)||hn.isReadableStream(e))return e;if(hn.isArrayBufferView(e))return e.buffer;if(hn.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return wn(e,new qn.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,r){return qn.isNode&&hn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=hn.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return wn(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return i||r?(t.setContentType("application/json",!1),function(e,t,n){if(hn.isString(e))try{return(t||JSON.parse)(e),hn.trim(e)}catch(r){if("SyntaxError"!==r.name)throw r}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Mn.transitional,n=t&&t.forcedJSONParsing,r="json"===this.responseType;if(hn.isResponse(e)||hn.isReadableStream(e))return e;if(e&&hn.isString(e)&&(n&&!this.responseType||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e)}catch(i){if(n){if("SyntaxError"===i.name)throw pn.from(i,pn.ERR_BAD_RESPONSE,this,null,this.response);throw i}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:qn.classes.FormData,Blob:qn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};hn.forEach(["delete","get","head","post","put","patch"],e=>{Mn.headers[e]={}});const Fn=hn.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),jn=Symbol("internals");function Bn(e){return e&&String(e).trim().toLowerCase()}function Dn(e){return!1===e||null==e?e:hn.isArray(e)?e.map(Dn):String(e)}function Ln(e,t,n,r,i){return hn.isFunction(r)?r.call(this,t,n):(i&&(t=n),hn.isString(t)?hn.isString(r)?-1!==t.indexOf(r):hn.isRegExp(r)?r.test(t):void 0:void 0)}let Un=class{constructor(e){e&&this.set(e)}set(e,t,n){const r=this;function i(e,t,n){const i=Bn(t);if(!i)throw new Error("header name must be a non-empty string");const s=hn.findKey(r,i);(!s||void 0===r[s]||!0===n||void 0===n&&!1!==r[s])&&(r[s||t]=Dn(e))}const s=(e,t)=>hn.forEach(e,(e,n)=>i(e,n,t));if(hn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(hn.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,r,i;return e&&e.split("\n").forEach(function(e){i=e.indexOf(":"),n=e.substring(0,i).trim().toLowerCase(),r=e.substring(i+1).trim(),!n||t[n]&&Fn[n]||("set-cookie"===n?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t})(e),t);else if(hn.isObject(e)&&hn.isIterable(e)){let n,r,i={};for(const t of e){if(!hn.isArray(t))throw TypeError("Object iterator must return a key-value pair");i[r=t[0]]=(n=i[r])?hn.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(i,t)}else null!=e&&i(t,e,n);return this}get(e,t){if(e=Bn(e)){const n=hn.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}(e);if(hn.isFunction(t))return t.call(this,e,n);if(hn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Bn(e)){const n=hn.findKey(this,e);return!(!n||void 0===this[n]||t&&!Ln(0,this[n],n,t))}return!1}delete(e,t){const n=this;let r=!1;function i(e){if(e=Bn(e)){const i=hn.findKey(n,e);!i||t&&!Ln(0,n[i],i,t)||(delete n[i],r=!0)}}return hn.isArray(e)?e.forEach(i):i(e),r}clear(e){const t=Object.keys(this);let n=t.length,r=!1;for(;n--;){const i=t[n];e&&!Ln(0,this[i],i,e,!0)||(delete this[i],r=!0)}return r}normalize(e){const t=this,n={};return hn.forEach(this,(r,i)=>{const s=hn.findKey(n,i);if(s)return t[s]=Dn(r),void delete t[i];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(i):String(i).trim();o!==i&&delete t[i],t[o]=Dn(r),n[o]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return hn.forEach(this,(n,r)=>{null!=n&&!1!==n&&(t[r]=e&&hn.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){const t=(this[jn]=this[jn]={accessors:{}}).accessors,n=this.prototype;function r(e){const r=Bn(e);t[r]||(!function(e,t){const n=hn.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(e,n,i){return this[r].call(this,t,e,n,i)},configurable:!0})})}(n,e),t[r]=!0)}return hn.isArray(e)?e.forEach(r):r(e),this}};function Zn(e,t){const n=this||Mn,r=t||n,i=Un.from(r.headers);let s=r.data;return hn.forEach(e,function(e){s=e.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function Kn(e){return!(!e||!e.__CANCEL__)}function zn(e,t,n){pn.call(this,null==e?"canceled":e,pn.ERR_CANCELED,t,n),this.name="CanceledError"}function Hn(e,t,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?t(new pn("Request failed with status code "+n.status,[pn.ERR_BAD_REQUEST,pn.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}Un.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),hn.reduceDescriptors(Un.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),hn.freezeMethods(Un),hn.inherits(zn,pn,{__CANCEL__:!0});const Vn=(e,t,n=3)=>{let r=0;const i=function(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i,s=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),u=r[o];i||(i=c),n[s]=a,r[s]=c;let d=o,l=0;for(;d!==s;)l+=n[d++],d%=e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),c-i<t)return;const h=u&&c-u;return h?Math.round(1e3*l/h):void 0}}(50,250);return function(e,t){let n,r,i=0,s=1e3/t;const o=(t,s=Date.now())=>{i=s,n=null,r&&(clearTimeout(r),r=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-i;a>=s?o(e,t):(n=e,r||(r=setTimeout(()=>{r=null,o(n)},s-a)))},()=>n&&o(n)]}(n=>{const s=n.loaded,o=n.lengthComputable?n.total:void 0,a=s-r,c=i(a);r=s;e({loaded:s,total:o,progress:o?s/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&s<=o?(o-s)/c:void 0,event:n,lengthComputable:null!=o,[t?"download":"upload"]:!0})},n)},Wn=(e,t)=>{const n=null!=e;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Jn=e=>(...t)=>hn.asap(()=>e(...t)),Gn=qn.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,qn.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(qn.origin),qn.navigator&&/(msie|trident)/i.test(qn.navigator.userAgent)):()=>!0,Xn=qn.hasStandardBrowserEnv?{write(e,t,n,r,i,s){const o=[e+"="+encodeURIComponent(t)];hn.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),hn.isString(r)&&o.push("path="+r),hn.isString(i)&&o.push("domain="+i),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Qn(e,t,n){let r=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(r||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Yn=e=>e instanceof Un?{...e}:e;function er(e,t){t=t||{};const n={};function r(e,t,n,r){return hn.isPlainObject(e)&&hn.isPlainObject(t)?hn.merge.call({caseless:r},e,t):hn.isPlainObject(t)?hn.merge({},t):hn.isArray(t)?t.slice():t}function i(e,t,n,i){return hn.isUndefined(t)?hn.isUndefined(e)?void 0:r(void 0,e,0,i):r(e,t,0,i)}function s(e,t){if(!hn.isUndefined(t))return r(void 0,t)}function o(e,t){return hn.isUndefined(t)?hn.isUndefined(e)?void 0:r(void 0,e):r(void 0,t)}function a(n,i,s){return s in t?r(n,i):s in e?r(void 0,n):void 0}const c={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,n)=>i(Yn(e),Yn(t),0,!0)};return hn.forEach(Object.keys(Object.assign({},e,t)),function(r){const s=c[r]||i,o=s(e[r],t[r],r);hn.isUndefined(o)&&s!==a||(n[r]=o)}),n}const tr=e=>{const t=er({},e);let n,{data:r,withXSRFToken:i,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Un.from(a),t.url=xn(Qn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),hn.isFormData(r))if(qn.hasStandardBrowserEnv||qn.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(n=a.getContentType())){const[e,...t]=n?n.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(qn.hasStandardBrowserEnv&&(i&&hn.isFunction(i)&&(i=i(t)),i||!1!==i&&Gn(t.url))){const e=s&&o&&Xn.read(o);e&&a.set(s,e)}return t},nr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const r=tr(e);let i=r.data;const s=Un.from(r.headers).normalize();let o,a,c,u,d,{responseType:l,onUploadProgress:h,onDownloadProgress:p}=r;function f(){u&&u(),d&&d(),r.cancelToken&&r.cancelToken.unsubscribe(o),r.signal&&r.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const r=Un.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Hn(function(e){t(e),f()},function(e){n(e),f()},{data:l&&"text"!==l&&"json"!==l?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:r,config:e,request:g}),g=null}g.open(r.method.toUpperCase(),r.url,!0),g.timeout=r.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(n(new pn("Request aborted",pn.ECONNABORTED,e,g)),g=null)},g.onerror=function(){n(new pn("Network Error",pn.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const i=r.transitional||kn;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),n(new pn(t,i.clarifyTimeoutError?pn.ETIMEDOUT:pn.ECONNABORTED,e,g)),g=null},void 0===i&&s.setContentType(null),"setRequestHeader"in g&&hn.forEach(s.toJSON(),function(e,t){g.setRequestHeader(t,e)}),hn.isUndefined(r.withCredentials)||(g.withCredentials=!!r.withCredentials),l&&"json"!==l&&(g.responseType=r.responseType),p&&([c,d]=Vn(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,u]=Vn(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",u)),(r.cancelToken||r.signal)&&(o=t=>{g&&(n(!t||t.type?new zn(null,e,g):t),g.abort(),g=null)},r.cancelToken&&r.cancelToken.subscribe(o),r.signal&&(r.signal.aborted?o():r.signal.addEventListener("abort",o)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(r.url);y&&-1===qn.protocols.indexOf(y)?n(new pn("Unsupported protocol "+y+":",pn.ERR_BAD_REQUEST,e)):g.send(i||null)})},rr=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,r=new AbortController;const i=function(e){if(!n){n=!0,o();const t=e instanceof Error?e:this.reason;r.abort(t instanceof pn?t:new zn(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,i(new pn(`timeout ${t} of ms exceeded`,pn.ETIMEDOUT))},t);const o=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(i):e.removeEventListener("abort",i)}),e=null)};e.forEach(e=>e.addEventListener("abort",i));const{signal:a}=r;return a.unsubscribe=()=>hn.asap(o),a}},ir=function*(e,t){let n=e.byteLength;if(n<t)return void(yield e);let r,i=0;for(;i<n;)r=i+t,yield e.slice(i,r),i=r},sr=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)break;yield n}}finally{await t.cancel()}},or=(e,t,n,r)=>{const i=async function*(e,t){for await(const n of sr(e))yield*ir(n,t)}(e,t);let s,o=0,a=e=>{s||(s=!0,r&&r(e))};return new ReadableStream({async pull(e){try{const{done:t,value:r}=await i.next();if(t)return a(),void e.close();let s=r.byteLength;if(n){let e=o+=s;n(e)}e.enqueue(new Uint8Array(r))}catch(t){throw a(t),t}},cancel:e=>(a(e),i.return())},{highWaterMark:2})},ar="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,cr=ar&&"function"==typeof ReadableStream,ur=ar&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),dr=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},lr=cr&&dr(()=>{let e=!1;const t=new Request(qn.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),hr=cr&&dr(()=>hn.isReadableStream(new Response("").body)),pr={stream:hr&&(e=>e.body)};var fr;ar&&(fr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!pr[e]&&(pr[e]=hn.isFunction(fr[e])?t=>t[e]():(t,n)=>{throw new pn(`Response type '${e}' is not supported`,pn.ERR_NOT_SUPPORT,n)})}));const gr=async(e,t)=>{const n=hn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(hn.isBlob(e))return e.size;if(hn.isSpecCompliantForm(e)){const t=new Request(qn.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return hn.isArrayBufferView(e)||hn.isArrayBuffer(e)?e.byteLength:(hn.isURLSearchParams(e)&&(e+=""),hn.isString(e)?(await ur(e)).byteLength:void 0)})(t):n},mr={http:null,xhr:nr,fetch:ar&&(async e=>{let{url:t,method:n,data:r,signal:i,cancelToken:s,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:u,headers:d,withCredentials:l="same-origin",fetchOptions:h}=tr(e);u=u?(u+"").toLowerCase():"text";let p,f=rr([i,s&&s.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&lr&&"get"!==n&&"head"!==n&&0!==(m=await gr(d,r))){let e,n=new Request(t,{method:"POST",body:r,duplex:"half"});if(hn.isFormData(r)&&(e=n.headers.get("content-type"))&&d.setContentType(e),n.body){const[e,t]=Wn(m,Vn(Jn(c)));r=or(n.body,65536,e,t)}}hn.isString(l)||(l=l?"include":"omit");const i="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:n.toUpperCase(),headers:d.normalize().toJSON(),body:r,duplex:"half",credentials:i?l:void 0});let s=await fetch(p,h);const o=hr&&("stream"===u||"response"===u);if(hr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=hn.toFiniteNumber(s.headers.get("content-length")),[n,r]=a&&Wn(t,Vn(Jn(a),!0))||[];s=new Response(or(s.body,65536,n,()=>{r&&r(),g&&g()}),e)}u=u||"text";let y=await pr[hn.findKey(pr,u)||"text"](s,e);return!o&&g&&g(),await new Promise((t,n)=>{Hn(t,n,{data:y,headers:Un.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:p})})}catch(y){if(g&&g(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new pn("Network Error",pn.ERR_NETWORK,e,p),{cause:y.cause||y});throw pn.from(y,y&&y.code,e,p)}})};hn.forEach(mr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const yr=e=>`- ${e}`,vr=e=>hn.isFunction(e)||null===e||!1===e,br=e=>{e=hn.isArray(e)?e:[e];const{length:t}=e;let n,r;const i={};for(let s=0;s<t;s++){let t;if(n=e[s],r=n,!vr(n)&&(r=mr[(t=String(n)).toLowerCase()],void 0===r))throw new pn(`Unknown adapter '${t}'`);if(r)break;i[t||"#"+s]=r}if(!r){const e=Object.entries(i).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new pn("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(yr).join("\n"):" "+yr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return r};function wr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new zn(null,e)}function _r(e){wr(e),e.headers=Un.from(e.headers),e.data=Zn.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return br(e.adapter||Mn.adapter)(e).then(function(t){return wr(e),t.data=Zn.call(e,e.transformResponse,t),t.headers=Un.from(t.headers),t},function(t){return Kn(t)||(wr(e),t&&t.response&&(t.response.data=Zn.call(e,e.transformResponse,t.response),t.response.headers=Un.from(t.response.headers))),Promise.reject(t)})}const Ir="1.10.0",Cr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Cr[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Tr={};Cr.transitional=function(e,t,n){function r(e,t){return"[Axios v"+Ir+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,i,s)=>{if(!1===e)throw new pn(r(i," has been removed"+(t?" in "+t:"")),pn.ERR_DEPRECATED);return t&&!Tr[i]&&(Tr[i]=!0,console.warn(r(i," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,i,s)}},Cr.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const xr={assertOptions:function(e,t,n){if("object"!=typeof e)throw new pn("options must be an object",pn.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const t=e[s],n=void 0===t||o(t,s,e);if(!0!==n)throw new pn("option "+s+" must be "+n,pn.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new pn("Unknown option "+s,pn.ERR_BAD_OPTION)}},validators:Cr},Ar=xr.validators;let kr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new An,response:new An}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{n.stack?t&&!String(n.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(n.stack+="\n"+t):n.stack=t}catch(r){}}throw n}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=er(this.defaults,t);const{transitional:n,paramsSerializer:r,headers:i}=t;void 0!==n&&xr.assertOptions(n,{silentJSONParsing:Ar.transitional(Ar.boolean),forcedJSONParsing:Ar.transitional(Ar.boolean),clarifyTimeoutError:Ar.transitional(Ar.boolean)},!1),null!=r&&(hn.isFunction(r)?t.paramsSerializer={serialize:r}:xr.assertOptions(r,{encode:Ar.function,serialize:Ar.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xr.assertOptions(t,{baseUrl:Ar.spelling("baseURL"),withXsrfToken:Ar.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=i&&hn.merge(i.common,i[t.method]);i&&hn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete i[e]}),t.headers=Un.concat(s,i);const o=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))});const c=[];let u;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let d,l=0;if(!a){const e=[_r.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),d=e.length,u=Promise.resolve(t);l<d;)u=u.then(e[l++],e[l++]);return u}d=o.length;let h=t;for(l=0;l<d;){const e=o[l++],t=o[l++];try{h=e(h)}catch(p){t.call(this,p);break}}try{u=_r.call(this,h)}catch(p){return Promise.reject(p)}for(l=0,d=c.length;l<d;)u=u.then(c[l++],c[l++]);return u}getUri(e){return xn(Qn((e=er(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};hn.forEach(["delete","get","head","options"],function(e){kr.prototype[e]=function(t,n){return this.request(er(n||{},{method:e,url:t,data:(n||{}).data}))}}),hn.forEach(["post","put","patch"],function(e){function t(t){return function(n,r,i){return this.request(er(i||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}kr.prototype[e]=t(),kr.prototype[e+"Form"]=t(!0)});const Sr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Sr).forEach(([e,t])=>{Sr[t]=e});const Rr=function e(t){const n=new kr(t),r=Tt(kr.prototype.request,n);return hn.extend(r,kr.prototype,n,{allOwnKeys:!0}),hn.extend(r,n,null,{allOwnKeys:!0}),r.create=function(n){return e(er(t,n))},r}(Mn);Rr.Axios=kr,Rr.CanceledError=zn,Rr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const r=new Promise(e=>{n.subscribe(e),t=e}).then(e);return r.cancel=function(){n.unsubscribe(t)},r},e(function(e,r,i){n.reason||(n.reason=new zn(e,r,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},Rr.isCancel=Kn,Rr.VERSION=Ir,Rr.toFormData=wn,Rr.AxiosError=pn,Rr.Cancel=Rr.CanceledError,Rr.all=function(e){return Promise.all(e)},Rr.spread=function(e){return function(t){return e.apply(null,t)}},Rr.isAxiosError=function(e){return hn.isObject(e)&&!0===e.isAxiosError},Rr.mergeConfig=er,Rr.AxiosHeaders=Un,Rr.formToJSON=e=>$n(hn.isHTMLForm(e)?new FormData(e):e),Rr.getAdapter=br,Rr.HttpStatusCode=Sr,Rr.default=Rr;const{Axios:Er,AxiosError:Or,CanceledError:Nr,isCancel:Pr,CancelToken:qr,VERSION:$r,all:Mr,Cancel:Fr,isAxiosError:jr,spread:Br,toFormData:Dr,AxiosHeaders:Lr,HttpStatusCode:Ur,formToJSON:Zr,getAdapter:Kr,mergeConfig:zr}=Rr,Hr="ConnectionsManager not initialized";class Vr extends n.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const i=this.hederaKit.client.network;this.network=i.toString().includes("mainnet")?"mainnet":"testnet";const s=this.hederaKit.signer.getAccountId().toString(),o=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new r.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new r.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:o,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,n,r){try{const i=await this.standardClient.handleConnectionRequest(e,t,n,r);return i&&i.connectionTopicId&&"object"==typeof i.connectionTopicId&&"toString"in i.connectionTopicId&&(i.connectionTopicId=i.connectionTopicId.toString()),i}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async sendMessage(e,t,n){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const r=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:r.topicSequenceNumber?.toNumber(),receipt:r,transactionId:"transactionId"in r?r.transactionId?.toString():void 0}}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const n=await Rr.get(e,{responseType:"arraybuffer"}),r=t.Buffer.from(n.data),i=new URL(e).pathname;return{buffer:r,filename:s.basename(i)||"profile.png"}}{if(!i.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=i.readFileSync(e);return{buffer:t,filename:s.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const n=await Rr.get(e.url,{responseType:"arraybuffer"}),r=t.Buffer.from(n.data);return{buffer:r,filename:e.filename||"profile.png"}}if(e.path){if(!i.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=i.readFileSync(e.path);return{buffer:t,filename:e.filename||s.basename(e.path)}}return null}catch(n){return this.logger.error("Failed to load profile picture:",n),null}}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?t.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let t=null;e.profilePicture&&(t=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==t?.buffer&&{pfpBuffer:t.buffer},...void 0!==t?.filename&&{pfpFileName:t.filename}};if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:i}=this.getAccountAndSigner();if(!i)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${i}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==i&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,i,s)}const i=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:i.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...i,name:e.name,accountId:i?.metadata?.accountId||i.state?.agentMetadata?.accountId}}}catch(t){throw this.logger.error("Failed to register agent:",t),t}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const n=t.topicInfo.inboundTopic;let r;void 0!==e.memo?r=e.memo:(r=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${r}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const i=await this.submitConnectionRequest(n,r);this.executeResult={success:!0,transactionId:"transactionId"in i?i.transactionId?.toString():void 0,receipt:i,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...i}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const n=this.stateManager?.getCurrentAgent();if(!n)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const i=this.stateManager?.getConnectionsManager();if(!i)throw new Error(Hr);await i.fetchConnectionData(n.accountId);const s=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const o=s.targetAccountId,a=s.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const t=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const i=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,i)}const u=await this.getInboundTopicId(),d=await this.handleConnectionRequest(u,o,a,c);let l=d?.connectionTopicId;if(l&&"object"==typeof l&&"toString"in l&&(l=l?.toString()),!l||"string"!=typeof l)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(l)}`);if(this.stateManager){const e=s.targetAgentName||`Agent ${o}`;s.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${o}'.`);let n=s.targetInboundTopicId||"";if(!n)try{const e=await this.getAgentProfile(o);e.success&&e.topicInfo?.inboundTopic&&(n=e.topicInfo.inboundTopic)}catch(t){this.logger.warn(`Could not fetch profile for ${o}:`,t)}const r={connectionId:`conn-${Date.now()}`,targetAccountId:o,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:l,status:"established",created:new Date};this.stateManager.addActiveConnection(r),i.markConnectionRequestProcessed(s.targetInboundTopicId||"",a)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:o,connectionTopicId:l,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:d}}}catch(n){throw this.logger.error("Failed to accept connection:",n),n}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let n;if(e.targetIdentifier.includes("@")){const t=e.targetIdentifier.split("@");if(2===t.length){const r=t[1];n=this.stateManager.getConnectionByIdentifier(r),n||this.addNote(`Could not find connection using request key '${e.targetIdentifier}', extracted account ID '${r}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(e.targetIdentifier)),!n){const t=this.stateManager.listConnections().map(e=>`${e.targetAccountId} (${e.connectionTopicId})`);throw new Error(`Connection not found for identifier: ${e.targetIdentifier}. Available connections: ${t.join(", ")||"none"}. Use 'list_connections' to see details.`)}let r=n.connectionTopicId;if(r&&"object"==typeof r&&"toString"in r&&(r=r?.toString()),!r||"string"!=typeof r)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(r)} (type: ${typeof r})`);const i=n.targetAgentName,s=`${t.inboundTopicId}@${t.accountId}`,o=await this.sendMessage(r,e.message,`Agent message from ${t.name}`);if(!o.sequenceNumber)throw new Error("Failed to send message");let a=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):a=await this.monitorResponses(r,s,o.sequenceNumber),this.executeResult={success:!0,transactionId:o.transactionId,receipt:o.receipt,scheduleId:void 0,rawResult:{targetAgentName:i,targetAccountId:n.targetAccountId,connectionTopicId:r,sequenceNumber:o.sequenceNumber,reply:a,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:o}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let r=0;for(;r<30;){try{const r=await this.getMessageStream(e);for(const e of r.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(i){this.logger.error(`Error monitoring responses: ${i}`)}await new Promise(e=>setTimeout(e,4e3)),r++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:t=!1,targetAccountId:n,monitorDurationSeconds:i=120,hbarFees:s=[],tokenFees:o=[],exemptAccountIds:a=[],defaultCollectorAccount:c}=e;if(!this.stateManager)throw new Error("StateManager is required for connection monitoring");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot monitor for connections. No agent is currently active.");const u=await this.getInboundTopicId(),d=Date.now()+1e3*i;let l=0,h=0;const p=new Set;for(;Date.now()<d;){try{const e=(await this.getMessages(u)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const i of e){const e=i.sequence_number;if(!e||p.has(e))continue;const d=i.operator_id?.split("@")[1];if(d)if(l++,n&&d!==n)this.logger.info(`Skipping request from ${d} (not target account)`);else if(t||n===d){let t;if(this.logger.info(`Accepting connection request from ${d}`),s.length>0||o.length>0){const e=new r.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,a)}for(const t of o){const n=t.collectorAccount||c||this.getOperatorId();e.addTokenFee(t.amount,t.tokenId,n,void 0,a)}t=e}await this.handleConnectionRequest(u,d,e,t),p.add(e),h++}}}catch(f){this.logger.error("Error during connection monitoring:",f)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:l,acceptedConnections:h,monitorDurationSeconds:i,processedRequestIds:Array.from(p)}},this.addNote(`Monitoring completed. Found ${l} requests, accepted ${h}.`),this}async manageConnectionRequests(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for managing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot manage connection requests. No agent is currently active.");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error(Hr);try{const{accountId:n}=this.getAccountAndSigner();await t.fetchConnectionData(n);const r=t.getPendingRequests(),i=t.getConnectionsNeedingConfirmation(),s=[...r,...i];switch(e.action){case"list":this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:s.map((e,t)=>({index:t+1,type:e.needsConfirmation?"incoming":"outgoing",requestKey:e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,created:e.created.toISOString(),memo:e.memo,bio:e.profileInfo?.bio}))}};break;case"view":{if(!e.requestKey)throw new Error("Request key is required for viewing a request");const t=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!t)throw new Error(`Request with key ${e.requestKey} not found`);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{request:{type:t.needsConfirmation?"incoming":"outgoing",requestKey:t.uniqueRequestKey||`${t.connectionRequestId||t.inboundRequestId||"unknown"}`,targetAccountId:t.targetAccountId,targetAgentName:t.targetAgentName||`Agent ${t.targetAccountId}`,created:t.created.toISOString(),memo:t.memo,profileInfo:t.profileInfo}}};break}case"reject":{if(!e.requestKey)throw new Error("Request key is required for rejecting a request");const n=s.find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!n)throw new Error(`Request with key ${e.requestKey} not found`);n.inboundRequestId?t.markConnectionRequestProcessed(n.targetInboundTopicId||"",n.inboundRequestId):n.connectionRequestId&&t.markConnectionRequestProcessed(n.originTopicId||"",n.connectionRequestId),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{rejectedRequest:{requestKey:e.requestKey,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName||`Agent ${n.targetAccountId}`}}};break}}}catch(n){throw this.logger.error("Failed to manage connection requests:",n),n}return this}async listUnapprovedConnectionRequests(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for listing connection requests");if(!this.stateManager.getCurrentAgent())throw new Error("Cannot list connection requests. No agent is currently active.");try{const e=await this.getInboundTopicId(),t=(await this.getMessages(e)).messages.filter(e=>"connection_request"===e.op).map(e=>({requestId:e.sequence_number,fromAccountId:e.operator_id?.split("@")[1]||"unknown",timestamp:e.timestamp||new Date(e?.created||"").getTime(),memo:e.m||"",data:e.data})).filter(e=>"unknown"!==e.fromAccountId);this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{requests:t,count:t.length}},0===t.length?this.addNote("No unapproved connection requests found."):this.addNote(`Found ${t.length} unapproved connection request(s).`)}catch(e){throw this.logger.error("Failed to list unapproved connection requests:",e),e}return this}async listConnections(e={}){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to list connections");const t=e.includeDetails??!0,n=e.showPending??!0;try{const e=await this.getEnhancedConnections();if(0===e.length)return this.executeResult={success:!0,rawResult:{connections:[],message:"There are currently no active connections."}},this;const r=e.filter(e=>"established"===e.status),i=e.filter(e=>e.isPending),s=e.filter(e=>e.needsConfirmation);let o="";r.length>0&&(o+=`🟢 Active Connections (${r.length}):\n`,r.forEach((e,n)=>{o+=this.formatConnection(e,n,t)}),o+="\n"),n&&s.length>0&&(o+=`🟠 Connections Needing Confirmation (${s.length}):\n`,s.forEach((e,n)=>{o+=this.formatConnection(e,n,t)}),o+="\n"),n&&i.length>0&&(o+=`⚪ Pending Connection Requests (${i.length}):\n`,i.forEach((e,n)=>{o+=this.formatConnection(e,n,t)})),this.executeResult={success:!0,rawResult:{connections:e,formattedOutput:o.trim(),activeCount:r.length,pendingCount:i.length,needsConfirmationCount:s.length}}}catch(r){this.logger.error("Failed to list connections:",r),this.executeResult={success:!1,error:`Failed to list connections: ${r instanceof Error?r.message:String(r)}`}}return this}formatConnection(e,t,n){const r=e;let i=`${t+1}. ${r.profileInfo?.display_name||r.targetAgentName||"Unknown Agent"} (${r.targetAccountId})\n`;i+=` Topic: ${r.isPending?"(Pending Request)":r.connectionTopicId}\n`;if(i+=` Status: ${r.status||"unknown"}\n`,n){if(r.profileInfo?.bio&&(i+=` Bio: ${r.profileInfo.bio.substring(0,100)}${r.profileInfo.bio.length>100?"...":""}\n`),r.created){i+=` ${r.isPending?"Request sent":"Connection established"}: ${r.created.toLocaleString()}\n`}r.lastActivity&&(i+=` Last activity: ${r.lastActivity.toLocaleString()}\n`)}return i}async getEnhancedConnections(){try{const{accountId:e}=this.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error(Hr),this.stateManager.listConnections();const n=await t.fetchConnectionData(e);for(const r of n)this.stateManager.addActiveConnection(r);return n}catch(e){return this.logger.error("Failed to get enhanced connections:",e),this.stateManager.listConnections()}}async checkMessages(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to check messages");const t=this.stateManager.getConnectionByIdentifier(e.targetIdentifier);if(!t)return this.executeResult={success:!1,error:`Could not find an active connection matching identifier "${e.targetIdentifier}". Use 'list_connections' to see active connections.`},this;const n=t.connectionTopicId||"";if(!n||!n.match(/^\d+\.\d+\.\d+$/))return this.logger.error(`Invalid connection topic ID format: ${n}`),this.executeResult={success:!1,error:`Invalid connection topic ID format: ${n}. Expected format: 0.0.XXXXX`},this;const r=t.targetAgentName,i=this.stateManager.getLastTimestamp(n);this.logger.info(`Checking messages for connection with ${r} (${t.targetAccountId}) on topic ${n} (fetchLatest: ${e.fetchLatest}, lastCount: ${e.lastMessagesCount}, since: ${i})`);try{const t=(await this.getMessages(n)).messages;if(!t||0===t.length)return this.executeResult={success:!0,rawResult:{messages:[],message:`No messages found on connection topic ${n}.`}},this;let o=[],a=i;const c=!0===e.fetchLatest;if(c){this.logger.info("Fetching latest messages regardless of timestamp.");const n=e.lastMessagesCount??1;o=t.slice(-n)}else this.logger.info(`Filtering for messages newer than ${i}`),o=t.filter(e=>1e6*e.timestamp>i),o.length>0&&(a=o.reduce((e,t)=>Math.max(e,1e6*t.timestamp),i));if(0===o.length){const e=c?`Could not retrieve the latest message(s). No messages found on topic ${n}.`:`No new messages found for connection with ${r} since last check.`;return this.executeResult={success:!0,rawResult:{messages:[],message:e}},this}this.logger.info(`Processing ${o.length} message(s).`);let u=c?`Latest message(s) from ${r}:\n`:`New messages from ${r}:\n`;const d=[];for(const e of o){let t=e.data;try{"string"==typeof t&&t.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${t}`),t=await this.getMessageContent(t),this.logger.debug(`Resolved content length: ${t?.length}`));let n=t;try{const e=JSON.parse(t||"{}");if("hcs-10"===e.p&&"message"===e.op&&e.data){n=`[${e.operator_id||"unknown_sender"}]: ${e.data}`}else n=t}catch{n=t}u+=`\n[${new Date(e.timestamp).toLocaleString()}] (Seq: ${e.sequence_number})\n${n}\n`,d.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(s){const t=`Error processing message (Seq: ${e.sequence_number}): ${s instanceof Error?s.message:String(s)}`;this.logger.error(t),u+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&a>i&&(this.logger.debug(`Updating timestamp for topic ${n} to ${a}`),this.stateManager.updateTimestamp(n,a)),this.executeResult={success:!0,rawResult:{messages:d,formattedOutput:u.trim(),targetAgentName:r,connectionTopicId:n}}}catch(s){this.logger.error(`Failed to check messages for topic ${n}: ${s}`),this.executeResult={success:!1,error:`Error checking messages for ${r}: ${s instanceof Error?s.message:String(s)}`}}return this}async findRegistrations(e){this.clearNotes();try{const t={network:this.network};e.accountId&&(t.accountId=e.accountId),e.tags&&e.tags.length>0&&(t.tags=e.tags);const n=await this.standardClient.findRegistrations(t);if(!n.success||n.error)return this.executeResult={success:!1,error:`Error finding registrations: ${n.error||"Unknown error"}`},this;if(!n.registrations||0===n.registrations.length)return this.executeResult={success:!0,rawResult:{registrations:[],message:"No registrations found matching the criteria."}},this;const r=n.registrations.map(e=>{const t=e;return`Agent: ${t.agent?.name||"Unknown Agent"} (${t.accountId||"Unknown Account"}), Capabilities: ${t.agent?.capabilities?.join(", ")||"None"}`}).join("\\n");this.executeResult={success:!0,rawResult:{registrations:n.registrations,formattedOutput:`Found ${n.registrations.length} registration(s):\\n${r}`}}}catch(t){this.logger.error("Error during FindRegistrations execution:",t),this.executeResult={success:!1,error:`Failed to search registrations: ${t instanceof Error?t.message:String(t)}`}}return this}async retrieveProfile(e){this.clearNotes();try{const t=await this.standardClient.retrieveProfile(e.accountId,e.disableCache||!1);if(!t.success)return this.executeResult={success:!1,error:`Failed to retrieve profile: ${t.error||"Unknown error"}`},this;const n=t.profile,r=t.topicInfo;let i=`Profile for ${e.accountId}:\n`;i+=`Name: ${n.name||"Unknown"}\n`,i+=`Bio: ${n.bio||"No bio provided"}\n`,i+=`Type: ${n.type||"Unknown"}\n`,i+=`Model: ${n.model||"Unknown"}\n`,n.capabilities&&n.capabilities.length>0?i+=`Capabilities: ${n.capabilities.join(", ")}\n`:i+="Capabilities: None listed\n",r&&(i+=`Inbound Topic: ${r.inboundTopic||"Unknown"}\n`,i+=`Outbound Topic: ${r.outboundTopic||"Unknown"}\n`,i+=`Profile Topic: ${r.profileTopicId||"Unknown"}\n`),n.social&&Object.keys(n.social).length>0&&(i+=`Social: ${Object.entries(n.social).map(([e,t])=>`${e}: ${t}`).join(", ")}\n`),n.properties&&Object.keys(n.properties).length>0&&(i+=`Properties: ${JSON.stringify(n.properties)}\n`),this.executeResult={success:!0,rawResult:{profileDetails:i,rawProfile:t}}}catch(t){this.logger.error(`Unexpected error retrieving profile for ${e.accountId}:`,t),this.executeResult={success:!1,error:`Unexpected error retrieving profile for ${e.accountId}: ${t instanceof Error?t.message:String(t)}`}}return this}async execute(){return this.executeResult?{success:this.executeResult.success,transactionId:this.executeResult.transactionId,receipt:this.executeResult.receipt,scheduleId:this.executeResult.scheduleId,error:this.executeResult.error,rawResult:this.executeResult.rawResult,notes:this.notes}:{success:!1,error:"No operation result available. Call a builder method first."}}}class Wr extends n.BasePlugin{constructor(){super(...arguments),this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new n.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>n.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>n.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>n.PluginRegistry}),e.AcceptConnectionRequestTool=yt,e.BaseHCS10QueryTool=d,e.BaseHCS10TransactionTool=u,e.CheckMessagesTool=ut,e.ConnectionMonitorTool=pt,e.FindRegistrationsTool=lt,e.HCS10Builder=Vr,e.HCS10Client=class{constructor(e,t,n,i){this.standardClient=new r.HCS10Client({network:n,operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:i?.registryUrl,logLevel:i?.logLevel}),this.guardedRegistryBaseUrl=i?.registryUrl||"",this.useEncryption=i?.useEncryption||!1;const s="true"===c.env.DISABLE_LOGGING;this.logger=new r.Logger({level:i?.logLevel||"info",silent:s})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,r){try{return await this.standardClient.handleConnectionRequest(e,t,n,r)}catch(i){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,i),new Error(`Failed to handle connection request: ${i instanceof Error?i.message:String(i)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,r=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,r)}async createAndRegisterAgent(e){const t=(new r.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[r.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(r.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(r.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),r=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return r?.metadata?.inboundTopicId&&r?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:r.metadata.inboundTopicId,outboundTopicId:r.metadata.outboundTopicId}),r}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,n,r){this.useEncryption;try{const i=await this.standardClient.sendMessage(e,t,n,r);return i.topicSequenceNumber?.toNumber()}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,t){return this.standardClient=new r.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HbarPricePlugin=Wr,e.InitiateConnectionTool=st,e.ListConnectionsTool=at,e.ListUnapprovedConnectionRequestsTool=_t,e.ManageConnectionRequestsTool=gt,e.OpenConvaiState=Ct,e.RegisterAgentTool=tt,e.RetrieveProfileTool=bt,e.SendMessageToConnectionTool=rt,e.initializeStandardsAgentKit=async e=>{const t=e?.clientConfig||{},i=t.operatorId||c.env.HEDERA_OPERATOR_ID,s=t.operatorKey||c.env.HEDERA_OPERATOR_KEY,o=t.network||c.env.HEDERA_NETWORK||"testnet";let a;if("mainnet"===o?a="mainnet":("testnet"===o||console.warn(`Unsupported network specified: '${o}'. Defaulting to 'testnet'.`),a="testnet"),!i||!s)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const u="true"===c.env.DISABLE_LOGGING,d=r.Logger.getInstance({level:t.logLevel||"info",silent:u}),l=e?.stateManager||new Ct({defaultEnvFilePath:It,defaultPrefix:"TODD"});d.info("State manager initialized");const h=new n.ServerSigner(i,s,a),p=new n.HederaAgentKit(h);await p.initialize(),d.info(`HederaAgentKit initialized for ${i} on ${a}`);const f=new Vr(p,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:t.logLevel});let g,m;if(e?.monitoringClient){const e=new n.ServerSigner(i,s,a);g=new n.HederaAgentKit(e),await g.initialize(),m=new Vr(g,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),d.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new tt({hederaKit:p,hcs10Builder:f,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new lt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.retrieveProfileTool=new bt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.initiateConnectionTool=new st({hederaKit:p,hcs10Builder:f,logger:void 0}),y.listConnectionsTool=new at({hederaKit:p,hcs10Builder:f,logger:void 0}),y.sendMessageToConnectionTool=new rt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.checkMessagesTool=new ut({hederaKit:p,hcs10Builder:f,logger:void 0}),y.connectionMonitorTool=new pt({hederaKit:g||p,hcs10Builder:m||f,logger:void 0}),y.manageConnectionRequestsTool=new gt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.acceptConnectionRequestTool=new yt({hederaKit:p,hcs10Builder:f,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new _t({hederaKit:p,hcs10Builder:f,logger:void 0}),d.info("All tools initialized")),{hederaKit:p,hcs10Builder:f,monitoringHederaKit:g,monitoringHcs10Builder:m,tools:y,stateManager:l}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("unenv/node/buffer"),require("hedera-agent-kit"),require("@hashgraphonline/standards-sdk"),require("unenv/node/fs"),require("unenv/node/path"),require("unenv/polyfill/globalthis"),require("unenv/node/timers"),require("unenv/node/process")):"function"==typeof define&&define.amd?define(["exports","unenv/node/buffer","hedera-agent-kit","@hashgraphonline/standards-sdk","unenv/node/fs","unenv/node/path","unenv/polyfill/globalthis","unenv/node/timers","unenv/node/process"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsAgentKit={},e["unenv/node/buffer"],e.HederaAgentKit,e.StandardsSDK,e.fs,e["unenv/node/path"],e["unenv/polyfill/globalthis"],e["unenv/node/timers"],e.process)}(this,function(e,t,n,i,r,s,a,o,c){"use strict";class d extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}class u extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs10",this.hcs10Builder=e.hcs10Builder}getServiceBuilder(){return this.hcs10Builder}}var l,p,h;(p=l||(l={})).assertEqual=e=>{},p.assertIs=function(e){},p.assertNever=function(e){throw new Error},p.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},p.getValidEnumValues=e=>{const t=p.objectKeys(e).filter(t=>"number"!=typeof e[e[t]]),n={};for(const i of t)n[i]=e[i];return p.objectValues(n)},p.objectValues=e=>p.objectKeys(e).map(function(t){return e[t]}),p.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},p.find=(e,t)=>{for(const n of e)if(t(n))return n},p.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,p.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},p.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,(h||(h={})).mergeShapes=(e,t)=>({...e,...t});const g=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),f=e=>{switch(typeof e){case"undefined":return g.undefined;case"string":return g.string;case"number":return Number.isNaN(e)?g.nan:g.number;case"boolean":return g.boolean;case"function":return g.function;case"bigint":return g.bigint;case"symbol":return g.symbol;case"object":return Array.isArray(e)?g.array:null===e?g.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?g.promise:"undefined"!=typeof Map&&e instanceof Map?g.map:"undefined"!=typeof Set&&e instanceof Set?g.set:"undefined"!=typeof Date&&e instanceof Date?g.date:g.object;default:return g.unknown}},m=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class y extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},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 y))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},n=[];for(const 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()}}y.create=e=>new y(e);const b=(e,t)=>{let n;switch(e.code){case m.invalid_type:n=e.received===g.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case m.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,l.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:n=`Unrecognized key(s) in object: ${l.joinValues(e.keys,", ")}`;break;case m.invalid_union:n="Invalid input";break;case m.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${l.joinValues(e.options)}`;break;case m.invalid_enum_value:n=`Invalid enum value. Expected ${l.joinValues(e.options)}, received '${e.received}'`;break;case m.invalid_arguments:n="Invalid function arguments";break;case m.invalid_return_type:n="Invalid function return type";break;case m.invalid_date:n="Invalid date";break;case m.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:l.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case m.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case m.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case m.custom:n="Invalid input";break;case m.invalid_intersection_types:n="Intersection results could not be merged";break;case m.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case m.not_finite:n="Number must be finite";break;default:n=t.defaultError,l.assertNever(e)}return{message:n}};let v=b;function w(e,t){const n=v,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===b?void 0:b].filter(e=>!!e)});e.common.issues.push(i)}class I{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 A;"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 I.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 A;if("aborted"===r.status)return A;"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 A=Object.freeze({status:"aborted"}),_=e=>({status:"dirty",value:e}),T=e=>({status:"valid",value:e}),C=e=>"aborted"===e.status,E=e=>"dirty"===e.status,R=e=>"valid"===e.status,S=e=>"undefined"!=typeof Promise&&e instanceof Promise;var x,k;(k=x||(x={})).errToObj=e=>"string"==typeof e?{message:e}:e||{},k.toString=e=>"string"==typeof e?e:e?.message;class O{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 N=(e,t)=>{if(R(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new y(e.common.issues);return this._error=t,this._error}}};function $(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 P{get description(){return this._def.description}_getType(e){return f(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:f(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I,ctx:{common:e.parent.common,data:e.data,parsedType:f(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(S(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:f(e)},i=this._parseSync({data:e,path:n.path,parent:n});return N(n,i)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:f(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return R(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=>R(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:f(e)},i=this._parse({data:e,path:n.path,parent:n}),r=await(S(i)?i:Promise.resolve(i));return N(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:m.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 $e({schema:this,typeName:Ue.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Pe.create(this,this._def)}nullable(){return Me.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ye.create(this)}promise(){return Ne.create(this,this._def)}or(e){return we.create([this,e],this._def)}and(e){return Ae.create(this,e,this._def)}transform(e){return new $e({...$(this._def),schema:this,typeName:Ue.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Fe({...$(this._def),innerType:this,defaultValue:t,typeName:Ue.ZodDefault})}brand(){return new Le({typeName:Ue.ZodBranded,type:this,...$(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new qe({...$(this._def),innerType:this,catchValue:t,typeName:Ue.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Be.create(this,e)}readonly(){return je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const M=/^c[^\s-]{8,}$/i,F=/^[0-9a-z]+$/,q=/^[0-9A-HJKMNP-TV-Z]{26}$/i,D=/^[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,L=/^[a-z0-9_-]{21}$/i,B=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,j=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,U=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let K;const H=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Z=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,z=/^(([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]))$/,G=/^(([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])$/,V=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,W=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,J="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",X=new RegExp(`^${J}$`);function Q(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function Y(e){return new RegExp(`^${Q(e)}$`)}function ee(e){let t=`${J}T${Q(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function te(e,t){return!("v4"!==t&&t||!H.test(e))||!("v6"!==t&&t||!z.test(e))}function ne(e,t){if(!B.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 ie(e,t){return!("v4"!==t&&t||!Z.test(e))||!("v6"!==t&&t||!G.test(e))}class re extends P{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==g.string){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.string,received:t.parsedType}),A}const t=new I;let n;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.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),w(n,{code:m.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?w(n,{code:m.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&w(n,{code:m.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)U.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"email",code:m.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)K||(K=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),K.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"emoji",code:m.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)D.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"uuid",code:m.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)L.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"nanoid",code:m.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)M.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid",code:m.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)F.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cuid2",code:m.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)q.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ulid",code:m.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),w(n,{validation:"url",code:m.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),w(n,{validation:"regex",code:m.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),w(n,{code:m.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),w(n,{code:m.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),w(n,{code:m.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){ee(i).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){X.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){Y(i).test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{code:m.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?j.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"duration",code:m.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?te(e.data,i.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"ip",code:m.invalid_string,message:i.message}),t.dirty()):"jwt"===i.kind?ne(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"jwt",code:m.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?ie(e.data,i.version)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"cidr",code:m.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?V.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64",code:m.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?W.test(e.data)||(n=this._getOrReturnCtx(e,n),w(n,{validation:"base64url",code:m.invalid_string,message:i.message}),t.dirty()):l.assertNever(i);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:m.invalid_string,...x.errToObj(n)})}_addCheck(e){return new re({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...x.errToObj(e)})}url(e){return this._addCheck({kind:"url",...x.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...x.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...x.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...x.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...x.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...x.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...x.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...x.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...x.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...x.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...x.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...x.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,...x.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,...x.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...x.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...x.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...x.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...x.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...x.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...x.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...x.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...x.errToObj(t)})}nonempty(e){return this.min(1,x.errToObj(e))}trim(){return new re({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new re({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new re({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function se(e,t){const n=(e.toString().split(".")[1]||"").length,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}re.create=e=>new re({checks:[],typeName:Ue.ZodString,coerce:e?.coerce??!1,...$(e)});class ae extends P{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)!==g.number){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.number,received:t.parsedType}),A}let t;const n=new I;for(const i of this._def.checks)if("int"===i.kind)l.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.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),w(t,{code:m.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),w(t,{code:m.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty())}else"multipleOf"===i.kind?0!==se(e.data,i.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):"finite"===i.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:m.not_finite,message:i.message}),n.dirty()):l.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,x.toString(t))}gt(e,t){return this.setLimit("min",e,!1,x.toString(t))}lte(e,t){return this.setLimit("max",e,!0,x.toString(t))}lt(e,t){return this.setLimit("max",e,!1,x.toString(t))}setLimit(e,t,n,i){return new ae({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:x.toString(i)}]})}_addCheck(e){return new ae({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:x.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:x.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:x.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:x.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:x.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:x.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&l.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ae.create=e=>new ae({checks:[],typeName:Ue.ZodNumber,coerce:e?.coerce||!1,...$(e)});class oe extends P{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)!==g.bigint)return this._getInvalidInput(e);let t;const n=new I;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),w(t,{code:m.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),w(t,{code:m.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),w(t,{code:m.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):l.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.bigint,received:t.parsedType}),A}gte(e,t){return this.setLimit("min",e,!0,x.toString(t))}gt(e,t){return this.setLimit("min",e,!1,x.toString(t))}lte(e,t){return this.setLimit("max",e,!0,x.toString(t))}lt(e,t){return this.setLimit("max",e,!1,x.toString(t))}setLimit(e,t,n,i){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:x.toString(i)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:x.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:x.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:x.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:x.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:x.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}}oe.create=e=>new oe({checks:[],typeName:Ue.ZodBigInt,coerce:e?.coerce??!1,...$(e)});class ce extends P{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==g.boolean){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.boolean,received:t.parsedType}),A}return T(e.data)}}ce.create=e=>new ce({typeName:Ue.ZodBoolean,coerce:e?.coerce||!1,...$(e)});class de extends P{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==g.date){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.date,received:t.parsedType}),A}if(Number.isNaN(e.data.getTime())){return w(this._getOrReturnCtx(e),{code:m.invalid_date}),A}const t=new I;let n;for(const i of this._def.checks)"min"===i.kind?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),w(n,{code:m.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),w(n,{code:m.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),t.dirty()):l.assertNever(i);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:x.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:x.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}de.create=e=>new de({checks:[],coerce:e?.coerce||!1,typeName:Ue.ZodDate,...$(e)});class ue extends P{_parse(e){if(this._getType(e)!==g.symbol){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.symbol,received:t.parsedType}),A}return T(e.data)}}ue.create=e=>new ue({typeName:Ue.ZodSymbol,...$(e)});class le extends P{_parse(e){if(this._getType(e)!==g.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.undefined,received:t.parsedType}),A}return T(e.data)}}le.create=e=>new le({typeName:Ue.ZodUndefined,...$(e)});class pe extends P{_parse(e){if(this._getType(e)!==g.null){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.null,received:t.parsedType}),A}return T(e.data)}}pe.create=e=>new pe({typeName:Ue.ZodNull,...$(e)});class he extends P{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}}he.create=e=>new he({typeName:Ue.ZodAny,...$(e)});class ge extends P{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}}ge.create=e=>new ge({typeName:Ue.ZodUnknown,...$(e)});class fe extends P{_parse(e){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.never,received:t.parsedType}),A}}fe.create=e=>new fe({typeName:Ue.ZodNever,...$(e)});class me extends P{_parse(e){if(this._getType(e)!==g.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.void,received:t.parsedType}),A}return T(e.data)}}me.create=e=>new me({typeName:Ue.ZodVoid,...$(e)});class ye extends P{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==g.array)return w(t,{code:m.invalid_type,expected:g.array,received:t.parsedType}),A;if(null!==i.exactLength){const e=t.data.length>i.exactLength.value,r=t.data.length<i.exactLength.value;(e||r)&&(w(t,{code:e?m.too_big:m.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&&(w(t,{code:m.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&&(w(t,{code:m.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 O(t,e,t.path,n)))).then(e=>I.mergeArray(n,e));const r=[...t.data].map((e,n)=>i.type._parseSync(new O(t,e,t.path,n)));return I.mergeArray(n,r)}get element(){return this._def.type}min(e,t){return new ye({...this._def,minLength:{value:e,message:x.toString(t)}})}max(e,t){return new ye({...this._def,maxLength:{value:e,message:x.toString(t)}})}length(e,t){return new ye({...this._def,exactLength:{value:e,message:x.toString(t)}})}nonempty(e){return this.min(1,e)}}function be(e){if(e instanceof ve){const t={};for(const n in e.shape){const i=e.shape[n];t[n]=Pe.create(be(i))}return new ve({...e._def,shape:()=>t})}return e instanceof ye?new ye({...e._def,type:be(e.element)}):e instanceof Pe?Pe.create(be(e.unwrap())):e instanceof Me?Me.create(be(e.unwrap())):e instanceof _e?_e.create(e.items.map(e=>be(e))):e}ye.create=(e,t)=>new ye({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ue.ZodArray,...$(t)});class ve extends P{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=l.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==g.object){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.object,received:t.parsedType}),A}const{status:t,ctx:n}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),s=[];if(!(this._def.catchall instanceof fe&&"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 O(n,t,n.path,o)),alwaysSet:o in n.data})}if(this._def.catchall instanceof fe){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&&(w(n,{code:m.unrecognized_keys,keys:s}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of s){const i=n.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new O(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=>I.mergeObjectSync(t,e)):I.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return x.errToObj,new ve({...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:x.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new ve({...this._def,unknownKeys:"strip"})}passthrough(){return new ve({...this._def,unknownKeys:"passthrough"})}extend(e){return new ve({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ve({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ue.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ve({...this._def,catchall:e})}pick(e){const t={};for(const n of l.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new ve({...this._def,shape:()=>t})}omit(e){const t={};for(const n of l.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new ve({...this._def,shape:()=>t})}deepPartial(){return be(this)}partial(e){const t={};for(const n of l.objectKeys(this.shape)){const i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}return new ve({...this._def,shape:()=>t})}required(e){const t={};for(const n of l.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof Pe;)e=e._def.innerType;t[n]=e}return new ve({...this._def,shape:()=>t})}keyof(){return xe(l.objectKeys(this.shape))}}ve.create=(e,t)=>new ve({shape:()=>e,unknownKeys:"strip",catchall:fe.create(),typeName:Ue.ZodObject,...$(t)}),ve.strictCreate=(e,t)=>new ve({shape:()=>e,unknownKeys:"strict",catchall:fe.create(),typeName:Ue.ZodObject,...$(t)}),ve.lazycreate=(e,t)=>new ve({shape:e,unknownKeys:"strip",catchall:fe.create(),typeName:Ue.ZodObject,...$(t)});class we extends P{_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 y(e.ctx.common.issues));return w(t,{code:m.invalid_union,unionErrors:n}),A});{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 y(e));return w(t,{code:m.invalid_union,unionErrors:r}),A}}get options(){return this._def.options}}function Ie(e,t){const n=f(e),i=f(t);if(e===t)return{valid:!0,data:e};if(n===g.object&&i===g.object){const n=l.objectKeys(t),i=l.objectKeys(e).filter(e=>-1!==n.indexOf(e)),r={...e,...t};for(const s of i){const n=Ie(e[s],t[s]);if(!n.valid)return{valid:!1};r[s]=n.data}return{valid:!0,data:r}}if(n===g.array&&i===g.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let i=0;i<e.length;i++){const r=Ie(e[i],t[i]);if(!r.valid)return{valid:!1};n.push(r.data)}return{valid:!0,data:n}}return n===g.date&&i===g.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}we.create=(e,t)=>new we({options:e,typeName:Ue.ZodUnion,...$(t)});class Ae extends P{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=(e,i)=>{if(C(e)||C(i))return A;const r=Ie(e.value,i.value);return r.valid?((E(e)||E(i))&&t.dirty(),{status:t.value,value:r.data}):(w(n,{code:m.invalid_intersection_types}),A)};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}))}}Ae.create=(e,t,n)=>new Ae({left:e,right:t,typeName:Ue.ZodIntersection,...$(n)});class _e extends P{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==g.array)return w(n,{code:m.invalid_type,expected:g.array,received:n.parsedType}),A;if(n.data.length<this._def.items.length)return w(n,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;!this._def.rest&&n.data.length>this._def.items.length&&(w(n,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((e,t)=>{const i=this._def.items[t]||this._def.rest;return i?i._parse(new O(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(i).then(e=>I.mergeArray(t,e)):I.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new _e({...this._def,rest:e})}}_e.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _e({items:e,typeName:Ue.ZodTuple,rest:null,...$(t)})};class Te extends P{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!==g.object)return w(n,{code:m.invalid_type,expected:g.object,received:n.parsedType}),A;const i=[],r=this._def.keyType,s=this._def.valueType;for(const a in n.data)i.push({key:r._parse(new O(n,a,n.path,a)),value:s._parse(new O(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?I.mergeObjectAsync(t,i):I.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return new Te(t instanceof P?{keyType:e,valueType:t,typeName:Ue.ZodRecord,...$(n)}:{keyType:re.create(),valueType:e,typeName:Ue.ZodRecord,...$(t)})}}class Ce extends P{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!==g.map)return w(n,{code:m.invalid_type,expected:g.map,received:n.parsedType}),A;const i=this._def.keyType,r=this._def.valueType,s=[...n.data.entries()].map(([e,t],s)=>({key:i._parse(new O(n,e,n.path,[s,"key"])),value:r._parse(new O(n,t,n.path,[s,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of s){const i=await n.key,r=await n.value;if("aborted"===i.status||"aborted"===r.status)return A;"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 A;"dirty"!==i.status&&"dirty"!==r.status||t.dirty(),e.set(i.value,r.value)}return{status:t.value,value:e}}}}Ce.create=(e,t,n)=>new Ce({valueType:t,keyType:e,typeName:Ue.ZodMap,...$(n)});class Ee extends P{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==g.set)return w(n,{code:m.invalid_type,expected:g.set,received:n.parsedType}),A;const i=this._def;null!==i.minSize&&n.data.size<i.minSize.value&&(w(n,{code:m.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&&(w(n,{code:m.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 A;"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 O(n,e,n.path,t)));return n.common.async?Promise.all(a).then(e=>s(e)):s(a)}min(e,t){return new Ee({...this._def,minSize:{value:e,message:x.toString(t)}})}max(e,t){return new Ee({...this._def,maxSize:{value:e,message:x.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ee.create=(e,t)=>new Ee({valueType:e,minSize:null,maxSize:null,typeName:Ue.ZodSet,...$(t)});class Re extends P{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})}}Re.create=(e,t)=>new Re({getter:e,typeName:Ue.ZodLazy,...$(t)});class Se extends P{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return w(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:e.data}}get value(){return this._def.value}}function xe(e,t){return new ke({values:e,typeName:Ue.ZodEnum,...$(t)})}Se.create=(e,t)=>new Se({value:e,typeName:Ue.ZodLiteral,...$(t)});class ke extends P{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{expected:l.joinValues(n),received:t.parsedType,code:m.invalid_type}),A}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return w(t,{received:t.data,code:m.invalid_enum_value,options:n}),A}return T(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ke.create(e,{...this._def,...t})}exclude(e,t=this._def){return ke.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}ke.create=xe;class Oe extends P{_parse(e){const t=l.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==g.string&&n.parsedType!==g.number){const e=l.objectValues(t);return w(n,{expected:l.joinValues(e),received:n.parsedType,code:m.invalid_type}),A}if(this._cache||(this._cache=new Set(l.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=l.objectValues(t);return w(n,{received:n.data,code:m.invalid_enum_value,options:e}),A}return T(e.data)}get enum(){return this._def.values}}Oe.create=(e,t)=>new Oe({values:e,typeName:Ue.ZodNativeEnum,...$(t)});class Ne extends P{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==g.promise&&!1===t.common.async)return w(t,{code:m.invalid_type,expected:g.promise,received:t.parsedType}),A;const n=t.parsedType===g.promise?t.data:Promise.resolve(t.data);return T(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:Ue.ZodPromise,...$(t)});class $e extends P{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ue.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,r={addIssue:e=>{w(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 A;const i=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===i.status?A:"dirty"===i.status||"dirty"===t.value?_(i.value):i});{if("aborted"===t.value)return A;const i=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===i.status?A:"dirty"===i.status||"dirty"===t.value?_(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?A:("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?A:("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(!R(e))return A;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=>R(e)?Promise.resolve(i.transform(e.value,r)).then(e=>({status:t.value,value:e})):A)}l.assertNever(i)}}$e.create=(e,t,n)=>new $e({schema:e,typeName:Ue.ZodEffects,effect:t,...$(n)}),$e.createWithPreprocess=(e,t,n)=>new $e({schema:t,effect:{type:"preprocess",transform:e},typeName:Ue.ZodEffects,...$(n)});class Pe extends P{_parse(e){return this._getType(e)===g.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Pe.create=(e,t)=>new Pe({innerType:e,typeName:Ue.ZodOptional,...$(t)});class Me extends P{_parse(e){return this._getType(e)===g.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:Ue.ZodNullable,...$(t)});class Fe extends P{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===g.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Fe.create=(e,t)=>new Fe({innerType:e,typeName:Ue.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...$(t)});class qe extends P{_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 S(i)?i.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===i.status?i.value:this._def.catchValue({get error(){return new y(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:Ue.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...$(t)});class De extends P{_parse(e){if(this._getType(e)!==g.nan){const t=this._getOrReturnCtx(e);return w(t,{code:m.invalid_type,expected:g.nan,received:t.parsedType}),A}return{status:"valid",value:e.data}}}De.create=e=>new De({typeName:Ue.ZodNaN,...$(e)});class Le extends P{_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 Be extends P{_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?A:"dirty"===e.status?(t.dirty(),_(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?A:"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 Be({in:e,out:t,typeName:Ue.ZodPipeline})}}class je extends P{_parse(e){const t=this._def.innerType._parse(e),n=e=>(R(e)&&(e.value=Object.freeze(e.value)),e);return S(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}var Ue,Ke;je.create=(e,t)=>new je({innerType:e,typeName:Ue.ZodReadonly,...$(t)}),(Ke=Ue||(Ue={})).ZodString="ZodString",Ke.ZodNumber="ZodNumber",Ke.ZodNaN="ZodNaN",Ke.ZodBigInt="ZodBigInt",Ke.ZodBoolean="ZodBoolean",Ke.ZodDate="ZodDate",Ke.ZodSymbol="ZodSymbol",Ke.ZodUndefined="ZodUndefined",Ke.ZodNull="ZodNull",Ke.ZodAny="ZodAny",Ke.ZodUnknown="ZodUnknown",Ke.ZodNever="ZodNever",Ke.ZodVoid="ZodVoid",Ke.ZodArray="ZodArray",Ke.ZodObject="ZodObject",Ke.ZodUnion="ZodUnion",Ke.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Ke.ZodIntersection="ZodIntersection",Ke.ZodTuple="ZodTuple",Ke.ZodRecord="ZodRecord",Ke.ZodMap="ZodMap",Ke.ZodSet="ZodSet",Ke.ZodFunction="ZodFunction",Ke.ZodLazy="ZodLazy",Ke.ZodLiteral="ZodLiteral",Ke.ZodEnum="ZodEnum",Ke.ZodEffects="ZodEffects",Ke.ZodNativeEnum="ZodNativeEnum",Ke.ZodOptional="ZodOptional",Ke.ZodNullable="ZodNullable",Ke.ZodDefault="ZodDefault",Ke.ZodCatch="ZodCatch",Ke.ZodPromise="ZodPromise",Ke.ZodBranded="ZodBranded",Ke.ZodPipeline="ZodPipeline",Ke.ZodReadonly="ZodReadonly";const He=re.create,Ze=ae.create,ze=ce.create,Ge=ge.create;fe.create;const Ve=ye.create,We=ve.create,Je=we.create;Ae.create,_e.create;const Xe=Te.create,Qe=ke.create,Ye=Oe.create;Ne.create,Pe.create,Me.create;const et=class{static parseCapabilities(e){if(!e)return[i.AIAgentCapability.TEXT_GENERATION];const t=e.toLowerCase(),n=new Set;for(const[i,r]of Object.entries(this.CAPABILITY_MAPPINGS))t.includes(i)&&r.forEach(e=>n.add(e));return 0===n.size&&n.add(i.AIAgentCapability.TEXT_GENERATION),Array.from(n)}static parseTagsOrCapabilities(e){if(Array.isArray(e)&&e.every(e=>"number"==typeof e))return e;if(Array.isArray(e)&&e.every(e=>"string"==typeof e)){const t=new Set;return e.forEach(e=>{this.parseCapabilities(e).forEach(e=>t.add(e))}),Array.from(t)}return"string"==typeof e?this.parseCapabilities(e):[i.AIAgentCapability.TEXT_GENERATION]}static getCapabilityName(e){return{[i.AIAgentCapability.TEXT_GENERATION]:"Text Generation",[i.AIAgentCapability.IMAGE_GENERATION]:"Image Generation",[i.AIAgentCapability.AUDIO_GENERATION]:"Audio Generation",[i.AIAgentCapability.VIDEO_GENERATION]:"Video Generation",[i.AIAgentCapability.CODE_GENERATION]:"Code Generation",[i.AIAgentCapability.LANGUAGE_TRANSLATION]:"Language Translation",[i.AIAgentCapability.SUMMARIZATION_EXTRACTION]:"Summarization & Extraction",[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL]:"Knowledge Retrieval",[i.AIAgentCapability.DATA_INTEGRATION]:"Data Integration",[i.AIAgentCapability.MARKET_INTELLIGENCE]:"Market Intelligence",[i.AIAgentCapability.TRANSACTION_ANALYTICS]:"Transaction Analytics",[i.AIAgentCapability.SMART_CONTRACT_AUDIT]:"Smart Contract Audit",[i.AIAgentCapability.GOVERNANCE_FACILITATION]:"Governance Facilitation",[i.AIAgentCapability.SECURITY_MONITORING]:"Security Monitoring",[i.AIAgentCapability.COMPLIANCE_ANALYSIS]:"Compliance Analysis",[i.AIAgentCapability.FRAUD_DETECTION]:"Fraud Detection",[i.AIAgentCapability.MULTI_AGENT_COORDINATION]:"Multi-Agent Coordination",[i.AIAgentCapability.API_INTEGRATION]:"API Integration",[i.AIAgentCapability.WORKFLOW_AUTOMATION]:"Workflow Automation"}[e]||"Unknown Capability"}};et.CAPABILITY_MAPPINGS={ai:[i.AIAgentCapability.TEXT_GENERATION],"artificial intelligence":[i.AIAgentCapability.TEXT_GENERATION],chat:[i.AIAgentCapability.TEXT_GENERATION],conversation:[i.AIAgentCapability.TEXT_GENERATION],text:[i.AIAgentCapability.TEXT_GENERATION],"text generation":[i.AIAgentCapability.TEXT_GENERATION],image:[i.AIAgentCapability.IMAGE_GENERATION],picture:[i.AIAgentCapability.IMAGE_GENERATION],visual:[i.AIAgentCapability.IMAGE_GENERATION],photo:[i.AIAgentCapability.IMAGE_GENERATION],audio:[i.AIAgentCapability.AUDIO_GENERATION],sound:[i.AIAgentCapability.AUDIO_GENERATION],voice:[i.AIAgentCapability.AUDIO_GENERATION],speech:[i.AIAgentCapability.AUDIO_GENERATION],video:[i.AIAgentCapability.VIDEO_GENERATION],movie:[i.AIAgentCapability.VIDEO_GENERATION],animation:[i.AIAgentCapability.VIDEO_GENERATION],code:[i.AIAgentCapability.CODE_GENERATION],programming:[i.AIAgentCapability.CODE_GENERATION],development:[i.AIAgentCapability.CODE_GENERATION],coding:[i.AIAgentCapability.CODE_GENERATION],translate:[i.AIAgentCapability.LANGUAGE_TRANSLATION],translation:[i.AIAgentCapability.LANGUAGE_TRANSLATION],language:[i.AIAgentCapability.LANGUAGE_TRANSLATION],summarize:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],summary:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],extract:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],extraction:[i.AIAgentCapability.SUMMARIZATION_EXTRACTION],knowledge:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],search:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],retrieve:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],lookup:[i.AIAgentCapability.KNOWLEDGE_RETRIEVAL],data:[i.AIAgentCapability.DATA_INTEGRATION],"data processing":[i.AIAgentCapability.DATA_INTEGRATION],"data integration":[i.AIAgentCapability.DATA_INTEGRATION],etl:[i.AIAgentCapability.DATA_INTEGRATION],market:[i.AIAgentCapability.MARKET_INTELLIGENCE],trading:[i.AIAgentCapability.MARKET_INTELLIGENCE],finance:[i.AIAgentCapability.MARKET_INTELLIGENCE],financial:[i.AIAgentCapability.MARKET_INTELLIGENCE],analytics:[i.AIAgentCapability.TRANSACTION_ANALYTICS],analysis:[i.AIAgentCapability.TRANSACTION_ANALYTICS],analyze:[i.AIAgentCapability.TRANSACTION_ANALYTICS],transactions:[i.AIAgentCapability.TRANSACTION_ANALYTICS],audit:[i.AIAgentCapability.SMART_CONTRACT_AUDIT],contract:[i.AIAgentCapability.SMART_CONTRACT_AUDIT],"smart contract":[i.AIAgentCapability.SMART_CONTRACT_AUDIT],governance:[i.AIAgentCapability.GOVERNANCE_FACILITATION],voting:[i.AIAgentCapability.GOVERNANCE_FACILITATION],dao:[i.AIAgentCapability.GOVERNANCE_FACILITATION],security:[i.AIAgentCapability.SECURITY_MONITORING],monitoring:[i.AIAgentCapability.SECURITY_MONITORING],threat:[i.AIAgentCapability.SECURITY_MONITORING],compliance:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],regulatory:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],regulation:[i.AIAgentCapability.COMPLIANCE_ANALYSIS],fraud:[i.AIAgentCapability.FRAUD_DETECTION],detection:[i.AIAgentCapability.FRAUD_DETECTION],anomaly:[i.AIAgentCapability.FRAUD_DETECTION],coordination:[i.AIAgentCapability.MULTI_AGENT_COORDINATION],"multi-agent":[i.AIAgentCapability.MULTI_AGENT_COORDINATION],orchestration:[i.AIAgentCapability.MULTI_AGENT_COORDINATION],api:[i.AIAgentCapability.API_INTEGRATION],integration:[i.AIAgentCapability.API_INTEGRATION],webhook:[i.AIAgentCapability.API_INTEGRATION],workflow:[i.AIAgentCapability.WORKFLOW_AUTOMATION],automation:[i.AIAgentCapability.WORKFLOW_AUTOMATION],process:[i.AIAgentCapability.WORKFLOW_AUTOMATION]};let tt=et;const nt=We({name:He().min(1).max(50).describe("A unique name for the agent (1-50 characters)"),description:He().max(500).optional().describe("Optional bio description for the agent (max 500 characters)"),alias:He().optional().transform(e=>{if(!e||e.toLowerCase().includes("random")){return`bot${Date.now().toString(36)}${Math.random().toString(36)}`}return e}).describe('Optional custom username/alias for the agent. Use "random" to generate a unique alias'),type:Qe(["autonomous","manual"]).optional().describe("Agent type (default: autonomous)"),model:He().optional().describe("AI model identifier (default: agent-model-2024)"),capabilities:Je([Ve(Ye(i.AIAgentCapability)),Ve(He()),He()]).optional().transform(e=>{if(e)return"string"==typeof e?tt.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?tt.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:Je([Ve(He()),He()]).optional().transform(e=>{if(e)return"string"==typeof e?tt.parseCapabilities(e):tt.parseTagsOrCapabilities(e)}).describe('Tags for the agent (alternative to capabilities) - e.g. "ai", "data", "analytics". Will be converted to appropriate capabilities.'),creator:He().optional().describe("Creator attribution for the agent"),socials:Xe(Qe(["twitter","github","discord","telegram","linkedin","youtube","website","x"]),He()).optional().describe('Social media links (e.g., {"twitter": "@handle", "discord": "username"})'),properties:Xe(Ge()).optional().describe("Custom metadata properties for the agent"),profilePicture:Je([He().describe("URL or local file path to profile picture"),We({url:He().optional(),path:He().optional(),filename:He().optional()})]).optional().describe("Optional profile picture as URL, file path, or object with url/path/filename"),existingProfilePictureTopicId:He().optional().describe("Topic ID of an existing profile picture to reuse (e.g., 0.0.12345)"),initialBalance:Ze().positive().optional().describe("Optional initial HBAR balance for the new agent account (will create new account if provided)"),userAccountId:He().optional().describe("Optional account ID (e.g., 0.0.12345) to use as the agent account instead of creating a new one"),hbarFee:Ze().positive().optional().describe("Optional HBAR fee amount to charge per message on the inbound topic"),tokenFees:Ve(We({amount:Ze().positive(),tokenId:He()})).optional().describe("Optional token fees to charge per message"),exemptAccountIds:Ve(He()).optional().describe("Optional account IDs to exempt from fees"),setAsCurrent:ze().optional().describe("Whether to set as current agent (default: true)"),persistence:We({prefix:He().optional()}).optional().describe("Optional persistence configuration")});class it extends d{constructor(e){super(e),this.name="register_agent",this.description='Creates and registers the AI agent on the Hedera network. Returns JSON string with agent details (accountId, privateKey, topics) on success. 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=nt,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 rt=We({targetIdentifier:He().describe("The request key (e.g., 'req-1:0.0.6155171@0.0.6154875'), account ID (e.g., 0.0.12345) of the target agent, OR the connection number (e.g., '1', '2') from the 'list_connections' tool. Request key is most deterministic."),message:He().describe("The text message content to send."),disableMonitoring:ze().optional().default(!1)});class st extends d{constructor(e){super(e),this.name="send_message_to_connection",this.description="Sends a text message to another agent using an existing active connection. Identify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'. Return back the reply from the target agent if possible",this.specificInputSchema=rt,this.requiresMultipleTransactions=!0,this.neverScheduleThisTool=!0}async callBuilderMethod(e,t){const n=e;await n.sendMessageToConnection({targetIdentifier:t.targetIdentifier,message:t.message,disableMonitoring:t.disableMonitoring})}}const at=We({targetAccountId:He().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with."),disableMonitor:ze().optional().describe("If true, does not wait for connection confirmation. Returns immediately after sending the request."),memo:He().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 ot extends d{constructor(e){super(e),this.name="initiate_connection",this.description="Actively STARTS a NEW HCS-10 connection TO a specific target agent identified by their account ID. Requires the targetAccountId parameter. Use this ONLY to INITIATE an OUTGOING connection request.",this.specificInputSchema=at,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 ct=We({includeDetails:ze().optional().describe("Whether to include detailed information about each connection"),showPending:ze().optional().describe("Whether to include pending connection requests")});class dt extends u{constructor(e){super(e),this.name="list_connections",this.description="Lists the currently active HCS-10 connections with detailed information. Shows connection status, agent details, and recent activity. Use this to get a comprehensive view of all active connections.",this.specificInputSchema=ct}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 ut=We({targetIdentifier:He().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:ze().optional().default(!1).describe("Set to true to fetch the latest messages even if they have been seen before, ignoring the last checked timestamp. Defaults to false (fetching only new messages)."),lastMessagesCount:Ze().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")});class lt extends u{constructor(e){super(e),this.name="check_messages",this.description="Checks for and retrieves messages from an active connection.\nIdentify the target agent using their account ID (e.g., 0.0.12345) or the connection number shown in 'list_connections'.\nBy default, it only retrieves messages newer than the last check.\nUse 'fetchLatest: true' to get the most recent messages regardless of when they arrived.\nUse 'lastMessagesCount' to specify how many latest messages to retrieve (default 1 when fetchLatest is true).",this.specificInputSchema=ut}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 pt=We({accountId:He().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:Je([Ve(Ye(i.AIAgentCapability)),Ve(He()),He()]).optional().transform(e=>{if(e)return"string"==typeof e?tt.parseCapabilities(e):Array.isArray(e)&&e.length>0&&"string"==typeof e[0]?tt.parseTagsOrCapabilities(e):e}).describe('Optional: Filter by capabilities/tags like "ai", "data", "analytics". Can be natural language terms or capability numbers.')});class ht extends u{constructor(e){super(e),this.name="find_registrations",this.description='Searches the configured agent registry for HCS-10 agents. You can filter by account ID or tags/capabilities using natural language like "ai", "data processing", "analytics". Returns basic registration info.',this.specificInputSchema=pt}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 gt=We({acceptAll:ze().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:He().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:Ve(We({amount:Ze(),collectorAccount:He().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:Ve(We({amount:Ze(),tokenId:He(),collectorAccount:He().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:Ve(He()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:Ze().optional().describe("How long to monitor for incoming requests in seconds. Default is 120."),defaultCollectorAccount:He().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")});class ft extends d{constructor(e){super(e),this.name="monitor_connections",this.description="Monitors for incoming connection requests and accepts them with optional fee settings. Use this to watch for connection requests and accept them, optionally setting HBAR or token fees on the connection. Note: When acceptAll=true, this tool requires multiple transactions and cannot be used in returnBytes mode.",this.specificInputSchema=gt,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 mt=We({action:Qe(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:He().optional().describe("The unique request key to view or reject (required for view and reject actions)")});class yt extends u{constructor(e){super(e),this.name="manage_connection_requests",this.description='Manage incoming connection requests. List pending requests, view details about requesting agents, and reject connection requests. Use the separate "accept_connection_request" tool to accept.',this.specificInputSchema=mt}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 bt=We({requestKey:He().describe('The unique request key of the specific request to accept. Use the "manage_connection_requests" tool with action="list" first to get valid keys.'),hbarFee:Ze().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:Ve(He()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")});class vt extends d{constructor(e){super(e),this.name="accept_connection_request",this.description="Accepts a pending HCS-10 connection request from another agent. Use list_unapproved_connection_requests to see pending requests.",this.specificInputSchema=bt,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 wt=We({accountId:He().describe("The Hedera account ID of the agent whose profile you want to retrieve (e.g., 0.0.12345)."),disableCache:ze().optional().describe("Optional: Force refresh from the network instead of using cache.")});class It extends u{constructor(e){super(e),this.name="retrieve_profile",this.description="Gets the detailed profile information for a specific HCS-10 agent by their account ID. Returns name, bio, capabilities, topics, and other metadata.",this.specificInputSchema=wt}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 At=We({});class _t extends u{constructor(e){super(e),this.name="list_unapproved_connection_requests",this.description="Lists all connection requests that are not fully established, including incoming requests needing approval and outgoing requests waiting for confirmation.",this.specificInputSchema=At}async executeQuery(){const e=this.hcs10Builder;await e.listUnapprovedConnectionRequests();const t=await e.execute();return"rawResult"in t?t.rawResult:t}}class Tt extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}class Ct extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="hcs2",this.hcs2Builder=e.hcs2Builder}getServiceBuilder(){return this.hcs2Builder}}const Et=We({registryType:Ye(i.HCS2RegistryType).optional().describe("Registry type: 0 for indexed, 1 for non-indexed (default: 0)"),ttl:Ze().int().positive().optional().describe("Time to live in seconds (default: 86400)"),adminKey:Je([He(),ze()]).optional().describe("Admin key: public key string or true to use operator key"),submitKey:Je([He(),ze()]).optional().describe("Submit key: public key string or true to use operator key")});const Rt=We({registryTopicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (e.g., 0.0.123456)"),targetTopicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The target topic ID to register (e.g., 0.0.123456)"),metadata:He().optional().describe("Optional metadata URI (HIP-412 format)"),memo:He().max(500).optional().describe("Optional memo (max 500 characters)")});const St=We({registryTopicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),targetTopicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to point to"),uid:He().describe("The unique ID of the entry to update"),metadata:He().optional().describe("Optional metadata URI (HIP-412 format)"),memo:He().max(500).optional().describe("Optional memo (max 500 characters)")});const xt=We({registryTopicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID (must be indexed)"),uid:He().describe("The unique ID of the entry to delete"),memo:He().max(500).optional().describe("Optional memo (max 500 characters)")});const kt=We({registryTopicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The current HCS-2 registry topic ID"),targetTopicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The new topic ID to migrate to"),metadata:He().optional().describe("Optional metadata URI for migration details"),memo:He().max(500).optional().describe("Optional memo (max 500 characters)")});const Ot=We({topicId:He().regex(/^\d+\.\d+\.\d+$/).describe("The HCS-2 registry topic ID to query"),limit:Ze().int().positive().optional().describe("Maximum number of entries to return"),order:Qe(["asc","desc"]).optional().describe("Order of results (ascending or descending)"),skip:Ze().int().min(0).optional().describe("Number of entries to skip")});class Nt extends n.BaseHederaTransactionTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}class $t extends n.BaseHederaQueryTool{constructor(e){super(e),this.namespace="inscriber",this.inscriberBuilder=e.inscriberBuilder}getServiceBuilder(){return this.inscriberBuilder}}const Pt=We({url:He().url().describe("The URL of the content to inscribe"),mode:Qe(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:Xe(Ge()).optional().describe("Metadata to attach to the inscription"),tags:Ve(He()).optional().describe("Tags to categorize the inscription"),chunkSize:Ze().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:ze().optional().describe("Whether to wait for inscription confirmation"),apiKey:He().optional().describe("API key for inscription service")});const Mt=We({filePath:He().describe("The file path of the content to inscribe"),mode:Qe(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:Xe(Ge()).optional().describe("Metadata to attach to the inscription"),tags:Ve(He()).optional().describe("Tags to categorize the inscription"),chunkSize:Ze().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:ze().optional().describe("Whether to wait for inscription confirmation"),apiKey:He().optional().describe("API key for inscription service")});const Ft=We({base64Data:He().describe("Base64 encoded content to inscribe"),fileName:He().describe("Name for the inscribed content"),mimeType:He().optional().describe("MIME type of the content"),mode:Qe(["file","hashinal"]).optional().describe("Inscription mode: file or hashinal NFT"),metadata:Xe(Ge()).optional().describe("Metadata to attach to the inscription"),tags:Ve(He()).optional().describe("Tags to categorize the inscription"),chunkSize:Ze().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:ze().optional().describe("Whether to wait for inscription confirmation"),apiKey:He().optional().describe("API key for inscription service")});const qt=We({url:He().url().describe("The URL of the content to inscribe as Hashinal NFT"),name:He().describe("Name of the Hashinal NFT"),creator:He().describe("Creator account ID or name"),description:He().describe("Description of the Hashinal NFT"),type:He().describe('Type of NFT (e.g., "image", "video", "audio")'),attributes:Ve(We({trait_type:He(),value:Je([He(),Ze()])})).optional().describe("NFT attributes"),properties:Xe(Ge()).optional().describe("Additional properties"),jsonFileURL:He().url().optional().describe("URL to JSON metadata file"),tags:Ve(He()).optional().describe("Tags to categorize the NFT"),chunkSize:Ze().int().positive().optional().describe("Chunk size for large files"),waitForConfirmation:ze().optional().describe("Whether to wait for inscription confirmation"),apiKey:He().optional().describe("API key for inscription service")});const Dt=We({transactionId:He().describe("The transaction ID of the inscription to retrieve"),apiKey:He().optional().describe("API key for inscription service")});const Lt=s.join(c.cwd(),".env");class Bt{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const t=e?.disableLogging||"true"===c.env.DISABLE_LOGGING;this.logger=new i.Logger({module:"OpenConvaiState",silent:t}),e?.baseClient&&this.initializeConnectionsManager(e.baseClient)}initializeConnectionsManager(e){return this.connectionsManager?this.logger.debug("ConnectionsManager already initialized"):(this.logger.debug("Initializing ConnectionsManager"),this.connectionsManager=new i.ConnectionsManager({baseClient:e,logLevel:"error"})),this.connectionsManager}getConnectionsManager(){return this.connectionsManager}setCurrentAgent(e){this.currentAgent=e,this.connectionMessageTimestamps={},this.connectionsManager&&this.connectionsManager.clearAll()}getCurrentAgent(){return this.currentAgent}addActiveConnection(e){if(!this.connectionsManager)throw this.logger.error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections."),new Error("ConnectionsManager not initialized. Call initializeConnectionsManager before adding connections.");const t={connectionTopicId:e.connectionTopicId,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:this.convertConnectionStatus(e.status||"established"),isPending:e.isPending||!1,needsConfirmation:e.needsConfirmation||!1,created:e.created||new Date,lastActivity:e.lastActivity,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId,processed:!0};this.connectionsManager.updateOrAddConnection(t),this.initializeTimestampIfNeeded(e.connectionTopicId)}updateOrAddConnection(e){this.addActiveConnection(e)}listConnections(){return this.connectionsManager?this.connectionsManager.getAllConnections().map(e=>this.convertToActiveConnection(e)):(this.logger.debug("ConnectionsManager not initialized, returning empty connections list"),[])}getConnectionByIdentifier(e){if(!this.connectionsManager)return;const t=this.listConnections(),n=parseInt(e)-1;if(!isNaN(n)&&n>=0&&n<t.length)return t[n];const i=this.connectionsManager.getConnectionByTopicId(e);if(i)return this.convertToActiveConnection(i);const r=this.connectionsManager.getConnectionByAccountId(e);return r?this.convertToActiveConnection(r):void 0}getLastTimestamp(e){return this.connectionMessageTimestamps[e]||0}updateTimestamp(e,t){if(!(e in this.connectionMessageTimestamps))return void(this.connectionMessageTimestamps[e]=t);t>this.connectionMessageTimestamps[e]&&(this.connectionMessageTimestamps[e]=t)}initializeTimestampIfNeeded(e){e in this.connectionMessageTimestamps||(this.connectionMessageTimestamps[e]=1e6*Date.now())}convertConnectionStatus(e){switch(e){case"pending":return"pending";case"established":default:return"established";case"needs confirmation":return"needs_confirmation"}}convertToActiveConnection(e){return{targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName||`Agent ${e.targetAccountId}`,targetInboundTopicId:e.targetInboundTopicId||"",connectionTopicId:e.connectionTopicId,status:this.convertToStateStatus(e.status),created:e.created,lastActivity:e.lastActivity,isPending:e.isPending,needsConfirmation:e.needsConfirmation,profileInfo:e.profileInfo,connectionRequestId:e.connectionRequestId}}convertToStateStatus(e){switch(e){case"pending":return"pending";case"established":case"closed":return"established";case"needs_confirmation":return"needs confirmation";default:return"unknown"}}async persistAgentData(e,t){if(t?.type&&"env-file"!==t.type)throw new Error(`Unsupported persistence type: ${t.type}. Only 'env-file' is supported.`);const n=t?.envFilePath||this.defaultEnvFilePath||c.env.ENV_FILE_PATH||".env",i=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const s={[`${i}_ACCOUNT_ID`]:e.accountId,[`${i}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${i}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(s[`${i}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(s[`${i}_PROFILE_TOPIC_ID`]=e.profileTopicId),await async function(e,t){let n="";r.existsSync(e)&&(n=r.readFileSync(e,"utf8"));const i=[...n.split("\n")];for(const[r,s]of Object.entries(t)){const e=i.findIndex(e=>e.startsWith(`${r}=`));-1!==e?i[e]=`${r}=${s}`:i.push(`${r}=${s}`)}r.writeFileSync(e,i.join("\n"))}(n,s)}}function jt(e,t){return function(){return e.apply(t,arguments)}}const{toString:Ut}=Object.prototype,{getPrototypeOf:Kt}=Object,{iterator:Ht,toStringTag:Zt}=Symbol,zt=(e=>t=>{const n=Ut.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Gt=e=>(e=e.toLowerCase(),t=>zt(t)===e),Vt=e=>t=>typeof t===e,{isArray:Wt}=Array,Jt=Vt("undefined");const Xt=Gt("ArrayBuffer");const Qt=Vt("string"),Yt=Vt("function"),en=Vt("number"),tn=e=>null!==e&&"object"==typeof e,nn=e=>{if("object"!==zt(e))return!1;const t=Kt(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Zt in e||Ht in e)},rn=Gt("Date"),sn=Gt("File"),an=Gt("Blob"),on=Gt("FileList"),cn=Gt("URLSearchParams"),[dn,un,ln,pn]=["ReadableStream","Request","Response","Headers"].map(Gt);function hn(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),Wt(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{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 gn(e,t){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 fn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:a,mn=e=>!Jt(e)&&e!==fn;const yn=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Kt(Uint8Array)),bn=Gt("HTMLFormElement"),vn=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),wn=Gt("RegExp"),In=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};hn(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)};const An=Gt("AsyncFunction"),_n=(Tn="function"==typeof o.setImmediate,Cn=Yt(fn.postMessage),Tn?o.setImmediate:Cn?(En=`axios@${Math.random()}`,Rn=[],fn.addEventListener("message",({source:e,data:t})=>{e===fn&&t===En&&Rn.length&&Rn.shift()()},!1),e=>{Rn.push(e),fn.postMessage(En,"*")}):e=>setTimeout(e));var Tn,Cn,En,Rn;const Sn="undefined"!=typeof queueMicrotask?queueMicrotask.bind(fn):void 0!==c&&c.nextTick||_n,xn={isArray:Wt,isArrayBuffer:Xt,isBuffer:function(e){return null!==e&&!Jt(e)&&null!==e.constructor&&!Jt(e.constructor)&&Yt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Yt(e.append)&&("formdata"===(t=zt(e))||"object"===t&&Yt(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Xt(e.buffer),t},isString:Qt,isNumber:en,isBoolean:e=>!0===e||!1===e,isObject:tn,isPlainObject:nn,isReadableStream:dn,isRequest:un,isResponse:ln,isHeaders:pn,isUndefined:Jt,isDate:rn,isFile:sn,isBlob:an,isRegExp:wn,isFunction:Yt,isStream:e=>tn(e)&&Yt(e.pipe),isURLSearchParams:cn,isTypedArray:yn,isFileList:on,forEach:hn,merge:function e(){const{caseless:t}=mn(this)&&this||{},n={},i=(i,r)=>{const s=t&&gn(n,r)||r;nn(n[s])&&nn(i)?n[s]=e(n[s],i):nn(i)?n[s]=e({},i):Wt(i)?n[s]=i.slice():n[s]=i};for(let r=0,s=arguments.length;r<s;r++)arguments[r]&&hn(arguments[r],i);return n},extend:(e,t,n,{allOwnKeys:i}={})=>(hn(t,(t,i)=>{n&&Yt(t)?e[i]=jt(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&&Kt(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:zt,kindOfTest:Gt,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(Wt(e))return e;let t=e.length;if(!en(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Ht]).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:bn,hasOwnProperty:vn,hasOwnProp:vn,reduceDescriptors:In,freezeMethods:e=>{In(e,(t,n)=>{if(Yt(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];Yt(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 Wt(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:gn,global:fn,isContextDefined:mn,isSpecCompliantForm:function(e){return!!(e&&Yt(e.append)&&"FormData"===e[Zt]&&e[Ht])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(tn(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[i]=e;const r=Wt(e)?[]:{};return hn(e,(e,t)=>{const s=n(e,i+1);!Jt(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:An,isThenable:e=>e&&(tn(e)||Yt(e))&&Yt(e.then)&&Yt(e.catch),setImmediate:_n,asap:Sn,isIterable:e=>null!=e&&Yt(e[Ht])};function kn(e,t,n,i,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),i&&(this.request=i),r&&(this.response=r,this.status=r.status?r.status:null)}xn.inherits(kn,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:xn.toJSONObject(this.config),code:this.code,status:this.status}}});const On=kn.prototype,Nn={};["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=>{Nn[e]={value:e}}),Object.defineProperties(kn,Nn),Object.defineProperty(On,"isAxiosError",{value:!0}),kn.from=(e,t,n,i,r,s)=>{const a=Object.create(On);return xn.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),kn.call(a,e.message,t,n,i,r),a.cause=e,a.name=e.name,s&&Object.assign(a,s),a};function $n(e){return xn.isPlainObject(e)||xn.isArray(e)}function Pn(e){return xn.endsWith(e,"[]")?e.slice(0,-2):e}function Mn(e,t,n){return e?e.concat(t).map(function(e,t){return e=Pn(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Fn=xn.toFlatObject(xn,{},null,function(e){return/^is[A-Z]/.test(e)});function qn(e,n,i){if(!xn.isObject(e))throw new TypeError("target must be an object");n=n||new FormData;const r=(i=xn.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!xn.isUndefined(t[e])})).metaTokens,s=i.visitor||u,a=i.dots,o=i.indexes,c=(i.Blob||"undefined"!=typeof Blob&&Blob)&&xn.isSpecCompliantForm(n);if(!xn.isFunction(s))throw new TypeError("visitor must be a function");function d(e){if(null===e)return"";if(xn.isDate(e))return e.toISOString();if(xn.isBoolean(e))return e.toString();if(!c&&xn.isBlob(e))throw new kn("Blob is not supported. Use a Buffer instead.");return xn.isArrayBuffer(e)||xn.isTypedArray(e)?c&&"function"==typeof Blob?new Blob([e]):t.Buffer.from(e):e}function u(e,t,i){let s=e;if(e&&!i&&"object"==typeof e)if(xn.endsWith(t,"{}"))t=r?t:t.slice(0,-2),e=JSON.stringify(e);else if(xn.isArray(e)&&function(e){return xn.isArray(e)&&!e.some($n)}(e)||(xn.isFileList(e)||xn.endsWith(t,"[]"))&&(s=xn.toArray(e)))return t=Pn(t),s.forEach(function(e,i){!xn.isUndefined(e)&&null!==e&&n.append(!0===o?Mn([t],i,a):null===o?t:t+"[]",d(e))}),!1;return!!$n(e)||(n.append(Mn(i,t,a),d(e)),!1)}const l=[],p=Object.assign(Fn,{defaultVisitor:u,convertValue:d,isVisitable:$n});if(!xn.isObject(e))throw new TypeError("data must be an object");return function e(t,i){if(!xn.isUndefined(t)){if(-1!==l.indexOf(t))throw Error("Circular reference detected in "+i.join("."));l.push(t),xn.forEach(t,function(t,r){!0===(!(xn.isUndefined(t)||null===t)&&s.call(n,t,xn.isString(r)?r.trim():r,i,p))&&e(t,i?i.concat(r):[r])}),l.pop()}}(e),n}function Dn(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Ln(e,t){this._pairs=[],e&&qn(e,this,t)}const Bn=Ln.prototype;function jn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Un(e,t,n){if(!t)return e;const i=n&&n.encode||jn;xn.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):xn.isURLSearchParams(t)?t.toString():new Ln(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}Bn.append=function(e,t){this._pairs.push([e,t])},Bn.toString=function(e){const t=e?function(t){return e.call(this,t,Dn)}:Dn;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Kn{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){xn.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Hn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zn={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ln,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},zn="undefined"!=typeof window&&"undefined"!=typeof document,Gn="object"==typeof navigator&&navigator||void 0,Vn=zn&&(!Gn||["ReactNative","NativeScript","NS"].indexOf(Gn.product)<0),Wn="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Jn=zn&&window.location.href||"http://localhost",Xn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:zn,hasStandardBrowserEnv:Vn,hasStandardBrowserWebWorkerEnv:Wn,navigator:Gn,origin:Jn},Symbol.toStringTag,{value:"Module"})),...Zn};function Qn(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&&xn.isArray(i)?i.length:s,o)return xn.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a;i[s]&&xn.isObject(i[s])||(i[s]=[]);return t(e,n,i[s],r)&&xn.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(xn.isFormData(e)&&xn.isFunction(e.entries)){const n={};return xn.forEachEntry(e,(e,i)=>{t(function(e){return xn.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null}const Yn={transitional:Hn,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=xn.isObject(e);r&&xn.isHTMLForm(e)&&(e=new FormData(e));if(xn.isFormData(e))return i?JSON.stringify(Qn(e)):e;if(xn.isArrayBuffer(e)||xn.isBuffer(e)||xn.isStream(e)||xn.isFile(e)||xn.isBlob(e)||xn.isReadableStream(e))return e;if(xn.isArrayBufferView(e))return e.buffer;if(xn.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return qn(e,new Xn.classes.URLSearchParams,Object.assign({visitor:function(e,t,n,i){return Xn.isNode&&xn.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((s=xn.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return qn(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(xn.isString(e))try{return(t||JSON.parse)(e),xn.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Yn.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(xn.isResponse(e)||xn.isReadableStream(e))return e;if(e&&xn.isString(e)&&(n&&!this.responseType||i)){const n=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(r){if(n){if("SyntaxError"===r.name)throw kn.from(r,kn.ERR_BAD_RESPONSE,this,null,this.response);throw r}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Xn.classes.FormData,Blob:Xn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};xn.forEach(["delete","get","head","post","put","patch"],e=>{Yn.headers[e]={}});const ei=xn.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"]),ti=Symbol("internals");function ni(e){return e&&String(e).trim().toLowerCase()}function ii(e){return!1===e||null==e?e:xn.isArray(e)?e.map(ii):String(e)}function ri(e,t,n,i,r){return xn.isFunction(i)?i.call(this,t,n):(r&&(t=n),xn.isString(t)?xn.isString(i)?-1!==t.indexOf(i):xn.isRegExp(i)?i.test(t):void 0:void 0)}let si=class{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=ni(t);if(!r)throw new Error("header name must be a non-empty string");const s=xn.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=ii(e))}const s=(e,t)=>xn.forEach(e,(e,n)=>r(e,n,t));if(xn.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(xn.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]&&ei[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(xn.isObject(e)&&xn.isIterable(e)){let n,i,r={};for(const t of e){if(!xn.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?xn.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=ni(e)){const n=xn.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(xn.isFunction(t))return t.call(this,e,n);if(xn.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=ni(e)){const n=xn.findKey(this,e);return!(!n||void 0===this[n]||t&&!ri(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=ni(e)){const r=xn.findKey(n,e);!r||t&&!ri(0,n[r],r,t)||(delete n[r],i=!0)}}return xn.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&&!ri(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return xn.forEach(this,(i,r)=>{const s=xn.findKey(n,r);if(s)return t[s]=ii(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]=ii(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return xn.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&xn.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[ti]=this[ti]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=ni(e);t[i]||(!function(e,t){const n=xn.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 xn.isArray(e)?e.forEach(i):i(e),this}};function ai(e,t){const n=this||Yn,i=t||n,r=si.from(i.headers);let s=i.data;return xn.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function oi(e){return!(!e||!e.__CANCEL__)}function ci(e,t,n){kn.call(this,null==e?"canceled":e,kn.ERR_CANCELED,t,n),this.name="CanceledError"}function di(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new kn("Request failed with status code "+n.status,[kn.ERR_BAD_REQUEST,kn.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}si.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),xn.reduceDescriptors(si.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),xn.freezeMethods(si),xn.inherits(ci,kn,{__CANCEL__:!0});const ui=(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 u=a,l=0;for(;u!==s;)l+=n[u++],u%=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*l/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.apply(null,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)},li=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},pi=e=>(...t)=>xn.asap(()=>e(...t)),hi=Xn.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Xn.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Xn.origin),Xn.navigator&&/(msie|trident)/i.test(Xn.navigator.userAgent)):()=>!0,gi=Xn.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const a=[e+"="+encodeURIComponent(t)];xn.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),xn.isString(i)&&a.push("path="+i),xn.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 fi(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 mi=e=>e instanceof si?{...e}:e;function yi(e,t){t=t||{};const n={};function i(e,t,n,i){return xn.isPlainObject(e)&&xn.isPlainObject(t)?xn.merge.call({caseless:i},e,t):xn.isPlainObject(t)?xn.merge({},t):xn.isArray(t)?t.slice():t}function r(e,t,n,r){return xn.isUndefined(t)?xn.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!xn.isUndefined(t))return i(void 0,t)}function a(e,t){return xn.isUndefined(t)?xn.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(mi(e),mi(t),0,!0)};return xn.forEach(Object.keys(Object.assign({},e,t)),function(i){const s=c[i]||r,a=s(e[i],t[i],i);xn.isUndefined(a)&&s!==o||(n[i]=a)}),n}const bi=e=>{const t=yi({},e);let n,{data:i,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:a,headers:o,auth:c}=t;if(t.headers=o=si.from(o),t.url=Un(fi(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),xn.isFormData(i))if(Xn.hasStandardBrowserEnv||Xn.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(Xn.hasStandardBrowserEnv&&(r&&xn.isFunction(r)&&(r=r(t)),r||!1!==r&&hi(t.url))){const e=s&&a&&gi.read(a);e&&o.set(s,e)}return t},vi="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=bi(e);let r=i.data;const s=si.from(i.headers).normalize();let a,o,c,d,u,{responseType:l,onUploadProgress:p,onDownloadProgress:h}=i;function g(){d&&d(),u&&u(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let f=new XMLHttpRequest;function m(){if(!f)return;const i=si.from("getAllResponseHeaders"in f&&f.getAllResponseHeaders());di(function(e){t(e),g()},function(e){n(e),g()},{data:l&&"text"!==l&&"json"!==l?f.response:f.responseText,status:f.status,statusText:f.statusText,headers:i,config:e,request:f}),f=null}f.open(i.method.toUpperCase(),i.url,!0),f.timeout=i.timeout,"onloadend"in f?f.onloadend=m:f.onreadystatechange=function(){f&&4===f.readyState&&(0!==f.status||f.responseURL&&0===f.responseURL.indexOf("file:"))&&setTimeout(m)},f.onabort=function(){f&&(n(new kn("Request aborted",kn.ECONNABORTED,e,f)),f=null)},f.onerror=function(){n(new kn("Network Error",kn.ERR_NETWORK,e,f)),f=null},f.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||Hn;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new kn(t,r.clarifyTimeoutError?kn.ETIMEDOUT:kn.ECONNABORTED,e,f)),f=null},void 0===r&&s.setContentType(null),"setRequestHeader"in f&&xn.forEach(s.toJSON(),function(e,t){f.setRequestHeader(t,e)}),xn.isUndefined(i.withCredentials)||(f.withCredentials=!!i.withCredentials),l&&"json"!==l&&(f.responseType=i.responseType),h&&([c,u]=ui(h,!0),f.addEventListener("progress",c)),p&&f.upload&&([o,d]=ui(p),f.upload.addEventListener("progress",o),f.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(a=t=>{f&&(n(!t||t.type?new ci(null,e,f):t),f.abort(),f=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===Xn.protocols.indexOf(y)?n(new kn("Unsupported protocol "+y+":",kn.ERR_BAD_REQUEST,e)):f.send(r||null)})},wi=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof kn?t:new ci(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new kn(`timeout ${t} of ms exceeded`,kn.ETIMEDOUT))},t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:o}=i;return o.unsubscribe=()=>xn.asap(a),o}},Ii=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},Ai=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()}},_i=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of Ai(e))yield*Ii(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})},Ti="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Ci=Ti&&"function"==typeof ReadableStream,Ei=Ti&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Ri=(e,...t)=>{try{return!!e(...t)}catch(n){return!1}},Si=Ci&&Ri(()=>{let e=!1;const t=new Request(Xn.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),xi=Ci&&Ri(()=>xn.isReadableStream(new Response("").body)),ki={stream:xi&&(e=>e.body)};var Oi;Ti&&(Oi=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!ki[e]&&(ki[e]=xn.isFunction(Oi[e])?t=>t[e]():(t,n)=>{throw new kn(`Response type '${e}' is not supported`,kn.ERR_NOT_SUPPORT,n)})}));const Ni=async(e,t)=>{const n=xn.toFiniteNumber(e.getContentLength());return null==n?(async e=>{if(null==e)return 0;if(xn.isBlob(e))return e.size;if(xn.isSpecCompliantForm(e)){const t=new Request(Xn.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return xn.isArrayBufferView(e)||xn.isArrayBuffer(e)?e.byteLength:(xn.isURLSearchParams(e)&&(e+=""),xn.isString(e)?(await Ei(e)).byteLength:void 0)})(t):n},$i={http:null,xhr:vi,fetch:Ti&&(async e=>{let{url:t,method:n,data:i,signal:r,cancelToken:s,timeout:a,onDownloadProgress:o,onUploadProgress:c,responseType:d,headers:u,withCredentials:l="same-origin",fetchOptions:p}=bi(e);d=d?(d+"").toLowerCase():"text";let h,g=wi([r,s&&s.toAbortSignal()],a);const f=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let m;try{if(c&&Si&&"get"!==n&&"head"!==n&&0!==(m=await Ni(u,i))){let e,n=new Request(t,{method:"POST",body:i,duplex:"half"});if(xn.isFormData(i)&&(e=n.headers.get("content-type"))&&u.setContentType(e),n.body){const[e,t]=li(m,ui(pi(c)));i=_i(n.body,65536,e,t)}}xn.isString(l)||(l=l?"include":"omit");const r="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:n.toUpperCase(),headers:u.normalize().toJSON(),body:i,duplex:"half",credentials:r?l:void 0});let s=await fetch(h,p);const a=xi&&("stream"===d||"response"===d);if(xi&&(o||a&&f)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=s[t]});const t=xn.toFiniteNumber(s.headers.get("content-length")),[n,i]=o&&li(t,ui(pi(o),!0))||[];s=new Response(_i(s.body,65536,n,()=>{i&&i(),f&&f()}),e)}d=d||"text";let y=await ki[xn.findKey(ki,d)||"text"](s,e);return!a&&f&&f(),await new Promise((t,n)=>{di(t,n,{data:y,headers:si.from(s.headers),status:s.status,statusText:s.statusText,config:e,request:h})})}catch(y){if(f&&f(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new kn("Network Error",kn.ERR_NETWORK,e,h),{cause:y.cause||y});throw kn.from(y,y&&y.code,e,h)}})};xn.forEach($i,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(n){}Object.defineProperty(e,"adapterName",{value:t})}});const Pi=e=>`- ${e}`,Mi=e=>xn.isFunction(e)||null===e||!1===e,Fi=e=>{e=xn.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,!Mi(n)&&(i=$i[(t=String(n)).toLowerCase()],void 0===i))throw new kn(`Unknown adapter '${t}'`);if(i)break;r[t||"#"+s]=i}if(!i){const e=Object.entries(r).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new kn("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Pi).join("\n"):" "+Pi(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function qi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ci(null,e)}function Di(e){qi(e),e.headers=si.from(e.headers),e.data=ai.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Fi(e.adapter||Yn.adapter)(e).then(function(t){return qi(e),t.data=ai.call(e,e.transformResponse,t),t.headers=si.from(t.headers),t},function(t){return oi(t)||(qi(e),t&&t.response&&(t.response.data=ai.call(e,e.transformResponse,t.response),t.response.headers=si.from(t.response.headers))),Promise.reject(t)})}const Li="1.10.0",Bi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Bi[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const ji={};Bi.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Li+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new kn(i(r," has been removed"+(t?" in "+t:"")),kn.ERR_DEPRECATED);return t&&!ji[r]&&(ji[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)}},Bi.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const Ui={assertOptions:function(e,t,n){if("object"!=typeof e)throw new kn("options must be an object",kn.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],a=t[s];if(a){const t=e[s],n=void 0===t||a(t,s,e);if(!0!==n)throw new kn("option "+s+" must be "+n,kn.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new kn("Unknown option "+s,kn.ERR_BAD_OPTION)}},validators:Bi},Ki=Ui.validators;let Hi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Kn,response:new Kn}}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=yi(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&Ui.assertOptions(n,{silentJSONParsing:Ki.transitional(Ki.boolean),forcedJSONParsing:Ki.transitional(Ki.boolean),clarifyTimeoutError:Ki.transitional(Ki.boolean)},!1),null!=i&&(xn.isFunction(i)?t.paramsSerializer={serialize:i}:Ui.assertOptions(i,{encode:Ki.function,serialize:Ki.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ui.assertOptions(t,{baseUrl:Ki.spelling("baseURL"),withXsrfToken:Ki.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&xn.merge(r.common,r[t.method]);r&&xn.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=si.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 u,l=0;if(!o){const e=[Di.bind(this),void 0];for(e.unshift.apply(e,a),e.push.apply(e,c),u=e.length,d=Promise.resolve(t);l<u;)d=d.then(e[l++],e[l++]);return d}u=a.length;let p=t;for(l=0;l<u;){const e=a[l++],t=a[l++];try{p=e(p)}catch(h){t.call(this,h);break}}try{d=Di.call(this,p)}catch(h){return Promise.reject(h)}for(l=0,u=c.length;l<u;)d=d.then(c[l++],c[l++]);return d}getUri(e){return Un(fi((e=yi(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};xn.forEach(["delete","get","head","options"],function(e){Hi.prototype[e]=function(t,n){return this.request(yi(n||{},{method:e,url:t,data:(n||{}).data}))}}),xn.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(yi(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}Hi.prototype[e]=t(),Hi.prototype[e+"Form"]=t(!0)});const Zi={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(Zi).forEach(([e,t])=>{Zi[t]=e});const zi=function e(t){const n=new Hi(t),i=jt(Hi.prototype.request,n);return xn.extend(i,Hi.prototype,n,{allOwnKeys:!0}),xn.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(yi(t,n))},i}(Yn);zi.Axios=Hi,zi.CanceledError=ci,zi.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 ci(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}}},zi.isCancel=oi,zi.VERSION=Li,zi.toFormData=qn,zi.AxiosError=kn,zi.Cancel=zi.CanceledError,zi.all=function(e){return Promise.all(e)},zi.spread=function(e){return function(t){return e.apply(null,t)}},zi.isAxiosError=function(e){return xn.isObject(e)&&!0===e.isAxiosError},zi.mergeConfig=yi,zi.AxiosHeaders=si,zi.formToJSON=e=>Qn(xn.isHTMLForm(e)?new FormData(e):e),zi.getAdapter=Fi,zi.HttpStatusCode=Zi,zi.default=zi;const{Axios:Gi,AxiosError:Vi,CanceledError:Wi,isCancel:Ji,CancelToken:Xi,VERSION:Qi,all:Yi,Cancel:er,isAxiosError:tr,spread:nr,toFormData:ir,AxiosHeaders:rr,HttpStatusCode:sr,formToJSON:ar,getAdapter:or,mergeConfig:cr}=zi,dr="ConnectionsManager not initialized";class ur extends n.BaseServiceBuilder{constructor(e,t,n){super(e),this.stateManager=t,this.useEncryption=n?.useEncryption||!1,this.guardedRegistryBaseUrl=n?.registryUrl||"";const r=this.hederaKit.client.network;this.network=r.toString().includes("mainnet")?"mainnet":"testnet";const s=this.hederaKit.signer.getAccountId().toString(),a=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";this.sdkLogger=new i.Logger({module:"HCS10Builder",level:n?.logLevel||"info"}),this.standardClient=new i.HCS10Client({network:this.network,operatorId:s,operatorPrivateKey:a,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl,logLevel:n?.logLevel||"info"}),this.stateManager&&this.stateManager.initializeConnectionsManager(this.standardClient)}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.network}getStateManager(){return this.stateManager}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Builder] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Builder] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Builder] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}async getAgentProfile(e){try{return await this.standardClient.retrieveProfile(e)}catch(t){throw this.logger.error(`[HCS10Builder] Error retrieving agent profile for account ${e}:`,t),t}}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async handleConnectionRequest(e,t,n,i){try{const r=await this.standardClient.handleConnectionRequest(e,t,n,i);return r&&r.connectionTopicId&&"object"==typeof r.connectionTopicId&&"toString"in r.connectionTopicId&&(r.connectionTopicId=r.connectionTopicId.toString()),r}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async sendMessage(e,t,n){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to sendMessage: ${JSON.stringify(e)}`);try{const i=await this.standardClient.sendMessage(e,t,n,void 0);return{sequenceNumber:i.topicSequenceNumber?.toNumber(),receipt:i,transactionId:"transactionId"in i?i.transactionId?.toString():void 0}}catch(i){throw this.logger.error(`Error sending message to topic ${e}:`,i),new Error(`Failed to send message: ${i instanceof Error?i.message:String(i)}`)}}async getMessages(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessages: ${JSON.stringify(e)}`);try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data||"",sequence_number:e.sequence_number,p:"hcs-10"}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){if(e&&"object"==typeof e&&"toString"in e&&(e=e?.toString()),!e||"string"!=typeof e)throw new Error(`Invalid topic ID provided to getMessageStream: ${JSON.stringify(e)}`);return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}getStandardClient(){return this.standardClient}async loadProfilePicture(e){try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){this.logger.info(`Loading profile picture from URL: ${e}`);const n=await zi.get(e,{responseType:"arraybuffer"}),i=t.Buffer.from(n.data),r=new URL(e).pathname;return{buffer:i,filename:s.basename(r)||"profile.png"}}{if(!r.existsSync(e))return this.logger.warn(`Profile picture file not found: ${e}`),null;this.logger.info(`Loading profile picture from file: ${e}`);const t=r.readFileSync(e);return{buffer:t,filename:s.basename(e)}}}if(e.url){this.logger.info(`Loading profile picture from URL: ${e.url}`);const n=await zi.get(e.url,{responseType:"arraybuffer"}),i=t.Buffer.from(n.data);return{buffer:i,filename:e.filename||"profile.png"}}if(e.path){if(!r.existsSync(e.path))return this.logger.warn(`Profile picture file not found: ${e.path}`),null;this.logger.info(`Loading profile picture from file: ${e.path}`);const t=r.readFileSync(e.path);return{buffer:t,filename:e.filename||s.basename(e.path)}}return null}catch(n){return this.logger.error("Failed to load profile picture:",n),null}}async createAndRegisterAgent(e){const t=(new i.AgentBuilder).setName(e.name).setBio(e.bio||"").setCapabilities(e.capabilities||[i.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(i.InboundTopicType.PUBLIC);e.alias&&t.setAlias(e.alias),e.creator&&t.setCreator(e.creator),e?.feeConfig&&(t.setInboundTopicType(i.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.existingProfilePictureTopicId?t.setExistingProfilePicture(e.existingProfilePictureTopicId):e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided. Agent creation might fail if required by the underlying SDK builder."),e.socials&&Object.entries(e.socials).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig);return await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:10})}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async registerAgent(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Agent registration requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{let t=null;e.profilePicture&&(t=await this.loadProfilePicture(e.profilePicture));const n={name:e.name,...void 0!==e.bio&&{bio:e.bio},...void 0!==e.alias&&{alias:e.alias},...void 0!==e.type&&{type:e.type},...void 0!==e.model&&{model:e.model},...void 0!==e.capabilities&&{capabilities:e.capabilities},...void 0!==e.creator&&{creator:e.creator},...void 0!==e.socials&&{socials:e.socials},...void 0!==e.properties&&{properties:e.properties},...void 0!==e.existingProfilePictureTopicId&&{existingProfilePictureTopicId:e.existingProfilePictureTopicId},...void 0!==t?.buffer&&{pfpBuffer:t.buffer},...void 0!==t?.filename&&{pfpFileName:t.filename}};if(e.hbarFee&&e.hbarFee>0){const t=new i.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:r}=this.getAccountAndSigner();if(!r)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${r}) as the fee collector since no specific collector was provided.`);const s=e.exemptAccountIds?.filter(e=>e!==r&&e.startsWith("0.0"))||[];n.feeConfig=t.addHbarFee(e.hbarFee,r,s)}const r=await this.createAndRegisterAgent(n);this.executeResult={success:!0,transactionId:r.transactionId,receipt:void 0,scheduleId:void 0,rawResult:{...r,name:e.name,accountId:r?.metadata?.accountId||r.state?.agentMetadata?.accountId}}}catch(t){throw this.logger.error("Failed to register agent:",t),t}return this}async initiateConnection(e){this.clearNotes();try{const t=await this.getAgentProfile(e.targetAccountId);if(!t.success||!t.topicInfo?.inboundTopic)throw new Error(`Could not retrieve inbound topic for target account ${e.targetAccountId}`);const n=t.topicInfo.inboundTopic;let i;void 0!==e.memo?i=e.memo:(i=e.disableMonitor?"false":"true",this.addNote(`No custom memo was provided. Using default memo '${i}' based on monitoring preference.`)),e.disableMonitor||this.addNote("Monitoring will be enabled for this connection request as disableMonitor was not specified.");const r=await this.submitConnectionRequest(n,i);this.executeResult={success:!0,transactionId:"transactionId"in r?r.transactionId?.toString():void 0,receipt:r,scheduleId:void 0,rawResult:{targetAccountId:e.targetAccountId,targetInboundTopicId:n,connectionRequestSent:!0,monitoringEnabled:!e.disableMonitor,...r}}}catch(t){throw this.logger.error("Failed to initiate connection:",t),t}return this}async acceptConnection(e){if(this.clearNotes(),"returnBytes"===this.hederaKit.operationalMode)throw new Error("Accepting connections requires multiple transactions and cannot be performed in returnBytes mode. Please use autonomous mode.");try{const n=this.stateManager?.getCurrentAgent();if(!n)throw new Error("Cannot accept connection request. No agent is currently active. Please register or select an agent first.");const r=this.stateManager?.getConnectionsManager();if(!r)throw new Error(dr);await r.fetchConnectionData(n.accountId);const s=[...r.getPendingRequests(),...r.getConnectionsNeedingConfirmation()].find(t=>t.uniqueRequestKey===e.requestKey||t.connectionRequestId?.toString()===e.requestKey||t.inboundRequestId?.toString()===e.requestKey);if(!s)throw new Error(`Request with key ${e.requestKey} not found or no longer pending.`);if(!s.needsConfirmation||!s.inboundRequestId)throw new Error(`Request with key ${e.requestKey} is not an inbound request that can be accepted.`);const a=s.targetAccountId,o=s.inboundRequestId;let c;if(e.hbarFee&&e.hbarFee>0){const t=new i.FeeConfigBuilder({network:this.network,logger:this.sdkLogger}),{accountId:n}=this.getAccountAndSigner();if(!n)throw new Error("Could not determine account ID for fee collection.");this.addNote(`Setting the operator account (${n}) as the fee collector since no specific collector was provided.`);const r=e.exemptAccountIds?.filter(e=>e!==n&&e.startsWith("0.0"))||[];c=t.addHbarFee(e.hbarFee,n,r)}const d=await this.getInboundTopicId(),u=await this.handleConnectionRequest(d,a,o,c);let l=u?.connectionTopicId;if(l&&"object"==typeof l&&"toString"in l&&(l=l?.toString()),!l||"string"!=typeof l)throw new Error(`Failed to create connection topic. Got: ${JSON.stringify(l)}`);if(this.stateManager){const e=s.targetAgentName||`Agent ${a}`;s.targetAgentName||this.addNote(`No agent name was provided in the connection request, using default name 'Agent ${a}'.`);let n=s.targetInboundTopicId||"";if(!n)try{const e=await this.getAgentProfile(a);e.success&&e.topicInfo?.inboundTopic&&(n=e.topicInfo.inboundTopic)}catch(t){this.logger.warn(`Could not fetch profile for ${a}:`,t)}const i={connectionId:`conn-${Date.now()}`,targetAccountId:a,targetAgentName:e,targetInboundTopicId:n,connectionTopicId:l,status:"established",created:new Date};this.stateManager.addActiveConnection(i),r.markConnectionRequestProcessed(s.targetInboundTopicId||"",o)}this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{targetAccountId:a,connectionTopicId:l,feeConfigured:!!e.hbarFee,hbarFee:e.hbarFee||0,confirmationResult:u}}}catch(n){throw this.logger.error("Failed to accept connection:",n),n}return this}async sendHCS10Message(e){this.clearNotes();try{const t=await this.sendMessage(e.topicId,e.message);this.executeResult={success:!0,transactionId:t.transactionId,receipt:t.receipt,scheduleId:void 0,rawResult:t},this.addNote(`Message sent to topic ${e.topicId}.`)}catch(t){throw this.logger.error("Failed to send message:",t),t}return this}async sendMessageToConnection(e){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required to send messages to connections");try{const t=this.stateManager.getCurrentAgent();if(!t)throw new Error("Cannot send message. No agent is currently active. Please register or select an agent first.");let n;if(e.targetIdentifier.includes("@")){const t=e.targetIdentifier.split("@");if(2===t.length){const i=t[1];n=this.stateManager.getConnectionByIdentifier(i),n||this.addNote(`Could not find connection using request key '${e.targetIdentifier}', extracted account ID '${i}'.`)}}if(n||(n=this.stateManager.getConnectionByIdentifier(e.targetIdentifier)),!n){const t=this.stateManager.listConnections().map(e=>`${e.targetAccountId} (${e.connectionTopicId})`);throw new Error(`Connection not found for identifier: ${e.targetIdentifier}. Available connections: ${t.join(", ")||"none"}. Use 'list_connections' to see details.`)}let i=n.connectionTopicId;if(i&&"object"==typeof i&&"toString"in i&&(i=i?.toString()),!i||"string"!=typeof i)throw new Error(`Invalid connection topic ID for ${n.targetAccountId}: ${JSON.stringify(i)} (type: ${typeof i})`);const r=n.targetAgentName,s=`${t.inboundTopicId}@${t.accountId}`,a=await this.sendMessage(i,e.message,`Agent message from ${t.name}`);if(!a.sequenceNumber)throw new Error("Failed to send message");let o=null;e.disableMonitoring?this.addNote("Message sent successfully. Response monitoring was disabled."):o=await this.monitorResponses(i,s,a.sequenceNumber),this.executeResult={success:!0,transactionId:a.transactionId,receipt:a.receipt,scheduleId:void 0,rawResult:{targetAgentName:r,targetAccountId:n.targetAccountId,connectionTopicId:i,sequenceNumber:a.sequenceNumber,reply:o,monitoringEnabled:!e.disableMonitoring,message:e.message,messageResult:a}}}catch(t){throw this.logger.error("Failed to send message to connection:",t),t}return this}async monitorResponses(e,t,n){let i=0;for(;i<30;){try{const i=await this.getMessageStream(e);for(const e of i.messages){if(e.sequence_number<n||e.operator_id===t)continue;return await this.getMessageContent(e.data||"")}}catch(r){this.logger.error(`Error monitoring responses: ${r}`)}await new Promise(e=>setTimeout(e,4e3)),i++}return null}async startPassiveConnectionMonitoring(){if(this.clearNotes(),!this.stateManager)throw new Error("StateManager is required for passive monitoring");const e=await this.getInboundTopicId();return this.logger.info(`Starting passive connection monitoring on topic ${e}...`),this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{inboundTopicId:e,message:`Started monitoring inbound topic ${e} for connection requests in the background.`}},this}async monitorConnections(e){this.clearNotes();const{acceptAll:t=!1,targetAccountId:n,monitorDurationSeconds:r=120,hbarFees:s=[],tokenFees: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(),u=Date.now()+1e3*r;let l=0,p=0;const h=new Set;for(;Date.now()<u;){try{const e=(await this.getMessages(d)).messages.filter(e=>"connection_request"===e.op&&"number"==typeof e.sequence_number);for(const r of e){const e=r.sequence_number;if(!e||h.has(e))continue;const u=r.operator_id?.split("@")[1];if(u)if(l++,n&&u!==n)this.logger.info(`Skipping request from ${u} (not target account)`);else if(t||n===u){let t;if(this.logger.info(`Accepting connection request from ${u}`),s.length>0||a.length>0){const e=new i.FeeConfigBuilder({network:this.network,logger:this.sdkLogger});for(const t of s){const n=t.collectorAccount||c||this.getOperatorId();e.addHbarFee(t.amount,n,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,u,e,t),h.add(e),p++}}}catch(g){this.logger.error("Error during connection monitoring:",g)}await new Promise(e=>setTimeout(e,3e3))}return this.executeResult={success:!0,transactionId:void 0,receipt:void 0,scheduleId:void 0,rawResult:{connectionRequestsFound:l,acceptedConnections:p,monitorDurationSeconds:r,processedRequestIds:Array.from(h)}},this.addNote(`Monitoring completed. Found ${l} 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(dr);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(dr),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 u=[];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`,u.push({timestamp:e.timestamp,sequenceNumber:e.sequence_number,content:n,raw:e})}catch(s){const t=`Error processing message (Seq: ${e.sequence_number}): ${s instanceof Error?s.message:String(s)}`;this.logger.error(t),d+=`\n[Error processing message Seq: ${e.sequence_number}]\n`}}!c&&o>r&&(this.logger.debug(`Updating timestamp for topic ${n} to ${o}`),this.stateManager.updateTimestamp(n,o)),this.executeResult={success:!0,rawResult:{messages:u,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 lr extends n.BasePlugin{constructor(){super(...arguments),this.id="hedera-hbar-price",this.name="Hedera HBAR Price Plugin",this.description="Provides tools to interact with Hedera network data, specifically HBAR price.",this.version="1.0.0",this.author="Hashgraph Online",this.tools=[]}async initialize(e){await super.initialize(e),this.initializeTools()}initializeTools(){this.tools=[new n.HederaGetHbarPriceTool({hederaKit:this.context.config.hederaKit,logger:this.context.logger})]}getTools(){return this.tools}}class pr extends n.BaseServiceBuilder{constructor(e){super(e)}async getHCS2Client(){if(!this.hcs2Client){const e=this.hederaKit.signer.getAccountId().toString(),t=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",n={network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet",operatorId:e,operatorKey:t};this.hcs2Client=new i.HCS2Client(n)}return this.hcs2Client}async createRegistry(e={}){const t=await this.getHCS2Client();return await t.createRegistry(e)}async registerEntry(e,t){const n=await this.getHCS2Client();return await n.registerEntry(e,t)}async updateEntry(e,t){const n=await this.getHCS2Client();return await n.updateEntry(e,t)}async deleteEntry(e,t){const n=await this.getHCS2Client();return await n.deleteEntry(e,t)}async migrateRegistry(e,t){const n=await this.getHCS2Client();return await n.migrateRegistry(e,t)}async getRegistry(e,t={}){const n=await this.getHCS2Client();return await n.getRegistry(e,t)}async submitMessage(e,t){const n=await this.getHCS2Client();return await n.submitMessage(e,t)}async getTopicInfo(e){const t=await this.getHCS2Client();return await t.getTopicInfo(e)}async close(){this.hcs2Client&&(this.hcs2Client.close(),this.hcs2Client=void 0)}}class hr extends n.BaseServiceBuilder{constructor(e){super(e)}async getInscriptionSDK(e){return null}async inscribe(e,t){const n={accountId:this.hederaKit.signer.getAccountId().toString(),privateKey:this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"",network:this.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};return await i.inscribe(e,n,t)}async inscribeWithSigner(e,t,n){return await i.inscribeWithSigner(e,t,n)}async retrieveInscription(e,t){const n=this.hederaKit.signer.getAccountId().toString(),r=this.hederaKit.signer?.getOperatorPrivateKey()?this.hederaKit.signer.getOperatorPrivateKey().toStringRaw():"";return await i.retrieveInscription(e,{...t,accountId:n,privateKey:r})}async close(){this.inscriptionSDK=void 0}}Object.defineProperty(e,"BasePlugin",{enumerable:!0,get:()=>n.BasePlugin}),Object.defineProperty(e,"GetHbarPriceTool",{enumerable:!0,get:()=>n.HederaGetHbarPriceTool}),Object.defineProperty(e,"PluginRegistry",{enumerable:!0,get:()=>n.PluginRegistry}),e.AcceptConnectionRequestTool=vt,e.BaseHCS10QueryTool=u,e.BaseHCS10TransactionTool=d,e.BaseHCS2QueryTool=Ct,e.BaseHCS2TransactionTool=Tt,e.BaseInscriberQueryTool=$t,e.BaseInscriberTransactionTool=Nt,e.CheckMessagesTool=lt,e.ConnectionMonitorTool=ft,e.CreateRegistryTool=class extends Ct{constructor(){super(...arguments),this.name="createHCS2Registry",this.description="Create a new HCS-2 registry topic for storing decentralized data"}get specificInputSchema(){return Et}async executeQuery(e,t){try{const t=await this.hcs2Builder.createRegistry({registryType:e.registryType,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey});if(!t.success)throw new Error(t.error||"Failed to create registry");return`Successfully created HCS-2 registry!\n\nTopic ID: ${t.topicId}\nRegistry Type: ${1===e.registryType?"Non-Indexed":"Indexed"}\nTTL: ${e.ttl||86400} seconds\n\nYou can now register entries to this registry using the topic ID.`}catch(n){const e=n instanceof Error?n.message:"Failed to create HCS-2 registry";throw new Error(`Registry creation failed: ${e}`)}}},e.DeleteEntryTool=class extends Ct{constructor(){super(...arguments),this.name="deleteHCS2Entry",this.description="Delete an entry from an indexed HCS-2 registry"}get specificInputSchema(){return xt}async executeQuery(e,t){try{const t=await this.hcs2Builder.deleteEntry(e.registryTopicId,{uid:e.uid,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to delete entry");return`Successfully deleted entry from HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been removed from the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to delete entry";throw new Error(`Entry deletion failed: ${e}`)}}},e.FindRegistrationsTool=ht,e.HCS10Builder=ur,e.HCS10Client=class{constructor(e,t,n,r){this.standardClient=new i.HCS10Client({network:n,operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:r?.registryUrl,logLevel:r?.logLevel}),this.guardedRegistryBaseUrl=r?.registryUrl||"",this.useEncryption=r?.useEncryption||!1;const s="true"===c.env.DISABLE_LOGGING;this.logger=new i.Logger({level:r?.logLevel||"info",silent:s})}getOperatorId(){const e=this.standardClient.getClient().operatorAccountId;if(!e)throw new Error("Operator Account ID not configured in standard client.");return e.toString()}getNetwork(){return this.standardClient.getNetwork()}async handleConnectionRequest(e,t,n,i){try{return await this.standardClient.handleConnectionRequest(e,t,n,i)}catch(r){throw this.logger.error(`Error handling connection request #${n} for topic ${e}:`,r),new Error(`Failed to handle connection request: ${r instanceof Error?r.message:String(r)}`)}}async getAgentProfile(e){return this.standardClient.retrieveProfile(e)}async submitConnectionRequest(e,t){return this.standardClient.submitConnectionRequest(e,t)}async waitForConnectionConfirmation(e,t,n=60,i=2e3){return this.standardClient.waitForConnectionConfirmation(e,t,n,i)}async createAndRegisterAgent(e){const t=(new i.AgentBuilder).setName(e.name).setBio(e.description||"").setCapabilities(e.capabilities?e.capabilities:[i.AIAgentCapability.TEXT_GENERATION]).setType(e.type||"autonomous").setModel(e.model||"agent-model-2024").setNetwork(this.getNetwork()).setInboundTopicType(i.InboundTopicType.PUBLIC);e?.feeConfig&&(t.setInboundTopicType(i.InboundTopicType.FEE_BASED),t.setFeeConfig(e.feeConfig)),e.pfpBuffer&&e.pfpFileName?0===e.pfpBuffer.byteLength?this.logger.warn("Provided PFP buffer is empty. Skipping profile picture."):(this.logger.info(`Setting profile picture: ${e.pfpFileName} (${e.pfpBuffer.byteLength} bytes)`),t.setProfilePicture(e.pfpBuffer,e.pfpFileName)):this.logger.warn("Profile picture not provided in metadata. Agent creation might fail if required by the underlying SDK builder."),e.social&&Object.entries(e.social).forEach(([e,n])=>{t.addSocial(e,n)}),e.properties&&Object.entries(e.properties).forEach(([e,n])=>{t.addProperty(e,n)});try{const n=Boolean(e?.feeConfig),i=await this.standardClient.createAndRegisterAgent(t,{initialBalance:n?50:void 0});return i?.metadata?.inboundTopicId&&i?.metadata?.outboundTopicId&&(this.agentChannels={inboundTopicId:i.metadata.inboundTopicId,outboundTopicId:i.metadata.outboundTopicId}),i}catch(n){throw this.logger.error("Error during agent creation/registration:",n),new Error(`Failed to create/register agent: ${n instanceof Error?n.message:String(n)}`)}}async sendMessage(e,t,n,i){this.useEncryption;try{const r=await this.standardClient.sendMessage(e,t,n,i);return r.topicSequenceNumber?.toNumber()}catch(r){throw this.logger.error(`Error sending message to topic ${e}:`,r),new Error(`Failed to send message: ${r instanceof Error?r.message:String(r)}`)}}async getMessages(e){try{const t=(await this.standardClient.getMessages(e)).messages.map(e=>{const t=e?.created?.getTime()||0;return{...e,timestamp:t,data:e.data,sequence_number:e.sequence_number}});return t.sort((e,t)=>e.timestamp-t.timestamp),{messages:t}}catch(t){return this.logger.error(`Error getting messages from topic ${e}:`,t),{messages:[]}}}async getMessageStream(e){return this.standardClient.getMessageStream(e)}async getMessageContent(e){try{return await this.standardClient.getMessageContent(e)}catch(t){throw this.logger.error(`Error retrieving message content for: ${e}`,t),new Error(`Failed to retrieve message content: ${t instanceof Error?t.message:String(t)}`)}}async getInboundTopicId(){try{const e=this.getOperatorId();this.logger.info(`[HCS10Client] Retrieving profile for operator ${e} to find inbound topic...`);const t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.inboundTopic)return this.logger.info(`[HCS10Client] Found inbound topic for operator ${e}: ${t.topicInfo.inboundTopic}`),t.topicInfo.inboundTopic;throw new Error(`Could not retrieve inbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}catch(e){this.logger.error(`[HCS10Client] Error fetching operator's inbound topic ID (${this.getOperatorId()}):`,e);const t=this.getOperatorId();let n=`Failed to get inbound topic ID for operator ${t}.`;throw e instanceof Error&&e.message.includes("does not have a valid HCS-11 memo")?n+=` The account profile may not exist or is invalid. Please ensure this operator account (${t}) is registered as an HCS-10 agent. You might need to register it first (e.g., using the 'register_agent' tool or SDK function).`:e instanceof Error?n+=` Reason: ${e.message}`:n+=` Unexpected error: ${String(e)}`,new Error(n)}}getAccountAndSigner(){const e=this.standardClient.getAccountAndSigner();return{accountId:e.accountId,signer:e.signer}}async getOutboundTopicId(){const e=this.getOperatorId(),t=await this.getAgentProfile(e);if(t.success&&t.topicInfo?.outboundTopic)return t.topicInfo.outboundTopic;throw new Error(`Could not retrieve outbound topic from profile for ${e}. Profile success: ${t.success}, Error: ${t.error}`)}setClient(e,t){return this.standardClient=new i.HCS10Client({network:this.getNetwork(),operatorId:e,operatorPrivateKey:t,guardedRegistryBaseUrl:this.guardedRegistryBaseUrl}),this.standardClient}async validateOperator(e){try{this.setClient(e.accountId,e.privateKey);return{isValid:!0,operator:{accountId:this.getOperatorId()}}}catch(t){return this.logger.error(`Validation error: ${t}`),{isValid:!1,error:t instanceof Error?t.message:String(t)}}}async initializeWithValidation(e){const t=await this.validateOperator(e);return t.isValid&&e.stateManager&&e.stateManager.initializeConnectionsManager(this.standardClient),t}},e.HCS2Builder=pr,e.HbarPricePlugin=lr,e.InitiateConnectionTool=ot,e.InscribeFromBufferTool=class extends $t{constructor(){super(...arguments),this.name="inscribeFromBuffer",this.description="Inscribe content from a buffer/base64 data to the Hedera network"}get specificInputSchema(){return Ft}async executeQuery(e,n){const i=t.Buffer.from(e.base64Data,"base64"),r={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{const t=new Promise((e,t)=>{setTimeout(()=>t(new Error("Inscription timed out after 30 seconds")),3e4)}),n=await Promise.race([this.inscriberBuilder.inscribe({type:"buffer",buffer:i,fileName:e.fileName,mimeType:e.mimeType},r),t]);if(n.confirmed){const e=n.inscription?.topic_id||n.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${r.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${n.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${n.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(s){const e=s instanceof Error?s.message:"Failed to inscribe from buffer";throw new Error(`Inscription failed: ${e}`)}}},e.InscribeFromFileTool=class extends $t{constructor(){super(...arguments),this.name="inscribeFromFile",this.description="Inscribe content from a local file to the Hedera network"}get specificInputSchema(){return Mt}async executeQuery(e,t){const n={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{const t=new Promise((e,t)=>{setTimeout(()=>t(new Error("Inscription timed out after 30 seconds")),3e4)}),i=await Promise.race([this.inscriberBuilder.inscribe({type:"file",path:e.filePath},n),t]);if(i.confirmed){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${n.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(i){const e=i instanceof Error?i.message:"Failed to inscribe from file";throw new Error(`Inscription failed: ${e}`)}}},e.InscribeFromUrlTool=class extends $t{constructor(){super(...arguments),this.name="inscribeFromUrl",this.description="Inscribe content from a URL to the Hedera network"}get specificInputSchema(){return Pt}async executeQuery(e,t){const n={mode:e.mode,metadata:e.metadata,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{const t=new Promise((e,t)=>{setTimeout(()=>t(new Error("Inscription timed out after 30 seconds")),3e4)}),i=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},n),t]);if(i.confirmed){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${n.network||"testnet"}`:null;return`Successfully inscribed and confirmed content on the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe inscription is now available.`}return`Successfully submitted inscription to the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(i){const e=i instanceof Error?i.message:"Failed to inscribe from URL";throw new Error(`Inscription failed: ${e}`)}}},e.InscribeHashinalTool=class extends $t{constructor(){super(...arguments),this.name="inscribeHashinal",this.description="Inscribe content as a Hashinal NFT on the Hedera network"}get specificInputSchema(){return qt}async executeQuery(e,t){const n={mode:"hashinal",metadata:{name:e.name,creator:e.creator,description:e.description,type:e.type,attributes:e.attributes,properties:e.properties},jsonFileURL:e.jsonFileURL,tags:e.tags,chunkSize:e.chunkSize,waitForConfirmation:e.waitForConfirmation??!0,waitMaxAttempts:10,waitIntervalMs:3e3,apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"};try{const t=new Promise((e,t)=>{setTimeout(()=>t(new Error("Inscription timed out after 30 seconds")),3e4)}),i=await Promise.race([this.inscriberBuilder.inscribe({type:"url",url:e.url},n),t]);if(i.confirmed){const e=i.inscription?.topic_id||i.result.topicId,t=e?`https://kiloscribe.com/api/inscription-cdn/${e}?network=${n.network||"testnet"}`:null;return`Successfully inscribed and confirmed Hashinal NFT on the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\nTopic ID: ${e||"N/A"}${t?`\nView inscription: ${t}`:""}\n\nThe Hashinal NFT is now available.`}return`Successfully submitted Hashinal NFT inscription to the Hedera network!\n\nTransaction ID: ${i.result.transactionId}\n\nThe inscription is processing and will be confirmed shortly.`}catch(i){const e=i instanceof Error?i.message:"Failed to inscribe Hashinal NFT";throw new Error(`Inscription failed: ${e}`)}}},e.InscriberBuilder=hr,e.ListConnectionsTool=dt,e.ListUnapprovedConnectionRequestsTool=_t,e.ManageConnectionRequestsTool=yt,e.MigrateRegistryTool=class extends Ct{constructor(){super(...arguments),this.name="migrateHCS2Registry",this.description="Migrate an HCS-2 registry to a new topic"}get specificInputSchema(){return kt}async executeQuery(e,t){try{const t=await this.hcs2Builder.migrateRegistry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to migrate registry");return`Successfully migrated HCS-2 registry!\n\nFrom Registry Topic: ${e.registryTopicId}\nTo Target Topic: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe registry has been migrated to the new topic.`}catch(n){const e=n instanceof Error?n.message:"Failed to migrate registry";throw new Error(`Registry migration failed: ${e}`)}}},e.NaturalLanguageMapper=tt,e.OpenConvaiState=Bt,e.QueryRegistryTool=class extends Ct{constructor(){super(...arguments),this.name="queryHCS2Registry",this.description="Query entries from an HCS-2 registry"}get specificInputSchema(){return Ot}async executeQuery(e,t){const n=await this.hcs2Builder.getRegistry(e.topicId,{limit:e.limit,order:e.order,skip:e.skip});return{topicId:n.topicId,registryType:0===n.registryType?"indexed":"non-indexed",ttl:n.ttl,totalEntries:n.entries.length,entries:n.entries.map(e=>({sequence:e.sequence,timestamp:e.timestamp,payer:e.payer,operation:e.message.op,targetTopicId:e.message.t_id,uid:e.message.uid,metadata:e.message.metadata,memo:e.message.m}))}}},e.RegisterAgentTool=it,e.RegisterEntryTool=class extends Ct{constructor(){super(...arguments),this.name="registerHCS2Entry",this.description="Register a new entry in an HCS-2 registry"}get specificInputSchema(){return Rt}async executeQuery(e,t){try{const t=await this.hcs2Builder.registerEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to register entry");return`Successfully registered entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nTarget Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been added to the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to register entry";throw new Error(`Entry registration failed: ${e}`)}}},e.RetrieveInscriptionTool=class extends $t{constructor(){super(...arguments),this.name="retrieveInscription",this.description="Retrieve details of an existing inscription from the Hedera network"}get specificInputSchema(){return Dt}async executeQuery(e,t){const n=await this.inscriberBuilder.retrieveInscription(e.transactionId,{apiKey:e.apiKey,network:this.inscriberBuilder.hederaKit.client.network.toString().includes("mainnet")?"mainnet":"testnet"});return{inscriptionId:n.inscriptionId,transactionId:n.transactionId,topicId:n.topic_id,status:n.status,holderId:n.holderId,metadata:n.metadata,tags:n.tags,mode:n.mode,chunks:n.chunks,createdAt:n.createdAt,completedAt:n.completed||n.completedAt,fileUrl:n.fileUrl,mimeType:n.mimeType,fileSize:n.fileSize}}},e.RetrieveProfileTool=It,e.SendMessageToConnectionTool=st,e.UpdateEntryTool=class extends Ct{constructor(){super(...arguments),this.name="updateHCS2Entry",this.description="Update an existing entry in an indexed HCS-2 registry"}get specificInputSchema(){return St}async executeQuery(e,t){try{const t=await this.hcs2Builder.updateEntry(e.registryTopicId,{targetTopicId:e.targetTopicId,uid:e.uid,metadata:e.metadata,memo:e.memo});if(!t.success)throw new Error(t.error||"Failed to update entry");return`Successfully updated entry in HCS-2 registry!\n\nRegistry Topic: ${e.registryTopicId}\nUID: ${e.uid}\nNew Target Topic ID: ${e.targetTopicId}${e.metadata?`\nMetadata: ${e.metadata}`:""}${e.memo?`\nMemo: ${e.memo}`:""}\n\nThe entry has been updated in the registry.`}catch(n){const e=n instanceof Error?n.message:"Failed to update entry";throw new Error(`Entry update failed: ${e}`)}}},e.initializeStandardsAgentKit=async e=>{const t=e?.clientConfig||{},r=t.operatorId||c.env.HEDERA_OPERATOR_ID,s=t.operatorKey||c.env.HEDERA_OPERATOR_KEY,a=t.network||c.env.HEDERA_NETWORK||"testnet";let o;if("mainnet"===a?o="mainnet":("testnet"===a||console.warn(`Unsupported network specified: '${a}'. Defaulting to 'testnet'.`),o="testnet"),!r||!s)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const d="true"===c.env.DISABLE_LOGGING,u=i.Logger.getInstance({level:t.logLevel||"info",silent:d}),l=e?.stateManager||new Bt({defaultEnvFilePath:Lt,defaultPrefix:"TODD"});u.info("State manager initialized");const p=new n.ServerSigner(r,s,o),h=new n.HederaAgentKit(p);await h.initialize(),u.info(`HederaAgentKit initialized for ${r} on ${o}`);const g=new ur(h,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:t.logLevel});let f,m;if(e?.monitoringClient){const e=new n.ServerSigner(r,s,o);f=new n.HederaAgentKit(e),await f.initialize(),m=new ur(f,l,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),u.info("Monitoring client initialized")}const y={};return y.registerAgentTool=new it({hederaKit:h,hcs10Builder:g,logger:void 0}),e?.createAllTools&&(y.findRegistrationsTool=new ht({hederaKit:h,hcs10Builder:g,logger:void 0}),y.retrieveProfileTool=new It({hederaKit:h,hcs10Builder:g,logger:void 0}),y.initiateConnectionTool=new ot({hederaKit:h,hcs10Builder:g,logger:void 0}),y.listConnectionsTool=new dt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.sendMessageToConnectionTool=new st({hederaKit:h,hcs10Builder:g,logger:void 0}),y.checkMessagesTool=new lt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.connectionMonitorTool=new ft({hederaKit:f||h,hcs10Builder:m||g,logger:void 0}),y.manageConnectionRequestsTool=new yt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.acceptConnectionRequestTool=new vt({hederaKit:h,hcs10Builder:g,logger:void 0}),y.listUnapprovedConnectionRequestsTool=new _t({hederaKit:h,hcs10Builder:g,logger:void 0}),u.info("All tools initialized")),{hederaKit:h,hcs10Builder:g,monitoringHederaKit:f,monitoringHcs10Builder:m,tools:y,stateManager:l}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=standards-agent-kit.umd.js.map