@hashgraphonline/standards-agent-kit 0.0.35 → 0.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/cjs/plugins/index.d.ts +1 -0
  2. package/dist/cjs/standards-agent-kit.cjs +1 -1
  3. package/dist/cjs/standards-agent-kit.cjs.map +1 -1
  4. package/dist/cjs/tools/ConnectionMonitorTool.d.ts +0 -1
  5. package/dist/es/plugins/index.d.ts +1 -0
  6. package/dist/es/standards-agent-kit.es.js +2 -0
  7. package/dist/es/standards-agent-kit.es.js.map +1 -1
  8. package/dist/es/standards-agent-kit.es11.js +0 -3
  9. package/dist/es/standards-agent-kit.es11.js.map +1 -1
  10. package/dist/es/standards-agent-kit.es16.js +1 -1
  11. package/dist/es/standards-agent-kit.es17.js +1 -1
  12. package/dist/es/standards-agent-kit.es2.js +1 -1
  13. package/dist/es/standards-agent-kit.es22.js.map +1 -1
  14. package/dist/es/standards-agent-kit.es23.js.map +1 -1
  15. package/dist/es/standards-agent-kit.es24.js +3 -3
  16. package/dist/es/standards-agent-kit.es24.js.map +1 -1
  17. package/dist/es/standards-agent-kit.es26.js +3 -24
  18. package/dist/es/standards-agent-kit.es26.js.map +1 -1
  19. package/dist/es/standards-agent-kit.es27.js +28 -0
  20. package/dist/es/standards-agent-kit.es27.js.map +1 -0
  21. package/dist/es/tools/ConnectionMonitorTool.d.ts +0 -1
  22. package/dist/umd/plugins/index.d.ts +1 -0
  23. package/dist/umd/standards-agent-kit.umd.js +2 -2
  24. package/dist/umd/standards-agent-kit.umd.js.map +1 -1
  25. package/dist/umd/tools/ConnectionMonitorTool.d.ts +0 -1
  26. package/package.json +1 -1
  27. package/src/plugins/GenericPlugin.ts +1 -1
  28. package/src/plugins/HCS10Plugin.ts +1 -1
  29. package/src/plugins/index.ts +1 -0
  30. package/src/plugins/openconvai/OpenConvAIPlugin.ts +2 -2
  31. package/src/plugins/weather/index.ts +1 -1
  32. package/src/tools/ConnectionMonitorTool.ts +0 -4
@@ -152,7 +152,7 @@ read:function(e,t,r,n,i){var o,a,s=8*i-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?i-1:0,h=r?
152
152
  * (c) 2017-2022 Joachim Wester
153
153
  * MIT licensed
154
154
  */
155
- const _hasOwnProperty=Object.prototype.hasOwnProperty;function hasOwnProperty(e,t){return _hasOwnProperty.call(e,t)}function _objectKeys(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)hasOwnProperty(e,r)&&t.push(r);return t}function _deepClone(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function isInteger(e){let t=0;const r=e.length;let n;for(;t<r;){if(n=e.charCodeAt(t),!(n>=48&&n<=57))return!1;t++}return!0}function unescapePathComponent(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function hasUndefined(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(hasUndefined(e[r]))return!0}else if("object"==typeof e){const r=_objectKeys(e),n=r.length;for(var t=0;t<n;t++)if(hasUndefined(e[r[t]]))return!0}return!1}function patchErrorMessageFormatter(e,t){const r=[e];for(const n in t){const e="object"==typeof t[n]?JSON.stringify(t[n],null,2):t[n];void 0!==e&&r.push(`${n}: ${e}`)}return r.join("\n")}class PatchError extends Error{constructor(e,t,r,n,i){super(patchErrorMessageFormatter(e,{name:t,index:r,operation:n,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=patchErrorMessageFormatter(e,{name:t,index:r,operation:n,tree:i})}}const JsonPatchError=PatchError,objOps={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=getValueByPointer(r,this.path);n&&(n=_deepClone(n));const i=applyOperation(r,{op:"remove",path:this.from}).removed;return applyOperation(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){const n=getValueByPointer(r,this.from);return applyOperation(r,{op:"add",path:this.path,value:_deepClone(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:_areEquals(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var arrOps={add:function(e,t,r){return isInteger(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:objOps.move,copy:objOps.copy,test:objOps.test,_get:objOps._get};function getValueByPointer(e,t){if(""==t)return e;var r={op:"_get",path:t};return applyOperation(e,r),r.value}function applyOperation(e,t,r=!1,n=!0,i=!0,o=0){if(r&&("function"==typeof r?r(t,0,e,t.path):validator(t,0)),""===t.path){let n={newDocument:e};if("add"===t.op)return n.newDocument=t.value,n;if("replace"===t.op)return n.newDocument=t.value,n.removed=e,n;if("move"===t.op||"copy"===t.op)return n.newDocument=getValueByPointer(e,t.from),"move"===t.op&&(n.removed=e),n;if("test"===t.op){if(n.test=_areEquals(e,t.value),!1===n.test)throw new JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n.newDocument=e,n}if("remove"===t.op)return n.removed=e,n.newDocument=null,n;if("_get"===t.op)return t.value=e,n;if(r)throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,t,e);return n}{n||(e=_deepClone(e));const a=(t.path||"").split("/");let s,c,u,l=e,d=1,h=a.length;for(u="function"==typeof r?r:validator;;){if(c=a[d],c&&-1!=c.indexOf("~")&&(c=unescapePathComponent(c)),i&&("__proto__"==c||"prototype"==c&&d>0&&"constructor"==a[d-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&void 0===s&&(void 0===l[c]?s=a.slice(0,d).join("/"):d==h-1&&(s=t.path),void 0!==s&&u(t,0,e,s)),d++,Array.isArray(l)){if("-"===c)c=l.length;else{if(r&&!isInteger(c))throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,t,e);isInteger(c)&&(c=~~c)}if(d>=h){if(r&&"add"===t.op&&c>l.length)throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,t,e);const n=arrOps[t.op].call(t,l,c,e);if(!1===n.test)throw new JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n}}else if(d>=h){const r=objOps[t.op].call(t,l,c,e);if(!1===r.test)throw new JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return r}if(l=l[c],r&&d<h&&(!l||"object"!=typeof l))throw new JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,t,e)}}}function applyPatch(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=_deepClone(e));const o=new Array(t.length);for(let a=0,s=t.length;a<s;a++)o[a]=applyOperation(e,t[a],r,!0,i,a),e=o[a].newDocument;return o.newDocument=e,o}function validator(e,t,r,n){if("object"!=typeof e||null===e||Array.isArray(e))throw new JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(!objOps[e.op])throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r);if("string"!=typeof e.path)throw new JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(0!==e.path.indexOf("/")&&e.path.length>0)throw new JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&hasUndefined(e.value))throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var i=e.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var a=validate([{op:"_get",path:e.from,value:void 0}],r);if(a&&"OPERATION_PATH_UNRESOLVABLE"===a.name)throw new JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function validate(e,t,r){try{if(!Array.isArray(e))throw new JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)applyPatch(_deepClone(t),_deepClone(e),r||!0);else{r=r||validator;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(i){if(i instanceof JsonPatchError)return i;throw i}}function _areEquals(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,n,i,o=Array.isArray(e),a=Array.isArray(t);if(o&&a){if((n=e.length)!=t.length)return!1;for(r=n;0!==r--;)if(!_areEquals(e[r],t[r]))return!1;return!0}if(o!=a)return!1;var s=Object.keys(e);if((n=s.length)!==Object.keys(t).length)return!1;for(r=n;0!==r--;)if(!t.hasOwnProperty(s[r]))return!1;for(r=n;0!==r--;)if(!_areEquals(e[i=s[r]],t[i]))return!1;return!0}return e!=e&&t!=t}class MockAsyncLocalStorage{getStore(){}run(e,t){return t()}enterWith(e){}}const mockAsyncLocalStorage=new MockAsyncLocalStorage,LC_CHILD_KEY=Symbol.for("lc:child_config");class AsyncLocalStorageProvider{getInstance(){return getGlobalAsyncLocalStorageInstance()??mockAsyncLocalStorage}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[LC_CHILD_KEY]}runWithConfig(e,t,r){const n=CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),o=i.getStore(),a=n?.getParentRunId(),s=n?.handlers?.find((e=>"langchain_tracer"===e?.name));let c;return s&&a?c=s.convertToRunTree(a):r||(c=new RunTree({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[LC_CHILD_KEY]:e}),void 0!==o&&void 0!==o[_CONTEXT_VARIABLES_KEY]&&(void 0===c&&(c={}),c[_CONTEXT_VARIABLES_KEY]=o[_CONTEXT_VARIABLES_KEY]),i.run(c,t)}initializeGlobalInstance(e){void 0===getGlobalAsyncLocalStorageInstance()&&setGlobalAsyncLocalStorageInstance(e)}}const AsyncLocalStorageProviderSingleton=new AsyncLocalStorageProvider,DEFAULT_RECURSION_LIMIT=25;async function getCallbackManagerForConfig(e){return CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function mergeConfigs(...e){const t={};for(const r of e.filter((e=>!!e)))for(const e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){const n=t[e]??[];t[e]=[...new Set(n.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){const e=t.callbacks,n=r.callbacks;if(Array.isArray(n))if(e)if(Array.isArray(e))t.callbacks=e.concat(n);else{const r=e.copy();for(const e of n)r.addHandler(ensureHandler(e),!0);t.callbacks=r}else t.callbacks=n;else if(n)if(e)if(Array.isArray(e)){const r=n.copy();for(const t of e)r.addHandler(ensureHandler(t),!0);t.callbacks=r}else t.callbacks=new CallbackManager(n._parentRunId,{handlers:e.handlers.concat(n.handlers),inheritableHandlers:e.inheritableHandlers.concat(n.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(n.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(n.inheritableTags))),metadata:{...e.metadata,...n.metadata}});else t.callbacks=n}else{const n=e;t[n]=r[n]??t[n]}return t}const PRIMITIVES=new Set(["string","number","boolean"]);function ensureConfig(e){const t=AsyncLocalStorageProviderSingleton.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:n,...i}=t;r=Object.entries(i).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)}if(e&&(r=Object.entries(e).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)),r?.configurable)for(const n of Object.keys(r.configurable))PRIMITIVES.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(void 0!==r.timeout){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function patchConfig(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:o,runId:a}={}){const s=ensureConfig(e);return void 0!==t&&(delete s.runName,s.callbacks=t),void 0!==n&&(s.recursionLimit=n),void 0!==r&&(s.maxConcurrency=r),void 0!==i&&(s.runName=i),void 0!==o&&(s.configurable={...s.configurable,...o}),void 0!==a&&delete s.runId,s}function pickRunnableConfigKeys(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function raceWithSignal(e,t){if(void 0===t)return e;let r;return Promise.race([e.catch((e=>{if(!t?.aborted)throw e})),new Promise(((e,n)=>{r=()=>{n(new Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&n(new Error("Aborted"))}))]).finally((()=>t.removeEventListener("abort",r)))}class IterableReadableStream extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new IterableReadableStream({start:e=>function r(){return t.read().then((({done:t,value:n})=>{if(!t)return e.enqueue(n),r();e.close()}))}(),cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new IterableReadableStream({async pull(t){const{value:r,done:n}=await e.next();n&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function atee(e,t=2){const r=Array.from({length:t},(()=>[]));return r.map((async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}}))}function concat(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const r={...e};for(const[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=concat(r[e],n):r[e]=n;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}class AsyncGeneratorWithSetup{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise(((t,r)=>{AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(e.config),(async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then((e=>t(void 0)),r)}),!0)}))}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config),this.signal?async()=>raceWithSignal(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}async function pipeGeneratorWithSetup(e,t,r,n,...i){const o=new AsyncGeneratorWithSetup({generator:t,startSetup:r,signal:n}),a=await o.setup;return{output:e(o,a,...i),setup:a}}class RunLogPatch{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=applyPatch({},t);return new RunLog({ops:t,state:r[r.length-1].newDocument})}}class RunLog extends RunLogPatch{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=applyPatch(this.state,e.ops);return new RunLog({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=applyPatch({},e.ops);return new RunLog({ops:e.ops,state:t[t.length-1].newDocument})}}const isLogStreamHandler=e=>"log_stream_tracer"===e.name;async function _getStandardizedInputs(e,t){if("original"===t)throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||""!==r?.input?r.input:void 0}async function _getStandardizedOutputs(e,t){const{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&void 0!==r?.output?r.output:r}function isChatGenerationChunk(e){return void 0!==e&&void 0!==e.message}class LogStreamCallbackHandler extends BaseTracer{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=IterableReadableStream.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new RunLogPatch({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new RunLogPatch({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await _getStandardizedInputs(e,this._schemaFormat)),await this.writer.write(new RunLogPatch({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await _getStandardizedInputs(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await _getStandardizedOutputs(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const n=new RunLogPatch({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new RunLogPatch({ops:[{op:"replace",path:"/final_output",value:await _getStandardizedOutputs(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const n=this.keyMapByRunId[e.id];if(void 0===n)return;let i;i=void 0!==e.inputs.messages?isChatGenerationChunk(r?.chunk)?r?.chunk:new AIMessageChunk({id:`run-${e.id}`,content:t}):t;const o=new RunLogPatch({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:i}]});await this.writer.write(o)}}class GenerationChunk{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new GenerationChunk({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function assignName({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const isStreamEventsHandler=e=>"event_stream_tracer"===e.name;class EventStreamCallbackHandler extends BaseTracer{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=IterableReadableStream.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const n=this.runInfoMap.get(e);if(void 0===n)return void(yield r.value);function i(e,t){return"llm"===e&&"string"==typeof t?new GenerationChunk({text:t}):t}let o=this.tappedPromises.get(e);if(void 0===o){let a;o=new Promise((e=>{a=e})),this.tappedPromises.set(e,o);try{const o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:i(n.runType,r.value)}},n),yield r.value;for await(const e of t)"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...o,data:{chunk:i(n.runType,e)}},n),yield e}finally{a()}}else{yield r.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);void 0!==r?r.then((()=>{this.send(e,t)})):await this.send(e,t)}async onLLMStart(e){const t=assignName(e),r=void 0!==e.inputs.messages?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);const i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){const n=this.runInfoMap.get(e.id);let i,o;if(void 0===n)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)o="on_chat_model_stream",i=void 0===r?.chunk?new AIMessageChunk({content:t,id:`run-${e.id}`}):r.chunk.message;else{if("llm"!==n.runType)throw new Error(`Unexpected run type ${n.runType}`);o="on_llm_stream",i=void 0===r?.chunk?new GenerationChunk({text:t}):r.chunk}await this.send({event:o,data:{chunk:i},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let r;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const n=e.outputs?.generations;let i;if("chat_model"===t.runType){for(const e of n??[]){if(void 0!==i)break;i=e[0]?.message}r="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);i={generations:n?.map((e=>e.map((e=>({text:e.text,generationInfo:e.generationInfo}))))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end"}await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=assignName(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let i={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(i={},n.inputs={}):void 0!==e.inputs.input?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:n};n.input&&1===Object.keys(n).length&&(i.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=assignName(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=void 0===e.outputs?.output?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=assignName(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const n=this.runInfoMap.get(r);if(void 0===n)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally((()=>{this.writer.close()}))}}class RootListenersTracer extends BaseTracer{constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}function isRunnableInterface(e){return!!e&&e.lc_runnable}class _RootEventFilter{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const n=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||n.some((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&n.every((e=>!this.excludeTags?.includes(e)))),r}}const ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},getDefaultOptions=e=>({...defaultOptions,...e}),getRefs=e=>{const t=getDefaultOptions(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function addErrorMessage(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function setResponseValueAndErrors(e,t,r,n,i){e[t]=r,addErrorMessage(e,t,n,i)}function parseAnyDef(){return{}}function parseArrayDef(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(r.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&setResponseValueAndErrors(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(r,"minItems",e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function parseBigintDef(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,t));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,t)}return r}function parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>parseDateDef(e,t,r)))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minimum",n.value,n.message,t);break;case"max":setResponseValueAndErrors(r,"maximum",n.value,n.message,t)}return r};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return"input"===t.effectStrategy?parseDef(e.schema._def,t):{}}function parseEnumDef(e){return{type:"string",enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function parseIntersectionDef(e,t){const r=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach((e=>{if(isJsonSchema7AllOfType(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;i.push(t)}})),i.length?{allOf:i,...n}:void 0}function parseLiteralDef(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(void 0===emojiRegex&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":setResponseValueAndErrors(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":addFormat(r,"email",n.message,t);break;case"format:idn-email":addFormat(r,"idn-email",n.message,t);break;case"pattern:zod":addPattern(r,zodPatterns.email,n.message,t)}break;case"url":addFormat(r,"uri",n.message,t);break;case"uuid":addFormat(r,"uuid",n.message,t);break;case"regex":addPattern(r,n.regex,n.message,t);break;case"cuid":addPattern(r,zodPatterns.cuid,n.message,t);break;case"cuid2":addPattern(r,zodPatterns.cuid2,n.message,t);break;case"startsWith":addPattern(r,RegExp(`^${escapeLiteralCheckValue(n.value,t)}`),n.message,t);break;case"endsWith":addPattern(r,RegExp(`${escapeLiteralCheckValue(n.value,t)}$`),n.message,t);break;case"datetime":addFormat(r,"date-time",n.message,t);break;case"date":addFormat(r,"date",n.message,t);break;case"time":addFormat(r,"time",n.message,t);break;case"duration":addFormat(r,"duration",n.message,t);break;case"length":setResponseValueAndErrors(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),setResponseValueAndErrors(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":addPattern(r,RegExp(escapeLiteralCheckValue(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&addFormat(r,"ipv4",n.message,t),"v4"!==n.version&&addFormat(r,"ipv6",n.message,t);break;case"base64url":addPattern(r,zodPatterns.base64url,n.message,t);break;case"jwt":addPattern(r,zodPatterns.jwt,n.message,t);break;case"cidr":"v6"!==n.version&&addPattern(r,zodPatterns.ipv4Cidr,n.message,t),"v4"!==n.version&&addPattern(r,zodPatterns.ipv6Cidr,n.message,t);break;case"emoji":addPattern(r,zodPatterns.emoji(),n.message,t);break;case"ulid":addPattern(r,zodPatterns.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":addFormat(r,"binary",n.message,t);break;case"contentEncoding:base64":setResponseValueAndErrors(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":addPattern(r,zodPatterns.base64,n.message,t)}break;case"nanoid":addPattern(r,zodPatterns.nanoid,n.message,t)}return r}function escapeLiteralCheckValue(e,t){return"escape"===t.patternStrategy?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(e){let t="";for(let r=0;r<e.length;r++)ALPHA_NUMERIC.has(e[r])||(t+="\\"),t+=e[r];return t}function addFormat(e,t,r,n){e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):setResponseValueAndErrors(e,"format",t,r,n)}function addPattern(e,t,r,n){e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):setResponseValueAndErrors(e,"pattern",stringifyRegExpWithFlags(t,n),r,n)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),i=e.flags.includes("s"),o=r?e.source.toLowerCase():e.source;let a="",s=!1,c=!1,u=!1;for(let l=0;l<o.length;l++)if(s)a+=o[l],s=!1;else{if(r)if(c){if(o[l].match(/[a-z]/)){u?(a+=o[l],a+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):"-"===o[l+1]&&o[l+2]?.match(/[a-z]/)?(a+=o[l],u=!0):a+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){a+=`[${o[l]}${o[l].toUpperCase()}]`;continue}if(n){if("^"===o[l]){a+="(^|(?<=[\r\n]))";continue}if("$"===o[l]){a+="($|(?=[\r\n]))";continue}}i&&"."===o[l]?a+=c?`${o[l]}\r\n`:`[${o[l]}\r\n]`:(a+=o[l],"\\"===o[l]?s=!0:c&&"]"===o[l]?c=!1:c||"["!==o[l]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function parseRecordDef(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((r,n)=>({...r,[n]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){const{type:n,...i}=parseStringDef(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...i}=parseBrandedDef(e.keyType._def,t);return{...r,propertyNames:i}}return r}function parseMapDef(e,t){if("record"===t.mapStrategy)return parseRecordDef(e,t);return{type:"array",maxItems:125,items:{type:"array",items:[parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}function parseNativeEnumDef(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),n=Array.from(new Set(r.map((e=>typeof e))));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}function parseNeverDef(){return{not:{}}}function parseNullDef(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(e,t){if("openApi3"===t.target)return asAnyOf(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in primitiveMappings&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=primitiveMappings[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function parseNullableDef(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:primitiveMappings[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",addErrorMessage(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,t));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,t)}return r}function parseObjectDef(e,t){const r="openAi"===t.target,n={type:"object",properties:{}},i=[],o=e.shape();for(const s in o){let e=o[s];if(void 0===e||void 0===e._def)continue;let a=safeIsOptional(e);a&&r&&(e instanceof ZodOptional&&(e=e._def.innerType),e.isNullable()||(e=e.nullable()),a=!1);const c=parseDef(e._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});void 0!==c&&(n.properties[s]=c,a||i.push(s))}i.length&&(n.required=i);const a=decideAdditionalProperties(e,t);return void 0!==a&&(n.additionalProperties=a),n}function decideAdditionalProperties(e,t){if("ZodNever"!==e.catchall._def.typeName)return parseDef(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function safeIsOptional(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef(e.innerType._def,t);const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},parsePipelineDef=(e,t)=>{if("input"===t.pipeStrategy)return parseDef(e.in._def,t);if("output"===t.pipeStrategy)return parseDef(e.out._def,t);const r=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){const r={type:"array",uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&setResponseValueAndErrors(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function parseTupleDef(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}function parseUndefinedDef(){return{not:{}}}function parseUnknownDef(){return{}}const parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,r)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef();case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,r);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef();case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef();case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef();case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:default:return}};function parseDef(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==ignoreOverride)return i}if(n&&!r){const e=get$ref(n,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const o=selectParser(e,e.typeName,t),a="function"==typeof o?parseDef(o(),t):o;if(a&&addMeta(e,t,a),t.postProcess){const r=t.postProcess(a,e,t);return i.jsonSchema=a,r}return i.jsonSchema=a,a}const get$ref=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:getRelativePath(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,r)=>t.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},getRelativePath=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},addMeta=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zodToJsonSchema=(e,t)=>{const r=getRefs(t),n=void 0,i=t?.name,o=parseDef(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},a=void 0===i?o:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function _escapeNodeLabel(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const MARKDOWN_SPECIAL_CHARS=["*","_","`"];function _generateMermaidGraphStyles(e){let t="";for(const[r,n]of Object.entries(e))t+=`\tclassDef ${r} ${n};\n`;return t}function drawMermaid(e,t,r){const{firstNode:n,lastNode:i,nodeColors:o,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:c=9}=r??{};let u=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(a){const t="default",r={[t]:"{0}({1})"};void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==i&&(r[i]="{0}([{1}]):::last");for(const[n,i]of Object.entries(e)){const e=i.name.split(":").pop()??"";let o=MARKDOWN_SPECIAL_CHARS.some((t=>e.startsWith(t)&&e.endsWith(t)))?`<p>${e}</p>`:e;Object.keys(i.metadata??{}).length&&(o+=`<hr/><small><em>${Object.entries(i.metadata??{}).map((([e,t])=>`${e} = ${t}`)).join("\n")}</em></small>`);const a=(r[n]??r[t]).replace("{0}",_escapeNodeLabel(n)).replace("{1}",o);u+=`\t${a}\n`}}const l={};for(const p of t){const e=p.source.split(":"),t=p.target.split(":"),r=e.filter(((e,r)=>e===t[r])).join(":");l[r]||(l[r]=[]),l[r].push(p)}const d=new Set;function h(e,t){const r=1===e.length&&e[0].source===e[0].target;if(t&&!r){const e=t.split(":").pop();if(d.has(e))throw new Error(`Found duplicate subgraph '${e}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(e),u+=`\tsubgraph ${e}\n`}for(const n of e){const{source:e,target:t,data:r,conditional:i}=n;let o="";if(void 0!==r){let e=r;const t=e.split(" ");t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},((e,r)=>t.slice(r*c,(r+1)*c).join(" "))).join("&nbsp;<br>&nbsp;")),o=i?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --\x3e `}else o=i?" -.-> ":" --\x3e ";u+=`\t${_escapeNodeLabel(e)}${o}${_escapeNodeLabel(t)};\n`}for(const n in l)n.startsWith(`${t}:`)&&n!==t&&h(l[n],n);t&&!r&&(u+="\tend\n")}h(l[""]??[],"");for(const p in l)p.includes(":")||""===p||h(l[p],p);return a&&(u+=_generateMermaidGraphStyles(o??{})),u}async function drawMermaidPng(e,t){let{backgroundColor:r="white"}=t??{};const n=btoa(e);if(void 0!==r){/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`)}const i=`https://mermaid.ink/img/${n}?bgColor=${r}`,o=await fetch(i);if(!o.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${o.status}`,`Status text: ${o.statusText}`].join("\n"));return await o.blob()}function nodeDataStr(e,t){if(void 0!==e&&!validate$1(e))return e;if(!isRunnableInterface(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(r){return t.getName()}}function nodeDataJson(e){return isRunnableInterface(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...zodToJsonSchema(e.data.schema),title:e.data.name}}}class Graph{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach(((t,r)=>{e[t.id]=validate$1(t.id)?r:t.id})),{nodes:Object.values(this.nodes).map((t=>({id:e[t.id],...nodeDataJson(t)}))),edges:this.edges.map((t=>{const r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r}))}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const n=t??v4(),i={id:n,data:e,name:nodeDataStr(t,e),metadata:r};return this.nodes[n]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter((t=>t.source!==e.id&&t.target!==e.id))}addEdge(e,t,r,n){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const i={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(i),i}firstNode(){return _firstNode(this)}lastNode(){return _lastNode(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map((e=>e.id)).every(validate$1)&&(r="");const n=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach((([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}}));const i=e.edges.map((e=>({...e,source:n(e.source),target:n(e.target)})));this.edges=[...this.edges,...i];const o=e.firstNode(),a=e.lastNode();return[o?{id:n(o.id),data:o.data}:void 0,a?{id:n(a.id),data:a.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&_firstNode(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&_lastNode(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map((e=>[e.id,e.name]))),t=new Map;Object.values(e).forEach((e=>{t.set(e,(t.get(e)||0)+1)}));const r=r=>{const n=e[r];return validate$1(r)&&1===t.get(n)?n:r};return new Graph({nodes:Object.fromEntries(Object.entries(this.nodes).map((([e,t])=>[r(e),{...t,id:r(e)}]))),edges:this.edges.map((e=>({...e,source:r(e.source),target:r(e.target)})))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},o=this.reid(),a=o.firstNode(),s=o.lastNode();return drawMermaid(o.nodes,o.edges,{firstNode:a?.id,lastNode:s?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:i})}async drawMermaidPng(e){return drawMermaidPng(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function _firstNode(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.source))).map((e=>e.target))),n=[];for(const i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function _lastNode(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.target))).map((e=>e.source))),n=[];for(const i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function convertToHttpEventStream(e){const t=new TextEncoder,r=new ReadableStream({async start(r){for await(const n of e)r.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(n)}\n\n`));r.enqueue(t.encode("event: end\n\n")),r.close()}});return IterableReadableStream.fromReadableStream(r)}function isIterableIterator(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}const isIterator=e=>null!=e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next;function isAsyncIterable(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*consumeIteratorInContext(e,t){for(;;){const{value:r,done:n}=AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(e),t.next.bind(t),!0);if(n)break;yield r}}async function*consumeAsyncIterableInContext(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:i}=await AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(e),r.next.bind(t),!0);if(i)break;yield n}}function _coerceToDict(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class Runnable extends Serializable{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new RunnableBinding({bound:this,kwargs:e,config:{}})}map(){return new RunnableEach({bound:this})}withRetry(e){return new RunnableRetry({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new RunnableBinding({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new RunnableWithFallbacks({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(ensureConfig);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter((([e])=>"runId"!==e)));return Array.from({length:t},((t,n)=>ensureConfig(0===n?e:r)))}return Array.from({length:t},(()=>ensureConfig(e)))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),i=n[0]?.maxConcurrency??r?.maxConcurrency,o=new AsyncCaller({maxConcurrency:i,onFailedAttempt:e=>{throw e}}),a=e.map(((e,t)=>o.call((async()=>{try{return await this.invoke(e,n[t])}catch(i){if(r?.returnExceptions)return i;throw i}}))));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this._streamIterator(e,r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=ensureConfig(void 0===e?e:{callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){const n=ensureConfig(r),i=await getCallbackManagerForConfig(n),o=await(i?.handleChainStart(this.toJSON(),_coerceToDict(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName()));let a;delete n.runId;try{const i=e.call(this,t,n,o);a=await raceWithSignal(i,r?.signal)}catch(s){throw await(o?.handleChainError(s)),s}return await(o?.handleChainEnd(_coerceToDict(a,"output"))),a}async _batchWithConfig(e,t,r,n){const i=this._getOptionsList(r??{},t.length),o=await Promise.all(i.map(getCallbackManagerForConfig)),a=await Promise.all(o.map((async(e,r)=>{const n=await(e?.handleChainStart(this.toJSON(),_coerceToDict(t[r],"input"),i[r].runId,i[r].runType,void 0,void 0,i[r].runName??this.getName()));return delete i[r].runId,n})));let s;try{const r=e.call(this,t,i,a,n);s=await raceWithSignal(r,i?.[0]?.signal)}catch(c){throw await Promise.all(a.map((e=>e?.handleChainError(c)))),c}return await Promise.all(a.map((e=>e?.handleChainEnd(_coerceToDict(s,"output"))))),s}async*_transformStreamWithConfig(e,t,r){let n,i,o=!0,a=!0;const s=ensureConfig(r),c=await getCallbackManagerForConfig(s);let u;try{const l=await pipeGeneratorWithSetup(t.bind(this),async function*(){for await(const t of e){if(o)if(void 0===n)n=t;else try{n=concat(n,t)}catch{n=void 0,o=!1}yield t}}(),(async()=>c?.handleChainStart(this.toJSON(),{input:""},s.runId,s.runType,void 0,void 0,s.runName??this.getName())),r?.signal,s);delete s.runId,u=l.setup;const d=u?.handlers.find(isStreamEventsHandler);let h=l.output;void 0!==d&&void 0!==u&&(h=d.tapOutputIterable(u.runId,h));const p=u?.handlers.find(isLogStreamHandler);void 0!==p&&void 0!==u&&(h=p.tapOutputIterable(u.runId,h));for await(const e of h)if(yield e,a)if(void 0===i)i=e;else try{i=concat(i,e)}catch{i=void 0,a=!1}}catch(l){throw await(u?.handleChainError(l,void 0,void 0,void 0,{inputs:_coerceToDict(n,"input")})),l}await(u?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:_coerceToDict(n,"input")}))}getGraph(e){const t=new Graph,r=t.addNode({name:`${this.getName()}Input`,schema:anyType()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:anyType()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new RunnableSequence({first:this,last:_coerceToRunnable(e)})}pick(e){return this.pipe(new RunnablePick(e))}assign(e){return this.pipe(new RunnableAssign(new RunnableMap({steps:e})))}async*transform(e,t){let r;for await(const n of e)r=void 0===r?n:concat(r,n);yield*this._streamIterator(r,ensureConfig(t))}async*streamLog(e,t,r){const n=new LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"original"}),i=ensureConfig(t);yield*this._streamLog(e,n,i)}async*_streamLog(e,t,r){const{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{const e=n.copy();e.addHandler(t,!0),r.callbacks=e}const i=this.stream(e,r);const o=async function(){try{const e=await i;for await(const r of e){const e=new RunLogPatch({ops:[{op:"add",path:"/streamed_output/-",value:r}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await o}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');n=this._streamEventsV2(e,t,r)}return"text/event-stream"===t.encoding?convertToHttpEventStream(n):IterableReadableStream.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new EventStreamCallbackHandler({...r,autoClose:!1}),i=ensureConfig(t),o=i.runId??v4();i.runId=o;const a=i.callbacks;if(void 0===a)i.callbacks=[n];else if(Array.isArray(a))i.callbacks=a.concat(n);else{const e=a.copy();e.addHandler(n,!0),i.callbacks=e}const s=new AbortController,c=this;const u=async function(){try{let r;t?.signal?"any"in AbortSignal?r=AbortSignal.any([s.signal,t.signal]):(r=t.signal,t.signal.addEventListener("abort",(()=>{s.abort()}),{once:!0})):r=s.signal;const a=await c.stream(e,{...i,signal:r}),u=n.tapOutputIterable(o,a);for await(const e of u)if(s.signal.aborted)break}finally{await n.finish()}}();let l,d=!1;try{for await(const t of n)d?(t.run_id===l&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,d=!0,l=t.run_id,yield t)}finally{s.abort(),await u}}async*_streamEventsV1(e,t,r){let n,i=!1;const o=ensureConfig(t),a=o.tags??[],s=o.metadata??{},c=o.runName??this.getName(),u=new LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new _RootEventFilter({...r}),d=this._streamLog(e,u,o);for await(const p of d){if(n=n?n.concat(p):RunLog.fromRunLogPatch(p),void 0===n.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;const t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:a,metadata:s,data:{input:e}};l.includeEvent(r,t.type)&&(yield r)}const t=p.ops.filter((e=>e.path.startsWith("/logs/"))).map((e=>e.path.split("/")[2])),r=[...new Set(t)];for(const e of r){let t,r={};const i=n.state.logs[e];if(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){const e=i.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}const{state:o}=n;if(o.streamed_output.length>0){const e=o.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${o.name}"`);const t={chunk:o.streamed_output[0]};o.streamed_output=[];const r={event:`on_${o.type}_stream`,run_id:o.id,tags:a,metadata:s,name:c,data:t};l.includeEvent(r,o.type)&&(yield r)}}const h=n?.state;if(void 0!==h){const e={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:a,metadata:s,data:{output:h.final_output}};l.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return isRunnableInterface(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new RunnableBinding({bound:this,config:{},configFactories:[n=>({callbacks:[new RootListenersTracer({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return convertRunnableToTool(this,e)}}class RunnableBinding extends Runnable{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=mergeConfigs(this.config,...e);return mergeConfigs(t,...this.configFactories?await Promise.all(this.configFactories.map((async e=>await e(t)))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new RunnableRetry({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}async batch(e,t,r){const n=Array.isArray(t)?await Promise.all(t.map((async e=>this._mergeConfig(ensureConfig(e),this.kwargs)))):await this._mergeConfig(ensureConfig(t),this.kwargs);return this.bound.batch(e,n,r)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}streamEvents(e,t,r){const n=this;return IterableReadableStream.fromAsyncGenerator(async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig(ensureConfig(t),n.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&Runnable.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new RunnableBinding({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[n=>({callbacks:[new RootListenersTracer({config:n,onStart:e,onEnd:t,onError:r})]})]})}}class RunnableEach extends Runnable{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new RunnableEach({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,patchConfig(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new RunnableEach({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class RunnableRetry extends RunnableBinding{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const n=e>1?`retry:attempt:${e}`:void 0;return patchConfig(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return pRetry((n=>super.invoke(e,this._patchConfigForRetry(n,t,r))),{onFailedAttempt:t=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){const i={};try{await pRetry((async o=>{const a=e.map(((e,t)=>t)).filter((e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error)),s=a.map((t=>e[t])),c=a.map((e=>this._patchConfigForRetry(o,t?.[e],r?.[e]))),u=await super.batch(s,c,{...n,returnExceptions:!0});let l;for(let e=0;e<u.length;e+=1){const t=u[e],r=a[e];t instanceof Error&&void 0===l&&(l=t,l.input=s[e]),i[r.toString()]=t}if(l)throw l;return u}),{onFailedAttempt:e=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(o){if(!0!==n?.returnExceptions)throw o}return Object.keys(i).sort(((e,t)=>parseInt(e,10)-parseInt(t,10))).map((e=>i[parseInt(e,10)]))}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class RunnableSequence extends Runnable{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),i=await(n?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;let o,a=e;try{const e=[this.first,...this.middle];for(let n=0;n<e.length;n+=1){const o=e[n].invoke(a,patchConfig(r,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${n+1}`)}));a=await raceWithSignal(o,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(a,patchConfig(r,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(s){throw await(i?.handleChainError(s)),s}return await(i?.handleChainEnd(_coerceToDict(o,"output"))),o}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(getCallbackManagerForConfig)),o=await Promise.all(i.map((async(t,r)=>{const i=await(t?.handleChainStart(this.toJSON(),_coerceToDict(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,i})));let a=e;try{for(let e=0;e<this.steps.length;e+=1){const t=this.steps[e].batch(a,o.map(((t,r)=>{const i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return patchConfig(n[r],{callbacks:i})})),r);a=await raceWithSignal(t,n[0]?.signal)}}catch(s){throw await Promise.all(o.map((e=>e?.handleChainError(s)))),s}return await Promise.all(o.map((e=>e?.handleChainEnd(_coerceToDict(a,"output"))))),a}async*_streamIterator(e,t){const r=await getCallbackManagerForConfig(t),{runId:n,...i}=t??{},o=await(r?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),n,void 0,void 0,void 0,i?.runName)),a=[this.first,...this.middle,this.last];let s,c=!0;try{let r=a[0].transform(async function*(){yield e}(),patchConfig(i,{callbacks:o?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e<a.length;e+=1){const t=a[e];r=await t.transform(r,patchConfig(i,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`)}))}for await(const e of r)if(t?.signal?.throwIfAborted(),yield e,c)if(void 0===s)s=e;else try{s=concat(s,e)}catch(u){s=void 0,c=!1}}catch(u){throw await(o?.handleChainError(u)),u}await(o?.handleChainEnd(_coerceToDict(s,"output")))}getGraph(e){const t=new Graph;let r=null;return this.steps.forEach(((n,i)=>{const o=n.getGraph(e);0!==i&&o.trimFirstNode(),i!==this.steps.length-1&&o.trimLastNode(),t.extend(o);const a=o.firstNode();if(!a)throw new Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,a),r=o.lastNode()})),t}pipe(e){return RunnableSequence.isRunnableSequence(e)?new RunnableSequence({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new RunnableSequence({first:this.first,middle:[...this.middle,this.last],last:_coerceToRunnable(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Runnable.isRunnable(e)}static from([e,...t],r){let n={};return"string"==typeof r?n.name=r:void 0!==r&&(n=r),new RunnableSequence({...n,first:_coerceToRunnable(e),middle:t.slice(0,-1).map(_coerceToRunnable),last:_coerceToRunnable(t[t.length-1])})}}class RunnableMap extends Runnable{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=_coerceToRunnable(r)}static from(e){return new RunnableMap({steps:e})}async invoke(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),i=await(n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;const o={};try{const n=Object.entries(this.steps).map((async([t,n])=>{o[t]=await n.invoke(e,patchConfig(r,{callbacks:i?.getChild(`map:key:${t}`)}))}));await raceWithSignal(Promise.all(n),t?.signal)}catch(a){throw await(i?.handleChainError(a)),a}return await(i?.handleChainEnd(o)),o}async*_transform(e,t,r){const n={...this.steps},i=atee(e,Object.keys(n).length),o=new Map(Object.entries(n).map((([e,n],o)=>{const a=n.transform(i[o],patchConfig(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,a.next().then((t=>({key:e,gen:a,result:t})))]})));for(;o.size;){const e=Promise.race(o.values()),{key:t,result:n,gen:i}=await raceWithSignal(e,r?.signal);o.delete(t),n.done||(yield{[t]:n.value},o.set(t,i.next().then((e=>({key:t,gen:i,result:e})))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnableTraceable extends Runnable{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!isTraceableFunction(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),n=await getCallbackManagerForConfig(r);return raceWithSignal(this.func(patchConfig(r,{callbacks:n}),e),r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);if(isAsyncIterable(n))for await(const i of n)r?.signal?.throwIfAborted(),yield i;else if(isIterator(n))for(;;){r?.signal?.throwIfAborted();const e=n.next();if(e.done)break;yield e.value}else yield n}static from(e){return new RunnableTraceable({func:e})}}function assertNonTraceableFunction(e){if(isTraceableFunction(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class RunnableLambda extends Runnable{static lc_name(){return"RunnableLambda"}constructor(e){if(isTraceableFunction(e.func))return RunnableTraceable.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),assertNonTraceableFunction(e.func),this.func=e.func}static from(e){return new RunnableLambda({func:e})}async _invoke(e,t,r){return new Promise(((n,i)=>{const o=patchConfig(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??DEFAULT_RECURSION_LIMIT)-1});AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(o),(async()=>{try{let i=await this.func(e,{...o});if(i&&Runnable.isRunnable(i)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");i=await i.invoke(e,{...o,recursionLimit:(o.recursionLimit??DEFAULT_RECURSION_LIMIT)-1})}else if(isAsyncIterable(i)){let e;for await(const n of consumeAsyncIterableInContext(o,i))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=concat(e,n)}catch(r){e=n}i=e}else if(isIterableIterator(i)){let e;for(const n of consumeIteratorInContext(o,i))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=concat(e,n)}catch(r){e=n}i=e}n(i)}catch(r){i(r)}}))}))}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let n;for await(const s of e)if(void 0===n)n=s;else try{n=concat(n,s)}catch(a){n=s}const i=patchConfig(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??DEFAULT_RECURSION_LIMIT)-1}),o=await new Promise(((e,t)=>{AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(i),(async()=>{try{const t=await this.func(n,{...i,config:i});e(t)}catch(a){t(a)}}))}));if(o&&Runnable.isRunnable(o)){if(0===r?.recursionLimit)throw new Error("Recursion limit reached.");const e=await o.stream(n,i);for await(const t of e)yield t}else if(isAsyncIterable(o))for await(const s of consumeAsyncIterableInContext(i,o))r?.signal?.throwIfAborted(),yield s;else if(isIterableIterator(o))for(const s of consumeIteratorInContext(i,o))r?.signal?.throwIfAborted(),yield s;else yield o}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnableWithFallbacks extends Runnable{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),{runId:i,...o}=r,a=await(n?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),i,void 0,void 0,void 0,o?.runName)),s=patchConfig(o,{callbacks:a?.getChild()});return await AsyncLocalStorageProviderSingleton.runWithConfig(s,(async()=>{let t;for(const i of this.runnables()){r?.signal?.throwIfAborted();try{const t=await i.invoke(e,s);return await(a?.handleChainEnd(_coerceToDict(t,"output"))),t}catch(n){void 0===t&&(t=n)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(a?.handleChainError(t)),t}))}async*_streamIterator(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),{runId:i,...o}=r,a=await(n?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),i,void 0,void 0,void 0,o?.runName));let s,c,u;for(const d of this.runnables()){r?.signal?.throwIfAborted();const t=patchConfig(o,{callbacks:a?.getChild()});try{c=consumeAsyncIterableInContext(t,await d.stream(e,t));break}catch(l){void 0===s&&(s=l)}}if(void 0===c){const e=s??new Error("No error stored at end of fallback.");throw await(a?.handleChainError(e)),e}try{for await(const e of c){yield e;try{u=void 0===u?u:concat(u,e)}catch(l){u=void 0}}}catch(l){throw await(a?.handleChainError(l)),l}await(a?.handleChainEnd(_coerceToDict(u,"output")))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map((e=>getCallbackManagerForConfig(e)))),o=await Promise.all(i.map((async(t,r)=>{const i=await(t?.handleChainStart(this.toJSON(),_coerceToDict(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,i})));let a;for(const c of this.runnables()){n[0].signal?.throwIfAborted();try{const t=await c.batch(e,o.map(((e,t)=>patchConfig(n[t],{callbacks:e?.getChild()}))),r);return await Promise.all(o.map(((e,r)=>e?.handleChainEnd(_coerceToDict(t[r],"output"))))),t}catch(s){void 0===a&&(a=s)}}if(!a)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(o.map((e=>e?.handleChainError(a)))),a}}function _coerceToRunnable(e){if("function"==typeof e)return new RunnableLambda({func:e});if(Runnable.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[r,n]of Object.entries(e))t[r]=_coerceToRunnable(n);return new RunnableMap({steps:t})}}class RunnableAssign extends Runnable{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof RunnableMap&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const n=this.mapper.getStepsKeys(),[i,o]=atee(e),a=this.mapper.transform(o,patchConfig(r,{callbacks:t?.getChild()})),s=a.next();for await(const c of i){if("object"!=typeof c||Array.isArray(c))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof c);const e=Object.fromEntries(Object.entries(c).filter((([e])=>!n.includes(e))));Object.keys(e).length>0&&(yield e)}yield(await s).value;for await(const c of a)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnablePick extends Runnable{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map((t=>[t,e[t]])).filter((e=>void 0!==e[1]));return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnableToolLike extends RunnableBinding{constructor(e){super({bound:RunnableSequence.from([RunnableLambda.from((async e=>{let t;if(_isToolCall(e))try{t=await this.schema.parseAsync(e.args)}catch(r){throw new ToolInputParsingException("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t})).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function convertRunnableToTool(e,t){const r=t.name??e.getName(),n=t.description??t.schema?.description;return t.schema.constructor===ZodString?new RunnableToolLike({name:r,description:n,schema:objectType({input:stringType()}).transform((e=>e.input)),bound:e}):new RunnableToolLike({name:r,description:n,schema:t.schema,bound:e})}const getVerbosity=()=>!1;class BaseLangChain extends Runnable{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??getVerbosity(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}function isZodSchema(e){if(!e)return!1;if("object"!=typeof e)return!1;if(Array.isArray(e))return!1;const t=e;if(t._def)return!0;return!!Object.values(ZodFirstPartyTypeKind).includes(t.constructor?.name??"NOT_INCLUDED")||"function"==typeof t.parse&&"function"==typeof t.parseAsync&&"function"==typeof t.safeParse&&"function"==typeof t.safeParseAsync}class StructuredTool extends BaseLangChain{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"verboseParsingErrors",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"content"}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat}async invoke(e,t){let r,n=ensureConfig(t);return _isToolCall(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){const n=_isToolCall(e)?e.args:e;let i;if(isZodSchema(this.schema))try{i=await this.schema.parseAsync(n)}catch(p){let t="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(t=`${t}\nDetails: ${p.message}`),new ToolInputParsingException(t,JSON.stringify(e))}else{const t=validate$2(n,this.schema);if(!t.valid){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.errors.map((e=>`${e.keywordLocation}: ${e.error}`)).join("\n")}`),new ToolInputParsingException(r,JSON.stringify(e))}i=n}const o=parseCallbackConfigArg(t),a=CallbackManager.configure(o.callbacks,this.callbacks,o.tags||r,this.tags,o.metadata,this.metadata,{verbose:this.verbose}),s=await(a?.handleToolStart(this.toJSON(),"string"==typeof e?e:JSON.stringify(e),o.runId,void 0,void 0,void 0,o.runName));let c,u,l,d;delete o.runId;try{c=await this._call(i,s,o)}catch(p){throw await(s?.handleToolError(p)),p}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(c)||2!==c.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(c)}`);[u,l]=c}else u=c;_isToolCall(e)&&(d=e.id),!d&&_configHasToolCallId(o)&&(d=o.toolCall.id);const h=_formatToolOutput({content:u,artifact:l,toolCallId:d,name:this.name});return await(s?.handleToolEnd(h)),h}}function _formatToolOutput(e){const{content:t,artifact:r,toolCallId:n}=e;return n&&!isDirectToolOutput(t)?"string"==typeof t||Array.isArray(t)&&t.every((e=>"object"==typeof e))?new ToolMessage({content:t,artifact:r,tool_call_id:n,name:e.name}):new ToolMessage({content:_stringify(t),artifact:r,tool_call_id:n,name:e.name}):t}function _stringify(e){try{return JSON.stringify(e,null,2)??""}catch(t){return`${e}`}}var empty=null,pathBrowserifyExports=requirePathBrowserify();const path=getDefaultExportFromCjs$2(pathBrowserifyExports);class RegisterAgentTool extends StructuredTool{constructor(e,t){super(),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. Optionally supports fee configuration for the agent's inbound topic using HBAR or specific tokens.",this.schema=objectType({name:stringType().describe("The name of the agent to register"),description:stringType().optional().describe("Optional description of the agent"),type:enumType(["autonomous","manual"]).optional().describe("Optional agent type (default: autonomous)"),model:stringType().optional().describe("Optional model identifier for the agent"),capabilities:arrayType(numberType()).optional().describe("Optional array of AIAgentCapability enum values (0-18). If not provided, defaults to just TEXT_GENERATION (0)"),profilePicture:unionType([stringType().describe("Path to a local image file or URL to an image"),objectType({url:stringType().describe("URL to an image file"),filename:stringType().describe("Filename to use for the image")}),objectType({path:stringType().describe("Path to a local image file"),filename:stringType().optional().describe("Optional custom filename")})]).optional().describe("Optional profile picture for the agent (local file path or URL)"),feeCollectorAccountId:stringType().optional().describe("The account ID to collect fees. If not specified, the new agent's account ID will be used. Required if any fee is specified."),hbarFee:numberType().optional().describe("Optional: The fee amount in HBAR to charge per message on the inbound topic (e.g., 0.5). If specified, inboundTopicType will be set to FEE_BASED."),tokenFee:objectType({amount:numberType(),tokenId:stringType()}).optional().describe('Optional: The fee amount and token ID to charge per message on the inbound topic (e.g., { amount: 10, tokenId: "0.0.12345" }). If specified, inboundTopicType will be set to FEE_BASED.'),hbarFees:arrayType(objectType({amount:numberType(),collectorAccount:stringType().optional()})).optional().describe("Optional: Array of HBAR fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),tokenFees:arrayType(objectType({amount:numberType(),tokenId:stringType(),collectorAccount:stringType().optional()})).optional().describe("Optional: Array of token fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),exemptAccountIds:arrayType(stringType()).optional().describe("Optional: Array of account IDs to exempt from ALL fees set for this agent."),setAsCurrent:booleanType().optional().describe("Optional: Whether to set the newly registered agent as the current active agent in the state manager. Default: true"),persistence:objectType({prefix:stringType().optional()}).optional().describe("Optional: Configuration for persisting agent data to environment variables. The prefix will determine the environment variable names (e.g., PREFIX_ACCOUNT_ID). Defaults to TODD if not specified.")}),this.client=e,this.stateManager=t}async loadProfilePicture(e){const t=Logger$2.getInstance({level:"debug"});try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){t.info(`Loading profile picture from URL: ${e}`);const r=await axios.get(e,{responseType:"arraybuffer"}),n=Buffer.from(r.data),i=new URL(e).pathname;return{buffer:n,filename:path.basename(i)||"profile.png"}}{if(!empty.existsSync(e))return t.warn(`Profile picture file not found: ${e}`),null;t.info(`Loading profile picture from file: ${e}`);const r=empty.readFileSync(e);return{buffer:r,filename:path.basename(e)}}}if("url"in e){t.info(`Loading profile picture from URL: ${e.url}`);const r=await axios.get(e.url,{responseType:"arraybuffer"}),n=Buffer.from(r.data);return{buffer:n,filename:e.filename||"profile.png"}}if("path"in e){if(!empty.existsSync(e.path))return t.warn(`Profile picture file not found: ${e.path}`),null;t.info(`Loading profile picture from file: ${e.path}`);const r=empty.readFileSync(e.path);return{buffer:r,filename:e.filename||path.basename(e.path)}}return null}catch(r){return t.error("Failed to load profile picture:",r),null}}async _call(e){const t=Logger$2.getInstance({level:"debug"}),r={name:e.name,description:e.description,type:e.type,model:e.model,capabilities:e.capabilities||[AIAgentCapability.TEXT_GENERATION],properties:{}};let n="";if(e.profilePicture){const t=await this.loadProfilePicture(e.profilePicture);if(t){const{buffer:i,filename:o}=t;r.pfpBuffer=i,r.pfpFileName=o,"string"==typeof e.profilePicture?n=e.profilePicture:"url"in e.profilePicture?n=e.profilePicture.url:"path"in e.profilePicture&&(n=e.profilePicture.path)}}const i=void 0!==e.hbarFee&&e.hbarFee>0,o=this.hasValidTokenFee(e.tokenFee),a=e.hbarFees&&e.hbarFees.length>0,s=e.tokenFees&&e.tokenFees.length>0;if(i||o||a||s){const{accountId:n}=this.client.getAccountAndSigner(),u=e.feeCollectorAccountId||n;if(!u)return"Error: Fee collector account ID is required when specifying fees and could not be determined.";const l=new FeeConfigBuilder({network:this.client.getNetwork(),logger:t});try{const n=e.exemptAccountIds?.filter((e=>e!==u&&e.startsWith("0.0")))||[];let c=l;if(i&&(t.info(`Adding HBAR fee: ${e.hbarFee} HBAR to be collected by ${u}`),c=c.addHbarFee(e.hbarFee,u,n)),a)for(const r of e.hbarFees){const e=r.collectorAccount||u;t.info(`Adding HBAR fee: ${r.amount} HBAR to be collected by ${e}`),c=c.addHbarFee(r.amount,e,n)}if(o&&(t.info(`Adding token fee: ${e.tokenFee.amount} of token ${e.tokenFee.tokenId} to be collected by ${u}`),c=await c.addTokenFee(e.tokenFee.amount,e.tokenFee.tokenId,u,void 0,n)),s)for(const r of e.tokenFees){const e=r.collectorAccount||u;t.info(`Adding token fee: ${r.amount} of token ${r.tokenId} to be collected by ${e}`),c=await c.addTokenFee(r.amount,r.tokenId,e,void 0,n)}r.feeConfig=c,t.info("FeeConfigBuilder created successfully")}catch(c){return`Error: Failed to configure fees. Reason: ${c instanceof Error?c.message:String(c)}`}}try{t.info("Registering agent with metadata");const i=await this.client.createAndRegisterAgent(r);return this.processRegistrationResult(i,e,n)}catch(c){return`Error: Failed to create/register agent "${e.name}". Reason: ${c instanceof Error?c.message:String(c)}`}}hasValidTokenFee(e){return!!(e&&e.amount>0&&e.tokenId&&""!==e.tokenId.trim())}async processRegistrationResult(e,t,r=""){const n=e?.metadata?.accountId||"",i=e?.metadata?.inboundTopicId||"",o=e?.metadata?.outboundTopicId||"",a=e?.metadata?.profileTopicId||"",s=e?.metadata?.privateKey||"",c=e?.metadata?.pfpTopicId;if(this.validateRegistrationResult(n,i,o,s),this.stateManager&&s&&n&&i&&o&&(void 0===t.setAsCurrent||t.setAsCurrent)){const e={name:t.name,accountId:n,inboundTopicId:i,outboundTopicId:o,profileTopicId:a,privateKey:s,pfpTopicId:c};if(this.stateManager.setCurrentAgent(e),this.stateManager.persistAgentData&&t.persistence)try{const r={type:"env-file",prefix:t.persistence.prefix};await this.stateManager.persistAgentData(e,r)}catch(h){Logger$2.getInstance().warn("Failed to persist agent data",h)}}await this.ensureAgentHasFunds(n,t.name);const u=this.createFeeDescription(t),l=u?` with ${u} fee on inbound topic`:"",d={success:!0,message:`Successfully registered agent '${t.name}'${l}.`,name:t.name,accountId:n,privateKey:s,inboundTopicId:i,outboundTopicId:o,profileTopicId:a||"N/A",capabilities:t.capabilities||[AIAgentCapability.TEXT_GENERATION],hasFees:!(!t.hbarFee&&!this.hasValidTokenFee(t.tokenFee)),hbarFee:t.hbarFee||0,tokenFee:t.tokenFee||null};return(c||r)&&(d.profilePicture={source:r,topicId:c}),JSON.stringify(d)}async ensureAgentHasFunds(e,t){try{await ensureAgentHasEnoughHbar(Logger$2.getInstance({module:"RegisterAgentTool"}),this.client.standardClient,e,t)}catch(r){Logger$2.getInstance().error("Failed to auto fund agent",r)}}validateRegistrationResult(e,t,r,n){if(!(e&&t&&r&&n)){const i=[!e&&"accountId",!t&&"inboundTopicId",!r&&"outboundTopicId",!n&&"privateKey"].filter(Boolean).join(", ");throw new Error(`Registration failed. The HCS client returned incomplete details (Missing: ${i}).`)}}createFeeDescription(e){const t=e.hbarFee&&e.hbarFee>0,r=this.hasValidTokenFee(e.tokenFee);if(!t&&!r)return"";let n="";if(t&&(n+=`${e.hbarFee} HBAR`),r&&e.tokenFee){const t=`${e.tokenFee.amount} of token ${e.tokenFee.tokenId}`;n+=n?` and ${t}`:t}return n}}class SendMessageTool extends StructuredTool{constructor(e){super(),this.name="send_message",this.description="Sends a message to a specified Hedera topic using HCS-10 and monitors for responses.",this.lastProcessedTimestamp=0,this.schema=objectType({topicId:stringType().describe("The Hedera topic ID to send the message to"),message:stringType().describe("The message content to send"),disableMonitoring:booleanType().optional().describe("Whether to disable monitoring for responses")}),this.client=e,this.logger=Logger$2.getInstance({module:"SendMessageTool"})}async _call(e){try{const t=await this.client.sendMessage(e.topicId,e.message);if(!t)throw new Error("Failed to send message");if(this.logger.info(`Message sent with sequence number ${t}`),e.disableMonitoring)return`Successfully sent message to topic ${e.topicId}`;{const r=await this.monitorResponses(e.topicId,t);return`Successfully sent message to topic ${e.topicId}${r?`\nResponse: ${r}`:""}`}}catch(t){throw new Error(`Failed to send message: ${t instanceof Error?t.message:String(t)}`)}}async monitorResponses(e,t){let r=0;for(;r<10;){try{const r=await this.client.getMessageStream(e);for(const e of r.messages)if(e.created&&e.created.getTime()>this.lastProcessedTimestamp){this.lastProcessedTimestamp=e.created.getTime();const r=await this.client.getMessageContent(e.data||"");let i;try{i=JSON.parse(r)}catch(n){this.logger.error(`Error parsing message content: ${n}`);continue}if(e.sequence_number>t)return i&&"string"==typeof i.data?i.data:JSON.stringify(i)}}catch(n){this.logger.error(`Error monitoring responses: ${n}`)}r++,await new Promise((e=>setTimeout(e,1e3)))}return null}}class ConnectionTool extends StructuredTool{constructor({client:e,stateManager:t,...r}){super(r),this.name="monitor_connections",this.description="Starts passively LISTENING on the current agent's own inbound topic for INCOMING HCS-10 connection requests. Handles received requests automatically. Takes NO arguments. DO NOT use this to start a new connection TO someone else.",this.isMonitoring=!1,this.monitoringTopic=null,this.schema=objectType({}),this.client=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ConnectionTool",level:"info"})}async _call(){let e;try{e=await this.client.getInboundTopicId()}catch(t){const e=`Error getting inbound topic ID for monitoring: ${t instanceof Error?t.message:String(t)}`;return this.logger.error(e),e}return e?this.isMonitoring?this.monitoringTopic===e?`Already monitoring topic ${e}.`:`Error: Already monitoring a different topic (${this.monitoringTopic}). Stop the current monitor first.`:(this.isMonitoring=!0,this.monitoringTopic=e,this.logger.info(`Initiating connection request monitoring for topic ${e}...`),this.monitorIncomingRequests(e).catch((t=>{this.logger.error(`Monitoring loop for ${e} encountered an unrecoverable error:`,t),this.isMonitoring=!1,this.monitoringTopic=null})),`Started monitoring inbound topic ${e} for connection requests in the background.`):"Error: Could not determine the inbound topic ID for the current agent."}async monitorIncomingRequests(e){this.logger.info(`Monitoring inbound topic ${e}...`);let t=0;const r=new Set;for(;this.isMonitoring&&this.monitoringTopic===e;){try{const i=(await this.client.getMessages(e)).messages,o=i.filter((e=>"connection_request"===e.op&&"number"==typeof e.sequence_number));for(const a of o){t=Math.max(t,a.sequence_number||0);const o=a.sequence_number;if(!o)continue;if(i.some((e=>"connection_created"===e.op&&e.connection_id===o))){this.logger.debug(`Connection request #${o} already handled (found connection_created). Skipping.`);continue}const s=a.operator_id||"",c=s.split("@")[1]||null;if(c)if(r.has(o))this.logger.info(`Connection request #${o} already processed in this session. Skipping.`);else{this.logger.info(`Processing connection request #${o} from account ${c}...`);try{const t=await this.client.handleConnectionRequest(e,c,o);r.add(o),this.logger.info(`Connection confirmed for request #${o}. New connection topic: ${t.connectionTopicId}`);const n={targetAccountId:c,targetAgentName:`Agent ${c}`,targetInboundTopicId:"N/A",connectionTopicId:t.connectionTopicId};this.stateManager.addActiveConnection(n),this.logger.info(`Added new active connection to ${c} state.`)}catch(n){this.logger.error(`Error handling connection request #${o} from ${c}:`,n)}}else this.logger.warn(`Could not determine requesting account ID from operator_id '${s}' for request #${o}. Skipping.`)}}catch(i){this.logger.error(`Error fetching or processing messages for topic ${e}:`,i)}await new Promise((e=>setTimeout(e,5e3)))}this.logger.info(`Monitoring loop stopped for topic ${e}.`),this.isMonitoring=!1,this.monitoringTopic=null}stopMonitoring(){this.isMonitoring?(this.logger.info(`Stopping monitoring for topic ${this.monitoringTopic}...`),this.isMonitoring=!1,this.monitoringTopic=null):this.logger.info("Monitor is not currently running.")}}class SendMessageToConnectionTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({targetIdentifier:stringType().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."),message:stringType().describe("The text message content to send."),disableMonitoring:booleanType().optional().default(!1)}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"SendMessageToConnectionTool"})}async _call({targetIdentifier:e,message:t,disableMonitoring:r}){const n=this.stateManager.getCurrentAgent();if(!n)return"Error: Cannot send message. No agent is currently active. Please register or select an agent first.";const i=this.stateManager.getConnectionByIdentifier(e);if(!i)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const o=i.connectionTopicId,a=i.targetAgentName,s=`${n.inboundTopicId}@${n.accountId}`;this.logger.info(`Sending message from ${s} to ${a} (${i.targetAccountId}) via connection topic ${o}`);try{const e=await this.hcsClient.sendMessage(o,t,`Agent message from ${n.name}`);if(!e)throw new Error("Failed to send message");if(!r)return`Message sent to ${a} (${i.targetAccountId}) via connection ${o}. Sequence Number: ${e}`;const c=await this.monitorResponses(o,s,e);return c?(this.logger.info(`Got reply from ${a}`,c),`Received reply from ${a}: ${c}`):`Message sent to ${a} (${i.targetAccountId}) via connection ${o}. Sequence Number: ${e}`}catch(c){return this.logger.error(`Failed to send message via connection ${o}: ${c}`),`Error sending message to ${a}: ${c instanceof Error?c.message:String(c)}`}}async monitorResponses(e,t,r){for(;;){try{const n=await this.hcsClient.getMessageStream(e);for(const e of n.messages){if(e.sequence_number<r||e.operator_id===t)continue;return await this.hcsClient.getMessageContent(e.data||"")}}catch(n){this.logger.error(`Error monitoring responses: ${n}`)}await new Promise((e=>setTimeout(e,4e3)))}return null}}class InitiateConnectionTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({targetAccountId:stringType().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with.")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"InitiateConnectionTool"})}async _call({targetAccountId:e}){const t=this.stateManager.getCurrentAgent();if(!t)return"Error: Cannot initiate connection. No agent is currently active. Please register or select an agent first.";this.logger.info(`Attempting connection from ${t.accountId} to ${e}`);try{this.logger.debug(`Retrieving profile for ${e}...`);const n=await this.hcsClient.getAgentProfile(e);if(!n?.topicInfo?.inboundTopic)return`Error: Could not retrieve profile or find inbound topic ID for target agent ${e}. They might not be registered or have a public profile.`;const i=n.topicInfo.inboundTopic,o=n.profile.name||`Agent ${e}`,a=await this.hcsClient.submitConnectionRequest(i,t.name),s=a?.topicSequenceNumber;if(!s)throw new Error("Connection request sequence number not found.");let c;try{if(c=s.toNumber(),isNaN(c))throw new Error("Converted sequence number is NaN.")}catch(r){throw new Error(`Failed to convert connection request sequence number: ${r}`)}const u=6e4,l=2e3,d=Math.ceil(u/l),h=await this.hcsClient.waitForConnectionConfirmation(i,c,d,l);if(!h?.connectionTopicId)return`Error: Connection confirmation not received from ${e} (for request ${c}) within ${u/1e3} seconds.`;const p=h.connectionTopicId;this.logger.info(`Connection confirmed! Topic ID: ${p}`);const f={targetAccountId:e,targetAgentName:o,targetInboundTopicId:i,connectionTopicId:p};this.stateManager.addActiveConnection(f);const m=this.stateManager.listConnections(),g=m.find((e=>e.connectionTopicId===p)),y=g?m.indexOf(g)+1:null;return`Successfully established connection ${y?`#${y}`:""} with ${o} (${e}). Connection Topic: ${p}. You can now send messages using this connection.`}catch(n){return this.logger.error(`Connection initiation failed: ${n}`),`Error initiating connection with ${e}: ${n instanceof Error?n.message:String(n)}`}}}class ListConnectionsTool extends StructuredTool{constructor({stateManager:e,hcsClient:t,...r}){super(r),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.schema=objectType({includeDetails:booleanType().optional().describe("Whether to include detailed information about each connection"),showPending:booleanType().optional().describe("Whether to include pending connection requests")}),this.stateManager=e,this.hcsClient=t,this.logger=new Logger$2({module:"ListConnectionsTool"})}async _call(e){const t=e.includeDetails??!0,r=e.showPending??!0,n=await this.getEnhancedConnections();if(0===n.length)return"There are currently no active connections.";const i=n.filter((e=>"established"===e.status)),o=n.filter((e=>e.isPending)),a=n.filter((e=>e.needsConfirmation));let s="";return i.length>0&&(s+=`🟢 Active Connections (${i.length}):\n`,i.forEach(((e,r)=>{s+=this.formatConnection(e,r,t)})),s+="\n"),r&&a.length>0&&(s+=`🟠 Connections Needing Confirmation (${a.length}):\n`,a.forEach(((e,r)=>{s+=this.formatConnection(e,r,t)})),s+="\n"),r&&o.length>0&&(s+=`⚪ Pending Connection Requests (${o.length}):\n`,o.forEach(((e,r)=>{s+=this.formatConnection(e,r,t)}))),s.trim()}formatConnection(e,t,r){let n=`${t+1}. ${e.profileInfo?.display_name||e.targetAgentName||"Unknown Agent"} (${e.targetAccountId})\n`;n+=` Topic: ${e.isPending?"(Pending Request)":e.connectionTopicId}\n`;if(n+=` Status: ${e.status||"unknown"}\n`,r){if(e.profileInfo?.bio&&(n+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),e.created){n+=` ${e.isPending?"Request sent":"Connection established"}: ${e.created.toLocaleString()}\n`}e.lastActivity&&(n+=` Last activity: ${e.lastActivity.toLocaleString()}\n`)}return n}async getEnhancedConnections(){if(!this.hcsClient)return this.stateManager.listConnections();try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error("ConnectionsManager not initialized"),this.stateManager.listConnections();const r=await t.fetchConnectionData(e);for(const n of r)this.stateManager.updateOrAddConnection(n);return r}catch(e){return console.error("Error fetching connection data:",e),this.stateManager.listConnections()}}}class CheckMessagesTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({targetIdentifier:stringType().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:booleanType().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:numberType().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"CheckMessagesTool"})}async _call({targetIdentifier:e,fetchLatest:t,lastMessagesCount:r}){const n=this.stateManager.getConnectionByIdentifier(e);if(!n)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const i=n.connectionTopicId,o=n.targetAgentName,a=this.stateManager.getLastTimestamp(i);this.logger.info(`Checking messages for connection with ${o} (${n.targetAccountId}) on topic ${i} (fetchLatest: ${t}, lastCount: ${r}, since: ${a})`);try{const e=(await this.hcsClient.getMessages(i)).messages;if(!e||0===e.length)return`No messages found on connection topic ${i}.`;let n=[],u=a;const l=!0===t;if(l){this.logger.info("Fetching latest messages regardless of timestamp.");const t=r??1;n=e.slice(-t)}else this.logger.info(`Filtering for messages newer than ${a}`),n=e.filter((e=>1e6*e.timestamp>a)),n.length>0&&(u=n.reduce(((e,t)=>Math.max(e,1e6*t.timestamp)),a));if(0===n.length)return l?`Could not retrieve the latest message(s). No messages found on topic ${i}.`:`No new messages found for connection with ${o} since last check.`;this.logger.info(`Processing ${n.length} message(s).`);let d=l?`Latest message(s) from ${o}:\n`:`New messages from ${o}:\n`;for(const t of n){let e=t.data;try{"string"==typeof e&&e.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${e}`),e=await this.hcsClient.getMessageContent(e),this.logger.debug(`Resolved content length: ${e?.length}`));let r=e;try{const t=JSON.parse(e||"{}");if("hcs-10"===t.p&&"message"===t.op&&t.data){r=`[${t.operator_id||"unknown_sender"}]: ${t.data}`}else r=e}catch(s){r=e}d+=`\n[${new Date(t.timestamp).toLocaleString()}] (Seq: ${t.sequence_number})\n${r}\n`}catch(c){const e=`Error processing message (Seq: ${t.sequence_number}): ${c instanceof Error?c.message:String(c)}`;this.logger.error(e),d+=`\n[Error processing message Seq: ${t.sequence_number}]\n`}}return!l&&u>a&&(this.logger.debug(`Updating timestamp for topic ${i} to ${u}`),this.stateManager.updateTimestamp(i,u)),d.trim()}catch(c){return this.logger.error(`Failed to check messages for topic ${i}: ${c}`),`Error checking messages for ${o}: ${c instanceof Error?c.message:String(c)}`}}}class FindRegistrationsTool extends StructuredTool{constructor({hcsClient:e,...t}){super(t),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.schema=objectType({accountId:stringType().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:arrayType(nativeEnumType(AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")}),this.hcsClient=e,this.logger=Logger$2.getInstance({module:"FindRegistrationsTool"})}async _call({accountId:e,tags:t}){this.logger.info("Searching registrations with filters - Account ID",JSON.stringify({accountId:e,tags:t}));const r={};e&&(r.accountId=e),t&&t.length>0&&(r.tags=t),r.network=this.hcsClient.getNetwork();try{if(!this.hcsClient.standardClient)throw new Error("Standard SDK client instance is not available in HCS10Client wrapper.");const e=await this.hcsClient.standardClient.findRegistrations(r);if(!e.success||e.error)return`Error finding registrations: ${e.error||"Unknown error"}`;if(!e.registrations||0===e.registrations.length)return"No registrations found matching the criteria.";let t=`Found ${e.registrations.length} registration(s):\n`;return e.registrations.forEach(((e,r)=>{const n=e.metadata;t+=`${r+1}. Name: ${n.alias||"N/A"}\n`,t+=`Description: ${n.bio||"N/A"}\n`,t+=` Account ID: ${e.accountId}\n`,t+=` Status: ${e.status}\n`,t+=` Model: ${n.properties?.model||"N/A"}\n`,n.properties?.capabilities&&n.properties.capabilities.length>0&&(t+=` Capabilities: ${n.properties.capabilities.join(", ")}\n`),n.properties&&(t+=` Properties: ${JSON.stringify(n.properties)}\n`),t+=` Inbound Topic: ${e.inboundTopicId}\n`,t+=` Outbound Topic: ${e.outboundTopicId}\n`,t+=` Created At: ${e.createdAt}\n`})),t.trim()}catch(n){return this.logger.error(`Failed to execute findRegistrations: ${n}`),`Error searching registrations: ${n instanceof Error?n.message:String(n)}`}}}class ConnectionMonitorTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.",this.schema=objectType({acceptAll:booleanType().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:stringType().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:arrayType(objectType({amount:numberType(),collectorAccount:stringType().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:arrayType(objectType({amount:numberType(),tokenId:stringType(),collectorAccount:stringType().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:arrayType(stringType()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:numberType().optional().describe("How long to monitor for incoming requests in seconds. Default is 60."),defaultCollectorAccount:stringType().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")}),this.isMonitoring=!1,this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ConnectionMonitorTool",level:"error"}),this.listConnectionsTool=new ListConnectionsTool({stateManager:t,hcsClient:e,...r})}updateClient(e){this.hcsClient=e,this.logger.info("Updated HCS10Client instance for ConnectionMonitorTool"),this.listConnectionsTool=new ListConnectionsTool({stateManager:this.stateManager,hcsClient:e})}async call(e){return this._call(e)}async _call({acceptAll:e=!1,targetAccountId:t,hbarFees:r=[],tokenFees:n=[],exemptAccountIds:i,monitorDurationSeconds:o=60,defaultCollectorAccount:a}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot monitor for connections. No agent is currently active. Please register or select an agent first.";if(this.isMonitoring)return"Already monitoring for connection requests. Please wait for the current monitoring session to complete.";try{this.isMonitoring=!0;const c=await this.hcsClient.getInboundTopicId();if(!c)return this.isMonitoring=!1,"Error: Could not find inbound topic ID for the current agent.";this.logger.info(`Starting to monitor inbound topic ${c} for connection requests...`);const u=this.createFeeConfig(r,n,i,t,a),l=Date.now()+1e3*o,d=3e3;let h=0,p=0,f=0,m=0;for(;Date.now()<l;)try{await this.listConnectionsTool.invoke({includeDetails:!1,showPending:!1});const r=this.stateManager.listConnections(),n=new Map;r.filter((e=>"established"===e.status&&!e.isPending)).forEach((e=>{n.has(e.targetAccountId)||n.set(e.targetAccountId,new Set),e.connectionRequestId&&n.get(e.targetAccountId)?.add(String(e.connectionRequestId))}));const i=(await this.hcsClient.getMessages(c)).messages.filter((e=>!(!e.sequence_number||e.sequence_number<=h)&&(h=Math.max(h,e.sequence_number),"connection_request"===e.op)));for(const o of i){const r=o.sequence_number;if(!r)continue;p++;const i=await this.hcsClient.getInboundTopicId()||"",a=this.stateManager.getConnectionsManager();if(!a){this.logger.error("ConnectionsManager not initialized in state manager");continue}if(a.isConnectionRequestProcessed(i,r)){this.logger.info(`Request #${r} already processed, skipping`),m++;continue}const s=this.extractAccountId(o);if(!s){a.markConnectionRequestProcessed(i,r);continue}if(t&&s!==t){this.logger.info(`Request #${r} doesn't match target ${t}`);continue}const c=n.get(s);if(c?.has(String(r)))this.logger.info(`Already processed connection request #${r} from ${s}, skipping`),a.markConnectionRequestProcessed(i,r),m++;else if(e){const e=await this.acceptConnectionRequest(r,s,u);a.markConnectionRequestProcessed(i,r),e.success&&(f++,this.logger.info(`Successfully accepted connection with ${s} for request #${r}`))}else this.logger.info(`Found request #${r} from ${s} (not auto-accepting)`)}await new Promise((e=>setTimeout(e,d)))}catch(s){this.logger.error(`Error polling for messages: ${s}`),await new Promise((e=>setTimeout(e,d)))}return this.isMonitoring=!1,0===p?`No connection requests received during the ${o} second monitoring period.`:e?`Monitored for ${o} seconds. Found ${p} connection requests, accepted ${f} connections, skipped ${m} existing connections${this.formatFeeString(r,n)}.`:`Monitored for ${o} seconds. Found ${p} connection requests. To accept them, call this tool again with acceptAll=true.`}catch(s){return this.isMonitoring=!1,this.logger.error(`Connection monitoring failed: ${s}`),`Error monitoring for connections: ${s instanceof Error?s.message:String(s)}`}}createFeeConfig(e=[],t=[],r,n,i){if(0!==e.length||0!==t.length)try{const o=this.hcsClient.getAccountAndSigner().accountId,a=i||o,s=new FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:a}),c=[...r||[]];n&&!c.includes(n)&&c.push(n);for(const t of e)if(t.amount>0){const e=t.collectorAccount||a;s.addHbarFee(t.amount,e,c),this.logger.info(`Added HBAR fee: ${t.amount} HBAR to be collected by ${e}`)}for(const e of t)if(e.amount>0&&e.tokenId){const t=e.collectorAccount||a;s.addTokenFee(e.amount,e.tokenId,t,void 0,c),this.logger.info(`Added token fee: ${e.amount} of token ${e.tokenId} to be collected by ${t}`)}return s}catch(o){return void this.logger.error(`Error creating fee configuration: ${o}`)}}extractAccountId(e){if(e.operator_id)return this.hcsClient.standardClient.extractAccountFromOperatorId(e.operator_id)}async acceptConnectionRequest(e,t,r){try{const i=await this.hcsClient.getInboundTopicId();this.logger.info(`Accepting connection request #${e} from ${t}`);const o=await this.hcsClient.handleConnectionRequest(i,t,e,r);if(!o?.connectionTopicId)return{success:!1,error:"Connection acceptance returned no connection topic ID"};const a=o.connectionTopicId;let s;this.logger.info(`Connection established! Topic ID: ${a}`);try{const e=await this.hcsClient.getAgentProfile(t);e.success&&e.profile&&(s=e.profile)}catch(n){this.logger.warn(`Could not fetch profile for ${t}: ${n}`)}const c=(await this.hcsClient.getAgentProfile(t))?.topicInfo?.inboundTopic||"",u={targetAccountId:t,targetAgentName:s?.display_name||`Agent ${t}`,targetInboundTopicId:c,connectionTopicId:a,profileInfo:s,created:new Date,status:"established",metadata:{requestId:e}};return this.stateManager.addActiveConnection(u),{success:!0,connectionTopicId:a}}catch(i){return this.logger.error(`Error accepting connection request: ${i}`),{success:!1,error:i instanceof Error?i.message:String(i)}}}formatFeeString(e=[],t=[]){if(0===e.length&&0===t.length)return"";let r=" with fees: ";if(e.length>0){const t=e.filter((e=>e.amount>0)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} HBAR${t}`})).join(", ");t&&(r+=t)}if(t.length>0){e.length>0&&(r+=" and ");const n=t.filter((e=>e.amount>0&&e.tokenId)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} of token ${e.tokenId}${t}`})).join(", ");n&&(r+=n)}return" with fees: "===r?"":r}update(){this.listConnectionsTool.invoke({includeDetails:!0,showPending:!0}).catch((e=>{this.logger.error(`Error updating connections: ${e}`)}))}}class ManageConnectionRequestsTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({action:enumType(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:stringType().optional().describe("The unique request key to view or reject (required for view and reject actions)")}),this.lastRefreshTime=0,this.refreshIntervalMs=3e4,this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ManageConnectionRequestsTool",level:"debug"})}async _call({action:e,requestKey:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot manage connection requests. No agent is currently active. Please register or select an agent first.";if(("view"===e||"reject"===e)&&void 0===t)return`Error: Request key is required for the "${e}" action. Use the "list" action first to see available requests.`;try{switch(await this.refreshRequestsIfNeeded(),e){case"list":return this.listRequests();case"view":return this.viewRequest(t);case"reject":return this.rejectRequest(t);default:return`Error: Unsupported action: ${e}`}}catch(r){return this.logger.error(`Error in ManageConnectionRequestsTool: ${r}`),`Error managing connection requests: ${r instanceof Error?r.message:String(r)}`}}async refreshRequestsIfNeeded(){const e=Date.now();e-this.lastRefreshTime>this.refreshIntervalMs&&(await this.refreshRequests(),this.lastRefreshTime=e)}async refreshRequests(){try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)throw new Error("Could not determine account ID for current agent");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error("ConnectionsManager not initialized");await t.fetchConnectionData(e)}catch(e){throw this.logger.error(`Error refreshing connection requests: ${e}`),e}}listRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return"Error: ConnectionsManager not initialized";const t=[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()];if(0===t.length)return console.log("No pending connection requests found.",t),"No pending connection requests found.";let r=`Found ${t.length} pending connection request(s):\n\n`;return[...t].sort(((e,t)=>t.created.getTime()-e.created.getTime())).forEach(((e,t)=>{const n=e.needsConfirmation?"🟠 Incoming":"⚪️ Outgoing",i=e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`;r+=`${t+1}. ${n} - Key: ${i}\n`,r+=` ${e.needsConfirmation?"From":"To"}: ${e.targetAgentName||`Agent ${e.targetAccountId}`} (${e.targetAccountId})\n`,r+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(r+=` Memo: ${e.memo}\n`),e.profileInfo&&e.profileInfo.bio&&(r+=` Bio: ${e.profileInfo.bio}\n`),r+="\n"})),r+='To view more details about a request, use action="view" with the specific requestKey.\n',r+='To reject a request, use action="reject" with the specific requestKey.',r}viewRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const r=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));if(!r)return`Error: Request with key ${e} not found or no longer pending.`;const n=r.needsConfirmation?"Incoming":"Outgoing",i=r.uniqueRequestKey||`${r.connectionRequestId||r.inboundRequestId||"unknown"}`;let o=`Details for ${n} connection request: ${i}\n\n`;return o+=`${r.needsConfirmation?"Requestor":"Target"} ID: ${r.targetAccountId}\n`,o+=`${r.needsConfirmation?"Requestor":"Target"} Name: ${r.targetAgentName||`Agent ${r.targetAccountId}`}\n`,o+=`Received: ${r.created.toLocaleString()}\n`,r.memo&&(o+=`Memo: ${r.memo}\n`),r.profileInfo&&(o+="\nAgent Profile Information:\n",(r.profileInfo.display_name||r.profileInfo.alias)&&(o+=`Name: ${r.profileInfo.display_name||r.profileInfo.alias}\n`),void 0!==r.profileInfo.type&&(o+=`Type: ${r.profileInfo.type}\n`),r.profileInfo.bio&&(o+=`Bio: ${r.profileInfo.bio}\n`)),o+="\nActions:\n",o+=`- To reject this request: action="reject", requestKey="${i}"\n`,o+='Use the separate "accept_connection_request" tool to accept requests.',o}async rejectRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const r=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));return r?(r.inboundRequestId?t.markConnectionRequestProcessed(r.targetInboundTopicId||"",r.inboundRequestId):r.connectionRequestId&&t.markConnectionRequestProcessed(r.originTopicId||"",r.connectionRequestId),`Connection request from ${r.targetAgentName||`Agent ${r.targetAccountId}`} was rejected.`):`Error: Request with key ${e} not found or no longer pending.`}}class AcceptConnectionRequestTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),this.name="accept_connection_request",this.description="Accepts a specific pending connection request from another agent, establishing a communication channel.",this.schema=objectType({requestKey:stringType().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:numberType().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:arrayType(stringType()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"AcceptConnectionRequestTool"})}async _call({requestKey:e,hbarFee:t,exemptAccountIds:r}){const n=this.stateManager.getCurrentAgent();if(!n)return"Error: Cannot accept connection request. No agent is currently active. Please register or select an agent first.";const i=this.stateManager.getConnectionsManager();if(!i)return"Error: ConnectionsManager not initialized";await i.fetchConnectionData(n.accountId);const o=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));if(!o)return`Error: Request with key ${e} not found or no longer pending. Use the manage_connection_requests tool with action="list" to verify.`;const a=o.connectionRequestId||o.inboundRequestId;if(!a)return`Error: Could not determine a valid request ID for the request with key ${e}.`;try{const u=await this.hcsClient.getInboundTopicId();let l;if(t&&t>0){const e=this.hcsClient.getAccountAndSigner().accountId;try{l=new FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:e});const i=[...r||[],n.accountId];l.addHbarFee(t,e,i),this.logger.info(`Setting HBAR fee: ${t} HBAR to be collected by ${e}`)}catch(s){this.logger.error(`Error creating fee configuration: ${s}`),l=void 0,this.logger.warn("Proceeding to accept request without fees due to configuration error.")}}this.logger.info(`Attempting to accept request Key: ${e} (ID: ${a}) from ${o.targetAccountId}`);const d=await this.hcsClient.handleConnectionRequest(u,o.targetAccountId,a,l);if(!d?.connectionTopicId)return`Error: Failed to accept connection request with key ${e}. The SDK did not return a connection topic ID.`;this.logger.info(`Successfully created connection topic: ${d.connectionTopicId}`);const h=d.connectionTopicId;let p="";try{const e=await this.hcsClient.standardClient.retrieveProfile(o.targetAccountId);p=e?.topicInfo?.inboundTopic||"",p||this.logger.warn(`Could not resolve target inbound topic for ${o.targetAccountId}`)}catch(c){this.logger.warn(`Error fetching target profile/topic for ${o.targetAccountId}: ${c}`)}const f=o.profileInfo?.display_name||o.profileInfo?.alias||`Agent ${o.targetAccountId}`,m={targetAccountId:o.targetAccountId,targetAgentName:f,targetInboundTopicId:p,connectionTopicId:h,profileInfo:o.profileInfo,created:new Date,status:"established"};this.stateManager.addActiveConnection(m),i.fetchConnectionData(o.targetAccountId),this.logger.info(`Removed request ${e} from pending requests`);let g="";t&&t>0&&l&&(g=` with a ${t} HBAR fee per message`);return`Successfully accepted connection request ${o.uniqueRequestKey||e} from ${f} ${g}. Connection established on topic: ${h}.`}catch(u){return this.logger.error(`Error accepting connection request ${e}: ${u}`),`Error accepting connection request ${e}: ${u instanceof Error?u.message:String(u)}`}}}class RetrieveProfileTool extends StructuredTool{constructor(e){super(),this.name="retrieve_profile",this.description="Retrieves the HCS-11 profile data associated with a given Hedera account ID. If no account ID is provided, it defaults to the current operator account ID. Returns the profile object as a JSON string on success.",this.schema=objectType({accountId:stringType().optional().describe("The Hedera account ID (e.g., 0.0.12345) to retrieve the profile for. If omitted, defaults to the current operator account ID."),disableCache:booleanType().optional().describe("Optional: Set to true to bypass the cache and fetch fresh profile data.")}),this.client=e,this.logger=Logger$2.getInstance({module:this.name})}async _call(e){let t;try{if(e.accountId?t=e.accountId:(this.logger.info("accountId not provided, defaulting to operator ID."),t=this.client.getOperatorId()),!t)throw new Error("Could not determine target account ID.");this.logger.info(`Attempting to retrieve profile for account: ${t}, Disable Cache: ${!!e.disableCache}`);const r=await this.client.standardClient.retrieveProfile(t,e.disableCache);if(r.success&&r.profile)return this.logger.info(`Successfully retrieved profile for ${t}.`),JSON.stringify(r.profile,null,2);{const e=`Error retrieving profile for ${t}: ${r.error||"Profile not found or invalid."}`;return this.logger.error(e),e}}catch(r){const t=`Unexpected error retrieving profile for ${e.accountId||"operator default"}: ${r instanceof Error?r.message:String(r)}`;return this.logger.error(t,r),t}}}class ListUnapprovedConnectionRequestsTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({sortBy:enumType(["time_asc","time_desc","name_asc","name_desc"]).optional().describe("Optional sorting criteria for the requests list (default: time_desc, newest first)"),limit:numberType().optional().describe("Optional limit on the number of requests to return (default: all)")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ListPendingRequestsTool",level:"debug"})}async _call({sortBy:e="time_desc",limit:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.";try{const r=await this.findAllPendingRequests();return this.formatRequestsList(r,e,t)}catch(r){return this.logger.error(`Error in ${this.name}: ${r}`),`Error listing pending requests: ${r instanceof Error?r.message:String(r)}`}}async findAllPendingRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return[];const t=this.stateManager.getCurrentAgent();if(!t)return[];await e.fetchConnectionData(t.accountId);return[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()]}formatRequestsList(e,t,r){if(0===e.length)return"No pending connection requests found (incoming or outgoing).";const n=this.sortRequests(e,t),i=r?n.slice(0,r):n;let o=`Found ${e.length} pending connection request(s):\n\n`;return i.forEach(((e,t)=>{const r="needs_confirmation"===e.status?"🟠 Incoming":"⚪️ Outgoing";o+=`${t+1}. ${r} - ID: ${e.uniqueRequestKey}\n`,o+=` ${"needs_confirmation"===e.status?"From:":"To: "} ${e.targetAgentName} (${e.targetAccountId})\n`,o+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(o+=` Memo: ${e.memo}\n`),e.profileInfo?.bio&&(o+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),o+="\n"})),o+="Use related tools (manage_requests, accept_request) to handle these items.",o}sortRequests(e,t){const r=[...e];switch(t){case"time_asc":return r.sort(((e,t)=>e.created.getTime()-t.created.getTime()));case"time_desc":default:return r.sort(((e,t)=>t.created.getTime()-e.created.getTime()));case"name_asc":return r.sort(((e,t)=>e.targetAgentName?.localeCompare(t?.targetAgentName||"")||0));case"name_desc":return r.sort(((e,t)=>t.targetAgentName?.localeCompare(e?.targetAgentName||"")||0))}}}const ENV_FILE_PATH=path.join(process$1$1.cwd(),".env");async function updateEnvFile(e,t){let r="";empty.existsSync(e)&&(r=empty.readFileSync(e,"utf8"));const n=[...r.split("\n")];for(const[i,o]of Object.entries(t)){const e=n.findIndex((e=>e.startsWith(`${i}=`)));-1!==e?n[e]=`${i}=${o}`:n.push(`${i}=${o}`)}empty.writeFileSync(e,n.join("\n"))}class OpenConvaiState{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const t=e?.disableLogging||"true"===process$1$1.env.DISABLE_LOGGING;this.logger=new Logger$2({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 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(),r=parseInt(e)-1;if(!isNaN(r)&&r>=0&&r<t.length)return t[r];const n=this.connectionsManager.getConnectionByTopicId(e);if(n)return this.convertToActiveConnection(n);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 r=t?.envFilePath||this.defaultEnvFilePath||process$1$1.env.ENV_FILE_PATH||".env",n=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const i={[`${n}_ACCOUNT_ID`]:e.accountId,[`${n}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${n}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(i[`${n}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(i[`${n}_PROFILE_TOPIC_ID`]=e.profileTopicId),await updateEnvFile(r,i)}}const initializeStandardsAgentKit=e=>{const t=e?.clientConfig||{},r=t.operatorId||process$1$1.env.HEDERA_OPERATOR_ID,n=t.operatorKey||process$1$1.env.HEDERA_OPERATOR_KEY,i=t.network||process$1$1.env.HEDERA_NETWORK||"testnet";let o;if("mainnet"===i?o="mainnet":("testnet"===i||console.warn(`Unsupported network specified: '${i}'. Defaulting to 'testnet'.`),o="testnet"),!r||!n)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const a="true"===process$1$1.env.DISABLE_LOGGING,s=Logger$2.getInstance({level:t.logLevel||"info",silent:a}),c=e?.stateManager||new OpenConvaiState({defaultEnvFilePath:ENV_FILE_PATH,defaultPrefix:"TODD"});s.info("State manager initialized");const u=new HCS10Client(r,n,o,{useEncryption:t.useEncryption,registryUrl:t.registryUrl});let l;s.info(`HCS10Client initialized for ${r} on ${o}`),e?.monitoringClient&&(l=new HCS10Client(r,n,o,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),s.info("Monitoring client initialized"));const d={};return d.registerAgentTool=new RegisterAgentTool(u,c),d.sendMessageTool=new SendMessageTool(u),d.connectionTool=new ConnectionTool({client:l||u,stateManager:c}),e?.createAllTools&&(d.findRegistrationsTool=new FindRegistrationsTool({hcsClient:u}),d.retrieveProfileTool=new RetrieveProfileTool(u),d.initiateConnectionTool=new InitiateConnectionTool({hcsClient:u,stateManager:c}),d.listConnectionsTool=new ListConnectionsTool({hcsClient:u,stateManager:c}),d.sendMessageToConnectionTool=new SendMessageToConnectionTool({hcsClient:u,stateManager:c}),d.checkMessagesTool=new CheckMessagesTool({hcsClient:u,stateManager:c}),d.connectionMonitorTool=new ConnectionMonitorTool({hcsClient:l||u,stateManager:c}),d.manageConnectionRequestsTool=new ManageConnectionRequestsTool({hcsClient:u,stateManager:c}),d.acceptConnectionRequestTool=new AcceptConnectionRequestTool({hcsClient:u,stateManager:c}),d.listUnapprovedConnectionRequestsTool=new ListUnapprovedConnectionRequestsTool({stateManager:c,hcsClient:u}),s.info("All tools initialized")),{hcs10Client:u,monitoringClient:l,tools:d,stateManager:c}};class PluginRegistry{constructor(e){this.plugins=new Map,this.context=e,this.logger=e.logger}async registerPlugin(e){if(this.plugins.has(e.id))throw new Error(`Plugin with ID ${e.id} is already registered`);await e.initialize(this.context),this.plugins.set(e.id,e),this.logger.info(`Plugin registered: ${e.name} (${e.id}) v${e.version}`)}getPlugin(e){return this.plugins.get(e)}getAllPlugins(){return Array.from(this.plugins.values())}getAllTools(){return this.getAllPlugins().flatMap((e=>e.getTools()))}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)return!1;if(t.cleanup)try{await t.cleanup()}catch(n){this.logger.error(`Error during plugin cleanup: ${n}`)}const r=this.plugins.delete(e);return r&&this.logger.info(`Plugin unregistered: ${t.name} (${t.id})`),r}async unregisterAllPlugins(){const e=Array.from(this.plugins.keys());for(const t of e)await this.unregisterPlugin(t)}}class BasePlugin{async initialize(e){this.context=e}async cleanup(){}}class PluginLoader{static async loadFromDirectory(e,t,r={initialize:!0}){const n=pathBrowserifyExports.join(e,"plugin.json");if(!(void 0)(n))throw new Error(`Plugin manifest not found at ${n}`)}static async loadFromPackage(e,t,r={initialize:!0}){try{const n=require.resolve(e),i=pathBrowserifyExports.dirname(n);return this.loadFromDirectory(i,t,r)}catch(n){throw new Error(`Failed to load plugin from package ${e}: ${n instanceof Error?n.message:String(n)}`)}}static isValidPlugin(e){return e&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.description&&"string"==typeof e.version&&"string"==typeof e.author&&"function"==typeof e.initialize&&"function"==typeof e.getTools}}const HEDERA_MIRROR_NODE_API="https://mainnet.mirrornode.hedera.com/api/v1",ExchangeRateResponseSchema=objectType({current_rate:objectType({cent_equivalent:numberType(),hbar_equivalent:numberType(),expiration_time:numberType()}),next_rate:objectType({cent_equivalent:numberType(),hbar_equivalent:numberType(),expiration_time:numberType()}),timestamp:stringType()});class GetHbarPriceTool extends StructuredTool{constructor(){super(...arguments),this.name="getHbarPrice",this.description="Retrieves the current price of HBAR in USD from the Hedera Mirror Node.",this.schema=objectType({})}async _call(){try{const e=(await axios.get(`${HEDERA_MIRROR_NODE_API}/network/exchangerate`)).data,t=ExchangeRateResponseSchema.safeParse(e);if(!t.success)throw console.error("Failed to parse exchange rate response:",t.error),new Error("Invalid API response format");const{current_rate:r}=t.data;return`The current price of HBAR is $${(r.cent_equivalent/r.hbar_equivalent/100).toFixed(6)} USD.`}catch(e){console.error("Error fetching HBAR price:",e);let t="An unknown error occurred";return axios.isAxiosError(e)?(t=e.message,e.response&&(t+=` (Status: ${e.response.status})`)):e instanceof Error&&(t=e.message),`Failed to retrieve HBAR price: ${t}`}}}class HbarPricePlugin{constructor(){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="Hedera Agent",this.tools=[new GetHbarPriceTool]}async initialize(){return Promise.resolve()}getTools(){return this.tools}async cleanup(){return Promise.resolve()}}class GenericPlugin extends BasePlugin{}class OpenConvAIPlugin extends GenericPlugin{constructor(){super(...arguments),this.id="openconvai-standards-agent-kit",this.name="OpenConvAI Standards Agent Kit Plugin",this.description="Comprehensive plugin providing all HCS-10 agent tools for registration, connections, and messaging",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="openconvai",this.tools=[]}async initialize(e){if(await super.initialize(e),!(e.client instanceof HCS10Client))throw new Error("OpenConvAIPlugin requires an HCS10Client instance");this.hcs10Client=e.client,this.stateManager=e.stateManager||new OpenConvaiState,this.initializeTools(),this.context.logger.info("OpenConvAI Standards Agent Kit Plugin initialized successfully")}initializeTools(){if(!this.hcs10Client||!this.stateManager)throw new Error("HCS10Client and StateManager must be initialized before creating tools");this.tools=[new RegisterAgentTool(this.hcs10Client,this.stateManager),new SendMessageTool(this.hcs10Client),new ConnectionTool({client:this.hcs10Client,stateManager:this.stateManager}),new FindRegistrationsTool({hcsClient:this.hcs10Client}),new RetrieveProfileTool(this.hcs10Client),new InitiateConnectionTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ListConnectionsTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new SendMessageToConnectionTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new CheckMessagesTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ConnectionMonitorTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ManageConnectionRequestsTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new AcceptConnectionRequestTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ListUnapprovedConnectionRequestsTool({stateManager:this.stateManager,hcsClient:this.hcs10Client})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.hcs10Client=void 0,this.stateManager=void 0,this.context.logger.info("OpenConvAI Standards Agent Kit Plugin cleaned up")}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global$2?global$2:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dist={},hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});for(var t={},r={byteLength:function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},toByteArray:function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,d=s>0?a-4:a;for(r=0;r<d;r+=4)t=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},fromByteArray:function(e){for(var t,r=e.length,i=r%3,o=[],a=16383,s=0,c=r-i;s<c;s+=a)o.push(u(e,s,s+a>c?c:s+a));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")}},n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],i[a.charCodeAt(s)]=s;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,r){for(var i,o,a=[],s=t;s<r;s+=3)i=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(n[(o=i)>>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63;var l={
155
+ const _hasOwnProperty=Object.prototype.hasOwnProperty;function hasOwnProperty(e,t){return _hasOwnProperty.call(e,t)}function _objectKeys(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let r in e)hasOwnProperty(e,r)&&t.push(r);return t}function _deepClone(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function isInteger(e){let t=0;const r=e.length;let n;for(;t<r;){if(n=e.charCodeAt(t),!(n>=48&&n<=57))return!1;t++}return!0}function unescapePathComponent(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function hasUndefined(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let r=0,n=e.length;r<n;r++)if(hasUndefined(e[r]))return!0}else if("object"==typeof e){const r=_objectKeys(e),n=r.length;for(var t=0;t<n;t++)if(hasUndefined(e[r[t]]))return!0}return!1}function patchErrorMessageFormatter(e,t){const r=[e];for(const n in t){const e="object"==typeof t[n]?JSON.stringify(t[n],null,2):t[n];void 0!==e&&r.push(`${n}: ${e}`)}return r.join("\n")}class PatchError extends Error{constructor(e,t,r,n,i){super(patchErrorMessageFormatter(e,{name:t,index:r,operation:n,tree:i})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.setPrototypeOf(this,new.target.prototype),this.message=patchErrorMessageFormatter(e,{name:t,index:r,operation:n,tree:i})}}const JsonPatchError=PatchError,objOps={add:function(e,t,r){return e[t]=this.value,{newDocument:r}},remove:function(e,t,r){var n=e[t];return delete e[t],{newDocument:r,removed:n}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:function(e,t,r){let n=getValueByPointer(r,this.path);n&&(n=_deepClone(n));const i=applyOperation(r,{op:"remove",path:this.from}).removed;return applyOperation(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(e,t,r){const n=getValueByPointer(r,this.from);return applyOperation(r,{op:"add",path:this.path,value:_deepClone(n)}),{newDocument:r}},test:function(e,t,r){return{newDocument:r,test:_areEquals(e[t],this.value)}},_get:function(e,t,r){return this.value=e[t],{newDocument:r}}};var arrOps={add:function(e,t,r){return isInteger(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:r,index:t}},remove:function(e,t,r){return{newDocument:r,removed:e.splice(t,1)[0]}},replace:function(e,t,r){var n=e[t];return e[t]=this.value,{newDocument:r,removed:n}},move:objOps.move,copy:objOps.copy,test:objOps.test,_get:objOps._get};function getValueByPointer(e,t){if(""==t)return e;var r={op:"_get",path:t};return applyOperation(e,r),r.value}function applyOperation(e,t,r=!1,n=!0,i=!0,o=0){if(r&&("function"==typeof r?r(t,0,e,t.path):validator(t,0)),""===t.path){let n={newDocument:e};if("add"===t.op)return n.newDocument=t.value,n;if("replace"===t.op)return n.newDocument=t.value,n.removed=e,n;if("move"===t.op||"copy"===t.op)return n.newDocument=getValueByPointer(e,t.from),"move"===t.op&&(n.removed=e),n;if("test"===t.op){if(n.test=_areEquals(e,t.value),!1===n.test)throw new JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n.newDocument=e,n}if("remove"===t.op)return n.removed=e,n.newDocument=null,n;if("_get"===t.op)return t.value=e,n;if(r)throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,t,e);return n}{n||(e=_deepClone(e));const a=(t.path||"").split("/");let s,c,u,l=e,d=1,h=a.length;for(u="function"==typeof r?r:validator;;){if(c=a[d],c&&-1!=c.indexOf("~")&&(c=unescapePathComponent(c)),i&&("__proto__"==c||"prototype"==c&&d>0&&"constructor"==a[d-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&void 0===s&&(void 0===l[c]?s=a.slice(0,d).join("/"):d==h-1&&(s=t.path),void 0!==s&&u(t,0,e,s)),d++,Array.isArray(l)){if("-"===c)c=l.length;else{if(r&&!isInteger(c))throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,t,e);isInteger(c)&&(c=~~c)}if(d>=h){if(r&&"add"===t.op&&c>l.length)throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,t,e);const n=arrOps[t.op].call(t,l,c,e);if(!1===n.test)throw new JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n}}else if(d>=h){const r=objOps[t.op].call(t,l,c,e);if(!1===r.test)throw new JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return r}if(l=l[c],r&&d<h&&(!l||"object"!=typeof l))throw new JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,t,e)}}}function applyPatch(e,t,r,n=!0,i=!0){if(r&&!Array.isArray(t))throw new JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(e=_deepClone(e));const o=new Array(t.length);for(let a=0,s=t.length;a<s;a++)o[a]=applyOperation(e,t[a],r,!0,i,a),e=o[a].newDocument;return o.newDocument=e,o}function validator(e,t,r,n){if("object"!=typeof e||null===e||Array.isArray(e))throw new JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,r);if(!objOps[e.op])throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,r);if("string"!=typeof e.path)throw new JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,r);if(0!==e.path.indexOf("/")&&e.path.length>0)throw new JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,r);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,r);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&hasUndefined(e.value))throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,r);if(r)if("add"==e.op){var i=e.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,r)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==n)throw new JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,r)}else if("move"===e.op||"copy"===e.op){var a=validate([{op:"_get",path:e.from,value:void 0}],r);if(a&&"OPERATION_PATH_UNRESOLVABLE"===a.name)throw new JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,r)}}function validate(e,t,r){try{if(!Array.isArray(e))throw new JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)applyPatch(_deepClone(t),_deepClone(e),r||!0);else{r=r||validator;for(var n=0;n<e.length;n++)r(e[n],n,t,void 0)}}catch(i){if(i instanceof JsonPatchError)return i;throw i}}function _areEquals(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var r,n,i,o=Array.isArray(e),a=Array.isArray(t);if(o&&a){if((n=e.length)!=t.length)return!1;for(r=n;0!==r--;)if(!_areEquals(e[r],t[r]))return!1;return!0}if(o!=a)return!1;var s=Object.keys(e);if((n=s.length)!==Object.keys(t).length)return!1;for(r=n;0!==r--;)if(!t.hasOwnProperty(s[r]))return!1;for(r=n;0!==r--;)if(!_areEquals(e[i=s[r]],t[i]))return!1;return!0}return e!=e&&t!=t}class MockAsyncLocalStorage{getStore(){}run(e,t){return t()}enterWith(e){}}const mockAsyncLocalStorage=new MockAsyncLocalStorage,LC_CHILD_KEY=Symbol.for("lc:child_config");class AsyncLocalStorageProvider{getInstance(){return getGlobalAsyncLocalStorageInstance()??mockAsyncLocalStorage}getRunnableConfig(){const e=this.getInstance();return e.getStore()?.extra?.[LC_CHILD_KEY]}runWithConfig(e,t,r){const n=CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),o=i.getStore(),a=n?.getParentRunId(),s=n?.handlers?.find((e=>"langchain_tracer"===e?.name));let c;return s&&a?c=s.convertToRunTree(a):r||(c=new RunTree({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[LC_CHILD_KEY]:e}),void 0!==o&&void 0!==o[_CONTEXT_VARIABLES_KEY]&&(void 0===c&&(c={}),c[_CONTEXT_VARIABLES_KEY]=o[_CONTEXT_VARIABLES_KEY]),i.run(c,t)}initializeGlobalInstance(e){void 0===getGlobalAsyncLocalStorageInstance()&&setGlobalAsyncLocalStorageInstance(e)}}const AsyncLocalStorageProviderSingleton=new AsyncLocalStorageProvider,DEFAULT_RECURSION_LIMIT=25;async function getCallbackManagerForConfig(e){return CallbackManager._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function mergeConfigs(...e){const t={};for(const r of e.filter((e=>!!e)))for(const e of Object.keys(r))if("metadata"===e)t[e]={...t[e],...r[e]};else if("tags"===e){const n=t[e]??[];t[e]=[...new Set(n.concat(r[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...r[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=r.timeout:void 0!==r.timeout&&(t.timeout=Math.min(t.timeout,r.timeout));else if("signal"===e)void 0===t.signal?t.signal=r.signal:void 0!==r.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,r.signal]):t.signal=r.signal);else if("callbacks"===e){const e=t.callbacks,n=r.callbacks;if(Array.isArray(n))if(e)if(Array.isArray(e))t.callbacks=e.concat(n);else{const r=e.copy();for(const e of n)r.addHandler(ensureHandler(e),!0);t.callbacks=r}else t.callbacks=n;else if(n)if(e)if(Array.isArray(e)){const r=n.copy();for(const t of e)r.addHandler(ensureHandler(t),!0);t.callbacks=r}else t.callbacks=new CallbackManager(n._parentRunId,{handlers:e.handlers.concat(n.handlers),inheritableHandlers:e.inheritableHandlers.concat(n.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(n.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(n.inheritableTags))),metadata:{...e.metadata,...n.metadata}});else t.callbacks=n}else{const n=e;t[n]=r[n]??t[n]}return t}const PRIMITIVES=new Set(["string","number","boolean"]);function ensureConfig(e){const t=AsyncLocalStorageProviderSingleton.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:n,...i}=t;r=Object.entries(i).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)}if(e&&(r=Object.entries(e).reduce(((e,[t,r])=>(void 0!==r&&(e[t]=r),e)),r)),r?.configurable)for(const n of Object.keys(r.configurable))PRIMITIVES.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(void 0!==r.timeout){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const e=AbortSignal.timeout(r.timeout);void 0!==r.signal?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,e])):r.signal=e,delete r.timeout}return r}function patchConfig(e={},{callbacks:t,maxConcurrency:r,recursionLimit:n,runName:i,configurable:o,runId:a}={}){const s=ensureConfig(e);return void 0!==t&&(delete s.runName,s.callbacks=t),void 0!==n&&(s.recursionLimit=n),void 0!==r&&(s.maxConcurrency=r),void 0!==i&&(s.runName=i),void 0!==o&&(s.configurable={...s.configurable,...o}),void 0!==a&&delete s.runId,s}function pickRunnableConfigKeys(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function raceWithSignal(e,t){if(void 0===t)return e;let r;return Promise.race([e.catch((e=>{if(!t?.aborted)throw e})),new Promise(((e,n)=>{r=()=>{n(new Error("Aborted"))},t.addEventListener("abort",r),t.aborted&&n(new Error("Aborted"))}))]).finally((()=>t.removeEventListener("abort",r)))}class IterableReadableStream extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new IterableReadableStream({start:e=>function r(){return t.read().then((({done:t,value:n})=>{if(!t)return e.enqueue(n),r();e.close()}))}(),cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new IterableReadableStream({async pull(t){const{value:r,done:n}=await e.next();n&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function atee(e,t=2){const r=Array.from({length:t},(()=>[]));return r.map((async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of r)e.push(t)}else{if(t[0].done)return;yield t.shift().value}}))}function concat(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const r={...e};for(const[e,n]of Object.entries(t))e in r&&!Array.isArray(r[e])?r[e]=concat(r[e],n):r[e]=n;return r}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}class AsyncGeneratorWithSetup{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise(((t,r)=>{AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(e.config),(async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then((e=>t(void 0)),r)}),!0)}))}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config),this.signal?async()=>raceWithSignal(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}async function pipeGeneratorWithSetup(e,t,r,n,...i){const o=new AsyncGeneratorWithSetup({generator:t,startSetup:r,signal:n}),a=await o.setup;return{output:e(o,a,...i),setup:a}}class RunLogPatch{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=applyPatch({},t);return new RunLog({ops:t,state:r[r.length-1].newDocument})}}class RunLog extends RunLogPatch{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=applyPatch(this.state,e.ops);return new RunLog({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=applyPatch({},e.ops);return new RunLog({ops:e.ops,state:t[t.length-1].newDocument})}}const isLogStreamHandler=e=>"log_stream_tracer"===e.name;async function _getStandardizedInputs(e,t){if("original"===t)throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=e;return["retriever","llm","prompt"].includes(e.run_type)?r:1!==Object.keys(r).length||""!==r?.input?r.input:void 0}async function _getStandardizedOutputs(e,t){const{outputs:r}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?r:void 0!==r&&1===Object.keys(r).length&&void 0!==r?.output?r.output:r}function isChatGenerationChunk(e){return void 0!==e&&void 0!==e.message}class LogStreamCallbackHandler extends BaseTracer{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=IterableReadableStream.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new RunLogPatch({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new RunLogPatch({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(r.inputs=await _getStandardizedInputs(e,this._schemaFormat)),await this.writer.write(new RunLogPatch({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const r=[];"streaming_events"===this._schemaFormat&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await _getStandardizedInputs(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await _getStandardizedOutputs(e,this._schemaFormat)}),void 0!==e.end_time&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const n=new RunLogPatch({ops:r});await this.writer.write(n)}finally{if(e.id===this.rootId){const t=new RunLogPatch({ops:[{op:"replace",path:"/final_output",value:await _getStandardizedOutputs(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const n=this.keyMapByRunId[e.id];if(void 0===n)return;let i;i=void 0!==e.inputs.messages?isChatGenerationChunk(r?.chunk)?r?.chunk:new AIMessageChunk({id:`run-${e.id}`,content:t}):t;const o=new RunLogPatch({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${n}/streamed_output/-`,value:i}]});await this.writer.write(o)}}class GenerationChunk{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new GenerationChunk({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}function assignName({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const isStreamEventsHandler=e=>"event_stream_tracer"===e.name;class EventStreamCallbackHandler extends BaseTracer{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=IterableReadableStream.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(r=r||void 0!==t.find((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(r=r&&t.every((e=>!this.excludeTags?.includes(e)))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const n=this.runInfoMap.get(e);if(void 0===n)return void(yield r.value);function i(e,t){return"llm"===e&&"string"==typeof t?new GenerationChunk({text:t}):t}let o=this.tappedPromises.get(e);if(void 0===o){let a;o=new Promise((e=>{a=e})),this.tappedPromises.set(e,o);try{const o={event:`on_${n.runType}_stream`,run_id:e,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:i(n.runType,r.value)}},n),yield r.value;for await(const e of t)"tool"!==n.runType&&"retriever"!==n.runType&&await this.send({...o,data:{chunk:i(n.runType,e)}},n),yield e}finally{a()}}else{yield r.value;for await(const e of t)yield e}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);void 0!==r?r.then((()=>{this.send(e,t)})):await this.send(e,t)}async onLLMStart(e){const t=assignName(e),r=void 0!==e.inputs.messages?"chat_model":"llm",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,n);const i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onLLMNewToken(e,t,r){const n=this.runInfoMap.get(e.id);let i,o;if(void 0===n)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===n.runType)o="on_chat_model_stream",i=void 0===r?.chunk?new AIMessageChunk({content:t,id:`run-${e.id}`}):r.chunk.message;else{if("llm"!==n.runType)throw new Error(`Unexpected run type ${n.runType}`);o="on_llm_stream",i=void 0===r?.chunk?new GenerationChunk({text:t}):r.chunk}await this.send({event:o,data:{chunk:i},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let r;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const n=e.outputs?.generations;let i;if("chat_model"===t.runType){for(const e of n??[]){if(void 0!==i)break;i=e[0]?.message}r="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);i={generations:n?.map((e=>e.map((e=>({text:e.text,generationInfo:e.generationInfo}))))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end"}await this.sendEndEvent({event:r,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=assignName(e),r=e.run_type??"chain",n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let i={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(i={},n.inputs={}):void 0!==e.inputs.input?(i.input=e.inputs.input,n.inputs=e.inputs.input):(i.input=e.inputs,n.inputs=e.inputs),this.runInfoMap.set(e.id,n),await this.send({event:`on_${r}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,n=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:n};n.input&&1===Object.keys(n).length&&(i.input=n.input,t.inputs=n.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=assignName(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=void 0===e.outputs?.output?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=assignName(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const n=this.runInfoMap.get(r);if(void 0===n)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:n.tags,metadata:n.metadata,data:t},n)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally((()=>{this.writer.close()}))}}class RootListenersTracer extends BaseTracer{constructor({config:e,onStart:t,onEnd:r,onError:n}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=n}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}function isRunnableInterface(e){return!!e&&e.lc_runnable}class _RootEventFilter{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const n=e.tags??[];return void 0!==this.includeNames&&(r=r||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(r=r||this.includeTypes.includes(t)),void 0!==this.includeTags&&(r=r||n.some((e=>this.includeTags?.includes(e)))),void 0!==this.excludeNames&&(r=r&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(r=r&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(r=r&&n.every((e=>!this.excludeTags?.includes(e)))),r}}const ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use"),defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},getDefaultOptions=e=>({...defaultOptions,...e}),getRefs=e=>{const t=getDefaultOptions(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function addErrorMessage(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function setResponseValueAndErrors(e,t,r,n,i){e[t]=r,addErrorMessage(e,t,n,i)}function parseAnyDef(){return{}}function parseArrayDef(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(r.items=parseDef(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&setResponseValueAndErrors(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&setResponseValueAndErrors(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(setResponseValueAndErrors(r,"minItems",e.exactLength.value,e.exactLength.message,t),setResponseValueAndErrors(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function parseBigintDef(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,t));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,t)}return r}function parseBooleanDef(){return{type:"boolean"}}function parseBrandedDef(e,t){return parseDef(e.type._def,t)}const parseCatchDef=(e,t)=>parseDef(e.innerType._def,t);function parseDateDef(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>parseDateDef(e,t,r)))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(e,t)}}const integerDateParser=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minimum",n.value,n.message,t);break;case"max":setResponseValueAndErrors(r,"maximum",n.value,n.message,t)}return r};function parseDefaultDef(e,t){return{...parseDef(e.innerType._def,t),default:e.defaultValue()}}function parseEffectsDef(e,t){return"input"===t.effectStrategy?parseDef(e.schema._def,t):{}}function parseEnumDef(e){return{type:"string",enum:Array.from(e.values)}}const isJsonSchema7AllOfType=e=>(!("type"in e)||"string"!==e.type)&&"allOf"in e;function parseIntersectionDef(e,t){const r=[parseDef(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),parseDef(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const i=[];return r.forEach((e=>{if(isJsonSchema7AllOfType(e))i.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);else{let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;i.push(t)}})),i.length?{allOf:i,...n}:void 0}function parseLiteralDef(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}let emojiRegex;const zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(void 0===emojiRegex&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":setResponseValueAndErrors(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":setResponseValueAndErrors(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":addFormat(r,"email",n.message,t);break;case"format:idn-email":addFormat(r,"idn-email",n.message,t);break;case"pattern:zod":addPattern(r,zodPatterns.email,n.message,t)}break;case"url":addFormat(r,"uri",n.message,t);break;case"uuid":addFormat(r,"uuid",n.message,t);break;case"regex":addPattern(r,n.regex,n.message,t);break;case"cuid":addPattern(r,zodPatterns.cuid,n.message,t);break;case"cuid2":addPattern(r,zodPatterns.cuid2,n.message,t);break;case"startsWith":addPattern(r,RegExp(`^${escapeLiteralCheckValue(n.value,t)}`),n.message,t);break;case"endsWith":addPattern(r,RegExp(`${escapeLiteralCheckValue(n.value,t)}$`),n.message,t);break;case"datetime":addFormat(r,"date-time",n.message,t);break;case"date":addFormat(r,"date",n.message,t);break;case"time":addFormat(r,"time",n.message,t);break;case"duration":addFormat(r,"duration",n.message,t);break;case"length":setResponseValueAndErrors(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),setResponseValueAndErrors(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":addPattern(r,RegExp(escapeLiteralCheckValue(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&addFormat(r,"ipv4",n.message,t),"v4"!==n.version&&addFormat(r,"ipv6",n.message,t);break;case"base64url":addPattern(r,zodPatterns.base64url,n.message,t);break;case"jwt":addPattern(r,zodPatterns.jwt,n.message,t);break;case"cidr":"v6"!==n.version&&addPattern(r,zodPatterns.ipv4Cidr,n.message,t),"v4"!==n.version&&addPattern(r,zodPatterns.ipv6Cidr,n.message,t);break;case"emoji":addPattern(r,zodPatterns.emoji(),n.message,t);break;case"ulid":addPattern(r,zodPatterns.ulid,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":addFormat(r,"binary",n.message,t);break;case"contentEncoding:base64":setResponseValueAndErrors(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":addPattern(r,zodPatterns.base64,n.message,t)}break;case"nanoid":addPattern(r,zodPatterns.nanoid,n.message,t)}return r}function escapeLiteralCheckValue(e,t){return"escape"===t.patternStrategy?escapeNonAlphaNumeric(e):e}const ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(e){let t="";for(let r=0;r<e.length;r++)ALPHA_NUMERIC.has(e[r])||(t+="\\"),t+=e[r];return t}function addFormat(e,t,r,n){e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):setResponseValueAndErrors(e,"format",t,r,n)}function addPattern(e,t,r,n){e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:stringifyRegExpWithFlags(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):setResponseValueAndErrors(e,"pattern",stringifyRegExpWithFlags(t,n),r,n)}function stringifyRegExpWithFlags(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),i=e.flags.includes("s"),o=r?e.source.toLowerCase():e.source;let a="",s=!1,c=!1,u=!1;for(let l=0;l<o.length;l++)if(s)a+=o[l],s=!1;else{if(r)if(c){if(o[l].match(/[a-z]/)){u?(a+=o[l],a+=`${o[l-2]}-${o[l]}`.toUpperCase(),u=!1):"-"===o[l+1]&&o[l+2]?.match(/[a-z]/)?(a+=o[l],u=!0):a+=`${o[l]}${o[l].toUpperCase()}`;continue}}else if(o[l].match(/[a-z]/)){a+=`[${o[l]}${o[l].toUpperCase()}]`;continue}if(n){if("^"===o[l]){a+="(^|(?<=[\r\n]))";continue}if("$"===o[l]){a+="($|(?=[\r\n]))";continue}}i&&"."===o[l]?a+=c?`${o[l]}\r\n`:`[${o[l]}\r\n]`:(a+=o[l],"\\"===o[l]?s=!0:c&&"]"===o[l]?c=!1:c||"["!==o[l]||(c=!0))}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function parseRecordDef(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce(((r,n)=>({...r,[n]:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return r;if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.checks?.length){const{type:n,...i}=parseStringDef(e.keyType._def,t);return{...r,propertyNames:i}}if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ZodFirstPartyTypeKind.ZodBranded&&e.keyType._def.type._def.typeName===ZodFirstPartyTypeKind.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...i}=parseBrandedDef(e.keyType._def,t);return{...r,propertyNames:i}}return r}function parseMapDef(e,t){if("record"===t.mapStrategy)return parseRecordDef(e,t);return{type:"array",maxItems:125,items:{type:"array",items:[parseDef(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}function parseNativeEnumDef(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),n=Array.from(new Set(r.map((e=>typeof e))));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}function parseNeverDef(){return{not:{}}}function parseNullDef(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}const primitiveMappings={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function parseUnionDef(e,t){if("openApi3"===t.target)return asAnyOf(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e._def.typeName in primitiveMappings&&(!e._def.checks||!e._def.checks.length)))){const e=r.reduce(((e,t)=>{const r=primitiveMappings[t._def.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e._def.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t._def.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t._def.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value]),[])}}}else if(r.every((e=>"ZodEnum"===e._def.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t._def.values.filter((t=>!e.includes(t)))]),[])};return asAnyOf(e,t)}const asAnyOf=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function parseNullableDef(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:primitiveMappings[e.innerType._def.typeName],nullable:!0}:{type:[primitiveMappings[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function parseNumberDef(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",addErrorMessage(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"minimum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),setResponseValueAndErrors(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?n.inclusive?setResponseValueAndErrors(r,"maximum",n.value,n.message,t):setResponseValueAndErrors(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),setResponseValueAndErrors(r,"maximum",n.value,n.message,t));break;case"multipleOf":setResponseValueAndErrors(r,"multipleOf",n.value,n.message,t)}return r}function parseObjectDef(e,t){const r="openAi"===t.target,n={type:"object",properties:{}},i=[],o=e.shape();for(const s in o){let e=o[s];if(void 0===e||void 0===e._def)continue;let a=safeIsOptional(e);a&&r&&(e instanceof ZodOptional&&(e=e._def.innerType),e.isNullable()||(e=e.nullable()),a=!1);const c=parseDef(e._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});void 0!==c&&(n.properties[s]=c,a||i.push(s))}i.length&&(n.required=i);const a=decideAdditionalProperties(e,t);return void 0!==a&&(n.additionalProperties=a),n}function decideAdditionalProperties(e,t){if("ZodNever"!==e.catchall._def.typeName)return parseDef(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function safeIsOptional(e){try{return e.isOptional()}catch{return!0}}const parseOptionalDef=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return parseDef(e.innerType._def,t);const r=parseDef(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}},parsePipelineDef=(e,t)=>{if("input"===t.pipeStrategy)return parseDef(e.in._def,t);if("output"===t.pipeStrategy)return parseDef(e.out._def,t);const r=parseDef(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,parseDef(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}};function parsePromiseDef(e,t){return parseDef(e.type._def,t)}function parseSetDef(e,t){const r={type:"array",uniqueItems:!0,items:parseDef(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&setResponseValueAndErrors(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&setResponseValueAndErrors(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function parseTupleDef(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:parseDef(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>parseDef(e._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}function parseUndefinedDef(){return{not:{}}}function parseUnknownDef(){return{}}const parseReadonlyDef=(e,t)=>parseDef(e.innerType._def,t),selectParser=(e,t,r)=>{switch(t){case ZodFirstPartyTypeKind.ZodString:return parseStringDef(e,r);case ZodFirstPartyTypeKind.ZodNumber:return parseNumberDef(e,r);case ZodFirstPartyTypeKind.ZodObject:return parseObjectDef(e,r);case ZodFirstPartyTypeKind.ZodBigInt:return parseBigintDef(e,r);case ZodFirstPartyTypeKind.ZodBoolean:return parseBooleanDef();case ZodFirstPartyTypeKind.ZodDate:return parseDateDef(e,r);case ZodFirstPartyTypeKind.ZodUndefined:return parseUndefinedDef();case ZodFirstPartyTypeKind.ZodNull:return parseNullDef(r);case ZodFirstPartyTypeKind.ZodArray:return parseArrayDef(e,r);case ZodFirstPartyTypeKind.ZodUnion:case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:return parseUnionDef(e,r);case ZodFirstPartyTypeKind.ZodIntersection:return parseIntersectionDef(e,r);case ZodFirstPartyTypeKind.ZodTuple:return parseTupleDef(e,r);case ZodFirstPartyTypeKind.ZodRecord:return parseRecordDef(e,r);case ZodFirstPartyTypeKind.ZodLiteral:return parseLiteralDef(e,r);case ZodFirstPartyTypeKind.ZodEnum:return parseEnumDef(e);case ZodFirstPartyTypeKind.ZodNativeEnum:return parseNativeEnumDef(e);case ZodFirstPartyTypeKind.ZodNullable:return parseNullableDef(e,r);case ZodFirstPartyTypeKind.ZodOptional:return parseOptionalDef(e,r);case ZodFirstPartyTypeKind.ZodMap:return parseMapDef(e,r);case ZodFirstPartyTypeKind.ZodSet:return parseSetDef(e,r);case ZodFirstPartyTypeKind.ZodLazy:return()=>e.getter()._def;case ZodFirstPartyTypeKind.ZodPromise:return parsePromiseDef(e,r);case ZodFirstPartyTypeKind.ZodNaN:case ZodFirstPartyTypeKind.ZodNever:return parseNeverDef();case ZodFirstPartyTypeKind.ZodEffects:return parseEffectsDef(e,r);case ZodFirstPartyTypeKind.ZodAny:return parseAnyDef();case ZodFirstPartyTypeKind.ZodUnknown:return parseUnknownDef();case ZodFirstPartyTypeKind.ZodDefault:return parseDefaultDef(e,r);case ZodFirstPartyTypeKind.ZodBranded:return parseBrandedDef(e,r);case ZodFirstPartyTypeKind.ZodReadonly:return parseReadonlyDef(e,r);case ZodFirstPartyTypeKind.ZodCatch:return parseCatchDef(e,r);case ZodFirstPartyTypeKind.ZodPipeline:return parsePipelineDef(e,r);case ZodFirstPartyTypeKind.ZodFunction:case ZodFirstPartyTypeKind.ZodVoid:case ZodFirstPartyTypeKind.ZodSymbol:default:return}};function parseDef(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==ignoreOverride)return i}if(n&&!r){const e=get$ref(n,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const o=selectParser(e,e.typeName,t),a="function"==typeof o?parseDef(o(),t):o;if(a&&addMeta(e,t,a),t.postProcess){const r=t.postProcess(a,e,t);return i.jsonSchema=a,r}return i.jsonSchema=a,a}const get$ref=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:getRelativePath(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,r)=>t.currentPath[r]===e))?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),{}):"seen"===t.$refStrategy?{}:void 0}},getRelativePath=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},addMeta=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),zodToJsonSchema=(e,t)=>{const r=getRefs(t),n=void 0,i=t?.name,o=parseDef(e._def,void 0===i?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??{},a=void 0===i?o:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function _escapeNodeLabel(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const MARKDOWN_SPECIAL_CHARS=["*","_","`"];function _generateMermaidGraphStyles(e){let t="";for(const[r,n]of Object.entries(e))t+=`\tclassDef ${r} ${n};\n`;return t}function drawMermaid(e,t,r){const{firstNode:n,lastNode:i,nodeColors:o,withStyles:a=!0,curveStyle:s="linear",wrapLabelNWords:c=9}=r??{};let u=a?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(a){const t="default",r={[t]:"{0}({1})"};void 0!==n&&(r[n]="{0}([{1}]):::first"),void 0!==i&&(r[i]="{0}([{1}]):::last");for(const[n,i]of Object.entries(e)){const e=i.name.split(":").pop()??"";let o=MARKDOWN_SPECIAL_CHARS.some((t=>e.startsWith(t)&&e.endsWith(t)))?`<p>${e}</p>`:e;Object.keys(i.metadata??{}).length&&(o+=`<hr/><small><em>${Object.entries(i.metadata??{}).map((([e,t])=>`${e} = ${t}`)).join("\n")}</em></small>`);const a=(r[n]??r[t]).replace("{0}",_escapeNodeLabel(n)).replace("{1}",o);u+=`\t${a}\n`}}const l={};for(const p of t){const e=p.source.split(":"),t=p.target.split(":"),r=e.filter(((e,r)=>e===t[r])).join(":");l[r]||(l[r]=[]),l[r].push(p)}const d=new Set;function h(e,t){const r=1===e.length&&e[0].source===e[0].target;if(t&&!r){const e=t.split(":").pop();if(d.has(e))throw new Error(`Found duplicate subgraph '${e}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(e),u+=`\tsubgraph ${e}\n`}for(const n of e){const{source:e,target:t,data:r,conditional:i}=n;let o="";if(void 0!==r){let e=r;const t=e.split(" ");t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},((e,r)=>t.slice(r*c,(r+1)*c).join(" "))).join("&nbsp;<br>&nbsp;")),o=i?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --\x3e `}else o=i?" -.-> ":" --\x3e ";u+=`\t${_escapeNodeLabel(e)}${o}${_escapeNodeLabel(t)};\n`}for(const n in l)n.startsWith(`${t}:`)&&n!==t&&h(l[n],n);t&&!r&&(u+="\tend\n")}h(l[""]??[],"");for(const p in l)p.includes(":")||""===p||h(l[p],p);return a&&(u+=_generateMermaidGraphStyles(o??{})),u}async function drawMermaidPng(e,t){let{backgroundColor:r="white"}=t??{};const n=btoa(e);if(void 0!==r){/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`)}const i=`https://mermaid.ink/img/${n}?bgColor=${r}`,o=await fetch(i);if(!o.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${o.status}`,`Status text: ${o.statusText}`].join("\n"));return await o.blob()}function nodeDataStr(e,t){if(void 0!==e&&!validate$1(e))return e;if(!isRunnableInterface(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch(r){return t.getName()}}function nodeDataJson(e){return isRunnableInterface(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...zodToJsonSchema(e.data.schema),title:e.data.name}}}class Graph{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach(((t,r)=>{e[t.id]=validate$1(t.id)?r:t.id})),{nodes:Object.values(this.nodes).map((t=>({id:e[t.id],...nodeDataJson(t)}))),edges:this.edges.map((t=>{const r={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(r.data=t.data),void 0!==t.conditional&&(r.conditional=t.conditional),r}))}}addNode(e,t,r){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const n=t??v4(),i={id:n,data:e,name:nodeDataStr(t,e),metadata:r};return this.nodes[n]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter((t=>t.source!==e.id&&t.target!==e.id))}addEdge(e,t,r,n){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const i={source:e.id,target:t.id,data:r,conditional:n};return this.edges.push(i),i}firstNode(){return _firstNode(this)}lastNode(){return _lastNode(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map((e=>e.id)).every(validate$1)&&(r="");const n=e=>r?`${r}:${e}`:e;Object.entries(e.nodes).forEach((([e,t])=>{this.nodes[n(e)]={...t,id:n(e)}}));const i=e.edges.map((e=>({...e,source:n(e.source),target:n(e.target)})));this.edges=[...this.edges,...i];const o=e.firstNode(),a=e.lastNode();return[o?{id:n(o.id),data:o.data}:void 0,a?{id:n(a.id),data:a.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&_firstNode(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&_lastNode(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map((e=>[e.id,e.name]))),t=new Map;Object.values(e).forEach((e=>{t.set(e,(t.get(e)||0)+1)}));const r=r=>{const n=e[r];return validate$1(r)&&1===t.get(n)?n:r};return new Graph({nodes:Object.fromEntries(Object.entries(this.nodes).map((([e,t])=>[r(e),{...t,id:r(e)}]))),edges:this.edges.map((e=>({...e,source:r(e.source),target:r(e.target)})))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:n={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},o=this.reid(),a=o.firstNode(),s=o.lastNode();return drawMermaid(o.nodes,o.edges,{firstNode:a?.id,lastNode:s?.id,withStyles:t,curveStyle:r,nodeColors:n,wrapLabelNWords:i})}async drawMermaidPng(e){return drawMermaidPng(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}function _firstNode(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.source))).map((e=>e.target))),n=[];for(const i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function _lastNode(e,t=[]){const r=new Set(e.edges.filter((e=>!t.includes(e.target))).map((e=>e.source))),n=[];for(const i of Object.values(e.nodes))t.includes(i.id)||r.has(i.id)||n.push(i);return 1===n.length?n[0]:void 0}function convertToHttpEventStream(e){const t=new TextEncoder,r=new ReadableStream({async start(r){for await(const n of e)r.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(n)}\n\n`));r.enqueue(t.encode("event: end\n\n")),r.close()}});return IterableReadableStream.fromReadableStream(r)}function isIterableIterator(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}const isIterator=e=>null!=e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next;function isAsyncIterable(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*consumeIteratorInContext(e,t){for(;;){const{value:r,done:n}=AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(e),t.next.bind(t),!0);if(n)break;yield r}}async function*consumeAsyncIterableInContext(e,t){const r=t[Symbol.asyncIterator]();for(;;){const{value:n,done:i}=await AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(e),r.next.bind(t),!0);if(i)break;yield n}}function _coerceToDict(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}class Runnable extends Serializable{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new RunnableBinding({bound:this,kwargs:e,config:{}})}map(){return new RunnableEach({bound:this})}withRetry(e){return new RunnableRetry({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new RunnableBinding({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new RunnableWithFallbacks({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(ensureConfig);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter((([e])=>"runId"!==e)));return Array.from({length:t},((t,n)=>ensureConfig(0===n?e:r)))}return Array.from({length:t},(()=>ensureConfig(e)))}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),i=n[0]?.maxConcurrency??r?.maxConcurrency,o=new AsyncCaller({maxConcurrency:i,onFailedAttempt:e=>{throw e}}),a=e.map(((e,t)=>o.call((async()=>{try{return await this.invoke(e,n[t])}catch(i){if(r?.returnExceptions)return i;throw i}}))));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this._streamIterator(e,r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(e){let t;t=ensureConfig(void 0===e?e:{callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){const n=ensureConfig(r),i=await getCallbackManagerForConfig(n),o=await(i?.handleChainStart(this.toJSON(),_coerceToDict(t,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName()));let a;delete n.runId;try{const i=e.call(this,t,n,o);a=await raceWithSignal(i,r?.signal)}catch(s){throw await(o?.handleChainError(s)),s}return await(o?.handleChainEnd(_coerceToDict(a,"output"))),a}async _batchWithConfig(e,t,r,n){const i=this._getOptionsList(r??{},t.length),o=await Promise.all(i.map(getCallbackManagerForConfig)),a=await Promise.all(o.map((async(e,r)=>{const n=await(e?.handleChainStart(this.toJSON(),_coerceToDict(t[r],"input"),i[r].runId,i[r].runType,void 0,void 0,i[r].runName??this.getName()));return delete i[r].runId,n})));let s;try{const r=e.call(this,t,i,a,n);s=await raceWithSignal(r,i?.[0]?.signal)}catch(c){throw await Promise.all(a.map((e=>e?.handleChainError(c)))),c}return await Promise.all(a.map((e=>e?.handleChainEnd(_coerceToDict(s,"output"))))),s}async*_transformStreamWithConfig(e,t,r){let n,i,o=!0,a=!0;const s=ensureConfig(r),c=await getCallbackManagerForConfig(s);let u;try{const l=await pipeGeneratorWithSetup(t.bind(this),async function*(){for await(const t of e){if(o)if(void 0===n)n=t;else try{n=concat(n,t)}catch{n=void 0,o=!1}yield t}}(),(async()=>c?.handleChainStart(this.toJSON(),{input:""},s.runId,s.runType,void 0,void 0,s.runName??this.getName())),r?.signal,s);delete s.runId,u=l.setup;const d=u?.handlers.find(isStreamEventsHandler);let h=l.output;void 0!==d&&void 0!==u&&(h=d.tapOutputIterable(u.runId,h));const p=u?.handlers.find(isLogStreamHandler);void 0!==p&&void 0!==u&&(h=p.tapOutputIterable(u.runId,h));for await(const e of h)if(yield e,a)if(void 0===i)i=e;else try{i=concat(i,e)}catch{i=void 0,a=!1}}catch(l){throw await(u?.handleChainError(l,void 0,void 0,void 0,{inputs:_coerceToDict(n,"input")})),l}await(u?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:_coerceToDict(n,"input")}))}getGraph(e){const t=new Graph,r=t.addNode({name:`${this.getName()}Input`,schema:anyType()}),n=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:anyType()});return t.addEdge(r,n),t.addEdge(n,i),t}pipe(e){return new RunnableSequence({first:this,last:_coerceToRunnable(e)})}pick(e){return this.pipe(new RunnablePick(e))}assign(e){return this.pipe(new RunnableAssign(new RunnableMap({steps:e})))}async*transform(e,t){let r;for await(const n of e)r=void 0===r?n:concat(r,n);yield*this._streamIterator(r,ensureConfig(t))}async*streamLog(e,t,r){const n=new LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"original"}),i=ensureConfig(t);yield*this._streamLog(e,n,i)}async*_streamLog(e,t,r){const{callbacks:n}=r;if(void 0===n)r.callbacks=[t];else if(Array.isArray(n))r.callbacks=n.concat([t]);else{const e=n.copy();e.addHandler(t,!0),r.callbacks=e}const i=this.stream(e,r);const o=async function(){try{const e=await i;for await(const r of e){const e=new RunLogPatch({ops:[{op:"add",path:"/streamed_output/-",value:r}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await o}}streamEvents(e,t,r){let n;if("v1"===t.version)n=this._streamEventsV1(e,t,r);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');n=this._streamEventsV2(e,t,r)}return"text/event-stream"===t.encoding?convertToHttpEventStream(n):IterableReadableStream.fromAsyncGenerator(n)}async*_streamEventsV2(e,t,r){const n=new EventStreamCallbackHandler({...r,autoClose:!1}),i=ensureConfig(t),o=i.runId??v4();i.runId=o;const a=i.callbacks;if(void 0===a)i.callbacks=[n];else if(Array.isArray(a))i.callbacks=a.concat(n);else{const e=a.copy();e.addHandler(n,!0),i.callbacks=e}const s=new AbortController,c=this;const u=async function(){try{let r;t?.signal?"any"in AbortSignal?r=AbortSignal.any([s.signal,t.signal]):(r=t.signal,t.signal.addEventListener("abort",(()=>{s.abort()}),{once:!0})):r=s.signal;const a=await c.stream(e,{...i,signal:r}),u=n.tapOutputIterable(o,a);for await(const e of u)if(s.signal.aborted)break}finally{await n.finish()}}();let l,d=!1;try{for await(const t of n)d?(t.run_id===l&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,d=!0,l=t.run_id,yield t)}finally{s.abort(),await u}}async*_streamEventsV1(e,t,r){let n,i=!1;const o=ensureConfig(t),a=o.tags??[],s=o.metadata??{},c=o.runName??this.getName(),u=new LogStreamCallbackHandler({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new _RootEventFilter({...r}),d=this._streamLog(e,u,o);for await(const p of d){if(n=n?n.concat(p):RunLog.fromRunLogPatch(p),void 0===n.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;const t={...n.state},r={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:a,metadata:s,data:{input:e}};l.includeEvent(r,t.type)&&(yield r)}const t=p.ops.filter((e=>e.path.startsWith("/logs/"))).map((e=>e.path.split("/")[2])),r=[...new Set(t)];for(const e of r){let t,r={};const i=n.state.logs[e];if(t=void 0===i.end_time?i.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==i.inputs&&(r.input=i.inputs);else if("end"===t)void 0!==i.inputs&&(r.input=i.inputs),r.output=i.final_output;else if("stream"===t){const e=i.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);r={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:r}}const{state:o}=n;if(o.streamed_output.length>0){const e=o.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${o.name}"`);const t={chunk:o.streamed_output[0]};o.streamed_output=[];const r={event:`on_${o.type}_stream`,run_id:o.id,tags:a,metadata:s,name:c,data:t};l.includeEvent(r,o.type)&&(yield r)}}const h=n?.state;if(void 0!==h){const e={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:a,metadata:s,data:{output:h.final_output}};l.includeEvent(e,h.type)&&(yield e)}}static isRunnable(e){return isRunnableInterface(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new RunnableBinding({bound:this,config:{},configFactories:[n=>({callbacks:[new RootListenersTracer({config:n,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return convertRunnableToTool(this,e)}}class RunnableBinding extends Runnable{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=mergeConfigs(this.config,...e);return mergeConfigs(t,...this.configFactories?await Promise.all(this.configFactories.map((async e=>await e(t)))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new RunnableRetry({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}async batch(e,t,r){const n=Array.isArray(t)?await Promise.all(t.map((async e=>this._mergeConfig(ensureConfig(e),this.kwargs)))):await this._mergeConfig(ensureConfig(t),this.kwargs);return this.bound.batch(e,n,r)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(ensureConfig(t),this.kwargs))}streamEvents(e,t,r){const n=this;return IterableReadableStream.fromAsyncGenerator(async function*(){yield*n.bound.streamEvents(e,{...await n._mergeConfig(ensureConfig(t),n.kwargs),version:t.version},r)}())}static isRunnableBinding(e){return e.bound&&Runnable.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new RunnableBinding({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[n=>({callbacks:[new RootListenersTracer({config:n,onStart:e,onEnd:t,onError:r})]})]})}}class RunnableEach extends Runnable{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new RunnableEach({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,patchConfig(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new RunnableEach({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class RunnableRetry extends RunnableBinding{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const n=e>1?`retry:attempt:${e}`:void 0;return patchConfig(t,{callbacks:r?.getChild(n)})}async _invoke(e,t,r){return pRetry((n=>super.invoke(e,this._patchConfigForRetry(n,t,r))),{onFailedAttempt:t=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,n){const i={};try{await pRetry((async o=>{const a=e.map(((e,t)=>t)).filter((e=>void 0===i[e.toString()]||i[e.toString()]instanceof Error)),s=a.map((t=>e[t])),c=a.map((e=>this._patchConfigForRetry(o,t?.[e],r?.[e]))),u=await super.batch(s,c,{...n,returnExceptions:!0});let l;for(let e=0;e<u.length;e+=1){const t=u[e],r=a[e];t instanceof Error&&void 0===l&&(l=t,l.input=s[e]),i[r.toString()]=t}if(l)throw l;return u}),{onFailedAttempt:e=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(o){if(!0!==n?.returnExceptions)throw o}return Object.keys(i).sort(((e,t)=>parseInt(e,10)-parseInt(t,10))).map((e=>i[parseInt(e,10)]))}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class RunnableSequence extends Runnable{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),i=await(n?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;let o,a=e;try{const e=[this.first,...this.middle];for(let n=0;n<e.length;n+=1){const o=e[n].invoke(a,patchConfig(r,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${n+1}`)}));a=await raceWithSignal(o,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(a,patchConfig(r,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(s){throw await(i?.handleChainError(s)),s}return await(i?.handleChainEnd(_coerceToDict(o,"output"))),o}async batch(e,t,r){const n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map(getCallbackManagerForConfig)),o=await Promise.all(i.map((async(t,r)=>{const i=await(t?.handleChainStart(this.toJSON(),_coerceToDict(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,i})));let a=e;try{for(let e=0;e<this.steps.length;e+=1){const t=this.steps[e].batch(a,o.map(((t,r)=>{const i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return patchConfig(n[r],{callbacks:i})})),r);a=await raceWithSignal(t,n[0]?.signal)}}catch(s){throw await Promise.all(o.map((e=>e?.handleChainError(s)))),s}return await Promise.all(o.map((e=>e?.handleChainEnd(_coerceToDict(a,"output"))))),a}async*_streamIterator(e,t){const r=await getCallbackManagerForConfig(t),{runId:n,...i}=t??{},o=await(r?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),n,void 0,void 0,void 0,i?.runName)),a=[this.first,...this.middle,this.last];let s,c=!0;try{let r=a[0].transform(async function*(){yield e}(),patchConfig(i,{callbacks:o?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e<a.length;e+=1){const t=a[e];r=await t.transform(r,patchConfig(i,{callbacks:o?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`)}))}for await(const e of r)if(t?.signal?.throwIfAborted(),yield e,c)if(void 0===s)s=e;else try{s=concat(s,e)}catch(u){s=void 0,c=!1}}catch(u){throw await(o?.handleChainError(u)),u}await(o?.handleChainEnd(_coerceToDict(s,"output")))}getGraph(e){const t=new Graph;let r=null;return this.steps.forEach(((n,i)=>{const o=n.getGraph(e);0!==i&&o.trimFirstNode(),i!==this.steps.length-1&&o.trimLastNode(),t.extend(o);const a=o.firstNode();if(!a)throw new Error(`Runnable ${n} has no first node`);r&&t.addEdge(r,a),r=o.lastNode()})),t}pipe(e){return RunnableSequence.isRunnableSequence(e)?new RunnableSequence({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new RunnableSequence({first:this.first,middle:[...this.middle,this.last],last:_coerceToRunnable(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Runnable.isRunnable(e)}static from([e,...t],r){let n={};return"string"==typeof r?n.name=r:void 0!==r&&(n=r),new RunnableSequence({...n,first:_coerceToRunnable(e),middle:t.slice(0,-1).map(_coerceToRunnable),last:_coerceToRunnable(t[t.length-1])})}}class RunnableMap extends Runnable{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=_coerceToRunnable(r)}static from(e){return new RunnableMap({steps:e})}async invoke(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),i=await(n?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName));delete r.runId;const o={};try{const n=Object.entries(this.steps).map((async([t,n])=>{o[t]=await n.invoke(e,patchConfig(r,{callbacks:i?.getChild(`map:key:${t}`)}))}));await raceWithSignal(Promise.all(n),t?.signal)}catch(a){throw await(i?.handleChainError(a)),a}return await(i?.handleChainEnd(o)),o}async*_transform(e,t,r){const n={...this.steps},i=atee(e,Object.keys(n).length),o=new Map(Object.entries(n).map((([e,n],o)=>{const a=n.transform(i[o],patchConfig(r,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,a.next().then((t=>({key:e,gen:a,result:t})))]})));for(;o.size;){const e=Promise.race(o.values()),{key:t,result:n,gen:i}=await raceWithSignal(e,r?.signal);o.delete(t),n.done||(yield{[t]:n.value},o.set(t,i.next().then((e=>({key:t,gen:i,result:e})))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnableTraceable extends Runnable{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!isTraceableFunction(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),n=await getCallbackManagerForConfig(r);return raceWithSignal(this.func(patchConfig(r,{callbacks:n}),e),r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),n=await this.invoke(e,t);if(isAsyncIterable(n))for await(const i of n)r?.signal?.throwIfAborted(),yield i;else if(isIterator(n))for(;;){r?.signal?.throwIfAborted();const e=n.next();if(e.done)break;yield e.value}else yield n}static from(e){return new RunnableTraceable({func:e})}}function assertNonTraceableFunction(e){if(isTraceableFunction(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class RunnableLambda extends Runnable{static lc_name(){return"RunnableLambda"}constructor(e){if(isTraceableFunction(e.func))return RunnableTraceable.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),assertNonTraceableFunction(e.func),this.func=e.func}static from(e){return new RunnableLambda({func:e})}async _invoke(e,t,r){return new Promise(((n,i)=>{const o=patchConfig(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??DEFAULT_RECURSION_LIMIT)-1});AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(o),(async()=>{try{let i=await this.func(e,{...o});if(i&&Runnable.isRunnable(i)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");i=await i.invoke(e,{...o,recursionLimit:(o.recursionLimit??DEFAULT_RECURSION_LIMIT)-1})}else if(isAsyncIterable(i)){let e;for await(const n of consumeAsyncIterableInContext(o,i))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=concat(e,n)}catch(r){e=n}i=e}else if(isIterableIterator(i)){let e;for(const n of consumeIteratorInContext(o,i))if(t?.signal?.throwIfAborted(),void 0===e)e=n;else try{e=concat(e,n)}catch(r){e=n}i=e}n(i)}catch(r){i(r)}}))}))}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let n;for await(const s of e)if(void 0===n)n=s;else try{n=concat(n,s)}catch(a){n=s}const i=patchConfig(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??DEFAULT_RECURSION_LIMIT)-1}),o=await new Promise(((e,t)=>{AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(i),(async()=>{try{const t=await this.func(n,{...i,config:i});e(t)}catch(a){t(a)}}))}));if(o&&Runnable.isRunnable(o)){if(0===r?.recursionLimit)throw new Error("Recursion limit reached.");const e=await o.stream(n,i);for await(const t of e)yield t}else if(isAsyncIterable(o))for await(const s of consumeAsyncIterableInContext(i,o))r?.signal?.throwIfAborted(),yield s;else if(isIterableIterator(o))for(const s of consumeIteratorInContext(i,o))r?.signal?.throwIfAborted(),yield s;else yield o}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnableWithFallbacks extends Runnable{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),{runId:i,...o}=r,a=await(n?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),i,void 0,void 0,void 0,o?.runName)),s=patchConfig(o,{callbacks:a?.getChild()});return await AsyncLocalStorageProviderSingleton.runWithConfig(s,(async()=>{let t;for(const i of this.runnables()){r?.signal?.throwIfAborted();try{const t=await i.invoke(e,s);return await(a?.handleChainEnd(_coerceToDict(t,"output"))),t}catch(n){void 0===t&&(t=n)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(a?.handleChainError(t)),t}))}async*_streamIterator(e,t){const r=ensureConfig(t),n=await getCallbackManagerForConfig(r),{runId:i,...o}=r,a=await(n?.handleChainStart(this.toJSON(),_coerceToDict(e,"input"),i,void 0,void 0,void 0,o?.runName));let s,c,u;for(const d of this.runnables()){r?.signal?.throwIfAborted();const t=patchConfig(o,{callbacks:a?.getChild()});try{c=consumeAsyncIterableInContext(t,await d.stream(e,t));break}catch(l){void 0===s&&(s=l)}}if(void 0===c){const e=s??new Error("No error stored at end of fallback.");throw await(a?.handleChainError(e)),e}try{for await(const e of c){yield e;try{u=void 0===u?u:concat(u,e)}catch(l){u=void 0}}}catch(l){throw await(a?.handleChainError(l)),l}await(a?.handleChainEnd(_coerceToDict(u,"output")))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(t??{},e.length),i=await Promise.all(n.map((e=>getCallbackManagerForConfig(e)))),o=await Promise.all(i.map((async(t,r)=>{const i=await(t?.handleChainStart(this.toJSON(),_coerceToDict(e[r],"input"),n[r].runId,void 0,void 0,void 0,n[r].runName));return delete n[r].runId,i})));let a;for(const c of this.runnables()){n[0].signal?.throwIfAborted();try{const t=await c.batch(e,o.map(((e,t)=>patchConfig(n[t],{callbacks:e?.getChild()}))),r);return await Promise.all(o.map(((e,r)=>e?.handleChainEnd(_coerceToDict(t[r],"output"))))),t}catch(s){void 0===a&&(a=s)}}if(!a)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(o.map((e=>e?.handleChainError(a)))),a}}function _coerceToRunnable(e){if("function"==typeof e)return new RunnableLambda({func:e});if(Runnable.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[r,n]of Object.entries(e))t[r]=_coerceToRunnable(n);return new RunnableMap({steps:t})}}class RunnableAssign extends Runnable{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof RunnableMap&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const n=this.mapper.getStepsKeys(),[i,o]=atee(e),a=this.mapper.transform(o,patchConfig(r,{callbacks:t?.getChild()})),s=a.next();for await(const c of i){if("object"!=typeof c||Array.isArray(c))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof c);const e=Object.fromEntries(Object.entries(c).filter((([e])=>!n.includes(e))));Object.keys(e).length>0&&(yield e)}yield(await s).value;for await(const c of a)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnablePick extends Runnable{static lc_name(){return"RunnablePick"}constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map((t=>[t,e[t]])).filter((e=>void 0!==e[1]));return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const r=ensureConfig(t),n=new AsyncGeneratorWithSetup({generator:this.transform(async function*(){yield e}(),r),config:r});return await n.setup,IterableReadableStream.fromAsyncGenerator(n)}}class RunnableToolLike extends RunnableBinding{constructor(e){super({bound:RunnableSequence.from([RunnableLambda.from((async e=>{let t;if(_isToolCall(e))try{t=await this.schema.parseAsync(e.args)}catch(r){throw new ToolInputParsingException("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t})).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function convertRunnableToTool(e,t){const r=t.name??e.getName(),n=t.description??t.schema?.description;return t.schema.constructor===ZodString?new RunnableToolLike({name:r,description:n,schema:objectType({input:stringType()}).transform((e=>e.input)),bound:e}):new RunnableToolLike({name:r,description:n,schema:t.schema,bound:e})}const getVerbosity=()=>!1;class BaseLangChain extends Runnable{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??getVerbosity(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}function isZodSchema(e){if(!e)return!1;if("object"!=typeof e)return!1;if(Array.isArray(e))return!1;const t=e;if(t._def)return!0;return!!Object.values(ZodFirstPartyTypeKind).includes(t.constructor?.name??"NOT_INCLUDED")||"function"==typeof t.parse&&"function"==typeof t.parseAsync&&"function"==typeof t.safeParse&&"function"==typeof t.safeParseAsync}class StructuredTool extends BaseLangChain{get lc_namespace(){return["langchain","tools"]}constructor(e){super(e??{}),Object.defineProperty(this,"returnDirect",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"verboseParsingErrors",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responseFormat",{enumerable:!0,configurable:!0,writable:!0,value:"content"}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat}async invoke(e,t){let r,n=ensureConfig(t);return _isToolCall(e)?(r=e.args,n={...n,toolCall:e}):r=e,this.call(r,n)}async call(e,t,r){const n=_isToolCall(e)?e.args:e;let i;if(isZodSchema(this.schema))try{i=await this.schema.parseAsync(n)}catch(p){let t="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(t=`${t}\nDetails: ${p.message}`),new ToolInputParsingException(t,JSON.stringify(e))}else{const t=validate$2(n,this.schema);if(!t.valid){let r="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(r=`${r}\nDetails: ${t.errors.map((e=>`${e.keywordLocation}: ${e.error}`)).join("\n")}`),new ToolInputParsingException(r,JSON.stringify(e))}i=n}const o=parseCallbackConfigArg(t),a=CallbackManager.configure(o.callbacks,this.callbacks,o.tags||r,this.tags,o.metadata,this.metadata,{verbose:this.verbose}),s=await(a?.handleToolStart(this.toJSON(),"string"==typeof e?e:JSON.stringify(e),o.runId,void 0,void 0,void 0,o.runName));let c,u,l,d;delete o.runId;try{c=await this._call(i,s,o)}catch(p){throw await(s?.handleToolError(p)),p}if("content_and_artifact"===this.responseFormat){if(!Array.isArray(c)||2!==c.length)throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(c)}`);[u,l]=c}else u=c;_isToolCall(e)&&(d=e.id),!d&&_configHasToolCallId(o)&&(d=o.toolCall.id);const h=_formatToolOutput({content:u,artifact:l,toolCallId:d,name:this.name});return await(s?.handleToolEnd(h)),h}}function _formatToolOutput(e){const{content:t,artifact:r,toolCallId:n}=e;return n&&!isDirectToolOutput(t)?"string"==typeof t||Array.isArray(t)&&t.every((e=>"object"==typeof e))?new ToolMessage({content:t,artifact:r,tool_call_id:n,name:e.name}):new ToolMessage({content:_stringify(t),artifact:r,tool_call_id:n,name:e.name}):t}function _stringify(e){try{return JSON.stringify(e,null,2)??""}catch(t){return`${e}`}}var empty=null,pathBrowserifyExports=requirePathBrowserify();const path=getDefaultExportFromCjs$2(pathBrowserifyExports);class RegisterAgentTool extends StructuredTool{constructor(e,t){super(),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. Optionally supports fee configuration for the agent's inbound topic using HBAR or specific tokens.",this.schema=objectType({name:stringType().describe("The name of the agent to register"),description:stringType().optional().describe("Optional description of the agent"),type:enumType(["autonomous","manual"]).optional().describe("Optional agent type (default: autonomous)"),model:stringType().optional().describe("Optional model identifier for the agent"),capabilities:arrayType(numberType()).optional().describe("Optional array of AIAgentCapability enum values (0-18). If not provided, defaults to just TEXT_GENERATION (0)"),profilePicture:unionType([stringType().describe("Path to a local image file or URL to an image"),objectType({url:stringType().describe("URL to an image file"),filename:stringType().describe("Filename to use for the image")}),objectType({path:stringType().describe("Path to a local image file"),filename:stringType().optional().describe("Optional custom filename")})]).optional().describe("Optional profile picture for the agent (local file path or URL)"),feeCollectorAccountId:stringType().optional().describe("The account ID to collect fees. If not specified, the new agent's account ID will be used. Required if any fee is specified."),hbarFee:numberType().optional().describe("Optional: The fee amount in HBAR to charge per message on the inbound topic (e.g., 0.5). If specified, inboundTopicType will be set to FEE_BASED."),tokenFee:objectType({amount:numberType(),tokenId:stringType()}).optional().describe('Optional: The fee amount and token ID to charge per message on the inbound topic (e.g., { amount: 10, tokenId: "0.0.12345" }). If specified, inboundTopicType will be set to FEE_BASED.'),hbarFees:arrayType(objectType({amount:numberType(),collectorAccount:stringType().optional()})).optional().describe("Optional: Array of HBAR fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),tokenFees:arrayType(objectType({amount:numberType(),tokenId:stringType(),collectorAccount:stringType().optional()})).optional().describe("Optional: Array of token fees with different collectors. If specified, inboundTopicType will be set to FEE_BASED."),exemptAccountIds:arrayType(stringType()).optional().describe("Optional: Array of account IDs to exempt from ALL fees set for this agent."),setAsCurrent:booleanType().optional().describe("Optional: Whether to set the newly registered agent as the current active agent in the state manager. Default: true"),persistence:objectType({prefix:stringType().optional()}).optional().describe("Optional: Configuration for persisting agent data to environment variables. The prefix will determine the environment variable names (e.g., PREFIX_ACCOUNT_ID). Defaults to TODD if not specified.")}),this.client=e,this.stateManager=t}async loadProfilePicture(e){const t=Logger$2.getInstance({level:"debug"});try{if(!e)return null;if("string"==typeof e){if(e.startsWith("http://")||e.startsWith("https://")){t.info(`Loading profile picture from URL: ${e}`);const r=await axios.get(e,{responseType:"arraybuffer"}),n=Buffer.from(r.data),i=new URL(e).pathname;return{buffer:n,filename:path.basename(i)||"profile.png"}}{if(!empty.existsSync(e))return t.warn(`Profile picture file not found: ${e}`),null;t.info(`Loading profile picture from file: ${e}`);const r=empty.readFileSync(e);return{buffer:r,filename:path.basename(e)}}}if("url"in e){t.info(`Loading profile picture from URL: ${e.url}`);const r=await axios.get(e.url,{responseType:"arraybuffer"}),n=Buffer.from(r.data);return{buffer:n,filename:e.filename||"profile.png"}}if("path"in e){if(!empty.existsSync(e.path))return t.warn(`Profile picture file not found: ${e.path}`),null;t.info(`Loading profile picture from file: ${e.path}`);const r=empty.readFileSync(e.path);return{buffer:r,filename:e.filename||path.basename(e.path)}}return null}catch(r){return t.error("Failed to load profile picture:",r),null}}async _call(e){const t=Logger$2.getInstance({level:"debug"}),r={name:e.name,description:e.description,type:e.type,model:e.model,capabilities:e.capabilities||[AIAgentCapability.TEXT_GENERATION],properties:{}};let n="";if(e.profilePicture){const t=await this.loadProfilePicture(e.profilePicture);if(t){const{buffer:i,filename:o}=t;r.pfpBuffer=i,r.pfpFileName=o,"string"==typeof e.profilePicture?n=e.profilePicture:"url"in e.profilePicture?n=e.profilePicture.url:"path"in e.profilePicture&&(n=e.profilePicture.path)}}const i=void 0!==e.hbarFee&&e.hbarFee>0,o=this.hasValidTokenFee(e.tokenFee),a=e.hbarFees&&e.hbarFees.length>0,s=e.tokenFees&&e.tokenFees.length>0;if(i||o||a||s){const{accountId:n}=this.client.getAccountAndSigner(),u=e.feeCollectorAccountId||n;if(!u)return"Error: Fee collector account ID is required when specifying fees and could not be determined.";const l=new FeeConfigBuilder({network:this.client.getNetwork(),logger:t});try{const n=e.exemptAccountIds?.filter((e=>e!==u&&e.startsWith("0.0")))||[];let c=l;if(i&&(t.info(`Adding HBAR fee: ${e.hbarFee} HBAR to be collected by ${u}`),c=c.addHbarFee(e.hbarFee,u,n)),a)for(const r of e.hbarFees){const e=r.collectorAccount||u;t.info(`Adding HBAR fee: ${r.amount} HBAR to be collected by ${e}`),c=c.addHbarFee(r.amount,e,n)}if(o&&(t.info(`Adding token fee: ${e.tokenFee.amount} of token ${e.tokenFee.tokenId} to be collected by ${u}`),c=await c.addTokenFee(e.tokenFee.amount,e.tokenFee.tokenId,u,void 0,n)),s)for(const r of e.tokenFees){const e=r.collectorAccount||u;t.info(`Adding token fee: ${r.amount} of token ${r.tokenId} to be collected by ${e}`),c=await c.addTokenFee(r.amount,r.tokenId,e,void 0,n)}r.feeConfig=c,t.info("FeeConfigBuilder created successfully")}catch(c){return`Error: Failed to configure fees. Reason: ${c instanceof Error?c.message:String(c)}`}}try{t.info("Registering agent with metadata");const i=await this.client.createAndRegisterAgent(r);return this.processRegistrationResult(i,e,n)}catch(c){return`Error: Failed to create/register agent "${e.name}". Reason: ${c instanceof Error?c.message:String(c)}`}}hasValidTokenFee(e){return!!(e&&e.amount>0&&e.tokenId&&""!==e.tokenId.trim())}async processRegistrationResult(e,t,r=""){const n=e?.metadata?.accountId||"",i=e?.metadata?.inboundTopicId||"",o=e?.metadata?.outboundTopicId||"",a=e?.metadata?.profileTopicId||"",s=e?.metadata?.privateKey||"",c=e?.metadata?.pfpTopicId;if(this.validateRegistrationResult(n,i,o,s),this.stateManager&&s&&n&&i&&o&&(void 0===t.setAsCurrent||t.setAsCurrent)){const e={name:t.name,accountId:n,inboundTopicId:i,outboundTopicId:o,profileTopicId:a,privateKey:s,pfpTopicId:c};if(this.stateManager.setCurrentAgent(e),this.stateManager.persistAgentData&&t.persistence)try{const r={type:"env-file",prefix:t.persistence.prefix};await this.stateManager.persistAgentData(e,r)}catch(h){Logger$2.getInstance().warn("Failed to persist agent data",h)}}await this.ensureAgentHasFunds(n,t.name);const u=this.createFeeDescription(t),l=u?` with ${u} fee on inbound topic`:"",d={success:!0,message:`Successfully registered agent '${t.name}'${l}.`,name:t.name,accountId:n,privateKey:s,inboundTopicId:i,outboundTopicId:o,profileTopicId:a||"N/A",capabilities:t.capabilities||[AIAgentCapability.TEXT_GENERATION],hasFees:!(!t.hbarFee&&!this.hasValidTokenFee(t.tokenFee)),hbarFee:t.hbarFee||0,tokenFee:t.tokenFee||null};return(c||r)&&(d.profilePicture={source:r,topicId:c}),JSON.stringify(d)}async ensureAgentHasFunds(e,t){try{await ensureAgentHasEnoughHbar(Logger$2.getInstance({module:"RegisterAgentTool"}),this.client.standardClient,e,t)}catch(r){Logger$2.getInstance().error("Failed to auto fund agent",r)}}validateRegistrationResult(e,t,r,n){if(!(e&&t&&r&&n)){const i=[!e&&"accountId",!t&&"inboundTopicId",!r&&"outboundTopicId",!n&&"privateKey"].filter(Boolean).join(", ");throw new Error(`Registration failed. The HCS client returned incomplete details (Missing: ${i}).`)}}createFeeDescription(e){const t=e.hbarFee&&e.hbarFee>0,r=this.hasValidTokenFee(e.tokenFee);if(!t&&!r)return"";let n="";if(t&&(n+=`${e.hbarFee} HBAR`),r&&e.tokenFee){const t=`${e.tokenFee.amount} of token ${e.tokenFee.tokenId}`;n+=n?` and ${t}`:t}return n}}class SendMessageTool extends StructuredTool{constructor(e){super(),this.name="send_message",this.description="Sends a message to a specified Hedera topic using HCS-10 and monitors for responses.",this.lastProcessedTimestamp=0,this.schema=objectType({topicId:stringType().describe("The Hedera topic ID to send the message to"),message:stringType().describe("The message content to send"),disableMonitoring:booleanType().optional().describe("Whether to disable monitoring for responses")}),this.client=e,this.logger=Logger$2.getInstance({module:"SendMessageTool"})}async _call(e){try{const t=await this.client.sendMessage(e.topicId,e.message);if(!t)throw new Error("Failed to send message");if(this.logger.info(`Message sent with sequence number ${t}`),e.disableMonitoring)return`Successfully sent message to topic ${e.topicId}`;{const r=await this.monitorResponses(e.topicId,t);return`Successfully sent message to topic ${e.topicId}${r?`\nResponse: ${r}`:""}`}}catch(t){throw new Error(`Failed to send message: ${t instanceof Error?t.message:String(t)}`)}}async monitorResponses(e,t){let r=0;for(;r<10;){try{const r=await this.client.getMessageStream(e);for(const e of r.messages)if(e.created&&e.created.getTime()>this.lastProcessedTimestamp){this.lastProcessedTimestamp=e.created.getTime();const r=await this.client.getMessageContent(e.data||"");let i;try{i=JSON.parse(r)}catch(n){this.logger.error(`Error parsing message content: ${n}`);continue}if(e.sequence_number>t)return i&&"string"==typeof i.data?i.data:JSON.stringify(i)}}catch(n){this.logger.error(`Error monitoring responses: ${n}`)}r++,await new Promise((e=>setTimeout(e,1e3)))}return null}}class ConnectionTool extends StructuredTool{constructor({client:e,stateManager:t,...r}){super(r),this.name="monitor_connections",this.description="Starts passively LISTENING on the current agent's own inbound topic for INCOMING HCS-10 connection requests. Handles received requests automatically. Takes NO arguments. DO NOT use this to start a new connection TO someone else.",this.isMonitoring=!1,this.monitoringTopic=null,this.schema=objectType({}),this.client=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ConnectionTool",level:"info"})}async _call(){let e;try{e=await this.client.getInboundTopicId()}catch(t){const e=`Error getting inbound topic ID for monitoring: ${t instanceof Error?t.message:String(t)}`;return this.logger.error(e),e}return e?this.isMonitoring?this.monitoringTopic===e?`Already monitoring topic ${e}.`:`Error: Already monitoring a different topic (${this.monitoringTopic}). Stop the current monitor first.`:(this.isMonitoring=!0,this.monitoringTopic=e,this.logger.info(`Initiating connection request monitoring for topic ${e}...`),this.monitorIncomingRequests(e).catch((t=>{this.logger.error(`Monitoring loop for ${e} encountered an unrecoverable error:`,t),this.isMonitoring=!1,this.monitoringTopic=null})),`Started monitoring inbound topic ${e} for connection requests in the background.`):"Error: Could not determine the inbound topic ID for the current agent."}async monitorIncomingRequests(e){this.logger.info(`Monitoring inbound topic ${e}...`);let t=0;const r=new Set;for(;this.isMonitoring&&this.monitoringTopic===e;){try{const i=(await this.client.getMessages(e)).messages,o=i.filter((e=>"connection_request"===e.op&&"number"==typeof e.sequence_number));for(const a of o){t=Math.max(t,a.sequence_number||0);const o=a.sequence_number;if(!o)continue;if(i.some((e=>"connection_created"===e.op&&e.connection_id===o))){this.logger.debug(`Connection request #${o} already handled (found connection_created). Skipping.`);continue}const s=a.operator_id||"",c=s.split("@")[1]||null;if(c)if(r.has(o))this.logger.info(`Connection request #${o} already processed in this session. Skipping.`);else{this.logger.info(`Processing connection request #${o} from account ${c}...`);try{const t=await this.client.handleConnectionRequest(e,c,o);r.add(o),this.logger.info(`Connection confirmed for request #${o}. New connection topic: ${t.connectionTopicId}`);const n={targetAccountId:c,targetAgentName:`Agent ${c}`,targetInboundTopicId:"N/A",connectionTopicId:t.connectionTopicId};this.stateManager.addActiveConnection(n),this.logger.info(`Added new active connection to ${c} state.`)}catch(n){this.logger.error(`Error handling connection request #${o} from ${c}:`,n)}}else this.logger.warn(`Could not determine requesting account ID from operator_id '${s}' for request #${o}. Skipping.`)}}catch(i){this.logger.error(`Error fetching or processing messages for topic ${e}:`,i)}await new Promise((e=>setTimeout(e,5e3)))}this.logger.info(`Monitoring loop stopped for topic ${e}.`),this.isMonitoring=!1,this.monitoringTopic=null}stopMonitoring(){this.isMonitoring?(this.logger.info(`Stopping monitoring for topic ${this.monitoringTopic}...`),this.isMonitoring=!1,this.monitoringTopic=null):this.logger.info("Monitor is not currently running.")}}class SendMessageToConnectionTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({targetIdentifier:stringType().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."),message:stringType().describe("The text message content to send."),disableMonitoring:booleanType().optional().default(!1)}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"SendMessageToConnectionTool"})}async _call({targetIdentifier:e,message:t,disableMonitoring:r}){const n=this.stateManager.getCurrentAgent();if(!n)return"Error: Cannot send message. No agent is currently active. Please register or select an agent first.";const i=this.stateManager.getConnectionByIdentifier(e);if(!i)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const o=i.connectionTopicId,a=i.targetAgentName,s=`${n.inboundTopicId}@${n.accountId}`;this.logger.info(`Sending message from ${s} to ${a} (${i.targetAccountId}) via connection topic ${o}`);try{const e=await this.hcsClient.sendMessage(o,t,`Agent message from ${n.name}`);if(!e)throw new Error("Failed to send message");if(!r)return`Message sent to ${a} (${i.targetAccountId}) via connection ${o}. Sequence Number: ${e}`;const c=await this.monitorResponses(o,s,e);return c?(this.logger.info(`Got reply from ${a}`,c),`Received reply from ${a}: ${c}`):`Message sent to ${a} (${i.targetAccountId}) via connection ${o}. Sequence Number: ${e}`}catch(c){return this.logger.error(`Failed to send message via connection ${o}: ${c}`),`Error sending message to ${a}: ${c instanceof Error?c.message:String(c)}`}}async monitorResponses(e,t,r){for(;;){try{const n=await this.hcsClient.getMessageStream(e);for(const e of n.messages){if(e.sequence_number<r||e.operator_id===t)continue;return await this.hcsClient.getMessageContent(e.data||"")}}catch(n){this.logger.error(`Error monitoring responses: ${n}`)}await new Promise((e=>setTimeout(e,4e3)))}return null}}class InitiateConnectionTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({targetAccountId:stringType().describe("The Hedera account ID (e.g., 0.0.12345) of the agent you want to connect with.")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"InitiateConnectionTool"})}async _call({targetAccountId:e}){const t=this.stateManager.getCurrentAgent();if(!t)return"Error: Cannot initiate connection. No agent is currently active. Please register or select an agent first.";this.logger.info(`Attempting connection from ${t.accountId} to ${e}`);try{this.logger.debug(`Retrieving profile for ${e}...`);const n=await this.hcsClient.getAgentProfile(e);if(!n?.topicInfo?.inboundTopic)return`Error: Could not retrieve profile or find inbound topic ID for target agent ${e}. They might not be registered or have a public profile.`;const i=n.topicInfo.inboundTopic,o=n.profile.name||`Agent ${e}`,a=await this.hcsClient.submitConnectionRequest(i,t.name),s=a?.topicSequenceNumber;if(!s)throw new Error("Connection request sequence number not found.");let c;try{if(c=s.toNumber(),isNaN(c))throw new Error("Converted sequence number is NaN.")}catch(r){throw new Error(`Failed to convert connection request sequence number: ${r}`)}const u=6e4,l=2e3,d=Math.ceil(u/l),h=await this.hcsClient.waitForConnectionConfirmation(i,c,d,l);if(!h?.connectionTopicId)return`Error: Connection confirmation not received from ${e} (for request ${c}) within ${u/1e3} seconds.`;const p=h.connectionTopicId;this.logger.info(`Connection confirmed! Topic ID: ${p}`);const f={targetAccountId:e,targetAgentName:o,targetInboundTopicId:i,connectionTopicId:p};this.stateManager.addActiveConnection(f);const m=this.stateManager.listConnections(),g=m.find((e=>e.connectionTopicId===p)),y=g?m.indexOf(g)+1:null;return`Successfully established connection ${y?`#${y}`:""} with ${o} (${e}). Connection Topic: ${p}. You can now send messages using this connection.`}catch(n){return this.logger.error(`Connection initiation failed: ${n}`),`Error initiating connection with ${e}: ${n instanceof Error?n.message:String(n)}`}}}class ListConnectionsTool extends StructuredTool{constructor({stateManager:e,hcsClient:t,...r}){super(r),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.schema=objectType({includeDetails:booleanType().optional().describe("Whether to include detailed information about each connection"),showPending:booleanType().optional().describe("Whether to include pending connection requests")}),this.stateManager=e,this.hcsClient=t,this.logger=new Logger$2({module:"ListConnectionsTool"})}async _call(e){const t=e.includeDetails??!0,r=e.showPending??!0,n=await this.getEnhancedConnections();if(0===n.length)return"There are currently no active connections.";const i=n.filter((e=>"established"===e.status)),o=n.filter((e=>e.isPending)),a=n.filter((e=>e.needsConfirmation));let s="";return i.length>0&&(s+=`🟢 Active Connections (${i.length}):\n`,i.forEach(((e,r)=>{s+=this.formatConnection(e,r,t)})),s+="\n"),r&&a.length>0&&(s+=`🟠 Connections Needing Confirmation (${a.length}):\n`,a.forEach(((e,r)=>{s+=this.formatConnection(e,r,t)})),s+="\n"),r&&o.length>0&&(s+=`⚪ Pending Connection Requests (${o.length}):\n`,o.forEach(((e,r)=>{s+=this.formatConnection(e,r,t)}))),s.trim()}formatConnection(e,t,r){let n=`${t+1}. ${e.profileInfo?.display_name||e.targetAgentName||"Unknown Agent"} (${e.targetAccountId})\n`;n+=` Topic: ${e.isPending?"(Pending Request)":e.connectionTopicId}\n`;if(n+=` Status: ${e.status||"unknown"}\n`,r){if(e.profileInfo?.bio&&(n+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),e.created){n+=` ${e.isPending?"Request sent":"Connection established"}: ${e.created.toLocaleString()}\n`}e.lastActivity&&(n+=` Last activity: ${e.lastActivity.toLocaleString()}\n`)}return n}async getEnhancedConnections(){if(!this.hcsClient)return this.stateManager.listConnections();try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)return this.stateManager.listConnections();const t=this.stateManager.getConnectionsManager();if(!t)return this.logger.error("ConnectionsManager not initialized"),this.stateManager.listConnections();const r=await t.fetchConnectionData(e);for(const n of r)this.stateManager.updateOrAddConnection(n);return r}catch(e){return console.error("Error fetching connection data:",e),this.stateManager.listConnections()}}}class CheckMessagesTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({targetIdentifier:stringType().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:booleanType().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:numberType().int().positive().optional().describe("When fetchLatest is true, specifies how many of the most recent messages to retrieve. Defaults to 1.")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"CheckMessagesTool"})}async _call({targetIdentifier:e,fetchLatest:t,lastMessagesCount:r}){const n=this.stateManager.getConnectionByIdentifier(e);if(!n)return`Error: Could not find an active connection matching identifier "${e}". Use 'list_connections' to see active connections.`;const i=n.connectionTopicId,o=n.targetAgentName,a=this.stateManager.getLastTimestamp(i);this.logger.info(`Checking messages for connection with ${o} (${n.targetAccountId}) on topic ${i} (fetchLatest: ${t}, lastCount: ${r}, since: ${a})`);try{const e=(await this.hcsClient.getMessages(i)).messages;if(!e||0===e.length)return`No messages found on connection topic ${i}.`;let n=[],u=a;const l=!0===t;if(l){this.logger.info("Fetching latest messages regardless of timestamp.");const t=r??1;n=e.slice(-t)}else this.logger.info(`Filtering for messages newer than ${a}`),n=e.filter((e=>1e6*e.timestamp>a)),n.length>0&&(u=n.reduce(((e,t)=>Math.max(e,1e6*t.timestamp)),a));if(0===n.length)return l?`Could not retrieve the latest message(s). No messages found on topic ${i}.`:`No new messages found for connection with ${o} since last check.`;this.logger.info(`Processing ${n.length} message(s).`);let d=l?`Latest message(s) from ${o}:\n`:`New messages from ${o}:\n`;for(const t of n){let e=t.data;try{"string"==typeof e&&e.startsWith("hcs://")&&(this.logger.debug(`Resolving inscribed message: ${e}`),e=await this.hcsClient.getMessageContent(e),this.logger.debug(`Resolved content length: ${e?.length}`));let r=e;try{const t=JSON.parse(e||"{}");if("hcs-10"===t.p&&"message"===t.op&&t.data){r=`[${t.operator_id||"unknown_sender"}]: ${t.data}`}else r=e}catch(s){r=e}d+=`\n[${new Date(t.timestamp).toLocaleString()}] (Seq: ${t.sequence_number})\n${r}\n`}catch(c){const e=`Error processing message (Seq: ${t.sequence_number}): ${c instanceof Error?c.message:String(c)}`;this.logger.error(e),d+=`\n[Error processing message Seq: ${t.sequence_number}]\n`}}return!l&&u>a&&(this.logger.debug(`Updating timestamp for topic ${i} to ${u}`),this.stateManager.updateTimestamp(i,u)),d.trim()}catch(c){return this.logger.error(`Failed to check messages for topic ${i}: ${c}`),`Error checking messages for ${o}: ${c instanceof Error?c.message:String(c)}`}}}class FindRegistrationsTool extends StructuredTool{constructor({hcsClient:e,...t}){super(t),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.schema=objectType({accountId:stringType().optional().describe("Optional: Filter registrations by a specific Hedera account ID (e.g., 0.0.12345)."),tags:arrayType(nativeEnumType(AIAgentCapability)).optional().describe("Optional: Filter registrations by a list of tags (API filter only).")}),this.hcsClient=e,this.logger=Logger$2.getInstance({module:"FindRegistrationsTool"})}async _call({accountId:e,tags:t}){this.logger.info("Searching registrations with filters - Account ID",JSON.stringify({accountId:e,tags:t}));const r={};e&&(r.accountId=e),t&&t.length>0&&(r.tags=t),r.network=this.hcsClient.getNetwork();try{if(!this.hcsClient.standardClient)throw new Error("Standard SDK client instance is not available in HCS10Client wrapper.");const e=await this.hcsClient.standardClient.findRegistrations(r);if(!e.success||e.error)return`Error finding registrations: ${e.error||"Unknown error"}`;if(!e.registrations||0===e.registrations.length)return"No registrations found matching the criteria.";let t=`Found ${e.registrations.length} registration(s):\n`;return e.registrations.forEach(((e,r)=>{const n=e.metadata;t+=`${r+1}. Name: ${n.alias||"N/A"}\n`,t+=`Description: ${n.bio||"N/A"}\n`,t+=` Account ID: ${e.accountId}\n`,t+=` Status: ${e.status}\n`,t+=` Model: ${n.properties?.model||"N/A"}\n`,n.properties?.capabilities&&n.properties.capabilities.length>0&&(t+=` Capabilities: ${n.properties.capabilities.join(", ")}\n`),n.properties&&(t+=` Properties: ${JSON.stringify(n.properties)}\n`),t+=` Inbound Topic: ${e.inboundTopicId}\n`,t+=` Outbound Topic: ${e.outboundTopicId}\n`,t+=` Created At: ${e.createdAt}\n`})),t.trim()}catch(n){return this.logger.error(`Failed to execute findRegistrations: ${n}`),`Error searching registrations: ${n instanceof Error?n.message:String(n)}`}}}class ConnectionMonitorTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.",this.schema=objectType({acceptAll:booleanType().optional().describe("Whether to automatically accept all incoming connection requests. Default is false."),targetAccountId:stringType().optional().describe("If provided, only accept connection requests from this specific account ID."),hbarFees:arrayType(objectType({amount:numberType(),collectorAccount:stringType().optional()})).optional().describe("Array of HBAR fee amounts to charge per message (with optional collector accounts)."),tokenFees:arrayType(objectType({amount:numberType(),tokenId:stringType(),collectorAccount:stringType().optional()})).optional().describe("Array of token fee amounts and IDs to charge per message (with optional collector accounts)."),exemptAccountIds:arrayType(stringType()).optional().describe("Array of account IDs to exempt from ALL fees set in this request."),monitorDurationSeconds:numberType().optional().describe("How long to monitor for incoming requests in seconds. Default is 60."),defaultCollectorAccount:stringType().optional().describe("Default account to collect fees if not specified at the fee level. Defaults to the agent account.")}),this.isMonitoring=!1,this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ConnectionMonitorTool",level:"error"}),this.listConnectionsTool=new ListConnectionsTool({stateManager:t,hcsClient:e,...r})}updateClient(e){this.hcsClient=e,this.logger.info("Updated HCS10Client instance for ConnectionMonitorTool"),this.listConnectionsTool=new ListConnectionsTool({stateManager:this.stateManager,hcsClient:e})}async _call({acceptAll:e=!1,targetAccountId:t,hbarFees:r=[],tokenFees:n=[],exemptAccountIds:i,monitorDurationSeconds:o=60,defaultCollectorAccount:a}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot monitor for connections. No agent is currently active. Please register or select an agent first.";if(this.isMonitoring)return"Already monitoring for connection requests. Please wait for the current monitoring session to complete.";try{this.isMonitoring=!0;const c=await this.hcsClient.getInboundTopicId();if(!c)return this.isMonitoring=!1,"Error: Could not find inbound topic ID for the current agent.";this.logger.info(`Starting to monitor inbound topic ${c} for connection requests...`);const u=this.createFeeConfig(r,n,i,t,a),l=Date.now()+1e3*o,d=3e3;let h=0,p=0,f=0,m=0;for(;Date.now()<l;)try{await this.listConnectionsTool.invoke({includeDetails:!1,showPending:!1});const r=this.stateManager.listConnections(),n=new Map;r.filter((e=>"established"===e.status&&!e.isPending)).forEach((e=>{n.has(e.targetAccountId)||n.set(e.targetAccountId,new Set),e.connectionRequestId&&n.get(e.targetAccountId)?.add(String(e.connectionRequestId))}));const i=(await this.hcsClient.getMessages(c)).messages.filter((e=>!(!e.sequence_number||e.sequence_number<=h)&&(h=Math.max(h,e.sequence_number),"connection_request"===e.op)));for(const o of i){const r=o.sequence_number;if(!r)continue;p++;const i=await this.hcsClient.getInboundTopicId()||"",a=this.stateManager.getConnectionsManager();if(!a){this.logger.error("ConnectionsManager not initialized in state manager");continue}if(a.isConnectionRequestProcessed(i,r)){this.logger.info(`Request #${r} already processed, skipping`),m++;continue}const s=this.extractAccountId(o);if(!s){a.markConnectionRequestProcessed(i,r);continue}if(t&&s!==t){this.logger.info(`Request #${r} doesn't match target ${t}`);continue}const c=n.get(s);if(c?.has(String(r)))this.logger.info(`Already processed connection request #${r} from ${s}, skipping`),a.markConnectionRequestProcessed(i,r),m++;else if(e){const e=await this.acceptConnectionRequest(r,s,u);a.markConnectionRequestProcessed(i,r),e.success&&(f++,this.logger.info(`Successfully accepted connection with ${s} for request #${r}`))}else this.logger.info(`Found request #${r} from ${s} (not auto-accepting)`)}await new Promise((e=>setTimeout(e,d)))}catch(s){this.logger.error(`Error polling for messages: ${s}`),await new Promise((e=>setTimeout(e,d)))}return this.isMonitoring=!1,0===p?`No connection requests received during the ${o} second monitoring period.`:e?`Monitored for ${o} seconds. Found ${p} connection requests, accepted ${f} connections, skipped ${m} existing connections${this.formatFeeString(r,n)}.`:`Monitored for ${o} seconds. Found ${p} connection requests. To accept them, call this tool again with acceptAll=true.`}catch(s){return this.isMonitoring=!1,this.logger.error(`Connection monitoring failed: ${s}`),`Error monitoring for connections: ${s instanceof Error?s.message:String(s)}`}}createFeeConfig(e=[],t=[],r,n,i){if(0!==e.length||0!==t.length)try{const o=this.hcsClient.getAccountAndSigner().accountId,a=i||o,s=new FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:a}),c=[...r||[]];n&&!c.includes(n)&&c.push(n);for(const t of e)if(t.amount>0){const e=t.collectorAccount||a;s.addHbarFee(t.amount,e,c),this.logger.info(`Added HBAR fee: ${t.amount} HBAR to be collected by ${e}`)}for(const e of t)if(e.amount>0&&e.tokenId){const t=e.collectorAccount||a;s.addTokenFee(e.amount,e.tokenId,t,void 0,c),this.logger.info(`Added token fee: ${e.amount} of token ${e.tokenId} to be collected by ${t}`)}return s}catch(o){return void this.logger.error(`Error creating fee configuration: ${o}`)}}extractAccountId(e){if(e.operator_id)return this.hcsClient.standardClient.extractAccountFromOperatorId(e.operator_id)}async acceptConnectionRequest(e,t,r){try{const i=await this.hcsClient.getInboundTopicId();this.logger.info(`Accepting connection request #${e} from ${t}`);const o=await this.hcsClient.handleConnectionRequest(i,t,e,r);if(!o?.connectionTopicId)return{success:!1,error:"Connection acceptance returned no connection topic ID"};const a=o.connectionTopicId;let s;this.logger.info(`Connection established! Topic ID: ${a}`);try{const e=await this.hcsClient.getAgentProfile(t);e.success&&e.profile&&(s=e.profile)}catch(n){this.logger.warn(`Could not fetch profile for ${t}: ${n}`)}const c=(await this.hcsClient.getAgentProfile(t))?.topicInfo?.inboundTopic||"",u={targetAccountId:t,targetAgentName:s?.display_name||`Agent ${t}`,targetInboundTopicId:c,connectionTopicId:a,profileInfo:s,created:new Date,status:"established",metadata:{requestId:e}};return this.stateManager.addActiveConnection(u),{success:!0,connectionTopicId:a}}catch(i){return this.logger.error(`Error accepting connection request: ${i}`),{success:!1,error:i instanceof Error?i.message:String(i)}}}formatFeeString(e=[],t=[]){if(0===e.length&&0===t.length)return"";let r=" with fees: ";if(e.length>0){const t=e.filter((e=>e.amount>0)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} HBAR${t}`})).join(", ");t&&(r+=t)}if(t.length>0){e.length>0&&(r+=" and ");const n=t.filter((e=>e.amount>0&&e.tokenId)).map((e=>{const t=e.collectorAccount?` to ${e.collectorAccount}`:"";return`${e.amount} of token ${e.tokenId}${t}`})).join(", ");n&&(r+=n)}return" with fees: "===r?"":r}update(){this.listConnectionsTool.invoke({includeDetails:!0,showPending:!0}).catch((e=>{this.logger.error(`Error updating connections: ${e}`)}))}}class ManageConnectionRequestsTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({action:enumType(["list","view","reject"]).describe("The action to perform: list all requests, view details of a specific request, or reject a request"),requestKey:stringType().optional().describe("The unique request key to view or reject (required for view and reject actions)")}),this.lastRefreshTime=0,this.refreshIntervalMs=3e4,this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ManageConnectionRequestsTool",level:"debug"})}async _call({action:e,requestKey:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot manage connection requests. No agent is currently active. Please register or select an agent first.";if(("view"===e||"reject"===e)&&void 0===t)return`Error: Request key is required for the "${e}" action. Use the "list" action first to see available requests.`;try{switch(await this.refreshRequestsIfNeeded(),e){case"list":return this.listRequests();case"view":return this.viewRequest(t);case"reject":return this.rejectRequest(t);default:return`Error: Unsupported action: ${e}`}}catch(r){return this.logger.error(`Error in ManageConnectionRequestsTool: ${r}`),`Error managing connection requests: ${r instanceof Error?r.message:String(r)}`}}async refreshRequestsIfNeeded(){const e=Date.now();e-this.lastRefreshTime>this.refreshIntervalMs&&(await this.refreshRequests(),this.lastRefreshTime=e)}async refreshRequests(){try{const{accountId:e}=this.hcsClient.getAccountAndSigner();if(!e)throw new Error("Could not determine account ID for current agent");const t=this.stateManager.getConnectionsManager();if(!t)throw new Error("ConnectionsManager not initialized");await t.fetchConnectionData(e)}catch(e){throw this.logger.error(`Error refreshing connection requests: ${e}`),e}}listRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return"Error: ConnectionsManager not initialized";const t=[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()];if(0===t.length)return console.log("No pending connection requests found.",t),"No pending connection requests found.";let r=`Found ${t.length} pending connection request(s):\n\n`;return[...t].sort(((e,t)=>t.created.getTime()-e.created.getTime())).forEach(((e,t)=>{const n=e.needsConfirmation?"🟠 Incoming":"⚪️ Outgoing",i=e.uniqueRequestKey||`${e.connectionRequestId||e.inboundRequestId||"unknown"}`;r+=`${t+1}. ${n} - Key: ${i}\n`,r+=` ${e.needsConfirmation?"From":"To"}: ${e.targetAgentName||`Agent ${e.targetAccountId}`} (${e.targetAccountId})\n`,r+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(r+=` Memo: ${e.memo}\n`),e.profileInfo&&e.profileInfo.bio&&(r+=` Bio: ${e.profileInfo.bio}\n`),r+="\n"})),r+='To view more details about a request, use action="view" with the specific requestKey.\n',r+='To reject a request, use action="reject" with the specific requestKey.',r}viewRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const r=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));if(!r)return`Error: Request with key ${e} not found or no longer pending.`;const n=r.needsConfirmation?"Incoming":"Outgoing",i=r.uniqueRequestKey||`${r.connectionRequestId||r.inboundRequestId||"unknown"}`;let o=`Details for ${n} connection request: ${i}\n\n`;return o+=`${r.needsConfirmation?"Requestor":"Target"} ID: ${r.targetAccountId}\n`,o+=`${r.needsConfirmation?"Requestor":"Target"} Name: ${r.targetAgentName||`Agent ${r.targetAccountId}`}\n`,o+=`Received: ${r.created.toLocaleString()}\n`,r.memo&&(o+=`Memo: ${r.memo}\n`),r.profileInfo&&(o+="\nAgent Profile Information:\n",(r.profileInfo.display_name||r.profileInfo.alias)&&(o+=`Name: ${r.profileInfo.display_name||r.profileInfo.alias}\n`),void 0!==r.profileInfo.type&&(o+=`Type: ${r.profileInfo.type}\n`),r.profileInfo.bio&&(o+=`Bio: ${r.profileInfo.bio}\n`)),o+="\nActions:\n",o+=`- To reject this request: action="reject", requestKey="${i}"\n`,o+='Use the separate "accept_connection_request" tool to accept requests.',o}async rejectRequest(e){const t=this.stateManager.getConnectionsManager();if(!t)return"Error: ConnectionsManager not initialized";const r=[...t.getPendingRequests(),...t.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));return r?(r.inboundRequestId?t.markConnectionRequestProcessed(r.targetInboundTopicId||"",r.inboundRequestId):r.connectionRequestId&&t.markConnectionRequestProcessed(r.originTopicId||"",r.connectionRequestId),`Connection request from ${r.targetAgentName||`Agent ${r.targetAccountId}`} was rejected.`):`Error: Request with key ${e} not found or no longer pending.`}}class AcceptConnectionRequestTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),this.name="accept_connection_request",this.description="Accepts a specific pending connection request from another agent, establishing a communication channel.",this.schema=objectType({requestKey:stringType().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:numberType().optional().describe("Optional HBAR fee amount to charge the connecting agent per message on the new connection topic."),exemptAccountIds:arrayType(stringType()).optional().describe("Optional list of account IDs to exempt from any configured fees on the new connection topic.")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"AcceptConnectionRequestTool"})}async _call({requestKey:e,hbarFee:t,exemptAccountIds:r}){const n=this.stateManager.getCurrentAgent();if(!n)return"Error: Cannot accept connection request. No agent is currently active. Please register or select an agent first.";const i=this.stateManager.getConnectionsManager();if(!i)return"Error: ConnectionsManager not initialized";await i.fetchConnectionData(n.accountId);const o=[...i.getPendingRequests(),...i.getConnectionsNeedingConfirmation()].find((t=>t.uniqueRequestKey===e||t.connectionRequestId?.toString()===e||t.inboundRequestId?.toString()===e));if(!o)return`Error: Request with key ${e} not found or no longer pending. Use the manage_connection_requests tool with action="list" to verify.`;const a=o.connectionRequestId||o.inboundRequestId;if(!a)return`Error: Could not determine a valid request ID for the request with key ${e}.`;try{const u=await this.hcsClient.getInboundTopicId();let l;if(t&&t>0){const e=this.hcsClient.getAccountAndSigner().accountId;try{l=new FeeConfigBuilder({network:this.hcsClient.getNetwork(),logger:this.logger,defaultCollectorAccountId:e});const i=[...r||[],n.accountId];l.addHbarFee(t,e,i),this.logger.info(`Setting HBAR fee: ${t} HBAR to be collected by ${e}`)}catch(s){this.logger.error(`Error creating fee configuration: ${s}`),l=void 0,this.logger.warn("Proceeding to accept request without fees due to configuration error.")}}this.logger.info(`Attempting to accept request Key: ${e} (ID: ${a}) from ${o.targetAccountId}`);const d=await this.hcsClient.handleConnectionRequest(u,o.targetAccountId,a,l);if(!d?.connectionTopicId)return`Error: Failed to accept connection request with key ${e}. The SDK did not return a connection topic ID.`;this.logger.info(`Successfully created connection topic: ${d.connectionTopicId}`);const h=d.connectionTopicId;let p="";try{const e=await this.hcsClient.standardClient.retrieveProfile(o.targetAccountId);p=e?.topicInfo?.inboundTopic||"",p||this.logger.warn(`Could not resolve target inbound topic for ${o.targetAccountId}`)}catch(c){this.logger.warn(`Error fetching target profile/topic for ${o.targetAccountId}: ${c}`)}const f=o.profileInfo?.display_name||o.profileInfo?.alias||`Agent ${o.targetAccountId}`,m={targetAccountId:o.targetAccountId,targetAgentName:f,targetInboundTopicId:p,connectionTopicId:h,profileInfo:o.profileInfo,created:new Date,status:"established"};this.stateManager.addActiveConnection(m),i.fetchConnectionData(o.targetAccountId),this.logger.info(`Removed request ${e} from pending requests`);let g="";t&&t>0&&l&&(g=` with a ${t} HBAR fee per message`);return`Successfully accepted connection request ${o.uniqueRequestKey||e} from ${f} ${g}. Connection established on topic: ${h}.`}catch(u){return this.logger.error(`Error accepting connection request ${e}: ${u}`),`Error accepting connection request ${e}: ${u instanceof Error?u.message:String(u)}`}}}class RetrieveProfileTool extends StructuredTool{constructor(e){super(),this.name="retrieve_profile",this.description="Retrieves the HCS-11 profile data associated with a given Hedera account ID. If no account ID is provided, it defaults to the current operator account ID. Returns the profile object as a JSON string on success.",this.schema=objectType({accountId:stringType().optional().describe("The Hedera account ID (e.g., 0.0.12345) to retrieve the profile for. If omitted, defaults to the current operator account ID."),disableCache:booleanType().optional().describe("Optional: Set to true to bypass the cache and fetch fresh profile data.")}),this.client=e,this.logger=Logger$2.getInstance({module:this.name})}async _call(e){let t;try{if(e.accountId?t=e.accountId:(this.logger.info("accountId not provided, defaulting to operator ID."),t=this.client.getOperatorId()),!t)throw new Error("Could not determine target account ID.");this.logger.info(`Attempting to retrieve profile for account: ${t}, Disable Cache: ${!!e.disableCache}`);const r=await this.client.standardClient.retrieveProfile(t,e.disableCache);if(r.success&&r.profile)return this.logger.info(`Successfully retrieved profile for ${t}.`),JSON.stringify(r.profile,null,2);{const e=`Error retrieving profile for ${t}: ${r.error||"Profile not found or invalid."}`;return this.logger.error(e),e}}catch(r){const t=`Unexpected error retrieving profile for ${e.accountId||"operator default"}: ${r instanceof Error?r.message:String(r)}`;return this.logger.error(t,r),t}}}class ListUnapprovedConnectionRequestsTool extends StructuredTool{constructor({hcsClient:e,stateManager:t,...r}){super(r),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.schema=objectType({sortBy:enumType(["time_asc","time_desc","name_asc","name_desc"]).optional().describe("Optional sorting criteria for the requests list (default: time_desc, newest first)"),limit:numberType().optional().describe("Optional limit on the number of requests to return (default: all)")}),this.hcsClient=e,this.stateManager=t,this.logger=Logger$2.getInstance({module:"ListPendingRequestsTool",level:"debug"})}async _call({sortBy:e="time_desc",limit:t}){if(!this.stateManager.getCurrentAgent())return"Error: Cannot list pending requests. No agent is currently active. Please register or select an agent first.";try{const r=await this.findAllPendingRequests();return this.formatRequestsList(r,e,t)}catch(r){return this.logger.error(`Error in ${this.name}: ${r}`),`Error listing pending requests: ${r instanceof Error?r.message:String(r)}`}}async findAllPendingRequests(){const e=this.stateManager.getConnectionsManager();if(!e)return[];const t=this.stateManager.getCurrentAgent();if(!t)return[];await e.fetchConnectionData(t.accountId);return[...e.getPendingRequests(),...e.getConnectionsNeedingConfirmation()]}formatRequestsList(e,t,r){if(0===e.length)return"No pending connection requests found (incoming or outgoing).";const n=this.sortRequests(e,t),i=r?n.slice(0,r):n;let o=`Found ${e.length} pending connection request(s):\n\n`;return i.forEach(((e,t)=>{const r="needs_confirmation"===e.status?"🟠 Incoming":"⚪️ Outgoing";o+=`${t+1}. ${r} - ID: ${e.uniqueRequestKey}\n`,o+=` ${"needs_confirmation"===e.status?"From:":"To: "} ${e.targetAgentName} (${e.targetAccountId})\n`,o+=` Sent/Rcvd: ${e.created.toLocaleString()}\n`,e.memo&&(o+=` Memo: ${e.memo}\n`),e.profileInfo?.bio&&(o+=` Bio: ${e.profileInfo.bio.substring(0,100)}${e.profileInfo.bio.length>100?"...":""}\n`),o+="\n"})),o+="Use related tools (manage_requests, accept_request) to handle these items.",o}sortRequests(e,t){const r=[...e];switch(t){case"time_asc":return r.sort(((e,t)=>e.created.getTime()-t.created.getTime()));case"time_desc":default:return r.sort(((e,t)=>t.created.getTime()-e.created.getTime()));case"name_asc":return r.sort(((e,t)=>e.targetAgentName?.localeCompare(t?.targetAgentName||"")||0));case"name_desc":return r.sort(((e,t)=>t.targetAgentName?.localeCompare(e?.targetAgentName||"")||0))}}}const ENV_FILE_PATH=path.join(process$1$1.cwd(),".env");async function updateEnvFile(e,t){let r="";empty.existsSync(e)&&(r=empty.readFileSync(e,"utf8"));const n=[...r.split("\n")];for(const[i,o]of Object.entries(t)){const e=n.findIndex((e=>e.startsWith(`${i}=`)));-1!==e?n[e]=`${i}=${o}`:n.push(`${i}=${o}`)}empty.writeFileSync(e,n.join("\n"))}class OpenConvaiState{constructor(e){this.currentAgent=null,this.connectionMessageTimestamps={},this.connectionsManager=null,this.defaultEnvFilePath=e?.defaultEnvFilePath,this.defaultPrefix=e?.defaultPrefix??"TODD";const t=e?.disableLogging||"true"===process$1$1.env.DISABLE_LOGGING;this.logger=new Logger$2({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 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(),r=parseInt(e)-1;if(!isNaN(r)&&r>=0&&r<t.length)return t[r];const n=this.connectionsManager.getConnectionByTopicId(e);if(n)return this.convertToActiveConnection(n);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 r=t?.envFilePath||this.defaultEnvFilePath||process$1$1.env.ENV_FILE_PATH||".env",n=t?.prefix||this.defaultPrefix;if(!e.accountId||!e.inboundTopicId||!e.outboundTopicId)throw new Error("Agent data incomplete, cannot persist to environment");const i={[`${n}_ACCOUNT_ID`]:e.accountId,[`${n}_INBOUND_TOPIC_ID`]:e.inboundTopicId,[`${n}_OUTBOUND_TOPIC_ID`]:e.outboundTopicId};e.privateKey&&(i[`${n}_PRIVATE_KEY`]=e.privateKey),e.profileTopicId&&(i[`${n}_PROFILE_TOPIC_ID`]=e.profileTopicId),await updateEnvFile(r,i)}}const initializeStandardsAgentKit=e=>{const t=e?.clientConfig||{},r=t.operatorId||process$1$1.env.HEDERA_OPERATOR_ID,n=t.operatorKey||process$1$1.env.HEDERA_OPERATOR_KEY,i=t.network||process$1$1.env.HEDERA_NETWORK||"testnet";let o;if("mainnet"===i?o="mainnet":("testnet"===i||console.warn(`Unsupported network specified: '${i}'. Defaulting to 'testnet'.`),o="testnet"),!r||!n)throw new Error("Operator ID and private key must be provided either through options or environment variables.");const a="true"===process$1$1.env.DISABLE_LOGGING,s=Logger$2.getInstance({level:t.logLevel||"info",silent:a}),c=e?.stateManager||new OpenConvaiState({defaultEnvFilePath:ENV_FILE_PATH,defaultPrefix:"TODD"});s.info("State manager initialized");const u=new HCS10Client(r,n,o,{useEncryption:t.useEncryption,registryUrl:t.registryUrl});let l;s.info(`HCS10Client initialized for ${r} on ${o}`),e?.monitoringClient&&(l=new HCS10Client(r,n,o,{useEncryption:t.useEncryption,registryUrl:t.registryUrl,logLevel:"error"}),s.info("Monitoring client initialized"));const d={};return d.registerAgentTool=new RegisterAgentTool(u,c),d.sendMessageTool=new SendMessageTool(u),d.connectionTool=new ConnectionTool({client:l||u,stateManager:c}),e?.createAllTools&&(d.findRegistrationsTool=new FindRegistrationsTool({hcsClient:u}),d.retrieveProfileTool=new RetrieveProfileTool(u),d.initiateConnectionTool=new InitiateConnectionTool({hcsClient:u,stateManager:c}),d.listConnectionsTool=new ListConnectionsTool({hcsClient:u,stateManager:c}),d.sendMessageToConnectionTool=new SendMessageToConnectionTool({hcsClient:u,stateManager:c}),d.checkMessagesTool=new CheckMessagesTool({hcsClient:u,stateManager:c}),d.connectionMonitorTool=new ConnectionMonitorTool({hcsClient:l||u,stateManager:c}),d.manageConnectionRequestsTool=new ManageConnectionRequestsTool({hcsClient:u,stateManager:c}),d.acceptConnectionRequestTool=new AcceptConnectionRequestTool({hcsClient:u,stateManager:c}),d.listUnapprovedConnectionRequestsTool=new ListUnapprovedConnectionRequestsTool({stateManager:c,hcsClient:u}),s.info("All tools initialized")),{hcs10Client:u,monitoringClient:l,tools:d,stateManager:c}};class PluginRegistry{constructor(e){this.plugins=new Map,this.context=e,this.logger=e.logger}async registerPlugin(e){if(this.plugins.has(e.id))throw new Error(`Plugin with ID ${e.id} is already registered`);await e.initialize(this.context),this.plugins.set(e.id,e),this.logger.info(`Plugin registered: ${e.name} (${e.id}) v${e.version}`)}getPlugin(e){return this.plugins.get(e)}getAllPlugins(){return Array.from(this.plugins.values())}getAllTools(){return this.getAllPlugins().flatMap((e=>e.getTools()))}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)return!1;if(t.cleanup)try{await t.cleanup()}catch(n){this.logger.error(`Error during plugin cleanup: ${n}`)}const r=this.plugins.delete(e);return r&&this.logger.info(`Plugin unregistered: ${t.name} (${t.id})`),r}async unregisterAllPlugins(){const e=Array.from(this.plugins.keys());for(const t of e)await this.unregisterPlugin(t)}}class BasePlugin{async initialize(e){this.context=e}async cleanup(){}}class PluginLoader{static async loadFromDirectory(e,t,r={initialize:!0}){const n=pathBrowserifyExports.join(e,"plugin.json");if(!(void 0)(n))throw new Error(`Plugin manifest not found at ${n}`)}static async loadFromPackage(e,t,r={initialize:!0}){try{const n=require.resolve(e),i=pathBrowserifyExports.dirname(n);return this.loadFromDirectory(i,t,r)}catch(n){throw new Error(`Failed to load plugin from package ${e}: ${n instanceof Error?n.message:String(n)}`)}}static isValidPlugin(e){return e&&"string"==typeof e.id&&"string"==typeof e.name&&"string"==typeof e.description&&"string"==typeof e.version&&"string"==typeof e.author&&"function"==typeof e.initialize&&"function"==typeof e.getTools}}const HEDERA_MIRROR_NODE_API="https://mainnet.mirrornode.hedera.com/api/v1",ExchangeRateResponseSchema=objectType({current_rate:objectType({cent_equivalent:numberType(),hbar_equivalent:numberType(),expiration_time:numberType()}),next_rate:objectType({cent_equivalent:numberType(),hbar_equivalent:numberType(),expiration_time:numberType()}),timestamp:stringType()});class GetHbarPriceTool extends StructuredTool{constructor(){super(...arguments),this.name="getHbarPrice",this.description="Retrieves the current price of HBAR in USD from the Hedera Mirror Node.",this.schema=objectType({})}async _call(){try{const e=(await axios.get(`${HEDERA_MIRROR_NODE_API}/network/exchangerate`)).data,t=ExchangeRateResponseSchema.safeParse(e);if(!t.success)throw console.error("Failed to parse exchange rate response:",t.error),new Error("Invalid API response format");const{current_rate:r}=t.data;return`The current price of HBAR is $${(r.cent_equivalent/r.hbar_equivalent/100).toFixed(6)} USD.`}catch(e){console.error("Error fetching HBAR price:",e);let t="An unknown error occurred";return axios.isAxiosError(e)?(t=e.message,e.response&&(t+=` (Status: ${e.response.status})`)):e instanceof Error&&(t=e.message),`Failed to retrieve HBAR price: ${t}`}}}class HbarPricePlugin{constructor(){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="Hedera Agent",this.tools=[new GetHbarPriceTool]}async initialize(){return Promise.resolve()}getTools(){return this.tools}async cleanup(){return Promise.resolve()}}class GenericPlugin extends BasePlugin{}class OpenConvAIPlugin extends GenericPlugin{constructor(){super(...arguments),this.id="openconvai-standards-agent-kit",this.name="OpenConvAI Standards Agent Kit Plugin",this.description="Comprehensive plugin providing all HCS-10 agent tools for registration, connections, and messaging",this.version="1.0.0",this.author="Hashgraph Online",this.namespace="openconvai",this.tools=[]}async initialize(e){if(await super.initialize(e),!(e.client instanceof HCS10Client))throw new Error("OpenConvAIPlugin requires an HCS10Client instance");this.hcs10Client=e.client,this.stateManager=e.stateManager||new OpenConvaiState,this.initializeTools(),this.context.logger.info("OpenConvAI Standards Agent Kit Plugin initialized successfully")}initializeTools(){if(!this.hcs10Client||!this.stateManager)throw new Error("HCS10Client and StateManager must be initialized before creating tools");this.tools=[new RegisterAgentTool(this.hcs10Client,this.stateManager),new SendMessageTool(this.hcs10Client),new ConnectionTool({client:this.hcs10Client,stateManager:this.stateManager}),new FindRegistrationsTool({hcsClient:this.hcs10Client}),new RetrieveProfileTool(this.hcs10Client),new InitiateConnectionTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ListConnectionsTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new SendMessageToConnectionTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new CheckMessagesTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ConnectionMonitorTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ManageConnectionRequestsTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new AcceptConnectionRequestTool({hcsClient:this.hcs10Client,stateManager:this.stateManager}),new ListUnapprovedConnectionRequestsTool({stateManager:this.stateManager,hcsClient:this.hcs10Client})]}getTools(){return this.tools}async cleanup(){this.tools=[],this.hcs10Client=void 0,this.stateManager=void 0,this.context.logger.info("OpenConvAI Standards Agent Kit Plugin cleaned up")}}class HCS10Plugin extends BasePlugin{}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global$2?global$2:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dist={},hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});for(var t={},r={byteLength:function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},toByteArray:function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,d=s>0?a-4:a;for(r=0;r<d;r+=4)t=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},fromByteArray:function(e){for(var t,r=e.length,i=r%3,o=[],a=16383,s=0,c=r-i;s<c;s+=a)o.push(u(e,s,s+a>c?c:s+a));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")}},n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],i[a.charCodeAt(s)]=s;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,r){for(var i,o,a=[],s=t;s<r;s+=3)i=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(n[(o=i)>>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63;var l={
156
156
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
157
157
  read:function(e,t,r,n,i){var o,a,s=8*i-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?i-1:0,h=r?-1:1,p=e[t+d];for(d+=h,o=p&(1<<-l)-1,p>>=-l,l+=s;l>0;o=256*o+e[t+d],d+=h,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+d],d+=h,l-=8);if(0===o)o=1-u;else{if(o===c)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),o-=u}return(p?-1:1)*a*Math.pow(2,o-n)},write:function(e,t,r,n,i,o){var a,s,c,u=8*o-i-1,l=(1<<u)-1,d=l>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,f=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(a++,c/=2),a+d>=l?(s=0,a=l):a+d>=1?(s=(t*c-1)*Math.pow(2,i),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+p]=255&s,p+=f,s/=256,i-=8);for(a=a<<i|s,u+=i;u>0;e[r+p]=255&a,p+=f,a/=256,u-=8);e[r+p-f]|=128*m}};
158
158
  /*!
@@ -161,5 +161,5 @@ read:function(e,t,r,n,i){var o,a,s=8*i-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?i-1:0,h=r?
161
161
  * @author Feross Aboukhadijeh <https://feross.org>
162
162
  * @license MIT
163
163
  */
164
- !function(e){const t=r,n=l,i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=d,e.SlowBuffer=function(e){+e!=e&&(e=0);return d.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;e.kMaxLength=o;const{Uint8Array:a,ArrayBuffer:s,SharedArrayBuffer:c}=globalThis;function u(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new a(e);return Object.setPrototypeOf(t,d.prototype),t}function d(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return h(e,t,r)}function h(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!d.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|b(e,t);let n=u(r);const i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(s.isView(e))return function(e){if(X(e,a)){const t=new a(e);return g(t.buffer,t.byteOffset,t.byteLength)}return m(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,s)||e&&X(e.buffer,s))return g(e,t,r);if(void 0!==c&&(X(e,c)||e&&X(e.buffer,c)))return g(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return d.from(n,t,r);const i=function(e){if(d.isBuffer(e)){const t=0|y(e.length),r=u(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||Q(e.length)?u(0):m(e);if("Buffer"===e.type&&Array.isArray(e.data))return m(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return d.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function p(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return p(e),u(e<0?0:0|y(e))}function m(e){const t=e.length<0?0:0|y(e.length),r=u(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function g(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new a(e):void 0===r?new a(e,t):new a(e,t,r),Object.setPrototypeOf(n,d.prototype),n}function y(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function b(e,t){if(d.isBuffer(e))return e.length;if(s.isView(e)||X(e,s))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(e).length;default:if(i)return n?-1:W(e).length;t=(""+t).toLowerCase(),i=!0}}function v(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return M(this,t,r);case"utf8":case"utf-8":return R(this,t,r);case"ascii":return $(this,t,r);case"latin1":case"binary":return C(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function w(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function _(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=d.from(t,n)),d.isBuffer(t))return 0===t.length?-1:k(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof a.prototype.indexOf?i?a.prototype.indexOf.call(e,t,r):a.prototype.lastIndexOf.call(e,t,r):k(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function k(e,t,r,n,i){let o,a=1,s=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,c/=2,r/=2}function u(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){let n=-1;for(o=r;o<s;o++)if(u(e,o)===u(t,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===c)return n*a}else-1!==n&&(o-=o-n),n=-1}else for(r+c>s&&(r=s-c),o=r;o>=0;o--){let r=!0;for(let n=0;n<c;n++)if(u(e,o+n)!==u(t,n)){r=!1;break}if(r)return o}return-1}function I(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=t.length;let a;for(n>o/2&&(n=o/2),a=0;a<n;++a){const n=parseInt(t.substr(2*a,2),16);if(Q(n))return a;e[r+a]=n}return a}function T(e,t,r,n){return J(W(t,e.length-r),e,r,n)}function A(e,t,r,n){return J(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function E(e,t,r,n){return J(Y(t),e,r,n)}function S(e,t,r,n){return J(function(e,t){let r,n,i;const o=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)r=e.charCodeAt(a),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function x(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function R(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let o=null,a=t>239?4:t>223?3:t>191?2:1;if(i+a<=r){let r,n,s,c;switch(a){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[i+1],n=e[i+2],s=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=a}return function(e){const t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=O));return r}(n)}d.TYPED_ARRAY_SUPPORT=function(){try{const e=new a(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,a.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),d.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(d.prototype,"parent",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.buffer}}),Object.defineProperty(d.prototype,"offset",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.byteOffset}}),d.poolSize=8192,d.from=function(e,t,r){return h(e,t,r)},Object.setPrototypeOf(d.prototype,a.prototype),Object.setPrototypeOf(d,a),d.alloc=function(e,t,r){return function(e,t,r){return p(e),e<=0?u(e):void 0!==t?"string"==typeof r?u(e).fill(t,r):u(e).fill(t):u(e)}(e,t,r)},d.allocUnsafe=function(e){return f(e)},d.allocUnsafeSlow=function(e){return f(e)},d.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==d.prototype},d.compare=function(e,t){if(X(e,a)&&(e=d.from(e,e.offset,e.byteLength)),X(t,a)&&(t=d.from(t,t.offset,t.byteLength)),!d.isBuffer(e)||!d.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},d.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},d.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return d.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=d.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(X(t,a))i+t.length>n.length?(d.isBuffer(t)||(t=d.from(t)),t.copy(n,i)):a.prototype.set.call(n,t,i);else{if(!d.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},d.byteLength=b,d.prototype._isBuffer=!0,d.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)w(this,t,t+1);return this},d.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},d.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},d.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):v.apply(this,arguments)},d.prototype.toLocaleString=d.prototype.toString,d.prototype.equals=function(e){if(!d.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===d.compare(this,e)},d.prototype.inspect=function(){let t="";const r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},i&&(d.prototype[i]=d.prototype.inspect),d.prototype.compare=function(e,t,r,n,i){if(X(e,a)&&(e=d.from(e,e.offset,e.byteLength)),!d.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0);const c=Math.min(o,s),u=this.slice(n,i),l=e.slice(t,r);for(let a=0;a<c;++a)if(u[a]!==l[a]){o=u[a],s=l[a];break}return o<s?-1:s<o?1:0},d.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},d.prototype.indexOf=function(e,t,r){return _(this,e,t,r,!0)},d.prototype.lastIndexOf=function(e,t,r){return _(this,e,t,r,!1)},d.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return I(this,e,t,r);case"utf8":case"utf-8":return T(this,e,t,r);case"ascii":case"latin1":case"binary":return A(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},d.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const O=4096;function $(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function C(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function M(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let o=t;o<r;++o)i+=ee[e[o]];return i}function P(e,t,r){const n=e.slice(t,r);let i="";for(let o=0;o<n.length-1;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function N(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function B(e,t,r,n,i,o){if(!d.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function D(e,t,r,n,i){G(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,i){G(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function j(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function q(e,t,r,i,o){return t=+t,r>>>=0,o||j(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function F(e,t,r,i,o){return t=+t,r>>>=0,o||j(e,0,r,8),n.write(e,t,r,i,52,8),r+8}d.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,d.prototype),n},d.prototype.readUintLE=d.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return n},d.prototype.readUintBE=d.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},d.prototype.readUint8=d.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},d.prototype.readUint16LE=d.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},d.prototype.readUint16BE=d.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},d.prototype.readUint32LE=d.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},d.prototype.readUint32BE=d.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},d.prototype.readBigUInt64LE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))})),d.prototype.readBigUInt64BE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)})),d.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},d.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},d.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},d.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},d.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},d.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},d.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},d.prototype.readBigInt64LE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),d.prototype.readBigInt64BE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),d.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!0,23,4)},d.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!1,23,4)},d.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!0,52,8)},d.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!1,52,8)},d.prototype.writeUintLE=d.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){B(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r},d.prototype.writeUintBE=d.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){B(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},d.prototype.writeUint8=d.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,1,255,0),this[t]=255&e,t+1},d.prototype.writeUint16LE=d.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeUint16BE=d.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeUint32LE=d.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},d.prototype.writeUint32BE=d.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},d.prototype.writeBigUInt64LE=te((function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),d.prototype.writeBigUInt64BE=te((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),d.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);B(this,e,t,r,n-1,-n)}let i=0,o=1,a=0;for(this[t]=255&e;++i<r&&(o*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/o|0)-a&255;return t+r},d.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);B(this,e,t,r,n-1,-n)}let i=r-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o|0)-a&255;return t+r},d.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},d.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},d.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},d.prototype.writeBigInt64LE=te((function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),d.prototype.writeBigInt64BE=te((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),d.prototype.writeFloatLE=function(e,t,r){return q(this,e,t,!0,r)},d.prototype.writeFloatBE=function(e,t,r){return q(this,e,t,!1,r)},d.prototype.writeDoubleLE=function(e,t,r){return F(this,e,t,!0,r)},d.prototype.writeDoubleBE=function(e,t,r){return F(this,e,t,!1,r)},d.prototype.copy=function(e,t,r,n){if(!d.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const i=n-r;return this===e&&"function"==typeof a.prototype.copyWithin?this.copyWithin(t,r,n):a.prototype.set.call(e,this.subarray(r,n),t),i},d.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!d.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const o=d.isBuffer(e)?e:d.from(e,n),a=o.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};const U={};function K(e,t,r){U[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function H(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function G(e,t,r,n,i,o){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let n;throw n=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new U.ERR_OUT_OF_RANGE("value",n,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,o)}function z(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw z(e,r),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}K("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),K("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),K("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n}),RangeError);const Z=/[^+/0-9A-Za-z-_]/g;function W(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let a=0;a<n;++a){if(r=e.charCodeAt(a),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(Z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const ee=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function te(e){return"undefined"==typeof BigInt?re:e}function re(){throw new Error("BigInt not supported")}}(t);const d=t.Buffer;e.Blob=t.Blob,e.BlobOptions=t.BlobOptions,e.Buffer=t.Buffer,e.File=t.File,e.FileOptions=t.FileOptions,e.INSPECT_MAX_BYTES=t.INSPECT_MAX_BYTES,e.SlowBuffer=t.SlowBuffer,e.TranscodeEncoding=t.TranscodeEncoding,e.atob=t.atob,e.btoa=t.btoa,e.constants=t.constants,e.default=d,e.isAscii=t.isAscii,e.isUtf8=t.isUtf8,e.kMaxLength=t.kMaxLength,e.kStringMaxLength=t.kStringMaxLength,e.resolveObjectURL=t.resolveObjectURL,e.transcode=t.transcode}(dist)),dist}var events={exports:{}},hasRequiredEvents;function requireEvents(){if(hasRequiredEvents)return events.exports;hasRequiredEvents=1;var e,t="object"==typeof Reflect?Reflect:null,r=t&&"function"==typeof t.apply?t.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}events.exports=i,events.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}f(e,t,o,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&f(e,"error",t,r)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,r,n){var i,o,c,u;if(a(r),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),c=o[t]),void 0===c)c=o[t]=r,++e._eventsCount;else if("function"==typeof c?c=o[t]=n?[r,c]:[c,r]:n?c.unshift(r):c.push(r),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,u=l,console&&console.warn&&console.warn(u)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=u.bind(n);return i.listener=r,n.wrapFn=i,i}function d(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):p(i,i.length)}function h(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function p(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function f(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){n.once&&e.removeEventListener(t,i),r(o)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)r(c,this,t);else{var u=c.length,l=p(c,u);for(n=0;n<u;++n)r(l[n],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},i.prototype.removeListener=function(e,t){var r,n,i,o,s;if(a(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,o=Object.keys(r);for(n=0;n<o.length;++n)"removeListener"!==(i=o[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},i.prototype.listeners=function(e){return d(this,e,!0)},i.prototype.rawListeners=function(e){return d(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},events.exports}var string_decoder={},safeBuffer={exports:{}},hasRequiredSafeBuffer,hasRequiredString_decoder;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function(e,t){var r=requireDist(),n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}(safeBuffer,safeBuffer.exports)),safeBuffer.exports}function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var e=requireSafeBuffer().Buffer,t=e.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(r){var n;switch(this.encoding=function(r){var n=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(r);if("string"!=typeof n&&(e.isEncoding===t||!t(r)))throw new Error("Unknown encoding: "+r);return n||r}(r),this.encoding){case"utf16le":this.text=o,this.end=a,n=4;break;case"utf8":this.fillLast=i,n=4;break;case"base64":this.text=s,this.end=c,n=3;break;default:return this.write=u,void(this.end=l)}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(n)}function n(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function i(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function o(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function a(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function s(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function c(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function u(e){return e.toString(this.encoding)}function l(e){return e&&e.length?this.write(e):""}return string_decoder.StringDecoder=r,r.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},r.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},r.prototype.text=function(e,t){var r=function(e,t,r){var i=t.length-1;if(i<r)return 0;var o=n(t[i]);if(o>=0)return o>0&&(e.lastNeed=o-1),o;if(--i<r||-2===o)return 0;if(o=n(t[i]),o>=0)return o>0&&(e.lastNeed=o-2),o;if(--i<r||-2===o)return 0;if(o=n(t[i]),o>=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var i=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},r.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length},string_decoder}var inherits_browser={exports:{}},hasRequiredInherits_browser,streamBrowser,hasRequiredStreamBrowser;function requireInherits_browser(){return hasRequiredInherits_browser||(hasRequiredInherits_browser=1,"function"==typeof Object.create?inherits_browser.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),inherits_browser.exports}function requireStreamBrowser(){return hasRequiredStreamBrowser?streamBrowser:(hasRequiredStreamBrowser=1,streamBrowser=requireEvents().EventEmitter)}var util={},types={},shams$1,hasRequiredShams$1,shams,hasRequiredShams,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,type,hasRequiredType,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign,hasRequiredSign,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,callBound,hasRequiredCallBound,isArguments,hasRequiredIsArguments,isRegex,hasRequiredIsRegex,safeRegexTest,hasRequiredSafeRegexTest,isGeneratorFunction,hasRequiredIsGeneratorFunction,isCallable,hasRequiredIsCallable,forEach_1,hasRequiredForEach,possibleTypedArrayNames,hasRequiredPossibleTypedArrayNames,availableTypedArrays,hasRequiredAvailableTypedArrays;function requireShams$1(){return hasRequiredShams$1?shams$1:(hasRequiredShams$1=1,shams$1=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0})}function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var e=requireShams$1();return shams=function(){return e()&&!!Symbol.toStringTag}}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function require_isNaN(){return hasRequired_isNaN?_isNaN:(hasRequired_isNaN=1,_isNaN=Number.isNaN||function(e){return e!=e})}function requireSign(){if(hasRequiredSign)return sign;hasRequiredSign=1;var e=require_isNaN();return sign=function(t){return e(t)||0===t?t:t<0?-1:1}}function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var e=requireGOPD();if(e)try{e([],"length")}catch(t){e=null}return gopd=e}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch(t){e=!1}return esDefineProperty=e}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var e="undefined"!=typeof Symbol&&Symbol,t=requireShams$1();return hasSymbols=function(){return"function"==typeof e&&("function"==typeof Symbol&&("symbol"==typeof e("foo")&&("symbol"==typeof Symbol("bar")&&t())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return implementation=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var o,a=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),s=t(0,i.length-a.length),c=[],u=0;u<s;u++)c[u]="$"+u;if(o=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(c,",")+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof o){var e=i.apply(this,r(a,arguments));return Object(e)===e?e:this}return i.apply(n,r(a,arguments))})),i.prototype){var l=function(){};l.prototype=i.prototype,o.prototype=new l,l.prototype=null}return o},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var e=requireImplementation();return functionBind=Function.prototype.bind||e}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireFunctionCall(),n=requireReflectApply();return actualApply=n||e.call(r,t)}function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var e=requireFunctionBind(),t=requireType(),r=requireFunctionCall(),n=requireActualApply();return callBindApplyHelpers=function(i){if(i.length<1||"function"!=typeof i[0])throw new t("a function is required");return n(e,r,i)}}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var e,t=requireCallBindApplyHelpers(),r=requireGopd();try{e=[].__proto__===Array.prototype}catch(a){if(!a||"object"!=typeof a||!("code"in a)||"ERR_PROTO_ACCESS"!==a.code)throw a}var n=!!e&&r&&r(Object.prototype,"__proto__"),i=Object,o=i.getPrototypeOf;return get=n&&"function"==typeof n.get?t([n.get]):"function"==typeof o&&function(e){return o(null==e?e:i(e))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var e=requireReflect_getPrototypeOf(),t=requireObject_getPrototypeOf(),r=requireGet();return getProto=e?function(t){return e(t)}:t?function(e){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("getProto: not an object");return t(e)}:r?function(e){return r(e)}:null}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=requireFunctionBind();return hasown=r.call(e,t)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;var e;hasRequiredGetIntrinsic=1;var t=requireEsObjectAtoms(),r=requireEsErrors(),n=require_eval(),i=requireRange(),o=requireRef(),a=requireSyntax(),s=requireType(),c=requireUri(),u=requireAbs(),l=requireFloor(),d=requireMax(),h=requireMin(),p=requirePow(),f=requireRound(),m=requireSign(),g=Function,y=function(e){try{return g('"use strict"; return ('+e+").constructor;")()}catch(t){}},b=requireGopd(),v=requireEsDefineProperty(),w=function(){throw new s},_=b?function(){try{return w}catch(e){try{return b(arguments,"callee").get}catch(t){return w}}}():w,k=requireHasSymbols()(),I=requireGetProto(),T=requireObject_getPrototypeOf(),A=requireReflect_getPrototypeOf(),E=requireFunctionApply(),S=requireFunctionCall(),x={},R="undefined"!=typeof Uint8Array&&I?I(Uint8Array):e,O={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?e:ArrayBuffer,"%ArrayIteratorPrototype%":k&&I?I([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":x,"%AsyncGenerator%":x,"%AsyncGeneratorFunction%":x,"%AsyncIteratorPrototype%":x,"%Atomics%":"undefined"==typeof Atomics?e:Atomics,"%BigInt%":"undefined"==typeof BigInt?e:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?e:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float32Array%":"undefined"==typeof Float32Array?e:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?e:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?e:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":x,"%Int8Array%":"undefined"==typeof Int8Array?e:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?e:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":k&&I?I(I([][Symbol.iterator]())):e,"%JSON%":"object"==typeof JSON?JSON:e,"%Map%":"undefined"==typeof Map?e:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&k&&I?I((new Map)[Symbol.iterator]()):e,"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?e:Promise,"%Proxy%":"undefined"==typeof Proxy?e:Proxy,"%RangeError%":i,"%ReferenceError%":o,"%Reflect%":"undefined"==typeof Reflect?e:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?e:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&k&&I?I((new Set)[Symbol.iterator]()):e,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":k&&I?I(""[Symbol.iterator]()):e,"%Symbol%":k?Symbol:e,"%SyntaxError%":a,"%ThrowTypeError%":_,"%TypedArray%":R,"%TypeError%":s,"%Uint8Array%":"undefined"==typeof Uint8Array?e:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?e:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?e:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?e:Uint32Array,"%URIError%":c,"%WeakMap%":"undefined"==typeof WeakMap?e:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?e:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?e:WeakSet,"%Function.prototype.call%":S,"%Function.prototype.apply%":E,"%Object.defineProperty%":v,"%Object.getPrototypeOf%":T,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":m,"%Reflect.getPrototypeOf%":A};if(I)try{null.error}catch(H){var $=I(I(H));O["%Error.prototype%"]=$}var C=function e(t){var r;if("%AsyncFunction%"===t)r=y("async function () {}");else if("%GeneratorFunction%"===t)r=y("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=y("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&I&&(r=I(i.prototype))}return O[t]=r,r},M={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},P=requireFunctionBind(),N=requireHasown(),B=P.call(S,Array.prototype.concat),D=P.call(E,Array.prototype.splice),L=P.call(S,String.prototype.replace),j=P.call(S,String.prototype.slice),q=P.call(S,RegExp.prototype.exec),F=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,U=/\\(\\)?/g,K=function(e,t){var r,n=e;if(N(M,n)&&(n="%"+(r=M[n])[0]+"%"),N(O,n)){var i=O[n];if(i===x&&(i=C(n)),void 0===i&&!t)throw new s("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new a("intrinsic "+e+" does not exist!")};return getIntrinsic=function(e,t){if("string"!=typeof e||0===e.length)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new s('"allowMissing" argument must be a boolean');if(null===q(/^%?[^%]*%?$/,e))throw new a("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=j(e,0,1),r=j(e,-1);if("%"===t&&"%"!==r)throw new a("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new a("invalid intrinsic syntax, expected opening `%`");var n=[];return L(e,F,(function(e,t,r,i){n[n.length]=r?L(i,U,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",i=K("%"+n+"%",t),o=i.name,c=i.value,u=!1,l=i.alias;l&&(n=l[0],D(r,B([0,1],l)));for(var d=1,h=!0;d<r.length;d+=1){var p=r[d],f=j(p,0,1),m=j(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===m||"'"===m||"`"===m)&&f!==m)throw new a("property names with quotes must have matching quotes");if("constructor"!==p&&h||(u=!0),N(O,o="%"+(n+="."+p)+"%"))c=O[o];else if(null!=c){if(!(p in c)){if(!t)throw new s("base intrinsic for "+e+" exists, but the property is not available.");return}if(b&&d+1>=r.length){var g=b(c,p);c=(h=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:c[p]}else h=N(c,p),c=c[p];h&&!u&&(O[o]=c)}}return c},getIntrinsic}function requireCallBound(){if(hasRequiredCallBound)return callBound;hasRequiredCallBound=1;var e=requireGetIntrinsic(),t=requireCallBindApplyHelpers(),r=t([e("%String.prototype.indexOf%")]);return callBound=function(n,i){var o=e(n,!!i);return"function"==typeof o&&r(n,".prototype.")>-1?t([o]):o}}function requireIsArguments(){if(hasRequiredIsArguments)return isArguments;hasRequiredIsArguments=1;var e=requireShams()(),t=requireCallBound()("Object.prototype.toString"),r=function(r){return!(e&&r&&"object"==typeof r&&Symbol.toStringTag in r)&&"[object Arguments]"===t(r)},n=function(e){return!!r(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==t(e)&&"callee"in e&&"[object Function]"===t(e.callee)},i=function(){return r(arguments)}();return r.isLegacyArguments=n,isArguments=i?r:n}function requireIsRegex(){if(hasRequiredIsRegex)return isRegex;hasRequiredIsRegex=1;var e,t=requireCallBound(),r=requireShams()(),n=requireHasown(),i=requireGopd();if(r){var o=t("RegExp.prototype.exec"),a={},s=function(){throw a},c={toString:s,valueOf:s};"symbol"==typeof Symbol.toPrimitive&&(c[Symbol.toPrimitive]=s),e=function(e){if(!e||"object"!=typeof e)return!1;var t=i(e,"lastIndex");if(!(t&&n(t,"value")))return!1;try{o(e,c)}catch(r){return r===a}}}else{var u=t("Object.prototype.toString");e=function(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&"[object RegExp]"===u(e)}}return isRegex=e}function requireSafeRegexTest(){if(hasRequiredSafeRegexTest)return safeRegexTest;hasRequiredSafeRegexTest=1;var e=requireCallBound(),t=requireIsRegex(),r=e("RegExp.prototype.exec"),n=requireType();return safeRegexTest=function(e){if(!t(e))throw new n("`regex` must be a RegExp");return function(t){return null!==r(e,t)}}}function requireIsGeneratorFunction(){if(hasRequiredIsGeneratorFunction)return isGeneratorFunction;hasRequiredIsGeneratorFunction=1;var e,t=requireCallBound(),r=requireSafeRegexTest()(/^\s*(?:function)?\*/),n=requireShams()(),i=requireGetProto(),o=t("Object.prototype.toString"),a=t("Function.prototype.toString");return isGeneratorFunction=function(t){if("function"!=typeof t)return!1;if(r(a(t)))return!0;if(!n)return"[object GeneratorFunction]"===o(t);if(!i)return!1;if(void 0===e){var s=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch(e){}}();e=!!s&&i(s)}return i(t)===e}}function requireIsCallable(){if(hasRequiredIsCallable)return isCallable;hasRequiredIsCallable=1;var e,t,r=Function.prototype.toString,n="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof n&&"function"==typeof Object.defineProperty)try{e=Object.defineProperty({},"length",{get:function(){throw t}}),t={},n((function(){throw 42}),null,e)}catch(h){h!==t&&(n=null)}else n=null;var i=/^\s*class\b/,o=function(e){try{var t=r.call(e);return i.test(t)}catch(n){return!1}},a=function(e){try{return!o(e)&&(r.call(e),!0)}catch(t){return!1}},s=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,u=!(0 in[,]),l=function(){return!1};if("object"==typeof document){var d=document.all;s.call(d)===s.call(document.all)&&(l=function(e){if((u||!e)&&(void 0===e||"object"==typeof e))try{var t=s.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(r){}return!1})}return isCallable=n?function(r){if(l(r))return!0;if(!r)return!1;if("function"!=typeof r&&"object"!=typeof r)return!1;try{n(r,null,e)}catch(i){if(i!==t)return!1}return!o(r)&&a(r)}:function(e){if(l(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return a(e);if(o(e))return!1;var t=s.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&a(e)}}function requireForEach(){if(hasRequiredForEach)return forEach_1;hasRequiredForEach=1;var e=requireIsCallable(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty;return forEach_1=function(n,i,o){if(!e(i))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=o),"[object Array]"===t.call(n)?function(e,t,n){for(var i=0,o=e.length;i<o;i++)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,a):"string"==typeof n?function(e,t,r){for(var n=0,i=e.length;n<i;n++)null==r?t(e.charAt(n),n,e):t.call(r,e.charAt(n),n,e)}(n,i,a):function(e,t,n){for(var i in e)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,a)},forEach_1}function requirePossibleTypedArrayNames(){return hasRequiredPossibleTypedArrayNames?possibleTypedArrayNames:(hasRequiredPossibleTypedArrayNames=1,possibleTypedArrayNames=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"])}function requireAvailableTypedArrays(){if(hasRequiredAvailableTypedArrays)return availableTypedArrays;hasRequiredAvailableTypedArrays=1;var e=requirePossibleTypedArrayNames(),t="undefined"==typeof globalThis?commonjsGlobal:globalThis;return availableTypedArrays=function(){for(var r=[],n=0;n<e.length;n++)"function"==typeof t[e[n]]&&(r[r.length]=e[n]);return r}}var callBind={exports:{}},defineDataProperty,hasRequiredDefineDataProperty,hasPropertyDescriptors_1,hasRequiredHasPropertyDescriptors,setFunctionLength,hasRequiredSetFunctionLength,applyBind,hasRequiredApplyBind,hasRequiredCallBind,whichTypedArray,hasRequiredWhichTypedArray,isTypedArray,hasRequiredIsTypedArray,hasRequiredTypes,isBufferBrowser,hasRequiredIsBufferBrowser,hasRequiredUtil,buffer_list,hasRequiredBuffer_list,destroy_1,hasRequiredDestroy;function requireDefineDataProperty(){if(hasRequiredDefineDataProperty)return defineDataProperty;hasRequiredDefineDataProperty=1;var e=requireEsDefineProperty(),t=requireSyntax(),r=requireType(),n=requireGopd();return defineDataProperty=function(i,o,a){if(!i||"object"!=typeof i&&"function"!=typeof i)throw new r("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new r("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,l=arguments.length>6&&arguments[6],d=!!n&&n(i,o);if(e)e(i,o,{configurable:null===u&&d?d.configurable:!u,enumerable:null===s&&d?d.enumerable:!s,value:a,writable:null===c&&d?d.writable:!c});else{if(!l&&(s||c||u))throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");i[o]=a}},defineDataProperty}function requireHasPropertyDescriptors(){if(hasRequiredHasPropertyDescriptors)return hasPropertyDescriptors_1;hasRequiredHasPropertyDescriptors=1;var e=requireEsDefineProperty(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return 1!==e([],"length",{value:1}).length}catch(t){return!0}},hasPropertyDescriptors_1=t}function requireSetFunctionLength(){if(hasRequiredSetFunctionLength)return setFunctionLength;hasRequiredSetFunctionLength=1;var e=requireGetIntrinsic(),t=requireDefineDataProperty(),r=requireHasPropertyDescriptors()(),n=requireGopd(),i=requireType(),o=e("%Math.floor%");return setFunctionLength=function(e,a){if("function"!=typeof e)throw new i("`fn` is not a function");if("number"!=typeof a||a<0||a>4294967295||o(a)!==a)throw new i("`length` must be a positive 32-bit integer");var s=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in e&&n){var l=n(e,"length");l&&!l.configurable&&(c=!1),l&&!l.writable&&(u=!1)}return(c||u||!s)&&(r?t(e,"length",a,!0,!0):t(e,"length",a)),e},setFunctionLength}function requireApplyBind(){if(hasRequiredApplyBind)return applyBind;hasRequiredApplyBind=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireActualApply();return applyBind=function(){return r(e,t,arguments)},applyBind}function requireCallBind(){return hasRequiredCallBind||(hasRequiredCallBind=1,e=callBind,t=requireSetFunctionLength(),r=requireEsDefineProperty(),n=requireCallBindApplyHelpers(),i=requireApplyBind(),e.exports=function(e){var r=n(arguments),i=e.length-(arguments.length-1);return t(r,1+(i>0?i:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i),callBind.exports;var e,t,r,n,i}function requireWhichTypedArray(){if(hasRequiredWhichTypedArray)return whichTypedArray;hasRequiredWhichTypedArray=1;var e=requireForEach(),t=requireAvailableTypedArrays(),r=requireCallBind(),n=requireCallBound(),i=requireGopd(),o=n("Object.prototype.toString"),a=requireShams()(),s="undefined"==typeof globalThis?commonjsGlobal:globalThis,c=t(),u=n("String.prototype.slice"),l=Object.getPrototypeOf,d=n("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r<e.length;r+=1)if(e[r]===t)return r;return-1},h={__proto__:null};e(c,a&&i&&l?function(e){var t=new s[e];if(Symbol.toStringTag in t){var n=l(t),o=i(n,Symbol.toStringTag);if(!o){var a=l(n);o=i(a,Symbol.toStringTag)}h["$"+e]=r(o.get)}}:function(e){var t=new s[e],n=t.slice||t.set;n&&(h["$"+e]=r(n))});return whichTypedArray=function(t){if(!t||"object"!=typeof t)return!1;if(!a){var r=u(o(t),8,-1);return d(c,r)>-1?r:"Object"===r&&function(t){var r=!1;return e(h,(function(e,n){if(!r)try{e(t),r=u(n,1)}catch(i){}})),r}(t)}return i?function(t){var r=!1;return e(h,(function(e,n){if(!r)try{"$"+e(t)===n&&(r=u(n,1))}catch(i){}})),r}(t):null}}function requireIsTypedArray(){if(hasRequiredIsTypedArray)return isTypedArray;hasRequiredIsTypedArray=1;var e=requireWhichTypedArray();return isTypedArray=function(t){return!!e(t)}}function requireTypes(){return hasRequiredTypes||(hasRequiredTypes=1,function(e){var t=requireIsArguments(),r=requireIsGeneratorFunction(),n=requireWhichTypedArray(),i=requireIsTypedArray();function o(e){return e.call.bind(e)}var a="undefined"!=typeof BigInt,s="undefined"!=typeof Symbol,c=o(Object.prototype.toString),u=o(Number.prototype.valueOf),l=o(String.prototype.valueOf),d=o(Boolean.prototype.valueOf);if(a)var h=o(BigInt.prototype.valueOf);if(s)var p=o(Symbol.prototype.valueOf);function f(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(r){return!1}}function m(e){return"[object Map]"===c(e)}function g(e){return"[object Set]"===c(e)}function y(e){return"[object WeakMap]"===c(e)}function b(e){return"[object WeakSet]"===c(e)}function v(e){return"[object ArrayBuffer]"===c(e)}function w(e){return"undefined"!=typeof ArrayBuffer&&(v.working?v(e):e instanceof ArrayBuffer)}function _(e){return"[object DataView]"===c(e)}function k(e){return"undefined"!=typeof DataView&&(_.working?_(e):e instanceof DataView)}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i,e.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},e.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):i(e)||k(e)},e.isUint8Array=function(e){return"Uint8Array"===n(e)},e.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===n(e)},e.isUint16Array=function(e){return"Uint16Array"===n(e)},e.isUint32Array=function(e){return"Uint32Array"===n(e)},e.isInt8Array=function(e){return"Int8Array"===n(e)},e.isInt16Array=function(e){return"Int16Array"===n(e)},e.isInt32Array=function(e){return"Int32Array"===n(e)},e.isFloat32Array=function(e){return"Float32Array"===n(e)},e.isFloat64Array=function(e){return"Float64Array"===n(e)},e.isBigInt64Array=function(e){return"BigInt64Array"===n(e)},e.isBigUint64Array=function(e){return"BigUint64Array"===n(e)},m.working="undefined"!=typeof Map&&m(new Map),e.isMap=function(e){return"undefined"!=typeof Map&&(m.working?m(e):e instanceof Map)},g.working="undefined"!=typeof Set&&g(new Set),e.isSet=function(e){return"undefined"!=typeof Set&&(g.working?g(e):e instanceof Set)},y.working="undefined"!=typeof WeakMap&&y(new WeakMap),e.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(y.working?y(e):e instanceof WeakMap)},b.working="undefined"!=typeof WeakSet&&b(new WeakSet),e.isWeakSet=function(e){return b(e)},v.working="undefined"!=typeof ArrayBuffer&&v(new ArrayBuffer),e.isArrayBuffer=w,_.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&_(new DataView(new ArrayBuffer(1),0,1)),e.isDataView=k;var I="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function T(e){return"[object SharedArrayBuffer]"===c(e)}function A(e){return void 0!==I&&(void 0===T.working&&(T.working=T(new I)),T.working?T(e):e instanceof I)}function E(e){return f(e,u)}function S(e){return f(e,l)}function x(e){return f(e,d)}function R(e){return a&&f(e,h)}function O(e){return s&&f(e,p)}e.isSharedArrayBuffer=A,e.isAsyncFunction=function(e){return"[object AsyncFunction]"===c(e)},e.isMapIterator=function(e){return"[object Map Iterator]"===c(e)},e.isSetIterator=function(e){return"[object Set Iterator]"===c(e)},e.isGeneratorObject=function(e){return"[object Generator]"===c(e)},e.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===c(e)},e.isNumberObject=E,e.isStringObject=S,e.isBooleanObject=x,e.isBigIntObject=R,e.isSymbolObject=O,e.isBoxedPrimitive=function(e){return E(e)||S(e)||x(e)||R(e)||O(e)},e.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(w(e)||A(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(t){Object.defineProperty(e,t,{enumerable:!1,value:function(){throw new Error(t+" is not supported in userland")}})}))}(types)),types}function requireIsBufferBrowser(){return hasRequiredIsBufferBrowser?isBufferBrowser:(hasRequiredIsBufferBrowser=1,isBufferBrowser=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8})}function requireUtil(){return hasRequiredUtil||(hasRequiredUtil=1,function(e){var t=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n<t.length;n++)r[t[n]]=Object.getOwnPropertyDescriptor(e,t[n]);return r},r=/%[sdj%]/g;e.format=function(e){if(!g(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(a(arguments[n]));return t.join(" ")}n=1;for(var i=arguments,o=i.length,s=String(e).replace(r,(function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(t){return"[Circular]"}default:return e}})),c=i[n];n<o;c=i[++n])f(c)||!v(c)?s+=" "+c:s+=" "+a(c);return s},e.deprecate=function(t,r){if(void 0!==process$1&&!0===process$1.noDeprecation)return t;if(void 0===process$1)return function(){return e.deprecate(t,r).apply(this,arguments)};var n=!1;return function(){if(!n){if(process$1.throwDeprecation)throw new Error(r);process$1.traceDeprecation?console.trace(r):console.error(r),n=!0}return t.apply(this,arguments)}};var n={},i=/^$/;if(process$1.env.NODE_DEBUG){var o=process$1.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}function a(t,r){var n={seen:[],stylize:c};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(r)?n.showHidden=r:r&&e._extend(n,r),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=s),u(n,t,n.depth)}function s(e,t){var r=a.styles[t];return r?"["+a.colors[r][0]+"m"+e+"["+a.colors[r][1]+"m":e}function c(e,t){return e}function u(t,r,n){if(t.customInspect&&r&&k(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,t);return g(i)||(i=u(t,i,n)),i}var o=function(e,t){if(y(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(m(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(f(t))return e.stylize("null","null")}(t,r);if(o)return o;var a=Object.keys(r),s=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(r)),_(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(r);if(0===a.length){if(k(r)){var c=r.name?": "+r.name:"";return t.stylize("[Function"+c+"]","special")}if(b(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(w(r))return t.stylize(Date.prototype.toString.call(r),"date");if(_(r))return l(r)}var v,I="",T=!1,A=["{","}"];(h(r)&&(T=!0,A=["[","]"]),k(r))&&(I=" [Function"+(r.name?": "+r.name:"")+"]");return b(r)&&(I=" "+RegExp.prototype.toString.call(r)),w(r)&&(I=" "+Date.prototype.toUTCString.call(r)),_(r)&&(I=" "+l(r)),0!==a.length||T&&0!=r.length?n<0?b(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),v=T?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a<s;++a)E(t,String(a))?o.push(d(e,t,r,n,String(a),!0)):o.push("");return i.forEach((function(i){i.match(/^\d+$/)||o.push(d(e,t,r,n,i,!0))})),o}(t,r,n,s,a):a.map((function(e){return d(t,r,n,s,e,T)})),t.seen.pop(),function(e,t,r){var n=e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(v,I,A)):A[0]+I+A[1]}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,i,o){var a,s,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(s=e.stylize("[Setter]","special")),E(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(c.value)<0?(s=f(r)?u(e,c.value,null):u(e,c.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),y(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.slice(1,-1),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function h(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function m(e){return"number"==typeof e}function g(e){return"string"==typeof e}function y(e){return void 0===e}function b(e){return v(e)&&"[object RegExp]"===I(e)}function v(e){return"object"==typeof e&&null!==e}function w(e){return v(e)&&"[object Date]"===I(e)}function _(e){return v(e)&&("[object Error]"===I(e)||e instanceof Error)}function k(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function T(e){return e<10?"0"+e.toString(10):e.toString(10)}e.debuglog=function(t){if(t=t.toUpperCase(),!n[t])if(i.test(t)){var r=process$1.pid;n[t]=function(){var n=e.format.apply(e,arguments);console.error("%s %d: %s",t,r,n)}}else n[t]=function(){};return n[t]},e.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.types=requireTypes(),e.isArray=h,e.isBoolean=p,e.isNull=f,e.isNullOrUndefined=function(e){return null==e},e.isNumber=m,e.isString=g,e.isSymbol=function(e){return"symbol"==typeof e},e.isUndefined=y,e.isRegExp=b,e.types.isRegExp=b,e.isObject=v,e.isDate=w,e.types.isDate=w,e.isError=_,e.types.isNativeError=_,e.isFunction=k,e.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},e.isBuffer=requireIsBufferBrowser();var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.log=function(){var t,r;console.log("%s - %s",(r=[T((t=new Date).getHours()),T(t.getMinutes()),T(t.getSeconds())].join(":"),[t.getDate(),A[t.getMonth()],r].join(" ")),e.format.apply(e,arguments))},e.inherits=requireInherits_browser(),e._extend=function(e,t){if(!t||!v(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var S="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function x(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}e.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(S&&e[S]){var r;if("function"!=typeof(r=e[S]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(r,S,{value:r,enumerable:!1,writable:!1,configurable:!0}),r}function r(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),i=[],o=0;o<arguments.length;o++)i.push(arguments[o]);i.push((function(e,n){e?r(e):t(n)}));try{e.apply(this,i)}catch(a){r(a)}return n}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),S&&Object.defineProperty(r,S,{value:r,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(r,t(e))},e.promisify.custom=S,e.callbackify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function r(){for(var t=[],r=0;r<arguments.length;r++)t.push(arguments[r]);var n=t.pop();if("function"!=typeof n)throw new TypeError("The last argument must be of type Function");var i=this,o=function(){return n.apply(i,arguments)};e.apply(this,t).then((function(e){process$1.nextTick(o.bind(null,null,e))}),(function(e){process$1.nextTick(x.bind(null,e,o))}))}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),Object.defineProperties(r,t(e)),r}}(util)),util}function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(e,t,r){return(t=i(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,t,r){return function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,i(n.key),n)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:String(t)}hasRequiredBuffer_list=1;var o=requireDist().Buffer,a=requireUtil().inspect,s=a&&a.custom||"inspect";return buffer_list=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return n(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t,r,n,i=o.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=i,n=s,o.prototype.copy.call(t,r,n),s+=a.data.length,a=a.next;return i}},{key:"consume",value:function(e,t){var r;return e<this.head.data.length?(r=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):r=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),r}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,r=1,n=t.data;for(e-=n.length;t=t.next;){var i=t.data,o=e>i.length?i.length:e;if(o===i.length?n+=i:n+=i.slice(0,e),0===(e-=o)){o===i.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var i=r.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),0===(e-=a)){a===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(a));break}++n}return this.length-=n,t}},{key:s,value:function(e,r){return a(this,t(t({},r),{},{depth:0,customInspect:!1}))}}]),e}()}function requireDestroy(){if(hasRequiredDestroy)return destroy_1;function e(e,n){r(e,n),t(e)}function t(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}return hasRequiredDestroy=1,destroy_1={destroy:function(n,i){var o=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(i?i(n):n&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process$1.nextTick(r,this,n)):process$1.nextTick(r,this,n)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(n||null,(function(r){!i&&r?o._writableState?o._writableState.errorEmitted?process$1.nextTick(t,o):(o._writableState.errorEmitted=!0,process$1.nextTick(e,o,r)):process$1.nextTick(e,o,r):i?(process$1.nextTick(t,o),i(r)):process$1.nextTick(t,o)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}}var errorsBrowser={},hasRequiredErrorsBrowser,state,hasRequiredState,browser,hasRequiredBrowser,_stream_writable,hasRequired_stream_writable,_stream_duplex,hasRequired_stream_duplex,endOfStream,hasRequiredEndOfStream,async_iterator,hasRequiredAsync_iterator,fromBrowser,hasRequiredFromBrowser,_stream_readable,hasRequired_stream_readable,_stream_transform,hasRequired_stream_transform,_stream_passthrough,hasRequired_stream_passthrough,pipeline_1,hasRequiredPipeline,streamBrowserify,hasRequiredStreamBrowserify;function requireErrorsBrowser(){if(hasRequiredErrorsBrowser)return errorsBrowser;hasRequiredErrorsBrowser=1;var e={};function t(t,r,n){n||(n=Error);var i=function(e){var t,n;function i(t,n,i){return e.call(this,function(e,t,n){return"string"==typeof r?r:r(e,t,n)}(t,n,i))||this}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,t.__proto__=n,i}(n);i.prototype.name=n.name,i.prototype.code=t,e[t]=i}function r(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}return t("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),t("ERR_INVALID_ARG_TYPE",(function(e,t,n){var i,o,a;if("string"==typeof t&&(o="not ",t.substr(0,o.length)===o)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))a="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var s=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(s," ").concat(i," ").concat(r(t,"type"))}return a+=". Received type ".concat(typeof n)}),TypeError),t("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),t("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),t("ERR_STREAM_PREMATURE_CLOSE","Premature close"),t("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),t("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),t("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),t("ERR_STREAM_WRITE_AFTER_END","write after end"),t("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),t("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),t("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),errorsBrowser.codes=e,errorsBrowser}function requireState(){if(hasRequiredState)return state;hasRequiredState=1;var e=requireErrorsBrowser().codes.ERR_INVALID_OPT_VALUE;return state={getHighWaterMark:function(t,r,n,i){var o=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(r,i,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new e(i?n:"highWaterMark",o);return Math.floor(o)}return t.objectMode?16:16384}}}function requireBrowser(){if(hasRequiredBrowser)return browser;function e(e){try{if(!commonjsGlobal.localStorage)return!1}catch(r){return!1}var t=commonjsGlobal.localStorage[e];return null!=t&&"true"===String(t).toLowerCase()}return hasRequiredBrowser=1,browser=function(t,r){if(e("noDeprecation"))return t;var n=!1;return function(){if(!n){if(e("throwDeprecation"))throw new Error(r);e("traceDeprecation")?console.trace(r):console.warn(r),n=!0}return t.apply(this,arguments)}},browser}function require_stream_writable(){if(hasRequired_stream_writable)return _stream_writable;function e(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,r){var n=e.entry;e.entry=null;for(;n;){var i=n.callback;t.pendingcb--,i(r),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var t;hasRequired_stream_writable=1,_stream_writable=_,_.WritableState=w;var r={deprecate:requireBrowser()},n=requireStreamBrowser(),i=requireDist().Buffer,o=(void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var a,s=requireDestroy(),c=requireState().getHighWaterMark,u=requireErrorsBrowser().codes,l=u.ERR_INVALID_ARG_TYPE,d=u.ERR_METHOD_NOT_IMPLEMENTED,h=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,f=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,g=u.ERR_STREAM_WRITE_AFTER_END,y=u.ERR_UNKNOWN_ENCODING,b=s.errorOrDestroy;function v(){}function w(r,n,i){t=t||require_stream_duplex(),r=r||{},"boolean"!=typeof i&&(i=n instanceof t),this.objectMode=!!r.objectMode,i&&(this.objectMode=this.objectMode||!!r.writableObjectMode),this.highWaterMark=c(this,r,"writableHighWaterMark",i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===r.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=r.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new h;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,i){--t.pendingcb,r?(process$1.nextTick(i,n),process$1.nextTick(S,e,t),e._writableState.errorEmitted=!0,b(e,n)):(i(n),e._writableState.errorEmitted=!0,b(e,n),S(e,t))}(e,r,n,t,i);else{var o=A(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||T(e,r),n?process$1.nextTick(I,e,r,o,i):I(e,r,o,i)}}(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==r.emitClose,this.autoDestroy=!!r.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}function _(e){var r=this instanceof(t=t||require_stream_duplex());if(!r&&!a.call(_,this))return new _(e);this._writableState=new w(e,this,r),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),n.call(this)}function k(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new f("write")):r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function I(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),S(e,t)}function T(t,r){r.bufferProcessing=!0;var n=r.bufferedRequest;if(t._writev&&n&&n.next){var i=r.bufferedRequestCount,o=new Array(i),a=r.corkedRequestsFree;a.entry=n;for(var s=0,c=!0;n;)o[s]=n,n.isBuf||(c=!1),n=n.next,s+=1;o.allBuffers=c,k(t,r,!0,r.length,o,"",a.finish),r.pendingcb++,r.lastBufferedRequest=null,a.next?(r.corkedRequestsFree=a.next,a.next=null):r.corkedRequestsFree=new e(r),r.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,d=n.callback;if(k(t,r,!1,r.objectMode?1:u.length,u,l,d),n=n.next,r.bufferedRequestCount--,r.writing)break}null===n&&(r.lastBufferedRequest=null)}r.bufferedRequest=n,r.bufferProcessing=!1}function A(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function E(e,t){e._final((function(r){t.pendingcb--,r&&b(e,r),t.prefinished=!0,e.emit("prefinish"),S(e,t)}))}function S(e,t){var r=A(t);if(r&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process$1.nextTick(E,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}return requireInherits_browser()(_,n),w.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(w.prototype,"buffer",{get:r.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(a=Function.prototype[Symbol.hasInstance],Object.defineProperty(_,Symbol.hasInstance,{value:function(e){return!!a.call(this,e)||this===_&&(e&&e._writableState instanceof w)}})):a=function(e){return e instanceof this},_.prototype.pipe=function(){b(this,new p)},_.prototype.write=function(e,t,r){var n,a=this._writableState,s=!1,c=!a.objectMode&&(n=e,i.isBuffer(n)||n instanceof o);return c&&!i.isBuffer(e)&&(e=function(e){return i.from(e)}(e)),"function"==typeof t&&(r=t,t=null),c?t="buffer":t||(t=a.defaultEncoding),"function"!=typeof r&&(r=v),a.ending?function(e,t){var r=new g;b(e,r),process$1.nextTick(t,r)}(this,r):(c||function(e,t,r,n){var i;return null===r?i=new m:"string"==typeof r||t.objectMode||(i=new l("chunk",["string","Buffer"],r)),!i||(b(e,i),process$1.nextTick(n,i),!1)}(this,a,e,r))&&(a.pendingcb++,s=function(e,t,r,n,o,a){if(!r){var s=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=i.from(t,r));return t}(t,n,o);n!==s&&(r=!0,o="buffer",n=s)}var c=t.objectMode?1:n.length;t.length+=c;var u=t.length<t.highWaterMark;u||(t.needDrain=!0);if(t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:o,isBuf:r,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else k(e,t,!1,c,n,o,a);return u}(this,a,c,e,t,r)),s},_.prototype.cork=function(){this._writableState.corked++},_.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||T(this,e))},_.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new y(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(_.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(_.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),_.prototype._write=function(e,t,r){r(new d("_write()"))},_.prototype._writev=null,_.prototype.end=function(e,t,r){var n=this._writableState;return"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||function(e,t,r){t.ending=!0,S(e,t),r&&(t.finished?process$1.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r),this},Object.defineProperty(_.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),_.prototype.destroy=s.destroy,_.prototype._undestroy=s.undestroy,_.prototype._destroy=function(e,t){t(e)},_stream_writable}function require_stream_duplex(){if(hasRequired_stream_duplex)return _stream_duplex;hasRequired_stream_duplex=1;var e=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};_stream_duplex=a;var t=require_stream_readable(),r=require_stream_writable();requireInherits_browser()(a,t);for(var n=e(r.prototype),i=0;i<n.length;i++){var o=n[i];a.prototype[o]||(a.prototype[o]=r.prototype[o])}function a(e){if(!(this instanceof a))return new a(e);t.call(this,e),r.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",s)))}function s(){this._writableState.ended||process$1.nextTick(c,this)}function c(e){e.end()}return Object.defineProperty(a.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(a.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(a.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),_stream_duplex}function requireEndOfStream(){if(hasRequiredEndOfStream)return endOfStream;hasRequiredEndOfStream=1;var e=requireErrorsBrowser().codes.ERR_STREAM_PREMATURE_CLOSE;function t(){}return endOfStream=function r(n,i,o){if("function"==typeof i)return r(n,null,i);i||(i={}),o=function(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.apply(this,n)}}}(o||t);var a=i.readable||!1!==i.readable&&n.readable,s=i.writable||!1!==i.writable&&n.writable,c=function(){n.writable||l()},u=n._writableState&&n._writableState.finished,l=function(){s=!1,u=!0,a||o.call(n)},d=n._readableState&&n._readableState.endEmitted,h=function(){a=!1,d=!0,s||o.call(n)},p=function(e){o.call(n,e)},f=function(){var t;return a&&!d?(n._readableState&&n._readableState.ended||(t=new e),o.call(n,t)):s&&!u?(n._writableState&&n._writableState.ended||(t=new e),o.call(n,t)):void 0},m=function(){n.req.on("finish",l)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(n)?s&&!n._writableState&&(n.on("end",c),n.on("close",c)):(n.on("complete",l),n.on("abort",f),n.req?m():n.on("request",m)),n.on("end",h),n.on("finish",l),!1!==i.error&&n.on("error",p),n.on("close",f),function(){n.removeListener("complete",l),n.removeListener("abort",f),n.removeListener("request",m),n.req&&n.req.removeListener("finish",l),n.removeListener("end",c),n.removeListener("close",c),n.removeListener("finish",l),n.removeListener("end",h),n.removeListener("error",p),n.removeListener("close",f)}},endOfStream}function requireAsync_iterator(){if(hasRequiredAsync_iterator)return async_iterator;var e;function t(e,t,r){return t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}hasRequiredAsync_iterator=1;var r=requireEndOfStream(),n=Symbol("lastResolve"),i=Symbol("lastReject"),o=Symbol("error"),a=Symbol("ended"),s=Symbol("lastPromise"),c=Symbol("handlePromise"),u=Symbol("stream");function l(e,t){return{value:e,done:t}}function d(e){var t=e[n];if(null!==t){var r=e[u].read();null!==r&&(e[s]=null,e[n]=null,e[i]=null,t(l(r,!1)))}}function h(e){process$1.nextTick(d,e)}var p=Object.getPrototypeOf((function(){})),f=Object.setPrototypeOf((t(e={get stream(){return this[u]},next:function(){var e=this,t=this[o];if(null!==t)return Promise.reject(t);if(this[a])return Promise.resolve(l(void 0,!0));if(this[u].destroyed)return new Promise((function(t,r){process$1.nextTick((function(){e[o]?r(e[o]):t(l(void 0,!0))}))}));var r,n=this[s];if(n)r=new Promise(function(e,t){return function(r,n){e.then((function(){t[a]?r(l(void 0,!0)):t[c](r,n)}),n)}}(n,this));else{var i=this[u].read();if(null!==i)return Promise.resolve(l(i,!1));r=new Promise(this[c])}return this[s]=r,r}},Symbol.asyncIterator,(function(){return this})),t(e,"return",(function(){var e=this;return new Promise((function(t,r){e[u].destroy(null,(function(e){e?r(e):t(l(void 0,!0))}))}))})),e),p);return async_iterator=function(e){var d,p=Object.create(f,(t(d={},u,{value:e,writable:!0}),t(d,n,{value:null,writable:!0}),t(d,i,{value:null,writable:!0}),t(d,o,{value:null,writable:!0}),t(d,a,{value:e._readableState.endEmitted,writable:!0}),t(d,c,{value:function(e,t){var r=p[u].read();r?(p[s]=null,p[n]=null,p[i]=null,e(l(r,!1))):(p[n]=e,p[i]=t)},writable:!0}),d));return p[s]=null,r(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=p[i];return null!==t&&(p[s]=null,p[n]=null,p[i]=null,t(e)),void(p[o]=e)}var r=p[n];null!==r&&(p[s]=null,p[n]=null,p[i]=null,r(l(void 0,!0))),p[a]=!0})),e.on("readable",h.bind(null,p)),p}}function requireFromBrowser(){return hasRequiredFromBrowser?fromBrowser:(hasRequiredFromBrowser=1,fromBrowser=function(){throw new Error("Readable.from is not available in the browser")})}function require_stream_readable(){if(hasRequired_stream_readable)return _stream_readable;var e;hasRequired_stream_readable=1,_stream_readable=_,_.ReadableState=w,requireEvents().EventEmitter;var t=function(e,t){return e.listeners(t).length},r=requireStreamBrowser(),n=requireDist().Buffer,i=(void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var o,a=requireUtil();o=a&&a.debuglog?a.debuglog("stream"):function(){};var s,c,u,l=requireBuffer_list(),d=requireDestroy(),h=requireState().getHighWaterMark,p=requireErrorsBrowser().codes,f=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,g=p.ERR_METHOD_NOT_IMPLEMENTED,y=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;requireInherits_browser()(_,r);var b=d.errorOrDestroy,v=["error","close","destroy","pause","resume"];function w(t,r,n){e=e||require_stream_duplex(),t=t||{},"boolean"!=typeof n&&(n=r instanceof e),this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=h(this,t,"readableHighWaterMark",n),this.buffer=new l,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(s||(s=requireString_decoder().StringDecoder),this.decoder=new s(t.encoding),this.encoding=t.encoding)}function _(t){if(e=e||require_stream_duplex(),!(this instanceof _))return new _(t);var n=this instanceof e;this._readableState=new w(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),r.call(this)}function k(e,t,r,a,s){o("readableAddChunk",t);var c,u=e._readableState;if(null===t)u.reading=!1,function(e,t){if(o("onEofChunk"),t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?E(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,S(e)))}(e,u);else if(s||(c=function(e,t){var r;o=t,n.isBuffer(o)||o instanceof i||"string"==typeof t||void 0===t||e.objectMode||(r=new f("chunk",["string","Buffer","Uint8Array"],t));var o;return r}(u,t)),c)b(e,c);else if(u.objectMode||t&&t.length>0)if("string"==typeof t||u.objectMode||Object.getPrototypeOf(t)===n.prototype||(t=function(e){return n.from(e)}(t)),a)u.endEmitted?b(e,new y):I(e,u,t,!0);else if(u.ended)b(e,new m);else{if(u.destroyed)return!1;u.reading=!1,u.decoder&&!r?(t=u.decoder.write(t),u.objectMode||0!==t.length?I(e,u,t,!1):x(e,u)):I(e,u,t,!1)}else a||(u.reading=!1,x(e,u));return!u.ended&&(u.length<u.highWaterMark||0===u.length)}function I(e,t,r,n){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&E(e)),x(e,t)}Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=d.destroy,_.prototype._undestroy=d.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var r,i=this._readableState;return i.objectMode?r=!0:"string"==typeof e&&((t=t||i.defaultEncoding)!==i.encoding&&(e=n.from(e,t),t=""),r=!0),k(this,e,t,!1,r)},_.prototype.unshift=function(e){return k(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.prototype.setEncoding=function(e){s||(s=requireString_decoder().StringDecoder);var t=new s(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,n="";null!==r;)n+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==n&&this._readableState.buffer.push(n),this._readableState.length=n.length,this};var T=1073741824;function A(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=T?e=T:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function E(e){var t=e._readableState;o("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(o("emitReadable",t.flowing),t.emittedReadable=!0,process$1.nextTick(S,e))}function S(e){var t=e._readableState;o("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,M(e)}function x(e,t){t.readingMore||(t.readingMore=!0,process$1.nextTick(R,e,t))}function R(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var r=t.length;if(o("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function O(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function $(e){o("readable nexttick read 0"),e.read(0)}function C(e,t){o("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),M(e),t.flowing&&!t.reading&&e.read(0)}function M(e){var t=e._readableState;for(o("flow",t.flowing);t.flowing&&null!==e.read(););}function P(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function N(e){var t=e._readableState;o("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process$1.nextTick(B,t,e))}function B(e,t){if(o("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function D(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}return _.prototype.read=function(e){o("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return o("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?N(this):E(this),null;if(0===(e=A(e,t))&&t.ended)return 0===t.length&&N(this),null;var n,i=t.needReadable;return o("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&o("length less than watermark",i=!0),t.ended||t.reading?o("reading or ended",i=!1):i&&(o("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=A(r,t))),null===(n=e>0?P(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&N(this)),null!==n&&this.emit("data",n),n},_.prototype._read=function(e){b(this,new g("_read()"))},_.prototype.pipe=function(e,r){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,o("pipe count=%d opts=%j",i.pipesCount,r);var a=(!r||!1!==r.end)&&e!==process$1.stdout&&e!==process$1.stderr?c:m;function s(t,r){o("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,o("cleanup"),e.removeListener("close",p),e.removeListener("finish",f),e.removeListener("drain",u),e.removeListener("error",h),e.removeListener("unpipe",s),n.removeListener("end",c),n.removeListener("end",m),n.removeListener("data",d),l=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||u())}function c(){o("onend"),e.end()}i.endEmitted?process$1.nextTick(a):n.once("end",a),e.on("unpipe",s);var u=function(e){return function(){var r=e._readableState;o("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,0===r.awaitDrain&&t(e,"data")&&(r.flowing=!0,M(e))}}(n);e.on("drain",u);var l=!1;function d(t){o("ondata");var r=e.write(t);o("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==D(i.pipes,e))&&!l&&(o("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function h(r){o("onerror",r),m(),e.removeListener("error",h),0===t(e,"error")&&b(e,r)}function p(){e.removeListener("finish",f),m()}function f(){o("onfinish"),e.removeListener("close",p),m()}function m(){o("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",h),e.once("close",p),e.once("finish",f),e.emit("pipe",n),i.flowing||(o("pipe resume"),n.resume()),e},_.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<i;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var a=D(t.pipes,e);return-1===a||(t.pipes.splice(a,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r)),this},_.prototype.on=function(e,t){var n=r.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,o("on readable",i.length,i.reading),i.length?E(this):i.reading||process$1.nextTick($,this))),n},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var n=r.prototype.removeListener.call(this,e,t);return"readable"===e&&process$1.nextTick(O,this),n},_.prototype.removeAllListeners=function(e){var t=r.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process$1.nextTick(O,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(o("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process$1.nextTick(C,e,t))}(this,e)),e.paused=!1,this},_.prototype.pause=function(){return o("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(o("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var i in e.on("end",(function(){if(o("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(o("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(t.push(i)||(n=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<v.length;a++)e.on(v[a],this.emit.bind(this,v[a]));return this._read=function(t){o("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===c&&(c=requireAsync_iterator()),c(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=P,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(e,t){return void 0===u&&(u=requireFromBrowser()),u(_,e,t)}),_stream_readable}function require_stream_transform(){if(hasRequired_stream_transform)return _stream_transform;hasRequired_stream_transform=1,_stream_transform=s;var e=requireErrorsBrowser().codes,t=e.ERR_METHOD_NOT_IMPLEMENTED,r=e.ERR_MULTIPLE_CALLBACK,n=e.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=e.ERR_TRANSFORM_WITH_LENGTH_0,o=require_stream_duplex();function a(e,t){var n=this._transformState;n.transforming=!1;var i=n.writecb;if(null===i)return this.emit("error",new r);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),i(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function s(e){if(!(this instanceof s))return new s(e);o.call(this,e),this._transformState={afterTransform:a.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",c)}function c(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?u(this,null,null):this._flush((function(t,r){u(e,t,r)}))}function u(e,t,r){if(t)return e.emit("error",t);if(null!=r&&e.push(r),e._writableState.length)throw new i;if(e._transformState.transforming)throw new n;return e.push(null)}return requireInherits_browser()(s,o),s.prototype.push=function(e,t){return this._transformState.needTransform=!1,o.prototype.push.call(this,e,t)},s.prototype._transform=function(e,r,n){n(new t("_transform()"))},s.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},s.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},s.prototype._destroy=function(e,t){o.prototype._destroy.call(this,e,(function(e){t(e)}))},_stream_transform}function require_stream_passthrough(){if(hasRequired_stream_passthrough)return _stream_passthrough;hasRequired_stream_passthrough=1,_stream_passthrough=t;var e=require_stream_transform();function t(r){if(!(this instanceof t))return new t(r);e.call(this,r)}return requireInherits_browser()(t,e),t.prototype._transform=function(e,t,r){r(null,e)},_stream_passthrough}function requirePipeline(){if(hasRequiredPipeline)return pipeline_1;var e;hasRequiredPipeline=1;var t=requireErrorsBrowser().codes,r=t.ERR_MISSING_ARGS,n=t.ERR_STREAM_DESTROYED;function i(e){if(e)throw e}function o(e){e()}function a(e,t){return e.pipe(t)}return pipeline_1=function(){for(var t=arguments.length,s=new Array(t),c=0;c<t;c++)s[c]=arguments[c];var u,l=function(e){return e.length?"function"!=typeof e[e.length-1]?i:e.pop():i}(s);if(Array.isArray(s[0])&&(s=s[0]),s.length<2)throw new r("streams");var d=s.map((function(t,r){var i=r<s.length-1;return function(t,r,i,o){o=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(o);var a=!1;t.on("close",(function(){a=!0})),void 0===e&&(e=requireEndOfStream()),e(t,{readable:r,writable:i},(function(e){if(e)return o(e);a=!0,o()}));var s=!1;return function(e){if(!a&&!s)return s=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new n("pipe"))}}(t,i,r>0,(function(e){u||(u=e),e&&d.forEach(o),i||(d.forEach(o),l(u))}))}));return s.reduce(a)},pipeline_1}function requireStreamBrowserify(){if(hasRequiredStreamBrowserify)return streamBrowserify;hasRequiredStreamBrowserify=1,streamBrowserify=t;var e=requireEvents().EventEmitter;function t(){e.call(this)}return requireInherits_browser()(t,e),t.Readable=require_stream_readable(),t.Writable=require_stream_writable(),t.Duplex=require_stream_duplex(),t.Transform=require_stream_transform(),t.PassThrough=require_stream_passthrough(),t.finished=requireEndOfStream(),t.pipeline=requirePipeline(),t.Stream=t,t.prototype.pipe=function(t,r){var n=this;function i(e){t.writable&&!1===t.write(e)&&n.pause&&n.pause()}function o(){n.readable&&n.resume&&n.resume()}n.on("data",i),t.on("drain",o),t._isStdio||r&&!1===r.end||(n.on("end",s),n.on("close",c));var a=!1;function s(){a||(a=!0,t.end())}function c(){a||(a=!0,"function"==typeof t.destroy&&t.destroy())}function u(t){if(l(),0===e.listenerCount(this,"error"))throw t}function l(){n.removeListener("data",i),t.removeListener("drain",o),n.removeListener("end",s),n.removeListener("close",c),n.removeListener("error",u),t.removeListener("error",u),n.removeListener("end",l),n.removeListener("close",l),t.removeListener("close",l)}return n.on("error",u),t.on("error",u),n.on("end",l),n.on("close",l),t.on("close",l),t.emit("pipe",n),t},streamBrowserify}var streamBrowserifyExports=requireStreamBrowserify();const index=getDefaultExportFromCjs(streamBrowserifyExports),index$1=Object.freeze(Object.defineProperty({__proto__:null,default:index},Symbol.toStringTag,{value:"Module"})),standardsSdk_es33=Object.freeze(Object.defineProperty({__proto__:null,i:index$1},Symbol.toStringTag,{value:"Module"}));exports.AcceptConnectionRequestTool=AcceptConnectionRequestTool,exports.BasePlugin=BasePlugin,exports.CheckMessagesTool=CheckMessagesTool,exports.ConnectionMonitorTool=ConnectionMonitorTool,exports.ConnectionTool=ConnectionTool,exports.FindRegistrationsTool=FindRegistrationsTool,exports.GenericPlugin=GenericPlugin,exports.GetHbarPriceTool=GetHbarPriceTool,exports.HCS10Client=HCS10Client,exports.HbarPricePlugin=HbarPricePlugin,exports.InitiateConnectionTool=InitiateConnectionTool,exports.ListConnectionsTool=ListConnectionsTool,exports.ListUnapprovedConnectionRequestsTool=ListUnapprovedConnectionRequestsTool,exports.ManageConnectionRequestsTool=ManageConnectionRequestsTool,exports.OpenConvAIPlugin=OpenConvAIPlugin,exports.OpenConvaiState=OpenConvaiState,exports.PluginLoader=PluginLoader,exports.PluginRegistry=PluginRegistry,exports.RegisterAgentTool=RegisterAgentTool,exports.RetrieveProfileTool=RetrieveProfileTool,exports.SendMessageToConnectionTool=SendMessageToConnectionTool,exports.SendMessageTool=SendMessageTool,exports.initializeStandardsAgentKit=initializeStandardsAgentKit,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
164
+ !function(e){const t=r,n=l,i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=d,e.SlowBuffer=function(e){+e!=e&&(e=0);return d.alloc(+e)},e.INSPECT_MAX_BYTES=50;const o=2147483647;e.kMaxLength=o;const{Uint8Array:a,ArrayBuffer:s,SharedArrayBuffer:c}=globalThis;function u(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new a(e);return Object.setPrototypeOf(t,d.prototype),t}function d(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return h(e,t,r)}function h(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!d.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|b(e,t);let n=u(r);const i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(s.isView(e))return function(e){if(X(e,a)){const t=new a(e);return g(t.buffer,t.byteOffset,t.byteLength)}return m(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,s)||e&&X(e.buffer,s))return g(e,t,r);if(void 0!==c&&(X(e,c)||e&&X(e.buffer,c)))return g(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return d.from(n,t,r);const i=function(e){if(d.isBuffer(e)){const t=0|y(e.length),r=u(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||Q(e.length)?u(0):m(e);if("Buffer"===e.type&&Array.isArray(e.data))return m(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return d.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function p(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function f(e){return p(e),u(e<0?0:0|y(e))}function m(e){const t=e.length<0?0:0|y(e.length),r=u(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function g(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new a(e):void 0===r?new a(e,t):new a(e,t,r),Object.setPrototypeOf(n,d.prototype),n}function y(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function b(e,t){if(d.isBuffer(e))return e.length;if(s.isView(e)||X(e,s))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(e).length;default:if(i)return n?-1:W(e).length;t=(""+t).toLowerCase(),i=!0}}function v(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return M(this,t,r);case"utf8":case"utf-8":return R(this,t,r);case"ascii":return $(this,t,r);case"latin1":case"binary":return C(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function w(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function _(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=d.from(t,n)),d.isBuffer(t))return 0===t.length?-1:k(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof a.prototype.indexOf?i?a.prototype.indexOf.call(e,t,r):a.prototype.lastIndexOf.call(e,t,r):k(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function k(e,t,r,n,i){let o,a=1,s=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,c/=2,r/=2}function u(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){let n=-1;for(o=r;o<s;o++)if(u(e,o)===u(t,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===c)return n*a}else-1!==n&&(o-=o-n),n=-1}else for(r+c>s&&(r=s-c),o=r;o>=0;o--){let r=!0;for(let n=0;n<c;n++)if(u(e,o+n)!==u(t,n)){r=!1;break}if(r)return o}return-1}function I(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=t.length;let a;for(n>o/2&&(n=o/2),a=0;a<n;++a){const n=parseInt(t.substr(2*a,2),16);if(Q(n))return a;e[r+a]=n}return a}function T(e,t,r,n){return J(W(t,e.length-r),e,r,n)}function A(e,t,r,n){return J(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function E(e,t,r,n){return J(Y(t),e,r,n)}function S(e,t,r,n){return J(function(e,t){let r,n,i;const o=[];for(let a=0;a<e.length&&!((t-=2)<0);++a)r=e.charCodeAt(a),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function x(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function R(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let o=null,a=t>239?4:t>223?3:t>191?2:1;if(i+a<=r){let r,n,s,c;switch(a){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[i+1],n=e[i+2],s=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=a}return function(e){const t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=O));return r}(n)}d.TYPED_ARRAY_SUPPORT=function(){try{const e=new a(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,a.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),d.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(d.prototype,"parent",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.buffer}}),Object.defineProperty(d.prototype,"offset",{enumerable:!0,get:function(){if(d.isBuffer(this))return this.byteOffset}}),d.poolSize=8192,d.from=function(e,t,r){return h(e,t,r)},Object.setPrototypeOf(d.prototype,a.prototype),Object.setPrototypeOf(d,a),d.alloc=function(e,t,r){return function(e,t,r){return p(e),e<=0?u(e):void 0!==t?"string"==typeof r?u(e).fill(t,r):u(e).fill(t):u(e)}(e,t,r)},d.allocUnsafe=function(e){return f(e)},d.allocUnsafeSlow=function(e){return f(e)},d.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==d.prototype},d.compare=function(e,t){if(X(e,a)&&(e=d.from(e,e.offset,e.byteLength)),X(t,a)&&(t=d.from(t,t.offset,t.byteLength)),!d.isBuffer(e)||!d.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},d.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},d.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return d.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=d.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(X(t,a))i+t.length>n.length?(d.isBuffer(t)||(t=d.from(t)),t.copy(n,i)):a.prototype.set.call(n,t,i);else{if(!d.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},d.byteLength=b,d.prototype._isBuffer=!0,d.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)w(this,t,t+1);return this},d.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},d.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},d.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):v.apply(this,arguments)},d.prototype.toLocaleString=d.prototype.toString,d.prototype.equals=function(e){if(!d.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===d.compare(this,e)},d.prototype.inspect=function(){let t="";const r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},i&&(d.prototype[i]=d.prototype.inspect),d.prototype.compare=function(e,t,r,n,i){if(X(e,a)&&(e=d.from(e,e.offset,e.byteLength)),!d.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0);const c=Math.min(o,s),u=this.slice(n,i),l=e.slice(t,r);for(let a=0;a<c;++a)if(u[a]!==l[a]){o=u[a],s=l[a];break}return o<s?-1:s<o?1:0},d.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},d.prototype.indexOf=function(e,t,r){return _(this,e,t,r,!0)},d.prototype.lastIndexOf=function(e,t,r){return _(this,e,t,r,!1)},d.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return I(this,e,t,r);case"utf8":case"utf-8":return T(this,e,t,r);case"ascii":case"latin1":case"binary":return A(this,e,t,r);case"base64":return E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},d.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const O=4096;function $(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function C(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function M(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let o=t;o<r;++o)i+=ee[e[o]];return i}function P(e,t,r){const n=e.slice(t,r);let i="";for(let o=0;o<n.length-1;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function N(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function B(e,t,r,n,i,o){if(!d.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function D(e,t,r,n,i){G(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function L(e,t,r,n,i){G(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function j(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function q(e,t,r,i,o){return t=+t,r>>>=0,o||j(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function F(e,t,r,i,o){return t=+t,r>>>=0,o||j(e,0,r,8),n.write(e,t,r,i,52,8),r+8}d.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,d.prototype),n},d.prototype.readUintLE=d.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return n},d.prototype.readUintBE=d.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},d.prototype.readUint8=d.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},d.prototype.readUint16LE=d.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},d.prototype.readUint16BE=d.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},d.prototype.readUint32LE=d.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},d.prototype.readUint32BE=d.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},d.prototype.readBigUInt64LE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))})),d.prototype.readBigUInt64BE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)})),d.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},d.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},d.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},d.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},d.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},d.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},d.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},d.prototype.readBigInt64LE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),d.prototype.readBigInt64BE=te((function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),d.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!0,23,4)},d.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!1,23,4)},d.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!0,52,8)},d.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!1,52,8)},d.prototype.writeUintLE=d.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){B(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r},d.prototype.writeUintBE=d.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){B(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},d.prototype.writeUint8=d.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,1,255,0),this[t]=255&e,t+1},d.prototype.writeUint16LE=d.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeUint16BE=d.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeUint32LE=d.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},d.prototype.writeUint32BE=d.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},d.prototype.writeBigUInt64LE=te((function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),d.prototype.writeBigUInt64BE=te((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),d.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);B(this,e,t,r,n-1,-n)}let i=0,o=1,a=0;for(this[t]=255&e;++i<r&&(o*=256);)e<0&&0===a&&0!==this[t+i-1]&&(a=1),this[t+i]=(e/o|0)-a&255;return t+r},d.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);B(this,e,t,r,n-1,-n)}let i=r-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o|0)-a&255;return t+r},d.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},d.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},d.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},d.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},d.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||B(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},d.prototype.writeBigInt64LE=te((function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),d.prototype.writeBigInt64BE=te((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),d.prototype.writeFloatLE=function(e,t,r){return q(this,e,t,!0,r)},d.prototype.writeFloatBE=function(e,t,r){return q(this,e,t,!1,r)},d.prototype.writeDoubleLE=function(e,t,r){return F(this,e,t,!0,r)},d.prototype.writeDoubleBE=function(e,t,r){return F(this,e,t,!1,r)},d.prototype.copy=function(e,t,r,n){if(!d.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const i=n-r;return this===e&&"function"==typeof a.prototype.copyWithin?this.copyWithin(t,r,n):a.prototype.set.call(e,this.subarray(r,n),t),i},d.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!d.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const o=d.isBuffer(e)?e:d.from(e,n),a=o.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};const U={};function K(e,t,r){U[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function H(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function G(e,t,r,n,i,o){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let n;throw n=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new U.ERR_OUT_OF_RANGE("value",n,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(n,i,o)}function z(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw z(e,r),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}K("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),K("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),K("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=H(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=H(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n}),RangeError);const Z=/[^+/0-9A-Za-z-_]/g;function W(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let a=0;a<n;++a){if(r=e.charCodeAt(a),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(Z,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const ee=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function te(e){return"undefined"==typeof BigInt?re:e}function re(){throw new Error("BigInt not supported")}}(t);const d=t.Buffer;e.Blob=t.Blob,e.BlobOptions=t.BlobOptions,e.Buffer=t.Buffer,e.File=t.File,e.FileOptions=t.FileOptions,e.INSPECT_MAX_BYTES=t.INSPECT_MAX_BYTES,e.SlowBuffer=t.SlowBuffer,e.TranscodeEncoding=t.TranscodeEncoding,e.atob=t.atob,e.btoa=t.btoa,e.constants=t.constants,e.default=d,e.isAscii=t.isAscii,e.isUtf8=t.isUtf8,e.kMaxLength=t.kMaxLength,e.kStringMaxLength=t.kStringMaxLength,e.resolveObjectURL=t.resolveObjectURL,e.transcode=t.transcode}(dist)),dist}var events={exports:{}},hasRequiredEvents;function requireEvents(){if(hasRequiredEvents)return events.exports;hasRequiredEvents=1;var e,t="object"==typeof Reflect?Reflect:null,r=t&&"function"==typeof t.apply?t.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}events.exports=i,events.exports.once=function(e,t){return new Promise((function(r,n){function i(r){e.removeListener(t,o),n(r)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),r([].slice.call(arguments))}f(e,t,o,{once:!0}),"error"!==t&&function(e,t,r){"function"==typeof e.on&&f(e,"error",t,r)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,r,n){var i,o,c,u;if(a(r),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),c=o[t]),void 0===c)c=o[t]=r,++e._eventsCount;else if("function"==typeof c?c=o[t]=n?[r,c]:[c,r]:n?c.unshift(r):c.push(r),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,u=l,console&&console.warn&&console.warn(u)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=u.bind(n);return i.listener=r,n.wrapFn=i,i}function d(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(i):p(i,i.length)}function h(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function p(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function f(e,t,r,n){if("function"==typeof e.on)n.once?e.once(t,r):e.on(t,r);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){n.once&&e.removeEventListener(t,i),r(o)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)r(c,this,t);else{var u=c.length,l=p(c,u);for(n=0;n<u;++n)r(l[n],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return a(t),this.on(e,l(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,l(this,e,t)),this},i.prototype.removeListener=function(e,t){var r,n,i,o,s;if(a(t),void 0===(n=this._events))return this;if(void 0===(r=n[e]))return this;if(r===t||r.listener===t)0===--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,o=r.length-1;o>=0;o--)if(r[o]===t||r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0===--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,o=Object.keys(r);for(n=0;n<o.length;++n)"removeListener"!==(i=o[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},i.prototype.listeners=function(e){return d(this,e,!0)},i.prototype.rawListeners=function(e){return d(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},i.prototype.listenerCount=h,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},events.exports}var string_decoder={},safeBuffer={exports:{}},hasRequiredSafeBuffer,hasRequiredString_decoder;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function(e,t){var r=requireDist(),n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}(safeBuffer,safeBuffer.exports)),safeBuffer.exports}function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var e=requireSafeBuffer().Buffer,t=e.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r(r){var n;switch(this.encoding=function(r){var n=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(r);if("string"!=typeof n&&(e.isEncoding===t||!t(r)))throw new Error("Unknown encoding: "+r);return n||r}(r),this.encoding){case"utf16le":this.text=o,this.end=a,n=4;break;case"utf8":this.fillLast=i,n=4;break;case"base64":this.text=s,this.end=c,n=3;break;default:return this.write=u,void(this.end=l)}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(n)}function n(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function i(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function o(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function a(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function s(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function c(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function u(e){return e.toString(this.encoding)}function l(e){return e&&e.length?this.write(e):""}return string_decoder.StringDecoder=r,r.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},r.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},r.prototype.text=function(e,t){var r=function(e,t,r){var i=t.length-1;if(i<r)return 0;var o=n(t[i]);if(o>=0)return o>0&&(e.lastNeed=o-1),o;if(--i<r||-2===o)return 0;if(o=n(t[i]),o>=0)return o>0&&(e.lastNeed=o-2),o;if(--i<r||-2===o)return 0;if(o=n(t[i]),o>=0)return o>0&&(2===o?o=0:e.lastNeed=o-3),o;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var i=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},r.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length},string_decoder}var inherits_browser={exports:{}},hasRequiredInherits_browser,streamBrowser,hasRequiredStreamBrowser;function requireInherits_browser(){return hasRequiredInherits_browser||(hasRequiredInherits_browser=1,"function"==typeof Object.create?inherits_browser.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),inherits_browser.exports}function requireStreamBrowser(){return hasRequiredStreamBrowser?streamBrowser:(hasRequiredStreamBrowser=1,streamBrowser=requireEvents().EventEmitter)}var util={},types={},shams$1,hasRequiredShams$1,shams,hasRequiredShams,esObjectAtoms,hasRequiredEsObjectAtoms,esErrors,hasRequiredEsErrors,_eval,hasRequired_eval,range,hasRequiredRange,ref,hasRequiredRef,syntax,hasRequiredSyntax,type,hasRequiredType,uri,hasRequiredUri,abs,hasRequiredAbs,floor,hasRequiredFloor,max,hasRequiredMax,min,hasRequiredMin,pow,hasRequiredPow,round,hasRequiredRound,_isNaN,hasRequired_isNaN,sign,hasRequiredSign,gOPD,hasRequiredGOPD,gopd,hasRequiredGopd,esDefineProperty,hasRequiredEsDefineProperty,hasSymbols,hasRequiredHasSymbols,Reflect_getPrototypeOf,hasRequiredReflect_getPrototypeOf,Object_getPrototypeOf,hasRequiredObject_getPrototypeOf,implementation,hasRequiredImplementation,functionBind,hasRequiredFunctionBind,functionCall,hasRequiredFunctionCall,functionApply,hasRequiredFunctionApply,reflectApply,hasRequiredReflectApply,actualApply,hasRequiredActualApply,callBindApplyHelpers,hasRequiredCallBindApplyHelpers,get,hasRequiredGet,getProto,hasRequiredGetProto,hasown,hasRequiredHasown,getIntrinsic,hasRequiredGetIntrinsic,callBound,hasRequiredCallBound,isArguments,hasRequiredIsArguments,isRegex,hasRequiredIsRegex,safeRegexTest,hasRequiredSafeRegexTest,isGeneratorFunction,hasRequiredIsGeneratorFunction,isCallable,hasRequiredIsCallable,forEach_1,hasRequiredForEach,possibleTypedArrayNames,hasRequiredPossibleTypedArrayNames,availableTypedArrays,hasRequiredAvailableTypedArrays;function requireShams$1(){return hasRequiredShams$1?shams$1:(hasRequiredShams$1=1,shams$1=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0})}function requireShams(){if(hasRequiredShams)return shams;hasRequiredShams=1;var e=requireShams$1();return shams=function(){return e()&&!!Symbol.toStringTag}}function requireEsObjectAtoms(){return hasRequiredEsObjectAtoms?esObjectAtoms:(hasRequiredEsObjectAtoms=1,esObjectAtoms=Object)}function requireEsErrors(){return hasRequiredEsErrors?esErrors:(hasRequiredEsErrors=1,esErrors=Error)}function require_eval(){return hasRequired_eval?_eval:(hasRequired_eval=1,_eval=EvalError)}function requireRange(){return hasRequiredRange?range:(hasRequiredRange=1,range=RangeError)}function requireRef(){return hasRequiredRef?ref:(hasRequiredRef=1,ref=ReferenceError)}function requireSyntax(){return hasRequiredSyntax?syntax:(hasRequiredSyntax=1,syntax=SyntaxError)}function requireType(){return hasRequiredType?type:(hasRequiredType=1,type=TypeError)}function requireUri(){return hasRequiredUri?uri:(hasRequiredUri=1,uri=URIError)}function requireAbs(){return hasRequiredAbs?abs:(hasRequiredAbs=1,abs=Math.abs)}function requireFloor(){return hasRequiredFloor?floor:(hasRequiredFloor=1,floor=Math.floor)}function requireMax(){return hasRequiredMax?max:(hasRequiredMax=1,max=Math.max)}function requireMin(){return hasRequiredMin?min:(hasRequiredMin=1,min=Math.min)}function requirePow(){return hasRequiredPow?pow:(hasRequiredPow=1,pow=Math.pow)}function requireRound(){return hasRequiredRound?round:(hasRequiredRound=1,round=Math.round)}function require_isNaN(){return hasRequired_isNaN?_isNaN:(hasRequired_isNaN=1,_isNaN=Number.isNaN||function(e){return e!=e})}function requireSign(){if(hasRequiredSign)return sign;hasRequiredSign=1;var e=require_isNaN();return sign=function(t){return e(t)||0===t?t:t<0?-1:1}}function requireGOPD(){return hasRequiredGOPD?gOPD:(hasRequiredGOPD=1,gOPD=Object.getOwnPropertyDescriptor)}function requireGopd(){if(hasRequiredGopd)return gopd;hasRequiredGopd=1;var e=requireGOPD();if(e)try{e([],"length")}catch(t){e=null}return gopd=e}function requireEsDefineProperty(){if(hasRequiredEsDefineProperty)return esDefineProperty;hasRequiredEsDefineProperty=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch(t){e=!1}return esDefineProperty=e}function requireHasSymbols(){if(hasRequiredHasSymbols)return hasSymbols;hasRequiredHasSymbols=1;var e="undefined"!=typeof Symbol&&Symbol,t=requireShams$1();return hasSymbols=function(){return"function"==typeof e&&("function"==typeof Symbol&&("symbol"==typeof e("foo")&&("symbol"==typeof Symbol("bar")&&t())))}}function requireReflect_getPrototypeOf(){return hasRequiredReflect_getPrototypeOf?Reflect_getPrototypeOf:(hasRequiredReflect_getPrototypeOf=1,Reflect_getPrototypeOf="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function requireObject_getPrototypeOf(){return hasRequiredObject_getPrototypeOf?Object_getPrototypeOf:(hasRequiredObject_getPrototypeOf=1,Object_getPrototypeOf=requireEsObjectAtoms().getPrototypeOf||null)}function requireImplementation(){if(hasRequiredImplementation)return implementation;hasRequiredImplementation=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return implementation=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var o,a=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),s=t(0,i.length-a.length),c=[],u=0;u<s;u++)c[u]="$"+u;if(o=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(c,",")+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof o){var e=i.apply(this,r(a,arguments));return Object(e)===e?e:this}return i.apply(n,r(a,arguments))})),i.prototype){var l=function(){};l.prototype=i.prototype,o.prototype=new l,l.prototype=null}return o},implementation}function requireFunctionBind(){if(hasRequiredFunctionBind)return functionBind;hasRequiredFunctionBind=1;var e=requireImplementation();return functionBind=Function.prototype.bind||e}function requireFunctionCall(){return hasRequiredFunctionCall?functionCall:(hasRequiredFunctionCall=1,functionCall=Function.prototype.call)}function requireFunctionApply(){return hasRequiredFunctionApply?functionApply:(hasRequiredFunctionApply=1,functionApply=Function.prototype.apply)}function requireReflectApply(){return hasRequiredReflectApply?reflectApply:(hasRequiredReflectApply=1,reflectApply="undefined"!=typeof Reflect&&Reflect&&Reflect.apply)}function requireActualApply(){if(hasRequiredActualApply)return actualApply;hasRequiredActualApply=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireFunctionCall(),n=requireReflectApply();return actualApply=n||e.call(r,t)}function requireCallBindApplyHelpers(){if(hasRequiredCallBindApplyHelpers)return callBindApplyHelpers;hasRequiredCallBindApplyHelpers=1;var e=requireFunctionBind(),t=requireType(),r=requireFunctionCall(),n=requireActualApply();return callBindApplyHelpers=function(i){if(i.length<1||"function"!=typeof i[0])throw new t("a function is required");return n(e,r,i)}}function requireGet(){if(hasRequiredGet)return get;hasRequiredGet=1;var e,t=requireCallBindApplyHelpers(),r=requireGopd();try{e=[].__proto__===Array.prototype}catch(a){if(!a||"object"!=typeof a||!("code"in a)||"ERR_PROTO_ACCESS"!==a.code)throw a}var n=!!e&&r&&r(Object.prototype,"__proto__"),i=Object,o=i.getPrototypeOf;return get=n&&"function"==typeof n.get?t([n.get]):"function"==typeof o&&function(e){return o(null==e?e:i(e))}}function requireGetProto(){if(hasRequiredGetProto)return getProto;hasRequiredGetProto=1;var e=requireReflect_getPrototypeOf(),t=requireObject_getPrototypeOf(),r=requireGet();return getProto=e?function(t){return e(t)}:t?function(e){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("getProto: not an object");return t(e)}:r?function(e){return r(e)}:null}function requireHasown(){if(hasRequiredHasown)return hasown;hasRequiredHasown=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=requireFunctionBind();return hasown=r.call(e,t)}function requireGetIntrinsic(){if(hasRequiredGetIntrinsic)return getIntrinsic;var e;hasRequiredGetIntrinsic=1;var t=requireEsObjectAtoms(),r=requireEsErrors(),n=require_eval(),i=requireRange(),o=requireRef(),a=requireSyntax(),s=requireType(),c=requireUri(),u=requireAbs(),l=requireFloor(),d=requireMax(),h=requireMin(),p=requirePow(),f=requireRound(),m=requireSign(),g=Function,y=function(e){try{return g('"use strict"; return ('+e+").constructor;")()}catch(t){}},b=requireGopd(),v=requireEsDefineProperty(),w=function(){throw new s},_=b?function(){try{return w}catch(e){try{return b(arguments,"callee").get}catch(t){return w}}}():w,k=requireHasSymbols()(),I=requireGetProto(),T=requireObject_getPrototypeOf(),A=requireReflect_getPrototypeOf(),E=requireFunctionApply(),S=requireFunctionCall(),x={},R="undefined"!=typeof Uint8Array&&I?I(Uint8Array):e,O={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?e:ArrayBuffer,"%ArrayIteratorPrototype%":k&&I?I([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":x,"%AsyncGenerator%":x,"%AsyncGeneratorFunction%":x,"%AsyncIteratorPrototype%":x,"%Atomics%":"undefined"==typeof Atomics?e:Atomics,"%BigInt%":"undefined"==typeof BigInt?e:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?e:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float32Array%":"undefined"==typeof Float32Array?e:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?e:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?e:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":x,"%Int8Array%":"undefined"==typeof Int8Array?e:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?e:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":k&&I?I(I([][Symbol.iterator]())):e,"%JSON%":"object"==typeof JSON?JSON:e,"%Map%":"undefined"==typeof Map?e:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&k&&I?I((new Map)[Symbol.iterator]()):e,"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?e:Promise,"%Proxy%":"undefined"==typeof Proxy?e:Proxy,"%RangeError%":i,"%ReferenceError%":o,"%Reflect%":"undefined"==typeof Reflect?e:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?e:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&k&&I?I((new Set)[Symbol.iterator]()):e,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":k&&I?I(""[Symbol.iterator]()):e,"%Symbol%":k?Symbol:e,"%SyntaxError%":a,"%ThrowTypeError%":_,"%TypedArray%":R,"%TypeError%":s,"%Uint8Array%":"undefined"==typeof Uint8Array?e:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?e:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?e:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?e:Uint32Array,"%URIError%":c,"%WeakMap%":"undefined"==typeof WeakMap?e:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?e:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?e:WeakSet,"%Function.prototype.call%":S,"%Function.prototype.apply%":E,"%Object.defineProperty%":v,"%Object.getPrototypeOf%":T,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":d,"%Math.min%":h,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":m,"%Reflect.getPrototypeOf%":A};if(I)try{null.error}catch(H){var $=I(I(H));O["%Error.prototype%"]=$}var C=function e(t){var r;if("%AsyncFunction%"===t)r=y("async function () {}");else if("%GeneratorFunction%"===t)r=y("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=y("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&I&&(r=I(i.prototype))}return O[t]=r,r},M={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},P=requireFunctionBind(),N=requireHasown(),B=P.call(S,Array.prototype.concat),D=P.call(E,Array.prototype.splice),L=P.call(S,String.prototype.replace),j=P.call(S,String.prototype.slice),q=P.call(S,RegExp.prototype.exec),F=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,U=/\\(\\)?/g,K=function(e,t){var r,n=e;if(N(M,n)&&(n="%"+(r=M[n])[0]+"%"),N(O,n)){var i=O[n];if(i===x&&(i=C(n)),void 0===i&&!t)throw new s("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new a("intrinsic "+e+" does not exist!")};return getIntrinsic=function(e,t){if("string"!=typeof e||0===e.length)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new s('"allowMissing" argument must be a boolean');if(null===q(/^%?[^%]*%?$/,e))throw new a("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=j(e,0,1),r=j(e,-1);if("%"===t&&"%"!==r)throw new a("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new a("invalid intrinsic syntax, expected opening `%`");var n=[];return L(e,F,(function(e,t,r,i){n[n.length]=r?L(i,U,"$1"):t||e})),n}(e),n=r.length>0?r[0]:"",i=K("%"+n+"%",t),o=i.name,c=i.value,u=!1,l=i.alias;l&&(n=l[0],D(r,B([0,1],l)));for(var d=1,h=!0;d<r.length;d+=1){var p=r[d],f=j(p,0,1),m=j(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===m||"'"===m||"`"===m)&&f!==m)throw new a("property names with quotes must have matching quotes");if("constructor"!==p&&h||(u=!0),N(O,o="%"+(n+="."+p)+"%"))c=O[o];else if(null!=c){if(!(p in c)){if(!t)throw new s("base intrinsic for "+e+" exists, but the property is not available.");return}if(b&&d+1>=r.length){var g=b(c,p);c=(h=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:c[p]}else h=N(c,p),c=c[p];h&&!u&&(O[o]=c)}}return c},getIntrinsic}function requireCallBound(){if(hasRequiredCallBound)return callBound;hasRequiredCallBound=1;var e=requireGetIntrinsic(),t=requireCallBindApplyHelpers(),r=t([e("%String.prototype.indexOf%")]);return callBound=function(n,i){var o=e(n,!!i);return"function"==typeof o&&r(n,".prototype.")>-1?t([o]):o}}function requireIsArguments(){if(hasRequiredIsArguments)return isArguments;hasRequiredIsArguments=1;var e=requireShams()(),t=requireCallBound()("Object.prototype.toString"),r=function(r){return!(e&&r&&"object"==typeof r&&Symbol.toStringTag in r)&&"[object Arguments]"===t(r)},n=function(e){return!!r(e)||null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==t(e)&&"callee"in e&&"[object Function]"===t(e.callee)},i=function(){return r(arguments)}();return r.isLegacyArguments=n,isArguments=i?r:n}function requireIsRegex(){if(hasRequiredIsRegex)return isRegex;hasRequiredIsRegex=1;var e,t=requireCallBound(),r=requireShams()(),n=requireHasown(),i=requireGopd();if(r){var o=t("RegExp.prototype.exec"),a={},s=function(){throw a},c={toString:s,valueOf:s};"symbol"==typeof Symbol.toPrimitive&&(c[Symbol.toPrimitive]=s),e=function(e){if(!e||"object"!=typeof e)return!1;var t=i(e,"lastIndex");if(!(t&&n(t,"value")))return!1;try{o(e,c)}catch(r){return r===a}}}else{var u=t("Object.prototype.toString");e=function(e){return!(!e||"object"!=typeof e&&"function"!=typeof e)&&"[object RegExp]"===u(e)}}return isRegex=e}function requireSafeRegexTest(){if(hasRequiredSafeRegexTest)return safeRegexTest;hasRequiredSafeRegexTest=1;var e=requireCallBound(),t=requireIsRegex(),r=e("RegExp.prototype.exec"),n=requireType();return safeRegexTest=function(e){if(!t(e))throw new n("`regex` must be a RegExp");return function(t){return null!==r(e,t)}}}function requireIsGeneratorFunction(){if(hasRequiredIsGeneratorFunction)return isGeneratorFunction;hasRequiredIsGeneratorFunction=1;var e,t=requireCallBound(),r=requireSafeRegexTest()(/^\s*(?:function)?\*/),n=requireShams()(),i=requireGetProto(),o=t("Object.prototype.toString"),a=t("Function.prototype.toString");return isGeneratorFunction=function(t){if("function"!=typeof t)return!1;if(r(a(t)))return!0;if(!n)return"[object GeneratorFunction]"===o(t);if(!i)return!1;if(void 0===e){var s=function(){if(!n)return!1;try{return Function("return function*() {}")()}catch(e){}}();e=!!s&&i(s)}return i(t)===e}}function requireIsCallable(){if(hasRequiredIsCallable)return isCallable;hasRequiredIsCallable=1;var e,t,r=Function.prototype.toString,n="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof n&&"function"==typeof Object.defineProperty)try{e=Object.defineProperty({},"length",{get:function(){throw t}}),t={},n((function(){throw 42}),null,e)}catch(h){h!==t&&(n=null)}else n=null;var i=/^\s*class\b/,o=function(e){try{var t=r.call(e);return i.test(t)}catch(n){return!1}},a=function(e){try{return!o(e)&&(r.call(e),!0)}catch(t){return!1}},s=Object.prototype.toString,c="function"==typeof Symbol&&!!Symbol.toStringTag,u=!(0 in[,]),l=function(){return!1};if("object"==typeof document){var d=document.all;s.call(d)===s.call(document.all)&&(l=function(e){if((u||!e)&&(void 0===e||"object"==typeof e))try{var t=s.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(r){}return!1})}return isCallable=n?function(r){if(l(r))return!0;if(!r)return!1;if("function"!=typeof r&&"object"!=typeof r)return!1;try{n(r,null,e)}catch(i){if(i!==t)return!1}return!o(r)&&a(r)}:function(e){if(l(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(c)return a(e);if(o(e))return!1;var t=s.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&a(e)}}function requireForEach(){if(hasRequiredForEach)return forEach_1;hasRequiredForEach=1;var e=requireIsCallable(),t=Object.prototype.toString,r=Object.prototype.hasOwnProperty;return forEach_1=function(n,i,o){if(!e(i))throw new TypeError("iterator must be a function");var a;arguments.length>=3&&(a=o),"[object Array]"===t.call(n)?function(e,t,n){for(var i=0,o=e.length;i<o;i++)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,a):"string"==typeof n?function(e,t,r){for(var n=0,i=e.length;n<i;n++)null==r?t(e.charAt(n),n,e):t.call(r,e.charAt(n),n,e)}(n,i,a):function(e,t,n){for(var i in e)r.call(e,i)&&(null==n?t(e[i],i,e):t.call(n,e[i],i,e))}(n,i,a)},forEach_1}function requirePossibleTypedArrayNames(){return hasRequiredPossibleTypedArrayNames?possibleTypedArrayNames:(hasRequiredPossibleTypedArrayNames=1,possibleTypedArrayNames=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"])}function requireAvailableTypedArrays(){if(hasRequiredAvailableTypedArrays)return availableTypedArrays;hasRequiredAvailableTypedArrays=1;var e=requirePossibleTypedArrayNames(),t="undefined"==typeof globalThis?commonjsGlobal:globalThis;return availableTypedArrays=function(){for(var r=[],n=0;n<e.length;n++)"function"==typeof t[e[n]]&&(r[r.length]=e[n]);return r}}var callBind={exports:{}},defineDataProperty,hasRequiredDefineDataProperty,hasPropertyDescriptors_1,hasRequiredHasPropertyDescriptors,setFunctionLength,hasRequiredSetFunctionLength,applyBind,hasRequiredApplyBind,hasRequiredCallBind,whichTypedArray,hasRequiredWhichTypedArray,isTypedArray,hasRequiredIsTypedArray,hasRequiredTypes,isBufferBrowser,hasRequiredIsBufferBrowser,hasRequiredUtil,buffer_list,hasRequiredBuffer_list,destroy_1,hasRequiredDestroy;function requireDefineDataProperty(){if(hasRequiredDefineDataProperty)return defineDataProperty;hasRequiredDefineDataProperty=1;var e=requireEsDefineProperty(),t=requireSyntax(),r=requireType(),n=requireGopd();return defineDataProperty=function(i,o,a){if(!i||"object"!=typeof i&&"function"!=typeof i)throw new r("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new r("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,l=arguments.length>6&&arguments[6],d=!!n&&n(i,o);if(e)e(i,o,{configurable:null===u&&d?d.configurable:!u,enumerable:null===s&&d?d.enumerable:!s,value:a,writable:null===c&&d?d.writable:!c});else{if(!l&&(s||c||u))throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");i[o]=a}},defineDataProperty}function requireHasPropertyDescriptors(){if(hasRequiredHasPropertyDescriptors)return hasPropertyDescriptors_1;hasRequiredHasPropertyDescriptors=1;var e=requireEsDefineProperty(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return 1!==e([],"length",{value:1}).length}catch(t){return!0}},hasPropertyDescriptors_1=t}function requireSetFunctionLength(){if(hasRequiredSetFunctionLength)return setFunctionLength;hasRequiredSetFunctionLength=1;var e=requireGetIntrinsic(),t=requireDefineDataProperty(),r=requireHasPropertyDescriptors()(),n=requireGopd(),i=requireType(),o=e("%Math.floor%");return setFunctionLength=function(e,a){if("function"!=typeof e)throw new i("`fn` is not a function");if("number"!=typeof a||a<0||a>4294967295||o(a)!==a)throw new i("`length` must be a positive 32-bit integer");var s=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in e&&n){var l=n(e,"length");l&&!l.configurable&&(c=!1),l&&!l.writable&&(u=!1)}return(c||u||!s)&&(r?t(e,"length",a,!0,!0):t(e,"length",a)),e},setFunctionLength}function requireApplyBind(){if(hasRequiredApplyBind)return applyBind;hasRequiredApplyBind=1;var e=requireFunctionBind(),t=requireFunctionApply(),r=requireActualApply();return applyBind=function(){return r(e,t,arguments)},applyBind}function requireCallBind(){return hasRequiredCallBind||(hasRequiredCallBind=1,e=callBind,t=requireSetFunctionLength(),r=requireEsDefineProperty(),n=requireCallBindApplyHelpers(),i=requireApplyBind(),e.exports=function(e){var r=n(arguments),i=e.length-(arguments.length-1);return t(r,1+(i>0?i:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i),callBind.exports;var e,t,r,n,i}function requireWhichTypedArray(){if(hasRequiredWhichTypedArray)return whichTypedArray;hasRequiredWhichTypedArray=1;var e=requireForEach(),t=requireAvailableTypedArrays(),r=requireCallBind(),n=requireCallBound(),i=requireGopd(),o=n("Object.prototype.toString"),a=requireShams()(),s="undefined"==typeof globalThis?commonjsGlobal:globalThis,c=t(),u=n("String.prototype.slice"),l=Object.getPrototypeOf,d=n("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r<e.length;r+=1)if(e[r]===t)return r;return-1},h={__proto__:null};e(c,a&&i&&l?function(e){var t=new s[e];if(Symbol.toStringTag in t){var n=l(t),o=i(n,Symbol.toStringTag);if(!o){var a=l(n);o=i(a,Symbol.toStringTag)}h["$"+e]=r(o.get)}}:function(e){var t=new s[e],n=t.slice||t.set;n&&(h["$"+e]=r(n))});return whichTypedArray=function(t){if(!t||"object"!=typeof t)return!1;if(!a){var r=u(o(t),8,-1);return d(c,r)>-1?r:"Object"===r&&function(t){var r=!1;return e(h,(function(e,n){if(!r)try{e(t),r=u(n,1)}catch(i){}})),r}(t)}return i?function(t){var r=!1;return e(h,(function(e,n){if(!r)try{"$"+e(t)===n&&(r=u(n,1))}catch(i){}})),r}(t):null}}function requireIsTypedArray(){if(hasRequiredIsTypedArray)return isTypedArray;hasRequiredIsTypedArray=1;var e=requireWhichTypedArray();return isTypedArray=function(t){return!!e(t)}}function requireTypes(){return hasRequiredTypes||(hasRequiredTypes=1,function(e){var t=requireIsArguments(),r=requireIsGeneratorFunction(),n=requireWhichTypedArray(),i=requireIsTypedArray();function o(e){return e.call.bind(e)}var a="undefined"!=typeof BigInt,s="undefined"!=typeof Symbol,c=o(Object.prototype.toString),u=o(Number.prototype.valueOf),l=o(String.prototype.valueOf),d=o(Boolean.prototype.valueOf);if(a)var h=o(BigInt.prototype.valueOf);if(s)var p=o(Symbol.prototype.valueOf);function f(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(r){return!1}}function m(e){return"[object Map]"===c(e)}function g(e){return"[object Set]"===c(e)}function y(e){return"[object WeakMap]"===c(e)}function b(e){return"[object WeakSet]"===c(e)}function v(e){return"[object ArrayBuffer]"===c(e)}function w(e){return"undefined"!=typeof ArrayBuffer&&(v.working?v(e):e instanceof ArrayBuffer)}function _(e){return"[object DataView]"===c(e)}function k(e){return"undefined"!=typeof DataView&&(_.working?_(e):e instanceof DataView)}e.isArgumentsObject=t,e.isGeneratorFunction=r,e.isTypedArray=i,e.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},e.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):i(e)||k(e)},e.isUint8Array=function(e){return"Uint8Array"===n(e)},e.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===n(e)},e.isUint16Array=function(e){return"Uint16Array"===n(e)},e.isUint32Array=function(e){return"Uint32Array"===n(e)},e.isInt8Array=function(e){return"Int8Array"===n(e)},e.isInt16Array=function(e){return"Int16Array"===n(e)},e.isInt32Array=function(e){return"Int32Array"===n(e)},e.isFloat32Array=function(e){return"Float32Array"===n(e)},e.isFloat64Array=function(e){return"Float64Array"===n(e)},e.isBigInt64Array=function(e){return"BigInt64Array"===n(e)},e.isBigUint64Array=function(e){return"BigUint64Array"===n(e)},m.working="undefined"!=typeof Map&&m(new Map),e.isMap=function(e){return"undefined"!=typeof Map&&(m.working?m(e):e instanceof Map)},g.working="undefined"!=typeof Set&&g(new Set),e.isSet=function(e){return"undefined"!=typeof Set&&(g.working?g(e):e instanceof Set)},y.working="undefined"!=typeof WeakMap&&y(new WeakMap),e.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(y.working?y(e):e instanceof WeakMap)},b.working="undefined"!=typeof WeakSet&&b(new WeakSet),e.isWeakSet=function(e){return b(e)},v.working="undefined"!=typeof ArrayBuffer&&v(new ArrayBuffer),e.isArrayBuffer=w,_.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&_(new DataView(new ArrayBuffer(1),0,1)),e.isDataView=k;var I="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function T(e){return"[object SharedArrayBuffer]"===c(e)}function A(e){return void 0!==I&&(void 0===T.working&&(T.working=T(new I)),T.working?T(e):e instanceof I)}function E(e){return f(e,u)}function S(e){return f(e,l)}function x(e){return f(e,d)}function R(e){return a&&f(e,h)}function O(e){return s&&f(e,p)}e.isSharedArrayBuffer=A,e.isAsyncFunction=function(e){return"[object AsyncFunction]"===c(e)},e.isMapIterator=function(e){return"[object Map Iterator]"===c(e)},e.isSetIterator=function(e){return"[object Set Iterator]"===c(e)},e.isGeneratorObject=function(e){return"[object Generator]"===c(e)},e.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===c(e)},e.isNumberObject=E,e.isStringObject=S,e.isBooleanObject=x,e.isBigIntObject=R,e.isSymbolObject=O,e.isBoxedPrimitive=function(e){return E(e)||S(e)||x(e)||R(e)||O(e)},e.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(w(e)||A(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(t){Object.defineProperty(e,t,{enumerable:!1,value:function(){throw new Error(t+" is not supported in userland")}})}))}(types)),types}function requireIsBufferBrowser(){return hasRequiredIsBufferBrowser?isBufferBrowser:(hasRequiredIsBufferBrowser=1,isBufferBrowser=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8})}function requireUtil(){return hasRequiredUtil||(hasRequiredUtil=1,function(e){var t=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n<t.length;n++)r[t[n]]=Object.getOwnPropertyDescriptor(e,t[n]);return r},r=/%[sdj%]/g;e.format=function(e){if(!g(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(a(arguments[n]));return t.join(" ")}n=1;for(var i=arguments,o=i.length,s=String(e).replace(r,(function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(t){return"[Circular]"}default:return e}})),c=i[n];n<o;c=i[++n])f(c)||!v(c)?s+=" "+c:s+=" "+a(c);return s},e.deprecate=function(t,r){if(void 0!==process$1&&!0===process$1.noDeprecation)return t;if(void 0===process$1)return function(){return e.deprecate(t,r).apply(this,arguments)};var n=!1;return function(){if(!n){if(process$1.throwDeprecation)throw new Error(r);process$1.traceDeprecation?console.trace(r):console.error(r),n=!0}return t.apply(this,arguments)}};var n={},i=/^$/;if(process$1.env.NODE_DEBUG){var o=process$1.env.NODE_DEBUG;o=o.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),i=new RegExp("^"+o+"$","i")}function a(t,r){var n={seen:[],stylize:c};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(r)?n.showHidden=r:r&&e._extend(n,r),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=s),u(n,t,n.depth)}function s(e,t){var r=a.styles[t];return r?"["+a.colors[r][0]+"m"+e+"["+a.colors[r][1]+"m":e}function c(e,t){return e}function u(t,r,n){if(t.customInspect&&r&&k(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,t);return g(i)||(i=u(t,i,n)),i}var o=function(e,t){if(y(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(m(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(f(t))return e.stylize("null","null")}(t,r);if(o)return o;var a=Object.keys(r),s=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(r)),_(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(r);if(0===a.length){if(k(r)){var c=r.name?": "+r.name:"";return t.stylize("[Function"+c+"]","special")}if(b(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(w(r))return t.stylize(Date.prototype.toString.call(r),"date");if(_(r))return l(r)}var v,I="",T=!1,A=["{","}"];(h(r)&&(T=!0,A=["[","]"]),k(r))&&(I=" [Function"+(r.name?": "+r.name:"")+"]");return b(r)&&(I=" "+RegExp.prototype.toString.call(r)),w(r)&&(I=" "+Date.prototype.toUTCString.call(r)),_(r)&&(I=" "+l(r)),0!==a.length||T&&0!=r.length?n<0?b(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),v=T?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a<s;++a)E(t,String(a))?o.push(d(e,t,r,n,String(a),!0)):o.push("");return i.forEach((function(i){i.match(/^\d+$/)||o.push(d(e,t,r,n,i,!0))})),o}(t,r,n,s,a):a.map((function(e){return d(t,r,n,s,e,T)})),t.seen.pop(),function(e,t,r){var n=e.reduce((function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(v,I,A)):A[0]+I+A[1]}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,i,o){var a,s,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(s=e.stylize("[Setter]","special")),E(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(c.value)<0?(s=f(r)?u(e,c.value,null):u(e,c.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),y(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.slice(1,-1),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function h(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function m(e){return"number"==typeof e}function g(e){return"string"==typeof e}function y(e){return void 0===e}function b(e){return v(e)&&"[object RegExp]"===I(e)}function v(e){return"object"==typeof e&&null!==e}function w(e){return v(e)&&"[object Date]"===I(e)}function _(e){return v(e)&&("[object Error]"===I(e)||e instanceof Error)}function k(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function T(e){return e<10?"0"+e.toString(10):e.toString(10)}e.debuglog=function(t){if(t=t.toUpperCase(),!n[t])if(i.test(t)){var r=process$1.pid;n[t]=function(){var n=e.format.apply(e,arguments);console.error("%s %d: %s",t,r,n)}}else n[t]=function(){};return n[t]},e.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.types=requireTypes(),e.isArray=h,e.isBoolean=p,e.isNull=f,e.isNullOrUndefined=function(e){return null==e},e.isNumber=m,e.isString=g,e.isSymbol=function(e){return"symbol"==typeof e},e.isUndefined=y,e.isRegExp=b,e.types.isRegExp=b,e.isObject=v,e.isDate=w,e.types.isDate=w,e.isError=_,e.types.isNativeError=_,e.isFunction=k,e.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},e.isBuffer=requireIsBufferBrowser();var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.log=function(){var t,r;console.log("%s - %s",(r=[T((t=new Date).getHours()),T(t.getMinutes()),T(t.getSeconds())].join(":"),[t.getDate(),A[t.getMonth()],r].join(" ")),e.format.apply(e,arguments))},e.inherits=requireInherits_browser(),e._extend=function(e,t){if(!t||!v(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var S="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function x(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}e.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(S&&e[S]){var r;if("function"!=typeof(r=e[S]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(r,S,{value:r,enumerable:!1,writable:!1,configurable:!0}),r}function r(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),i=[],o=0;o<arguments.length;o++)i.push(arguments[o]);i.push((function(e,n){e?r(e):t(n)}));try{e.apply(this,i)}catch(a){r(a)}return n}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),S&&Object.defineProperty(r,S,{value:r,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(r,t(e))},e.promisify.custom=S,e.callbackify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function r(){for(var t=[],r=0;r<arguments.length;r++)t.push(arguments[r]);var n=t.pop();if("function"!=typeof n)throw new TypeError("The last argument must be of type Function");var i=this,o=function(){return n.apply(i,arguments)};e.apply(this,t).then((function(e){process$1.nextTick(o.bind(null,null,e))}),(function(e){process$1.nextTick(x.bind(null,e,o))}))}return Object.setPrototypeOf(r,Object.getPrototypeOf(e)),Object.defineProperties(r,t(e)),r}}(util)),util}function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(e,t,r){return(t=i(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,t,r){return function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,i(n.key),n)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:String(t)}hasRequiredBuffer_list=1;var o=requireDist().Buffer,a=requireUtil().inspect,s=a&&a.custom||"inspect";return buffer_list=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return n(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t,r,n,i=o.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=i,n=s,o.prototype.copy.call(t,r,n),s+=a.data.length,a=a.next;return i}},{key:"consume",value:function(e,t){var r;return e<this.head.data.length?(r=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):r=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),r}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,r=1,n=t.data;for(e-=n.length;t=t.next;){var i=t.data,o=e>i.length?i.length:e;if(o===i.length?n+=i:n+=i.slice(0,e),0===(e-=o)){o===i.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var i=r.data,a=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,a),0===(e-=a)){a===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(a));break}++n}return this.length-=n,t}},{key:s,value:function(e,r){return a(this,t(t({},r),{},{depth:0,customInspect:!1}))}}]),e}()}function requireDestroy(){if(hasRequiredDestroy)return destroy_1;function e(e,n){r(e,n),t(e)}function t(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}return hasRequiredDestroy=1,destroy_1={destroy:function(n,i){var o=this,a=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return a||s?(i?i(n):n&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process$1.nextTick(r,this,n)):process$1.nextTick(r,this,n)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(n||null,(function(r){!i&&r?o._writableState?o._writableState.errorEmitted?process$1.nextTick(t,o):(o._writableState.errorEmitted=!0,process$1.nextTick(e,o,r)):process$1.nextTick(e,o,r):i?(process$1.nextTick(t,o),i(r)):process$1.nextTick(t,o)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}}var errorsBrowser={},hasRequiredErrorsBrowser,state,hasRequiredState,browser,hasRequiredBrowser,_stream_writable,hasRequired_stream_writable,_stream_duplex,hasRequired_stream_duplex,endOfStream,hasRequiredEndOfStream,async_iterator,hasRequiredAsync_iterator,fromBrowser,hasRequiredFromBrowser,_stream_readable,hasRequired_stream_readable,_stream_transform,hasRequired_stream_transform,_stream_passthrough,hasRequired_stream_passthrough,pipeline_1,hasRequiredPipeline,streamBrowserify,hasRequiredStreamBrowserify;function requireErrorsBrowser(){if(hasRequiredErrorsBrowser)return errorsBrowser;hasRequiredErrorsBrowser=1;var e={};function t(t,r,n){n||(n=Error);var i=function(e){var t,n;function i(t,n,i){return e.call(this,function(e,t,n){return"string"==typeof r?r:r(e,t,n)}(t,n,i))||this}return n=e,(t=i).prototype=Object.create(n.prototype),t.prototype.constructor=t,t.__proto__=n,i}(n);i.prototype.name=n.name,i.prototype.code=t,e[t]=i}function r(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}return t("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),t("ERR_INVALID_ARG_TYPE",(function(e,t,n){var i,o,a;if("string"==typeof t&&(o="not ",t.substr(0,o.length)===o)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))a="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var s=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(s," ").concat(i," ").concat(r(t,"type"))}return a+=". Received type ".concat(typeof n)}),TypeError),t("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),t("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),t("ERR_STREAM_PREMATURE_CLOSE","Premature close"),t("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),t("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),t("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),t("ERR_STREAM_WRITE_AFTER_END","write after end"),t("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),t("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),t("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),errorsBrowser.codes=e,errorsBrowser}function requireState(){if(hasRequiredState)return state;hasRequiredState=1;var e=requireErrorsBrowser().codes.ERR_INVALID_OPT_VALUE;return state={getHighWaterMark:function(t,r,n,i){var o=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(r,i,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new e(i?n:"highWaterMark",o);return Math.floor(o)}return t.objectMode?16:16384}}}function requireBrowser(){if(hasRequiredBrowser)return browser;function e(e){try{if(!commonjsGlobal.localStorage)return!1}catch(r){return!1}var t=commonjsGlobal.localStorage[e];return null!=t&&"true"===String(t).toLowerCase()}return hasRequiredBrowser=1,browser=function(t,r){if(e("noDeprecation"))return t;var n=!1;return function(){if(!n){if(e("throwDeprecation"))throw new Error(r);e("traceDeprecation")?console.trace(r):console.warn(r),n=!0}return t.apply(this,arguments)}},browser}function require_stream_writable(){if(hasRequired_stream_writable)return _stream_writable;function e(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,r){var n=e.entry;e.entry=null;for(;n;){var i=n.callback;t.pendingcb--,i(r),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var t;hasRequired_stream_writable=1,_stream_writable=_,_.WritableState=w;var r={deprecate:requireBrowser()},n=requireStreamBrowser(),i=requireDist().Buffer,o=(void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var a,s=requireDestroy(),c=requireState().getHighWaterMark,u=requireErrorsBrowser().codes,l=u.ERR_INVALID_ARG_TYPE,d=u.ERR_METHOD_NOT_IMPLEMENTED,h=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,f=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,g=u.ERR_STREAM_WRITE_AFTER_END,y=u.ERR_UNKNOWN_ENCODING,b=s.errorOrDestroy;function v(){}function w(r,n,i){t=t||require_stream_duplex(),r=r||{},"boolean"!=typeof i&&(i=n instanceof t),this.objectMode=!!r.objectMode,i&&(this.objectMode=this.objectMode||!!r.writableObjectMode),this.highWaterMark=c(this,r,"writableHighWaterMark",i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===r.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=r.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new h;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,i){--t.pendingcb,r?(process$1.nextTick(i,n),process$1.nextTick(S,e,t),e._writableState.errorEmitted=!0,b(e,n)):(i(n),e._writableState.errorEmitted=!0,b(e,n),S(e,t))}(e,r,n,t,i);else{var o=A(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||T(e,r),n?process$1.nextTick(I,e,r,o,i):I(e,r,o,i)}}(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==r.emitClose,this.autoDestroy=!!r.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}function _(e){var r=this instanceof(t=t||require_stream_duplex());if(!r&&!a.call(_,this))return new _(e);this._writableState=new w(e,this,r),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),n.call(this)}function k(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new f("write")):r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function I(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),S(e,t)}function T(t,r){r.bufferProcessing=!0;var n=r.bufferedRequest;if(t._writev&&n&&n.next){var i=r.bufferedRequestCount,o=new Array(i),a=r.corkedRequestsFree;a.entry=n;for(var s=0,c=!0;n;)o[s]=n,n.isBuf||(c=!1),n=n.next,s+=1;o.allBuffers=c,k(t,r,!0,r.length,o,"",a.finish),r.pendingcb++,r.lastBufferedRequest=null,a.next?(r.corkedRequestsFree=a.next,a.next=null):r.corkedRequestsFree=new e(r),r.bufferedRequestCount=0}else{for(;n;){var u=n.chunk,l=n.encoding,d=n.callback;if(k(t,r,!1,r.objectMode?1:u.length,u,l,d),n=n.next,r.bufferedRequestCount--,r.writing)break}null===n&&(r.lastBufferedRequest=null)}r.bufferedRequest=n,r.bufferProcessing=!1}function A(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function E(e,t){e._final((function(r){t.pendingcb--,r&&b(e,r),t.prefinished=!0,e.emit("prefinish"),S(e,t)}))}function S(e,t){var r=A(t);if(r&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process$1.nextTick(E,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}return requireInherits_browser()(_,n),w.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(w.prototype,"buffer",{get:r.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(a=Function.prototype[Symbol.hasInstance],Object.defineProperty(_,Symbol.hasInstance,{value:function(e){return!!a.call(this,e)||this===_&&(e&&e._writableState instanceof w)}})):a=function(e){return e instanceof this},_.prototype.pipe=function(){b(this,new p)},_.prototype.write=function(e,t,r){var n,a=this._writableState,s=!1,c=!a.objectMode&&(n=e,i.isBuffer(n)||n instanceof o);return c&&!i.isBuffer(e)&&(e=function(e){return i.from(e)}(e)),"function"==typeof t&&(r=t,t=null),c?t="buffer":t||(t=a.defaultEncoding),"function"!=typeof r&&(r=v),a.ending?function(e,t){var r=new g;b(e,r),process$1.nextTick(t,r)}(this,r):(c||function(e,t,r,n){var i;return null===r?i=new m:"string"==typeof r||t.objectMode||(i=new l("chunk",["string","Buffer"],r)),!i||(b(e,i),process$1.nextTick(n,i),!1)}(this,a,e,r))&&(a.pendingcb++,s=function(e,t,r,n,o,a){if(!r){var s=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=i.from(t,r));return t}(t,n,o);n!==s&&(r=!0,o="buffer",n=s)}var c=t.objectMode?1:n.length;t.length+=c;var u=t.length<t.highWaterMark;u||(t.needDrain=!0);if(t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:o,isBuf:r,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else k(e,t,!1,c,n,o,a);return u}(this,a,c,e,t,r)),s},_.prototype.cork=function(){this._writableState.corked++},_.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||T(this,e))},_.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new y(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(_.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(_.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),_.prototype._write=function(e,t,r){r(new d("_write()"))},_.prototype._writev=null,_.prototype.end=function(e,t,r){var n=this._writableState;return"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||function(e,t,r){t.ending=!0,S(e,t),r&&(t.finished?process$1.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r),this},Object.defineProperty(_.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),_.prototype.destroy=s.destroy,_.prototype._undestroy=s.undestroy,_.prototype._destroy=function(e,t){t(e)},_stream_writable}function require_stream_duplex(){if(hasRequired_stream_duplex)return _stream_duplex;hasRequired_stream_duplex=1;var e=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};_stream_duplex=a;var t=require_stream_readable(),r=require_stream_writable();requireInherits_browser()(a,t);for(var n=e(r.prototype),i=0;i<n.length;i++){var o=n[i];a.prototype[o]||(a.prototype[o]=r.prototype[o])}function a(e){if(!(this instanceof a))return new a(e);t.call(this,e),r.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",s)))}function s(){this._writableState.ended||process$1.nextTick(c,this)}function c(e){e.end()}return Object.defineProperty(a.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(a.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(a.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),_stream_duplex}function requireEndOfStream(){if(hasRequiredEndOfStream)return endOfStream;hasRequiredEndOfStream=1;var e=requireErrorsBrowser().codes.ERR_STREAM_PREMATURE_CLOSE;function t(){}return endOfStream=function r(n,i,o){if("function"==typeof i)return r(n,null,i);i||(i={}),o=function(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.apply(this,n)}}}(o||t);var a=i.readable||!1!==i.readable&&n.readable,s=i.writable||!1!==i.writable&&n.writable,c=function(){n.writable||l()},u=n._writableState&&n._writableState.finished,l=function(){s=!1,u=!0,a||o.call(n)},d=n._readableState&&n._readableState.endEmitted,h=function(){a=!1,d=!0,s||o.call(n)},p=function(e){o.call(n,e)},f=function(){var t;return a&&!d?(n._readableState&&n._readableState.ended||(t=new e),o.call(n,t)):s&&!u?(n._writableState&&n._writableState.ended||(t=new e),o.call(n,t)):void 0},m=function(){n.req.on("finish",l)};return!function(e){return e.setHeader&&"function"==typeof e.abort}(n)?s&&!n._writableState&&(n.on("end",c),n.on("close",c)):(n.on("complete",l),n.on("abort",f),n.req?m():n.on("request",m)),n.on("end",h),n.on("finish",l),!1!==i.error&&n.on("error",p),n.on("close",f),function(){n.removeListener("complete",l),n.removeListener("abort",f),n.removeListener("request",m),n.req&&n.req.removeListener("finish",l),n.removeListener("end",c),n.removeListener("close",c),n.removeListener("finish",l),n.removeListener("end",h),n.removeListener("error",p),n.removeListener("close",f)}},endOfStream}function requireAsync_iterator(){if(hasRequiredAsync_iterator)return async_iterator;var e;function t(e,t,r){return t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}hasRequiredAsync_iterator=1;var r=requireEndOfStream(),n=Symbol("lastResolve"),i=Symbol("lastReject"),o=Symbol("error"),a=Symbol("ended"),s=Symbol("lastPromise"),c=Symbol("handlePromise"),u=Symbol("stream");function l(e,t){return{value:e,done:t}}function d(e){var t=e[n];if(null!==t){var r=e[u].read();null!==r&&(e[s]=null,e[n]=null,e[i]=null,t(l(r,!1)))}}function h(e){process$1.nextTick(d,e)}var p=Object.getPrototypeOf((function(){})),f=Object.setPrototypeOf((t(e={get stream(){return this[u]},next:function(){var e=this,t=this[o];if(null!==t)return Promise.reject(t);if(this[a])return Promise.resolve(l(void 0,!0));if(this[u].destroyed)return new Promise((function(t,r){process$1.nextTick((function(){e[o]?r(e[o]):t(l(void 0,!0))}))}));var r,n=this[s];if(n)r=new Promise(function(e,t){return function(r,n){e.then((function(){t[a]?r(l(void 0,!0)):t[c](r,n)}),n)}}(n,this));else{var i=this[u].read();if(null!==i)return Promise.resolve(l(i,!1));r=new Promise(this[c])}return this[s]=r,r}},Symbol.asyncIterator,(function(){return this})),t(e,"return",(function(){var e=this;return new Promise((function(t,r){e[u].destroy(null,(function(e){e?r(e):t(l(void 0,!0))}))}))})),e),p);return async_iterator=function(e){var d,p=Object.create(f,(t(d={},u,{value:e,writable:!0}),t(d,n,{value:null,writable:!0}),t(d,i,{value:null,writable:!0}),t(d,o,{value:null,writable:!0}),t(d,a,{value:e._readableState.endEmitted,writable:!0}),t(d,c,{value:function(e,t){var r=p[u].read();r?(p[s]=null,p[n]=null,p[i]=null,e(l(r,!1))):(p[n]=e,p[i]=t)},writable:!0}),d));return p[s]=null,r(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=p[i];return null!==t&&(p[s]=null,p[n]=null,p[i]=null,t(e)),void(p[o]=e)}var r=p[n];null!==r&&(p[s]=null,p[n]=null,p[i]=null,r(l(void 0,!0))),p[a]=!0})),e.on("readable",h.bind(null,p)),p}}function requireFromBrowser(){return hasRequiredFromBrowser?fromBrowser:(hasRequiredFromBrowser=1,fromBrowser=function(){throw new Error("Readable.from is not available in the browser")})}function require_stream_readable(){if(hasRequired_stream_readable)return _stream_readable;var e;hasRequired_stream_readable=1,_stream_readable=_,_.ReadableState=w,requireEvents().EventEmitter;var t=function(e,t){return e.listeners(t).length},r=requireStreamBrowser(),n=requireDist().Buffer,i=(void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var o,a=requireUtil();o=a&&a.debuglog?a.debuglog("stream"):function(){};var s,c,u,l=requireBuffer_list(),d=requireDestroy(),h=requireState().getHighWaterMark,p=requireErrorsBrowser().codes,f=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,g=p.ERR_METHOD_NOT_IMPLEMENTED,y=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;requireInherits_browser()(_,r);var b=d.errorOrDestroy,v=["error","close","destroy","pause","resume"];function w(t,r,n){e=e||require_stream_duplex(),t=t||{},"boolean"!=typeof n&&(n=r instanceof e),this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=h(this,t,"readableHighWaterMark",n),this.buffer=new l,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(s||(s=requireString_decoder().StringDecoder),this.decoder=new s(t.encoding),this.encoding=t.encoding)}function _(t){if(e=e||require_stream_duplex(),!(this instanceof _))return new _(t);var n=this instanceof e;this._readableState=new w(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),r.call(this)}function k(e,t,r,a,s){o("readableAddChunk",t);var c,u=e._readableState;if(null===t)u.reading=!1,function(e,t){if(o("onEofChunk"),t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?E(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,S(e)))}(e,u);else if(s||(c=function(e,t){var r;o=t,n.isBuffer(o)||o instanceof i||"string"==typeof t||void 0===t||e.objectMode||(r=new f("chunk",["string","Buffer","Uint8Array"],t));var o;return r}(u,t)),c)b(e,c);else if(u.objectMode||t&&t.length>0)if("string"==typeof t||u.objectMode||Object.getPrototypeOf(t)===n.prototype||(t=function(e){return n.from(e)}(t)),a)u.endEmitted?b(e,new y):I(e,u,t,!0);else if(u.ended)b(e,new m);else{if(u.destroyed)return!1;u.reading=!1,u.decoder&&!r?(t=u.decoder.write(t),u.objectMode||0!==t.length?I(e,u,t,!1):x(e,u)):I(e,u,t,!1)}else a||(u.reading=!1,x(e,u));return!u.ended&&(u.length<u.highWaterMark||0===u.length)}function I(e,t,r,n){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&E(e)),x(e,t)}Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=d.destroy,_.prototype._undestroy=d.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var r,i=this._readableState;return i.objectMode?r=!0:"string"==typeof e&&((t=t||i.defaultEncoding)!==i.encoding&&(e=n.from(e,t),t=""),r=!0),k(this,e,t,!1,r)},_.prototype.unshift=function(e){return k(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.prototype.setEncoding=function(e){s||(s=requireString_decoder().StringDecoder);var t=new s(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,n="";null!==r;)n+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==n&&this._readableState.buffer.push(n),this._readableState.length=n.length,this};var T=1073741824;function A(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=T?e=T:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function E(e){var t=e._readableState;o("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(o("emitReadable",t.flowing),t.emittedReadable=!0,process$1.nextTick(S,e))}function S(e){var t=e._readableState;o("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,M(e)}function x(e,t){t.readingMore||(t.readingMore=!0,process$1.nextTick(R,e,t))}function R(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var r=t.length;if(o("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function O(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function $(e){o("readable nexttick read 0"),e.read(0)}function C(e,t){o("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),M(e),t.flowing&&!t.reading&&e.read(0)}function M(e){var t=e._readableState;for(o("flow",t.flowing);t.flowing&&null!==e.read(););}function P(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function N(e){var t=e._readableState;o("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process$1.nextTick(B,t,e))}function B(e,t){if(o("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function D(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}return _.prototype.read=function(e){o("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return o("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?N(this):E(this),null;if(0===(e=A(e,t))&&t.ended)return 0===t.length&&N(this),null;var n,i=t.needReadable;return o("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&o("length less than watermark",i=!0),t.ended||t.reading?o("reading or ended",i=!1):i&&(o("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=A(r,t))),null===(n=e>0?P(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&N(this)),null!==n&&this.emit("data",n),n},_.prototype._read=function(e){b(this,new g("_read()"))},_.prototype.pipe=function(e,r){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,o("pipe count=%d opts=%j",i.pipesCount,r);var a=(!r||!1!==r.end)&&e!==process$1.stdout&&e!==process$1.stderr?c:m;function s(t,r){o("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,o("cleanup"),e.removeListener("close",p),e.removeListener("finish",f),e.removeListener("drain",u),e.removeListener("error",h),e.removeListener("unpipe",s),n.removeListener("end",c),n.removeListener("end",m),n.removeListener("data",d),l=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||u())}function c(){o("onend"),e.end()}i.endEmitted?process$1.nextTick(a):n.once("end",a),e.on("unpipe",s);var u=function(e){return function(){var r=e._readableState;o("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,0===r.awaitDrain&&t(e,"data")&&(r.flowing=!0,M(e))}}(n);e.on("drain",u);var l=!1;function d(t){o("ondata");var r=e.write(t);o("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==D(i.pipes,e))&&!l&&(o("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function h(r){o("onerror",r),m(),e.removeListener("error",h),0===t(e,"error")&&b(e,r)}function p(){e.removeListener("finish",f),m()}function f(){o("onfinish"),e.removeListener("close",p),m()}function m(){o("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",h),e.once("close",p),e.once("finish",f),e.emit("pipe",n),i.flowing||(o("pipe resume"),n.resume()),e},_.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<i;o++)n[o].emit("unpipe",this,{hasUnpiped:!1});return this}var a=D(t.pipes,e);return-1===a||(t.pipes.splice(a,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r)),this},_.prototype.on=function(e,t){var n=r.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,o("on readable",i.length,i.reading),i.length?E(this):i.reading||process$1.nextTick($,this))),n},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var n=r.prototype.removeListener.call(this,e,t);return"readable"===e&&process$1.nextTick(O,this),n},_.prototype.removeAllListeners=function(e){var t=r.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process$1.nextTick(O,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(o("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process$1.nextTick(C,e,t))}(this,e)),e.paused=!1,this},_.prototype.pause=function(){return o("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(o("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var i in e.on("end",(function(){if(o("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(o("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(t.push(i)||(n=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<v.length;a++)e.on(v[a],this.emit.bind(this,v[a]));return this._read=function(t){o("wrapped _read",t),n&&(n=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===c&&(c=requireAsync_iterator()),c(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=P,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(e,t){return void 0===u&&(u=requireFromBrowser()),u(_,e,t)}),_stream_readable}function require_stream_transform(){if(hasRequired_stream_transform)return _stream_transform;hasRequired_stream_transform=1,_stream_transform=s;var e=requireErrorsBrowser().codes,t=e.ERR_METHOD_NOT_IMPLEMENTED,r=e.ERR_MULTIPLE_CALLBACK,n=e.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=e.ERR_TRANSFORM_WITH_LENGTH_0,o=require_stream_duplex();function a(e,t){var n=this._transformState;n.transforming=!1;var i=n.writecb;if(null===i)return this.emit("error",new r);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),i(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function s(e){if(!(this instanceof s))return new s(e);o.call(this,e),this._transformState={afterTransform:a.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",c)}function c(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?u(this,null,null):this._flush((function(t,r){u(e,t,r)}))}function u(e,t,r){if(t)return e.emit("error",t);if(null!=r&&e.push(r),e._writableState.length)throw new i;if(e._transformState.transforming)throw new n;return e.push(null)}return requireInherits_browser()(s,o),s.prototype.push=function(e,t){return this._transformState.needTransform=!1,o.prototype.push.call(this,e,t)},s.prototype._transform=function(e,r,n){n(new t("_transform()"))},s.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},s.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},s.prototype._destroy=function(e,t){o.prototype._destroy.call(this,e,(function(e){t(e)}))},_stream_transform}function require_stream_passthrough(){if(hasRequired_stream_passthrough)return _stream_passthrough;hasRequired_stream_passthrough=1,_stream_passthrough=t;var e=require_stream_transform();function t(r){if(!(this instanceof t))return new t(r);e.call(this,r)}return requireInherits_browser()(t,e),t.prototype._transform=function(e,t,r){r(null,e)},_stream_passthrough}function requirePipeline(){if(hasRequiredPipeline)return pipeline_1;var e;hasRequiredPipeline=1;var t=requireErrorsBrowser().codes,r=t.ERR_MISSING_ARGS,n=t.ERR_STREAM_DESTROYED;function i(e){if(e)throw e}function o(e){e()}function a(e,t){return e.pipe(t)}return pipeline_1=function(){for(var t=arguments.length,s=new Array(t),c=0;c<t;c++)s[c]=arguments[c];var u,l=function(e){return e.length?"function"!=typeof e[e.length-1]?i:e.pop():i}(s);if(Array.isArray(s[0])&&(s=s[0]),s.length<2)throw new r("streams");var d=s.map((function(t,r){var i=r<s.length-1;return function(t,r,i,o){o=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(o);var a=!1;t.on("close",(function(){a=!0})),void 0===e&&(e=requireEndOfStream()),e(t,{readable:r,writable:i},(function(e){if(e)return o(e);a=!0,o()}));var s=!1;return function(e){if(!a&&!s)return s=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new n("pipe"))}}(t,i,r>0,(function(e){u||(u=e),e&&d.forEach(o),i||(d.forEach(o),l(u))}))}));return s.reduce(a)},pipeline_1}function requireStreamBrowserify(){if(hasRequiredStreamBrowserify)return streamBrowserify;hasRequiredStreamBrowserify=1,streamBrowserify=t;var e=requireEvents().EventEmitter;function t(){e.call(this)}return requireInherits_browser()(t,e),t.Readable=require_stream_readable(),t.Writable=require_stream_writable(),t.Duplex=require_stream_duplex(),t.Transform=require_stream_transform(),t.PassThrough=require_stream_passthrough(),t.finished=requireEndOfStream(),t.pipeline=requirePipeline(),t.Stream=t,t.prototype.pipe=function(t,r){var n=this;function i(e){t.writable&&!1===t.write(e)&&n.pause&&n.pause()}function o(){n.readable&&n.resume&&n.resume()}n.on("data",i),t.on("drain",o),t._isStdio||r&&!1===r.end||(n.on("end",s),n.on("close",c));var a=!1;function s(){a||(a=!0,t.end())}function c(){a||(a=!0,"function"==typeof t.destroy&&t.destroy())}function u(t){if(l(),0===e.listenerCount(this,"error"))throw t}function l(){n.removeListener("data",i),t.removeListener("drain",o),n.removeListener("end",s),n.removeListener("close",c),n.removeListener("error",u),t.removeListener("error",u),n.removeListener("end",l),n.removeListener("close",l),t.removeListener("close",l)}return n.on("error",u),t.on("error",u),n.on("end",l),n.on("close",l),t.on("close",l),t.emit("pipe",n),t},streamBrowserify}var streamBrowserifyExports=requireStreamBrowserify();const index=getDefaultExportFromCjs(streamBrowserifyExports),index$1=Object.freeze(Object.defineProperty({__proto__:null,default:index},Symbol.toStringTag,{value:"Module"})),standardsSdk_es33=Object.freeze(Object.defineProperty({__proto__:null,i:index$1},Symbol.toStringTag,{value:"Module"}));exports.AcceptConnectionRequestTool=AcceptConnectionRequestTool,exports.BasePlugin=BasePlugin,exports.CheckMessagesTool=CheckMessagesTool,exports.ConnectionMonitorTool=ConnectionMonitorTool,exports.ConnectionTool=ConnectionTool,exports.FindRegistrationsTool=FindRegistrationsTool,exports.GenericPlugin=GenericPlugin,exports.GetHbarPriceTool=GetHbarPriceTool,exports.HCS10Client=HCS10Client,exports.HCS10Plugin=HCS10Plugin,exports.HbarPricePlugin=HbarPricePlugin,exports.InitiateConnectionTool=InitiateConnectionTool,exports.ListConnectionsTool=ListConnectionsTool,exports.ListUnapprovedConnectionRequestsTool=ListUnapprovedConnectionRequestsTool,exports.ManageConnectionRequestsTool=ManageConnectionRequestsTool,exports.OpenConvAIPlugin=OpenConvAIPlugin,exports.OpenConvaiState=OpenConvaiState,exports.PluginLoader=PluginLoader,exports.PluginRegistry=PluginRegistry,exports.RegisterAgentTool=RegisterAgentTool,exports.RetrieveProfileTool=RetrieveProfileTool,exports.SendMessageToConnectionTool=SendMessageToConnectionTool,exports.SendMessageTool=SendMessageTool,exports.initializeStandardsAgentKit=initializeStandardsAgentKit,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
165
165
  //# sourceMappingURL=standards-agent-kit.umd.js.map