@0xmonaco/mcp-server 1.1.1 → 1.1.2

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 (2) hide show
  1. package/dist/bin.js +1 -1
  2. package/package.json +3 -3
package/dist/bin.js CHANGED
@@ -127,7 +127,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
127
127
  `:`[${n[c]}\r
128
128
  ]`;continue}if(o+=n[c],n[c]==="\\")i=!0;else if(s&&n[c]==="]")s=!1;else if(!s&&n[c]==="[")s=!0}try{new RegExp(o)}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 o}function k0(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===pe.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Ue(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Vt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Ue(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===pe.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=A0(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===pe.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===pe.ZodBranded&&e.keyType._def.type._def.typeName===pe.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=I0(e.keyType._def,t);return{...r,propertyNames:o}}return r}function t$(e,t){if(t.mapStrategy==="record")return k0(e,t);let r=Ue(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Vt(t),n=Ue(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Vt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function r$(e){let t=e.values,n=Object.keys(e.values).filter((i)=>typeof t[t[i]]!=="number").map((i)=>t[i]),o=Array.from(new Set(n.map((i)=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function n$(e){return e.target==="openAi"?void 0:{not:Vt({...e,currentPath:[...e.currentPath,"not"]})}}function o$(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Am={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function s$(e,t){if(t.target==="openApi3")return i$(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in Am)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Am[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((i)=>!n.includes(i))],[])};return i$(e,t)}var i$=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Ue(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function a$(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:Am[e.innerType._def.typeName],nullable:!0};return{type:[Am[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=Ue(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=Ue(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function c$(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",N1(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)dt(r,"minimum",n.value,n.message,t);else dt(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;dt(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)dt(r,"maximum",n.value,n.message,t);else dt(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;dt(r,"maximum",n.value,n.message,t)}break;case"multipleOf":dt(r,"multipleOf",n.value,n.message,t);break}return r}function u$(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let l=Nne(c);if(l&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();l=!1}let d=Ue(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(d===void 0)continue;if(n.properties[a]=d,!l)o.push(a)}if(o.length)n.required=o;let s=Mne(e,t);if(s!==void 0)n.additionalProperties=s;return n}function Mne(e,t){if(e.catchall._def.typeName!=="ZodNever")return Ue(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Nne(e){try{return e.isOptional()}catch{return!0}}var l$=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Ue(e.innerType._def,t);let r=Ue(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Vt(t)},r]}:Vt(t)};var d$=(e,t)=>{if(t.pipeStrategy==="input")return Ue(e.in._def,t);else if(t.pipeStrategy==="output")return Ue(e.out._def,t);let r=Ue(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Ue(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function p$(e,t){return Ue(e.type._def,t)}function f$(e,t){let n={type:"array",uniqueItems:!0,items:Ue(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)dt(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)dt(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function m$(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Ue(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Ue(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Ue(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function h$(e){return{not:Vt(e)}}function g$(e){return Vt(e)}var y$=(e,t)=>Ue(e.innerType._def,t);var b$=(e,t,r)=>{switch(t){case pe.ZodString:return A0(e,r);case pe.ZodNumber:return c$(e,r);case pe.ZodObject:return u$(e,r);case pe.ZodBigInt:return VN(e,r);case pe.ZodBoolean:return ZN();case pe.ZodDate:return $1(e,r);case pe.ZodUndefined:return h$(r);case pe.ZodNull:return o$(r);case pe.ZodArray:return GN(e,r);case pe.ZodUnion:case pe.ZodDiscriminatedUnion:return s$(e,r);case pe.ZodIntersection:return QN(e,r);case pe.ZodTuple:return m$(e,r);case pe.ZodRecord:return k0(e,r);case pe.ZodLiteral:return XN(e,r);case pe.ZodEnum:return JN(e);case pe.ZodNativeEnum:return r$(e);case pe.ZodNullable:return a$(e,r);case pe.ZodOptional:return l$(e,r);case pe.ZodMap:return t$(e,r);case pe.ZodSet:return f$(e,r);case pe.ZodLazy:return()=>e.getter()._def;case pe.ZodPromise:return p$(e,r);case pe.ZodNaN:case pe.ZodNever:return n$(r);case pe.ZodEffects:return YN(e,r);case pe.ZodAny:return Vt(r);case pe.ZodUnknown:return g$(r);case pe.ZodDefault:return KN(e,r);case pe.ZodBranded:return I0(e,r);case pe.ZodReadonly:return y$(e,r);case pe.ZodCatch:return WN(e,r);case pe.ZodPipeline:return d$(e,r);case pe.ZodFunction:case pe.ZodVoid:case pe.ZodSymbol:return;default:return((n)=>{return})(t)}};function Ue(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==qN)return a}if(n&&!r){let a=$ne(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=b$(e,e.typeName,t),s=typeof i==="function"?Ue(i(),t):i;if(s)Lne(e,t,s);if(t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var $ne=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:P0(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Vt(t);return t.$refStrategy==="seen"?Vt(t):void 0}}},Lne=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var z1=(e,t)=>{let r=HN(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,d])=>({...c,[l]:Ue(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Vt(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=Ue(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Vt(r),s=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(s!==void 0)i.title=s;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("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.");return a};function Bne(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function D1(e,t){if(Ii(e))return m1(e,{target:Bne(t?.target),io:t?.pipeStrategy??"input"});return z1(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function F1(e){let r=Na(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=Ul(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function U1(e,t){let r=Ma(e,t);if(!r.success)throw r.error;return r.data}var zne=60000;class q1{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(u0,(t)=>{this._oncancel(t)}),this.setNotificationHandler(d0,(t)=>{this._onprogress(t)}),this.setRequestHandler(l0,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(p0,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ae(Re.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(m0,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new Ae(Re.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let s;while(s=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(s.type==="response"||s.type==="error"){let a=s.message,c=a.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),s.type==="response")l(a);else{let d=a,p=new Ae(d.error.code,d.error.message,d.error.data);l(p)}else{let d=s.type==="response"?"Response":"Error";this._onerror(Error(`${d} handler missing for request ${c}`))}continue}await this._transport?.send(s.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new Ae(Re.InvalidParams,`Task not found: ${o}`);if(!Ba(i.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(Ba(i.status)){let s=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...s,_meta:{...s._meta,[La]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(h0,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Ae(Re.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(y0,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Ae(Re.InvalidParams,`Task not found: ${t.params.taskId}`);if(Ba(n.status))throw new Ae(Re.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Ae(Re.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof Ae)throw n;throw new Ae(Re.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ae.fromError(Re.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{if(n?.(o,i),xm(o)||kN(o))this._onresponse(o);else if(w1(o))this._onrequest(o,i);else if(AN(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=Ae.fromError(Re.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[La]?.taskId,i=n?.sessionId,s=this._taskStore,a=!0,c;if(o&&s&&this._taskMessageQueue&&i!==void 0)a=!1,c=(async()=>{if(!await s.getTask(o,i))throw new Ae(Re.InvalidParams,`Task not found: ${o}`);a=!0})();if(r===void 0){let g={jsonrpc:"2.0",id:e.id,error:{code:Re.MethodNotFound,message:"Method not found"}};if(o&&c){let y={type:"error",message:g,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,y,i),()=>n?.send(g)).catch((b)=>this._onerror(Error(`Failed to send an error response: ${b}`)))}else if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},n?.sessionId).catch((y)=>this._onerror(Error(`Failed to enqueue error response: ${y}`)));else n?.send(g).catch((y)=>this._onerror(Error(`Failed to send an error response: ${y}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let d=EN(e.params)?e.params.task:void 0,p=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,h={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(g)=>{if(l.signal.aborted)return;let y={relatedRequestId:e.id};if(o)y.relatedTask={taskId:o};await this.notification(g,y)},sendRequest:async(g,y,b)=>{if(l.signal.aborted)throw new Ae(Re.ConnectionClosed,"Request was cancelled");let T={...b,relatedRequestId:e.id};if(o&&!T.relatedTask)T.relatedTask={taskId:o};let S=T.relatedTask?.taskId??o;if(S&&p)await p.updateTaskStatus(S,"input_required");return await this.request(g,y,T)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:p,taskRequestedTtl:d?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new Ae(Re.ConnectionClosed,"Request was cancelled");if(d)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,h)).then(async(g)=>{if(l.signal.aborted)return;let y={result:g,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:y,timestamp:Date.now()},n?.sessionId);else await n?.send(y)},async(g)=>{if(l.signal.aborted)return;let y={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(g.code)?g.code:Re.InternalError,message:g.message??"Internal error",...g.data!==void 0&&{data:g.data}}};if(o&&this._taskMessageQueue&&a)await this._enqueueTaskMessage(o,{type:"error",message:y,timestamp:Date.now()},n?.sessionId);else await n?.send(y)}).catch((g)=>this._onerror(Error(`Failed to send response: ${g}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===l)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&i&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),xm(e))r(e);else{let i=new Ae(e.error.code,e.error.message,e.error.data);r(i)}return}let n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(xm(e)&&e.result&&typeof e.result==="object"){let i=e.result;if(i.task&&typeof i.task==="object"){let s=i.task;if(typeof s.taskId==="string")o=!0,this._taskProgressTokens.set(s.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(xm(e))n(e);else{let i=Ae.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(i){yield{type:"error",error:i instanceof Ae?i:new Ae(Re.InternalError,String(i))}}return}let o;try{let i=await this.request(e,jl,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Ae(Re.InternalError,"Task creation did not return a task");while(!0){let s=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:s},Ba(s.status)){if(s.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(s.status==="failed")yield{type:"error",error:new Ae(Re.InternalError,`Task ${o} failed`)};else if(s.status==="cancelled")yield{type:"error",error:new Ae(Re.InternalError,`Task ${o} was cancelled`)};return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=s.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof Ae?i:new Ae(Re.InternalError,String(i))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i,task:s,relatedTask:a}=r??{};return new Promise((c,l)=>{let d=(S)=>{l(S)};if(!this._transport){d(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),s)this.assertTaskCapability(e.method)}catch(S){d(S);return}r?.signal?.throwIfAborted();let p=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:p};if(r?.onprogress)this._progressHandlers.set(p,r.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}};if(s)h.params={...h.params,task:s};if(a)h.params={...h.params,_meta:{...h.params?._meta||{},[La]:a}};let g=(S)=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((_)=>this._onerror(Error(`Failed to send cancellation: ${_}`)));let v=S instanceof Ae?S:new Ae(Re.RequestTimeout,String(S));l(v)};this._responseHandlers.set(p,(S)=>{if(r?.signal?.aborted)return;if(S instanceof Error)return l(S);try{let v=Ma(t,S.result);if(!v.success)l(v.error);else c(v.data)}catch(v){l(v)}}),r?.signal?.addEventListener("abort",()=>{g(r?.signal?.reason)});let y=r?.timeout??zne,b=()=>g(Ae.fromError(Re.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,r?.maxTotalTimeout,b,r?.resetTimeoutOnProgress??!1);let T=a?.taskId;if(T){let S=(v)=>{let _=this._responseHandlers.get(p);if(_)_(v);else this._onerror(Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(T,{type:"request",message:h,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(h,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:i}).catch((S)=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},f0,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},g0,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},CN,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[La]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[La]:t.relatedTask}}};this._transport?.send(s,t).catch((a)=>this._onerror(a))});return}let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[La]:t.relatedTask}}};await this._transport.send(i,t)}setRequestHandler(e,t){let r=F1(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let i=U1(e,n);return Promise.resolve(t(i,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=F1(e);this._notificationHandlers.set(r,(n)=>{let o=U1(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&w1(n.message)){let o=n.message.id,i=this._requestResolvers.get(o);if(i)i(new Ae(Re.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e,r);if(o?.pollInterval)n=o.pollInterval}catch{}return new Promise((o,i)=>{if(t.aborted){i(new Ae(Re.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(s),i(new Ae(Re.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new Ae(Re.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,i)=>{await r.storeTaskResult(n,o,i,t);let s=await r.getTask(n,t);if(s){let a=vm.parse({method:"notifications/tasks/status",params:s});if(await this.notification(a),Ba(s.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,i)=>{let s=await r.getTask(n,t);if(!s)throw new Ae(Re.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ba(s.status))throw new Ae(Re.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,i,t);let a=await r.getTask(n,t);if(a){let c=vm.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Ba(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function x$(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function w$(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];if(x$(s)&&x$(i))r[o]={...s,...i};else r[o]=i}return r}var M4=un(OE(),1),N4=un(C4(),1);function Cde(){let e=new M4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return N4.default(e),e}class FE{constructor(e){this._ajv=e??Cde()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class UE{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some((l)=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some((l)=>l.type==="tool_use");if(i){if(o.some((l)=>l.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter((p)=>p.type==="tool_use").map((p)=>p.id)),d=new Set(o.filter((p)=>p.type==="tool_result").map((p)=>p.toolUseId));if(l.size!==d.size||![...l].every((p)=>d.has(p)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Im,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Vl,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function $4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function L4(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class qE extends q1{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Pm.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new FE,this.setRequestHandler(_1,(r)=>this._oninitialize(r)),this.setNotificationHandler(v1,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(O1,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,s=Pm.safeParse(i);if(s.success)this._loggingLevels.set(o,s.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new UE(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=w$(this._capabilities,e)}setRequestHandler(e,t){let n=Na(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=Ul(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(a,c)=>{let l=Ma(Gl,a);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new Ae(Re.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=l.data,p=await Promise.resolve(t(a,c));if(d.task){let g=Ma(jl,p);if(!g.success){let y=g.error instanceof Error?g.error.message:String(g.error);throw new Ae(Re.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}let h=Ma(v0,p);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new Ae(Re.InvalidParams,`Invalid tools/call result: ${g}`)}return h.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){L4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;$4(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:TN.includes(t)?t:b1,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},c0)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=i?Array.isArray(i.content)?i.content:[i.content]:[],a=s.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(s.filter((d)=>d.type==="tool_use").map((d)=>d.id)),l=new Set(n.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(c.size!==l.size||![...c].every((d)=>l.has(d)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},C1,t);return this.request({method:"sampling/createMessage",params:e},Im,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},Vl,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},Vl,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!s.valid)throw new Ae(Re.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(i){if(i instanceof Ae)throw i;throw new Ae(Re.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},M1,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var z4=Symbol.for("mcp.completable");function jE(e){return!!e&&typeof e==="object"&&z4 in e}function D4(e){return e[z4]?.complete}var B4;(function(e){e.Completable="McpCompletable"})(B4||(B4={}));var Mde=/^[A-Za-z0-9._-]{1,128}$/;function Nde(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!Mde.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function $de(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function HE(e){let t=Nde(e);return $de(e,t.warnings),t.isValid}class GE{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}function Lde(e,t){let r=0,n=[e];while(n.length>0){let o=n.pop();if(o===null||typeof o!=="object")continue;if(Array.isArray(o))for(let i of o){if(++r>t)return r;if(i!==null&&typeof i==="object")n.push(i)}else for(let i in o){if(!Object.prototype.hasOwnProperty.call(o,i))continue;if(++r>t)return r;let s=o[i];if(s!==null&&typeof s==="object")n.push(s)}}return r}function Bde(e){if(e===void 0||e===1/0)return;if(typeof e!=="number"||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}class ZE{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new qE(e,t),this._maxToolInputElements=Bde(t?.maxToolInputElements)}get experimental(){if(!this._experimental)this._experimental={tasks:new GE(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(nc(_0)),this.server.assertCanSetRequestHandler(nc(Gl)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(_0,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=Fl(t.inputSchema);return n?D1(n,{strictUnions:!0,pipeStrategy:"input"}):zde})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=Fl(t.outputSchema);if(n)r.outputSchema=D1(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Gl,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new Ae(Re.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new Ae(Re.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new Ae(Re.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new Ae(Re.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&i)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,s,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof Ae){if(r.code===Re.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&Lde(t,this._maxToolInputElements)>this._maxToolInputElements)throw new Ae(Re.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let o=Fl(e.inputSchema)??e.inputSchema,i=await Xy(o,t??{});if(!i.success){let s="error"in i?i.error:"Unknown error",a=e0(s);throw new Ae(Re.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return i.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new Ae(Re.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Fl(e.outputSchema),o=await Xy(n,t.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",s=e0(i);throw new Ae(Re.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${s}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,i));else return await Promise.resolve(n.createTask(i))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,i={...r,taskStore:r.taskStore},s=n?await Promise.resolve(o.createTask(n,i)):await Promise.resolve(o.createTask(i)),a=s.task.taskId,c=s.task,l=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((p)=>setTimeout(p,l));let d=await r.taskStore.getTask(a);if(!d)throw new Ae(Re.InternalError,`Task ${a} not found during polling`);c=d}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(nc(E0)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(E0,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return zN(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return DN(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Ae(Re.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new Ae(Re.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new Ae(Re.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return qm;let o=Na(r.argsSchema)?.[e.params.argument.name];if(!jE(o))return qm;let i=D4(o);if(!i)return qm;let s=await i(e.params.argument.value,e.params.context);return U4(s)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((i)=>i.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return qm;throw new Ae(Re.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return qm;let o=await n(e.params.argument.value,e.params.context);return U4(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(nc(b0)),this.server.assertCanSetRequestHandler(nc(x0)),this.server.assertCanSetRequestHandler(nc(w0)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(b0,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(t);for(let s of i.resources)n.push({...o.metadata,...s})}return{resources:[...r,...n]}}),this.server.setRequestHandler(x0,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(w0,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new Ae(Re.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,t)}throw new Ae(Re.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(nc(S0)),this.server.assertCanSetRequestHandler(nc(T0)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(S0,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Dde(t.argsSchema):void 0}))})),this.server.setRequestHandler(T0,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new Ae(Re.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new Ae(Re.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Fl(r.argsSchema),o=await Xy(n,e.params.arguments??{});if(!o.success){let a="error"in o?o.error:"Unknown error",c=e0(a);throw new Ae(Re.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let i=o.data,s=r.callback;return await Promise.resolve(s(i,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let i={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:(s)=>{if(typeof s.uri<"u"&&s.uri!==r){if(delete this._registeredResources[r],s.uri)this._registeredResources[s.uri]=i}if(typeof s.name<"u")i.name=s.name;if(typeof s.title<"u")i.title=s.title;if(typeof s.metadata<"u")i.metadata=s.metadata;if(typeof s.callback<"u")i.readCallback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=i,i}_createRegisteredResourceTemplate(e,t,r,n,o){let i={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=i}if(typeof c.title<"u")i.title=c.title;if(typeof c.template<"u")i.resourceTemplate=c.template;if(typeof c.metadata<"u")i.metadata=c.metadata;if(typeof c.callback<"u")i.readCallback=c.callback;if(typeof c.enabled<"u")i.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let s=r.uriTemplate.variableNames;if(Array.isArray(s)&&s.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return i}_createRegisteredPrompt(e,t,r,n,o){let i={title:t,description:r,argsSchema:n===void 0?void 0:iu(n),callback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:(s)=>{if(typeof s.name<"u"&&s.name!==e){if(delete this._registeredPrompts[e],s.name)this._registeredPrompts[s.name]=i}if(typeof s.title<"u")i.title=s.title;if(typeof s.description<"u")i.description=s.description;if(typeof s.argsSchema<"u")i.argsSchema=iu(s.argsSchema);if(typeof s.callback<"u")i.callback=s.callback;if(typeof s.enabled<"u")i.enabled=s.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=i,n){if(Object.values(n).some((a)=>{let c=a instanceof o0?a._def?.innerType:a;return jE(c)}))this.setCompletionRequestHandler()}return i}_createRegisteredTool(e,t,r,n,o,i,s,a,c){HE(e);let l={title:t,description:r,inputSchema:F4(n),outputSchema:F4(o),annotations:i,execution:s,_meta:a,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:(d)=>{if(typeof d.name<"u"&&d.name!==e){if(typeof d.name==="string")HE(d.name);if(delete this._registeredTools[e],d.name)this._registeredTools[d.name]=l}if(typeof d.title<"u")l.title=d.title;if(typeof d.description<"u")l.description=d.description;if(typeof d.paramsSchema<"u")l.inputSchema=iu(d.paramsSchema);if(typeof d.outputSchema<"u")l.outputSchema=iu(d.outputSchema);if(typeof d.callback<"u")l.handler=d.callback;if(typeof d.annotations<"u")l.annotations=d.annotations;if(typeof d._meta<"u")l._meta=d._meta;if(typeof d.enabled<"u")l.enabled=d.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,i;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(VE(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!VE(t[0]))i=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,n,o,i,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:i,outputSchema:s,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,i,s,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],i=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:i}=t,s=this._createRegisteredPrompt(e,n,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var zde={type:"object",properties:{}};function q4(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function j4(e){return"_def"in e||"_zod"in e||q4(e)}function VE(e){if(typeof e!=="object"||e===null)return!1;if(j4(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(q4)}function F4(e){if(!e)return;if(VE(e))return iu(e);if(!j4(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function Dde(e){let t=Na(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=qM(n),i=jM(n);return{name:r,description:o,required:!i}})}function nc(e){let r=Na(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=Ul(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function U4(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var qm={completion:{values:[],hasMore:!1}};import G4 from"node:process";var Fde=10485760;class WE{constructor(e){this._maxBufferSize=e?.maxBufferSize??Fde}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
129
129
  `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Ude(t)}clear(){this._buffer=void 0}}function Ude(e){return RN.parse(JSON.parse(e))}function H4(e){return JSON.stringify(e)+`
130
- `}class KE{constructor(e=G4.stdin,t=G4.stdout,r){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=(n)=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=(n)=>{this.onerror?.(n)},this._readBuffer=new WE({maxBufferSize:r?.maxBufferSize})}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=H4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var wb={name:"@0xmonaco/mcp-server",version:"1.1.1",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.1.1","@0xmonaco/types":"1.1.1","@modelcontextprotocol/sdk":"^1.32.1","node-fetch":"^3.3.2",viem:"^2.57.10",ws:"^8.22.0",zod:"^4.6.7"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.2"}};var Sb=["read","market-maker","full"],Fi=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trader_metrics",description:"Get public current long/short account counts, account shares and ratio, plus active-trader counts for a margin pair. Accounts are classified by net position across open risk buckets. Small cohorts are suppressed; activity counts include system user IDs on liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trade_flow",description:"Get bounded UTC-aligned taker buy/sell quote-notional buckets and cumulative volume delta for a margin pair, including liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"list_liquidation_events",description:"List paginated public per-fill liquidation events, including public wallets and quote-asset notional using each event's captured mark.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_liquidation_metrics",description:"Get bounded UTC-aligned long/short liquidation totals; event counts represent persisted rows and notionals use each row's event-time mark.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current one-sided LONG open interest (each contract counted once) for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair-set and side filters).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_sub_account",description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_sub_account",description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_fee_schedule",description:"Get a trading pair's fee tier schedule: volume thresholds and maker/taker bps per tier (no credentials required).",category:"fees",authMode:"public",sideEffect:"read-only"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your TraderCodes rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned TraderCodes rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],NAe=Fi.map((e)=>e.name),V4=Fi.filter((e)=>e.authMode==="public").map((e)=>e.name),$Ae=Fi.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),LAe=Fi.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),BAe=Fi.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),zAe=Fi.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),Z4=Fi.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var jde=new Map(Fi.map((e)=>[e.name,e.sideEffect]));function W4(e){let t=jde.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var K4={read:0,"market-maker":1,full:2},YE=V4,JE=Object.fromEntries(Fi.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),Y4=Object.fromEntries(Object.entries(JE).map(([e,t])=>[e,t.capability])),UAe=new Set(Z4);function J4(e){let t=JE[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function Q4(e){return J4(e)==="read"}function X4(e,t){if(t.network==="mainnet"&&JE[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(YE.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return K4[t.capability]>=K4[J4(e)]}var Hde=new Set([...YE,...Object.keys(Y4)]),Gde={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function e8(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function pu(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!Sb.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${Sb.join(", ")}.`);let c=a||"read",l=e8(e.MONACO_TOOL_ALLOWLIST),d=e8(e.MONACO_TOOL_DENYLIST),p=[...l,...d].filter((y)=>!Hde.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let h=e.MONACO_RPC_URL||Gde[s],g=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");g=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:h,capability:c,allow:l,deny:d,delegatedOwnerUserId:g}}function Vde(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Cr(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Cr(r));let t={};for(let[r,n]of Object.entries(e))t[Vde(r)]=typeof n==="object"&&n!==null?Cr(n):n;return t}function Tb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var QE=(e)=>e?`"${e}" `:"";function jm(e,t=""){if(typeof e!=="number")throw TypeError(QE(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(QE(t)+"expected integer >= 0, got "+e);return e}function Ui(e,t,r=""){if(Tb(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)jm(t,"length");let n=Tb(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=QE(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var Zde=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},t8=(e,t)=>{Zde(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function XE(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function n8(e,t){Ui(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function fd(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _b(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Yo(e,t){return e<<32-t|e>>>t}var o8=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Wde=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ao(e){if(Ui(e),o8)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Wde[e[r]];return t}function r8(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Cs(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(o8)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=r8(e.charCodeAt(i)),a=r8(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function fu(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{fd(t)}}function eP(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];Ui(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function Kde(e,t,r="opts"){if(t8(e,"defaults"),t!==void 0)t8(t,r);return Object.assign(Object.create(null),e,t)}function tP(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=Kde({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}function i8(e=32){jm(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var rP=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var vb=(()=>BigInt(4294967295))(),s8=BigInt(32);function Yde(e,t=!1){if(t)return{h:Number(e&vb),l:Number(e>>s8&vb)};return{h:Number(e>>s8&vb)|0,l:Number(e&vb)|0}}function a8(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=Yde(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var Jde=(e)=>e/4294967296|0,Qde=(e)=>e>>>0;function c8(e,t,r,n){let o=Jde(r),i=Qde(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}var nP=(e,t,r)=>e>>>r,oP=(e,t,r)=>e<<32-r|t>>>r,mu=(e,t,r)=>e>>>r|t<<32-r,hu=(e,t,r)=>e<<32-r|t>>>r,Hm=(e,t,r)=>e<<64-r|t>>>r-32,Gm=(e,t,r)=>e>>>r-32|t<<64-r;function qi(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/4294967296|0)|0,l:o|0}}var u8=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),l8=(e,t,r,n)=>t+r+n+(e/4294967296|0)|0,d8=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),p8=(e,t,r,n,o)=>t+r+n+o+(e/4294967296|0)|0,f8=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),m8=(e,t,r,n,o,i)=>t+r+n+o+i+(e/4294967296|0)|0;function h8(e,t,r){return e&t^~e&r}function g8(e,t,r){return e&t^e&r^t&r}class Eb{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=_b(this.buffer)}update(e){XE(this),Ui(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=_b(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){XE(this),n8(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);c8(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:_b(e),a=this.outputLen,c=a/4,l=this.get();if(a%4||c>l.length)throw Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var y8=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var b8=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var epe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),oc=new Uint32Array(64);class x8 extends Eb{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)oc[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=oc[d-15],h=oc[d-2],g=Yo(p,7)^Yo(p,18)^p>>>3,y=Yo(h,17)^Yo(h,19)^h>>>10;oc[d]=y+oc[d-7]+g+oc[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let d=0;d<64;d++){let p=Yo(s,6)^Yo(s,11)^Yo(s,25),h=l+p+h8(s,a,c)+epe[d]+oc[d]|0,y=(Yo(r,2)^Yo(r,13)^Yo(r,22))+g8(r,n,o)|0;l=c,c=a,a=s,s=i+h|0,i=o,o=n,n=r,r=h+y|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,o,i,s,a,c,l)}roundClean(){fd(oc)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),fd(this.buffer)}}class w8 extends x8{constructor(){super(32,y8)}}var S8=(()=>a8(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),tpe=(()=>S8[0])(),rpe=(()=>S8[1])(),ic=new Uint32Array(80),sc=new Uint32Array(80);class T8 extends Eb{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1);this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:l,Fh:d,Fl:p,Gh:h,Gl:g,Hh:y,Hl:b}=this;return[e,t,r,n,o,i,s,a,c,l,d,p,h,g,y,b]}set(e,t,r,n,o,i,s,a,c,l,d,p,h,g,y,b){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=p|0,this.Gh=h|0,this.Gl=g|0,this.Hh=y|0,this.Hl=b|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let v=0;v<16;v++,t+=4)ic[v]=e.getUint32(t),sc[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let _=ic[v-15]|0,E=sc[v-15]|0,P=mu(_,E,1)^mu(_,E,8)^nP(_,E,7),A=hu(_,E,1)^hu(_,E,8)^oP(_,E,7),C=ic[v-2]|0,N=sc[v-2]|0,F=mu(C,N,19)^Hm(C,N,61)^nP(C,N,6),R=hu(C,N,19)^Gm(C,N,61)^oP(C,N,6),V=d8(A,R,sc[v-7],sc[v-16]),Z=p8(V,P,F,ic[v-7],ic[v-16]);ic[v]=Z|0,sc[v]=V|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:l,Eh:d,El:p,Fh:h,Fl:g,Gh:y,Gl:b,Hh:T,Hl:S}=this;for(let v=0;v<80;v++){let _=mu(d,p,14)^mu(d,p,18)^Hm(d,p,41),E=hu(d,p,14)^hu(d,p,18)^Gm(d,p,41),P=d&h^~d&y,A=p&g^~p&b,C=f8(S,E,A,rpe[v],sc[v]),N=m8(C,T,_,P,tpe[v],ic[v]),F=C|0,R=mu(r,n,28)^Hm(r,n,34)^Hm(r,n,39),V=hu(r,n,28)^Gm(r,n,34)^Gm(r,n,39),Z=r&o^r&s^o&s,se=n&i^n&a^i&a;T=y|0,S=b|0,y=h|0,b=g|0,h=d|0,g=p|0,{h:d,l:p}=qi(c|0,l|0,N|0,F|0),c=s|0,l=a|0,s=o|0,a=i|0,o=r|0,i=n|0;let q=u8(F,V,se);r=l8(q,N,R,Z),n=q|0}({h:r,l:n}=qi(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=qi(this.Bh|0,this.Bl|0,o|0,i|0),{h:s,l:a}=qi(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l}=qi(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:p}=qi(this.Eh|0,this.El|0,d|0,p|0),{h,l:g}=qi(this.Fh|0,this.Fl|0,h|0,g|0),{h:y,l:b}=qi(this.Gh|0,this.Gl|0,y|0,b|0),{h:T,l:S}=qi(this.Hh|0,this.Hl|0,T|0,S|0),this.set(r,n,o,i,s,a,c,l,d,p,h,g,y,b,T,S)}roundClean(){fd(ic,sc)}destroy(){this.destroyed=!0,fd(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class _8 extends T8{constructor(){super(64,b8)}}var Pb=tP(()=>new w8,rP(1));var iP=tP(()=>new _8,rP(3));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ab(e,t,r=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let n=0;n<e.length;n++)r(e[n],`${t}[${n}]`);return e}var Bn=(e,t,r)=>Ui(e,t,r),sP=jm;function ac(e,t="object"){if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function gu(e,t){if(typeof e!=="function")throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var E8=ao,aP=(...e)=>eP(...e),P8=(e)=>Cs(e),Vm=Tb,cP=(e)=>i8(e),Ib=BigInt(0),v8=BigInt(1),npe=(e)=>e?`"${e}" `:"";function Ms(e,t=""){if(typeof e!=="boolean")throw TypeError(npe(t)+"expected boolean, got type="+typeof e);return e}function ope(e){if(typeof e==="bigint"){if(!cc(e))throw RangeError("positive bigint expected, got "+e)}else sP(e);return e}function md(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function I8(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?Ib:BigInt("0x"+e)}function kb(e){return I8(ao(e))}function hd(e){return I8(ao(Zm(Ui(e)).reverse()))}function uP(e,t){if(jm(t),t===0)throw Error("zero output length is invalid");e=ope(e);let r=t*2,n=e.toString(16);if(n.length>r)throw RangeError("number is too large");return Cs(n.padStart(r,"0"))}function A8(e,t){return uP(e,t).reverse()}function Zm(e){return Uint8Array.from(Bn(e))}function cc(e){return typeof e==="bigint"&&Ib<=e}function lP(e,t,r){return cc(e)&&cc(t)&&cc(r)&&t<=e&&e<r}function dP(e,t,r,n){if(!lP(t,r,n))throw RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function pP(e){if(e<Ib)throw Error("expected non-negative bigint, got "+e);return e===Ib?0:e.toString(2).length}var k8=(e)=>(md(e,"n"),(v8<<BigInt(e))-v8);function uc(e,t={},r={},n="object"){ac(e,n),ac(t,"fields"),ac(r,"optFields");function o(s,a,c){let l=n==="object"?`param "${String(s)}"`:`"${n}.${String(s)}"`,d=e[s];if(!Object.hasOwn(e,s)&&(c?d!==void 0:a!=="function"))throw TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;let p=typeof d;if(p!==a||d===null)throw TypeError(`${l} is invalid: expected ${a}, got ${p}`)}let i=(s,a)=>Object.entries(s).forEach(([c,l])=>o(c,l,a));i(t,!1),i(r,!0)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Mr=BigInt(0),Wt=BigInt(1),yu=BigInt(2),C8=BigInt(3),mP=BigInt(4),M8=BigInt(5),ipe=BigInt(7),N8=BigInt(8),spe=BigInt(9),ape=BigInt(15),$8=BigInt(16),cpe=BigInt("0x10000000000000000");function hr(e,t){if(t<=Mr)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Mr?r:t+r}function upe(e,t,r){if(r<=Wt)throw Error("pow: expected modulus > 1, got "+r);if(typeof t!=="bigint")throw TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<Mr)throw Error("invalid exponent, negatives unsupported");if(t===Mr)return Wt;if(t===Wt)return e;let n=e%r;if(n<Mr)n+=r;if(t<cpe){let a=Wt;while(t>Mr){if(t&Wt)a=a*n%r;n=n*n%r,t>>=Wt}return a}let o=[];while(t>Mr)o.push(Number(t&ape)),t>>=mP;let i=Array(16);i[0]=Wt,i[1]=n;for(let a=2;a<16;a++)i[a]=i[a-1]*n%r;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%r,s=s*s%r,s=s*s%r,s=s*s%r;let c=o[a];if(c!==0)s=s*i[c]%r}return s}function Jo(e,t,r){if(r<=Wt)throw Error("pow2: expected modulus > 1, got "+r);if(t<Mr)throw Error("pow2: expected non-negative exponent, got "+t);let n=e;while(t-- >Mr)n*=n,n%=r;return n}function R8(e,t){if(e===Mr)throw Error("invert: expected non-zero number");if(t<=Wt)throw Error("invert: expected modulus > 1, got "+t);let r=hr(e,t),n=t,o=Mr,i=Wt;while(r!==Mr){let a=n/r,c=n-r*a,l=o-i*a;n=r,r=c,o=i,i=l}if(n!==Wt)throw Error("invert: does not exist");return hr(o,t)}function hP(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw Error("Cannot find square root")}function gP(e,t){if((e&Wt)===Mr)throw Error(t+": expected odd modulus, got "+e)}function L8(e,t){let r=e,n=(r.ORDER+Wt)/mP,o=r.pow(t,n);return hP(r,o,t),o}function lpe(e,t){let r=e,n=(r.ORDER-M8)/N8,o=r.mul(t,yu),i=r.pow(o,n),s=r.mul(t,i),a=r.mul(r.mul(s,yu),i),c=r.mul(s,r.sub(a,r.ONE));return hP(r,c,t),c}function dpe(e){let t=Ob(e),r=B8(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+ipe)/$8;return(a,c)=>{let l=a,d=l.pow(c,s),p=l.mul(d,n),h=l.mul(d,o),g=l.mul(d,i),y=l.eql(l.sqr(p),c),b=l.eql(l.sqr(h),c);d=l.cmov(d,p,y),p=l.cmov(g,h,b);let T=l.eql(l.sqr(p),c),S=l.cmov(d,p,T);return hP(l,S,c),S}}function B8(e){if(e<C8)throw Error("sqrt is not defined for small field");gP(e,"tonelliShanks");let t=e-Wt,r=0;while(t%yu===Mr)t/=yu,r++;let n=yu,o=Ob(e);while(Wm(o,n)===1)if(n++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return L8;let i=o.pow(n,t),s=(t+Wt)/yu;return function(c,l){let d=c;if(d.is0(l))return l;if(Wm(d,l)!==1)throw Error("Cannot find square root");let p=r,h=d.mul(d.ONE,i),g=d.pow(l,t),y=d.pow(l,s);while(!d.eql(g,d.ONE)){if(d.is0(g))throw Error("Cannot find square root: probably non-prime P");let b=1,T=d.sqr(g);while(!d.eql(T,d.ONE))if(b++,T=d.sqr(T),b===p)throw Error("Cannot find square root");let S=Wt<<BigInt(p-b-1),v=d.pow(h,S);p=b,h=d.sqr(v),g=d.mul(g,h),y=d.mul(y,v)}return y}}function ppe(e){if(gP(e,"Fp.sqrt"),e%mP===C8)return L8;if(e%N8===M8)return lpe;if(e%$8===spe)return dpe(e);return B8(e)}var z8=(e,t)=>(hr(e,t)&Wt)===Wt,fpe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gd(e){if(ac(e,"field"),typeof e.ORDER!=="bigint")throw TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);md(e.BYTES,"BYTES"),md(e.BITS,"BITS");for(let t of fpe)gu(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=Wt)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Rb(e,t,r=!1){gd(e),Ab(t,"nums"),Ms(r,"passZero");let n=e,o=Array(t.length).fill(r?n.ZERO:void 0),i=t.reduce((a,c,l)=>{if(n.is0(c))return a;return o[l]=a,n.mul(a,c)},n.ONE),s=n.inv(i);return t.reduceRight((a,c,l)=>{if(n.is0(c))return a;return o[l]=n.mul(a,o[l]),n.mul(a,c)},s),o}function Wm(e,t){gd(e);let r=e;gP(r.ORDER,"FpLegendre");let n=(r.ORDER-Wt)/yu,o=r.pow(t,n),i=r.eql(o,r.ONE),s=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function mpe(e,t){if(t!==void 0)sP(t);if(e<=Mr)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=pP(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${r})`);let n=t!==void 0?t:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var O8=new WeakMap;class fP{ORDER;BITS;BYTES;isLE;ZERO=Mr;ONE=Wt;_lengths;_mod;constructor(e,t={}){if(e<=Wt)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:n,nByteLength:o}=mpe(e,r);if(o>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(e){return hr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Mr<=e&&e<this.ORDER}is0(e){return e===Mr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Wt)===Wt}neg(e){return hr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return hr(e*e,this.ORDER)}add(e,t){return hr(e+t,this.ORDER)}sub(e,t){return hr(e-t,this.ORDER)}mul(e,t){return hr(e*t,this.ORDER)}pow(e,t){return upe(e,t,this.ORDER)}div(e,t){return hr(e*R8(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return R8(e,this.ORDER)}sqrt(e){let t=O8.get(this);if(!t)O8.set(this,t=ppe(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?A8(e,this.BYTES):uP(e,this.BYTES)}fromBytes(e,t=!1){Bn(e);let{_lengths:r,BYTES:n,isLE:o,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(n);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==n)throw Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let a=o?hd(e):kb(e);if(s)a=hr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Rb(this,e,!0)}cmov(e,t,r){return Ms(r,"condition"),r?t:e}}function Ob(e,t={}){return Object.freeze(fP.prototype),new fP(e,t)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var xP=BigInt(0),Km=BigInt(1),hpe=BigInt(4),yP=16,D8=128,gpe=5,F8=(()=>2147483648)();function Ym(e){let t=e;if(typeof t!=="function")throw TypeError('"Point" expected constructor, got type='+typeof e);gu(t.fromAffine,"Point.fromAffine"),gu(t.fromBytes,"Point.fromBytes"),gu(t.fromHex,"Point.fromHex"),ac(t.BASE,"Point.BASE"),ac(t.ZERO,"Point.ZERO"),gd(t.Fp),gd(t.Fn)}function q8(e,t){Ym(e),j8(t,e);let r=Rb(e.Fp,t.map((n)=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function ype(e,t,r=1){if(!Number.isSafeInteger(e)||e<r||e>t)throw Error("invalid window size, expected ["+r+".."+t+"], got W="+e)}function bpe(e,t){let r=e*(4*t+128);if(r>F8)throw Error("invalid window size: table would need ~"+Math.ceil(r/1048576)+" MiB, max "+F8/1048576+" MiB")}function xpe(e,t){if(e===void 0)return;gu(e,"randomBytes");try{let r=e(t);if(!Vm(r)||r.length!==t)return}catch{return}return e}function j8(e,t){Ab(e,"points"),e.forEach((r,n)=>{if(!(r instanceof t))throw Error("invalid point at index "+n)})}function wpe(e,t,r){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach((n,o)=>{if(!(r===void 0?t.isValid(n):cc(n)&&n<r))throw Error("invalid scalar at index "+o)})}var H8=new WeakMap;function bP(e){return H8.get(e)||1}function Spe(e,t){let r=e.double(),n=[e];for(let o=1;o<t;o++)n.push(n[o-1].add(r));return n}function Tpe(e,t){let r=2**t,n=r/2,o=BigInt(r-1),i=[];while(e>xP){let s=0;if(e&Km){if(s=Number(e&o),s>=n)s-=r;e-=BigInt(s)}i.push(s),e>>=Km}return i}function _pe(e,t,r){let n=2**t,o=n/2,i=BigInt(n-1),s=BigInt(t),a=[];for(let c=0;c<r;c++){let l=Number(e&i);if(e>>=s,l>o)l-=n,e+=Km;a.push(l)}if(e!==xP)throw Error("invalid wnaf");return a}function vpe(e,t,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=e;for(let i=n-1;i>=0;i--){if(i!==n-1)o=o.double();for(let s=0;s<r.length;s++){let a=r[s][i];if(a){let c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class wP{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Ym(e),this.randomBytes=xpe(t,yP),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let n=Math.ceil(r/t)+1,o=2**(t-1),i=[],s=e;for(let a=0;a<n;a++){let c=s;for(let l=0;l<o;l++)i.push(c),c=c.add(s);s=i[i.length-1].double()}return{W:t,bits:r,windows:n,comp:i}}wnafCachedCT(e,t){let{W:r,windows:n,comp:o}=e,i=2**(r-1),s=_pe(t,r,n),a=this.ZERO,c=this.BASE;for(let l=0;l<n;l++){let d=s[l],p=l*i,h=Math.abs(d)-1,g=o[p];for(let b=1;b<i;b++)g=b===h?o[p+b]:g;let y=g.negate();if(d===0)c=c.add(o[p]);else a=a.add(d<0?y:g)}return{p:a,f:c}}getWnafPrecomputes(e,t,r,n){let o=this.wnafPrecomputes.get(t),i=o?.find((s)=>s.W===e&&s.bits===r);if(!i){if(i=this.buildWnafTable(t,e,r),typeof n==="function")i={...i,comp:n(i.comp)};if(!o)o=[],this.wnafPrecomputes.set(t,o);o.push(i)}return i}assertPoint(e){if(!(e instanceof this.Point))throw TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!lP(t,Km,this.Point.Fn.ORDER))throw Error("invalid scalar")}runCT(e,t,r,n){let o=bP(e);if(o===1)return this.fixedWindowCT(e,t,r);return this.wnafCachedCT(this.getWnafPrecomputes(o,e,r,n),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+D8,o=this.randomBytes(yP);if(!Vm(o)||o.length!==yP)throw Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+kb(o)*this.Point.Fn.ORDER;return this.runCT(e,i,n,r)}fixedWindowCT(e,t,r){let n=gpe,o=1<<n,i=k8(n),s=Array(o);s[0]=this.ZERO;for(let l=1;l<o;l++)s[l]=s[l-1].add(e);let a=Math.ceil(r/n),c=this.ZERO;for(let l=a-1;l>=0;l--){if(l!==a-1)for(let h=0;h<n;h++)c=c.double();let d=Number(t>>BigInt(l*n)&i),p=s[0];for(let h=1;h<o;h++)p=h===d?s[h]:p;c=c.add(p)}return{p:c,f:c}}shouldBlind(e,t){if(this.randomBytes===void 0)return!1;if(t===Km)return!0;if(e!==this.BASE)return!1;if(this.baseCanBeBlinded===void 0)this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0();return this.baseCanBeBlinded}mulSecret(e,t,r,n){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,n):this.mulCT(e,t,n)}mulUnsafe(e,t,r){if(this.assertPoint(e),!cc(t))throw Error("invalid scalar");let n=bP(e);if(n===1||t>=this.Point.Fn.ORDER)return Epe(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),ype(t,this.bits);let r=Math.ceil((this.bits+D8)/t)+1;bpe(r*2**(t-1),this.Point.Fp.BYTES),H8.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return bP(e)!==1}}function Epe(e,t,r,n=!1){if(Ym(e),j8(t,e),Ms(n,"allowOversized"),wpe(r,e.Fn,n?e.Fn.ORDER**hpe:void 0),t.length!==r.length)throw Error("arrays of points and scalars must have equal length");let o=t.map((s)=>Spe(s,4)),i=r.map((s)=>Tpe(s,4));return vpe(e.ZERO,o,i)}function U8(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return gd(t),t}else return Ob(e,{isLE:r})}function G8(e,t,r={},n){if(e!=="weierstrass"&&e!=="edwards")throw Error('expected curve type "weierstrass" or "edwards"');if(n===void 0)n=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);uc(r);for(let c of["p","n","h"]){let l=t[c];if(!(cc(l)&&l!==xP))throw Error(`CURVE.${c} must be positive bigint`)}let o=U8(t.p,r.Fp,n),i=U8(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function V8(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Cb=BigInt(0),Mb=BigInt(1),Nb=BigInt(2),Ppe=BigInt(4),Z8=BigInt(8);function Ipe(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function W8(e,t={}){uc(t,{},{},"extraOpts");let r=t,n=G8("edwards",e,r,r.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;if(Wm(o,s.a)!==1)throw Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Wm(o,s.d)!==-1)throw Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");uc(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?cP:r.randomBytes,l=Nb<<BigInt(o.BYTES*8)-Mb;function d(v){if(!o.isOdd)throw Error("Field does not have .isOdd()");return o.isOdd(v)}let p=r.uvRatio===void 0?(v,_)=>{try{return{isValid:!0,value:o.sqrt(o.div(v,_))}}catch(E){return{isValid:!1,value:Cb}}}:r.uvRatio;if(!Ipe(o,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");let h=o.eql(s.a,o.neg(o.ONE))?(v)=>o.neg(v):o.eql(s.a,o.ONE)?(v)=>v:(v)=>o.mul(s.a,v);function g(v,_,E=!1){let P=E?Mb:Cb;return dP("coordinate "+v,_,P,l),_}function y(v){if(!(v instanceof b))throw Error("EdwardsPoint expected")}class b{static BASE=new b(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new b(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(v,_,E,P){this.X=g("x",v),this.Y=g("y",_),this.Z=g("z",E,!0),this.T=g("t",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){if(v instanceof b)throw Error("extended point not allowed");let{x:_,y:E}=v||{};return g("x",_),g("y",E),new b(_,E,o.ONE,o.mul(_,E))}static fromBytes(v,_=!1){let E=o.BYTES,{a:P,d:A}=s;v=Zm(Bn(v,E,"point")),Ms(_,"zip215");let C=Zm(v),N=v[E-1];C[E-1]=N&-129;let F=hd(C),R=_?l:o.ORDER;dP("point.y",F,Cb,R);let V=o.sqr(F),Z=o.sub(V,o.ONE),se=o.sub(o.mulN(A,V),P),{isValid:q,value:L}=p(Z,se);if(!q)throw Error("bad point: invalid y coordinate");let G=d(L),ae=(N&128)!==0;if(!_&&o.is0(L)&&ae)throw Error("bad point: x=0 and x_0=1");if(ae!==G)L=o.neg(L);return b.fromAffine({x:L,y:F})}static fromHex(v,_=!1){return b.fromBytes(P8(v),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,_=!0){if(S.setWindowSize(this,v),!_)this.multiply(Nb);return this}assertValidity(){let v=this,{a:_,d:E}=s;if(v.is0())throw Error("bad point: ZERO");let{X:P,Y:A,Z:C,T:N}=v,F=o.sqr(P),R=o.sqr(A),V=o.sqr(C),Z=o.sqr(V),se=o.mul(F,_),q=o.mul(o.add(se,R),V),L=o.add(Z,o.mul(E,o.mul(F,R)));if(!o.eql(q,L))throw Error("bad point: equation left != right (1)");let G=o.mul(P,A),ae=o.mul(C,N);if(!o.eql(G,ae))throw Error("bad point: equation left != right (2)")}equals(v){y(v);let{X:_,Y:E,Z:P}=this,{X:A,Y:C,Z:N}=v,F=o.mul(_,N),R=o.mul(A,P),V=o.mul(E,N),Z=o.mul(C,P);return o.eql(F,R)&&o.eql(V,Z)}is0(){return this.equals(b.ZERO)}negate(){return new b(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:v,Y:_,Z:E}=this,P=o.sqr(v),A=o.sqr(_),C=o.mul(o.sqr(E),Nb),N=h(P),F=o.addN(v,_),R=o.sub(o.subN(o.sqr(F),P),A),V=o.addN(N,A),Z=o.subN(V,C),se=o.subN(N,A),q=o.mul(R,Z),L=o.mul(V,se),G=o.mul(R,se),ae=o.mul(Z,V);return new b(q,L,ae,G)}add(v){y(v);let{d:_}=s,{X:E,Y:P,Z:A,T:C}=this,{X:N,Y:F,Z:R,T:V}=v,Z=o.mul(E,N),se=o.mul(P,F),q=o.mul(o.mulN(C,_),V),L=o.mul(A,R),G=o.sub(o.subN(o.mulN(o.addN(E,P),o.addN(N,F)),Z),se),ae=o.subN(L,q),we=o.addN(L,q),ye=o.sub(se,h(Z)),Me=o.mul(G,ae),bt=o.mul(we,ye),be=o.mul(G,ye),Pt=o.mul(ae,we);return new b(Me,bt,Pt,be)}subtract(v){return y(v),this.add(v.negate())}multiply(v){if(!i.isValidNot0(v))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:E}=S.mulSecret(this,v,a,T);return T([_,E])[0]}multiplyUnsafe(v){if(!i.isValid(v))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(v===Cb)return b.ZERO;if(this.is0()||v===Mb)return this;return S.mulUnsafe(this,v,T)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return S.mulUnsafe(this,s.n).is0()}toAffine(v){let _=this,E=v;if(E!=null&&typeof E!=="bigint")throw TypeError('"invertedZ" expected bigint, got type='+typeof E);let{X:P,Y:A,Z:C}=_,N=_.is0();if(E==null)E=N?o.create(Z8):o.inv(C);let F=o.mul(P,E),R=o.mul(A,E),V=o.mul(C,E);if(N)return{x:o.ZERO,y:o.ONE};if(!o.eql(V,o.ONE))throw Error("invZ was invalid");return{x:F,y:R}}clearCofactor(){if(a===Mb)return this;if(a===Nb)return this.double();if(a===Ppe)return this.double().double();if(a===Z8)return this.double().double().double();return this.multiplyUnsafe(a)}toBytes(){let{x:v,y:_}=this.toAffine(),E=o.toBytes(_);return E[E.length-1]|=d(v)?128:0,E}toHex(){return E8(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let T=(v)=>q8(b,v),S=new wP(b,c);if(S.bits>=6)b.BASE.precompute(6);return Object.freeze(b.prototype),Object.freeze(b),b}function K8(e,t,r={}){if(Ym(e),typeof t!=="function")throw Error('"hash" function param is required');let n=t,o=r;uc(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=n.outputLen,d=2*a.BYTES;if(l!==void 0){if(md(l,"hash.outputLen"),l!==d)throw Error(`hash.outputLen must be ${d}, got ${l}`)}let p=o.randomBytes===void 0?cP:o.randomBytes,{toMontgomery:h,toMontgomerySecret:g}=o,y=o.adjustScalarBytes===void 0?(q)=>q:o.adjustScalarBytes,b=o.domain===void 0?(q,L,G)=>{if(Ms(G,"phflag"),L.length||G)throw Error("Contexts/pre-hash are not supported");return q}:o.domain;function T(q){return c.create(hd(q))}function S(q){let L=F.secretKey;Bn(q,F.secretKey,"secretKey");let G=Bn(n(q),2*L,"hashedSecretKey"),ae=y(G.slice(0,L)),we=G.slice(L,2*L),ye=T(ae);return{head:ae,prefix:we,scalar:ye}}function v(q){let{head:L,prefix:G,scalar:ae}=S(q),we=s.multiply(ae),ye=we.toBytes();return{head:L,prefix:G,scalar:ae,point:we,pointBytes:ye}}function _(q){return v(q).pointBytes}function E(q=Uint8Array.of(),...L){let G=aP(...L);return T(n(b(G,Bn(q,void 0,"context"),!!i)))}function P(q,L,G={}){if(uc(G,{},{},"options"),q=Zm(Bn(q,void 0,"message")),i)q=i(q);let{prefix:ae,scalar:we,pointBytes:ye}=v(L),Me=E(G.context,ae,q),bt=s.multiply(Me).toBytes(),be=E(G.context,bt,ye,q),Pt=c.create(Me+be*we);if(!c.isValid(Pt))throw Error("sign failed: invalid s");let Ye=aP(bt,c.toBytes(Pt));return Bn(Ye,F.signature,"result")}let A={zip215:o.zip215};function C(q,L,G,ae=A){uc(ae);let{context:we}=ae,ye=ae.zip215===void 0?!!A.zip215:ae.zip215,Me=F.signature;if(q=Bn(q,Me,"signature"),L=Bn(L,void 0,"message"),G=Bn(G,F.publicKey,"publicKey"),ye!==void 0)Ms(ye,"zip215");if(i)L=i(L);let bt=Me/2,be=q.subarray(0,bt),Pt=hd(q.subarray(bt,Me)),Ye,rt,lr;try{Ye=e.fromBytes(G,ye),rt=e.fromBytes(be,ye),lr=s.multiplyUnsafe(Pt)}catch(Yr){return!1}if(!ye&&Ye.isSmallOrder())return!1;let En=E(we,be,G,L);return rt.add(Ye.multiplyUnsafe(En)).subtract(lr).clearCofactor().is0()}let N=a.BYTES,F={secretKey:N,publicKey:N,signature:2*N,seed:N};function R(q){return q=q===void 0?p(F.seed):q,Bn(q,F.seed,"seed")}function V(q){return Vm(q)&&q.length===F.secretKey}function Z(q,L){try{return!!e.fromBytes(q,L===void 0?A.zip215:L)}catch(G){return!1}}let se={getExtendedPublicKey:v,randomSecretKey:R,isValidSecretKey:V,isValidPublicKey:Z,toMontgomery(q){if(h===void 0)throw Error("Montgomery conversion is not supported for this curve");return h(e.fromBytes(q))},toMontgomerySecret(q){if(g===void 0)throw Error("Montgomery conversion is not supported for this curve");return g(q)}};return Object.freeze(F),Object.freeze(se),Object.freeze({keygen:V8(R,_),getPublicKey:_,sign:P,verify:C,utils:se,Point:e,lengths:F})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var SP=BigInt(1),Y8=BigInt(2);var Ape=BigInt(5),kpe=BigInt(8),TP=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Rpe=(()=>({p:TP,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:kpe,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ope(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=TP,a=e*e%i*e%i,c=Jo(a,Y8,i)*a%i,l=Jo(c,SP,i)*e%i,d=Jo(l,Ape,i)*l%i,p=Jo(d,t,i)*d%i,h=Jo(p,r,i)*p%i,g=Jo(h,n,i)*h%i,y=Jo(g,o,i)*g%i,b=Jo(y,o,i)*g%i,T=Jo(b,t,i)*d%i;return{pow_p_5_8:Jo(T,Y8,i)*e%i,b2:a}}function X8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var J8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Cpe(e,t){let r=TP,n=hr(t*t*t,r),o=hr(n*n*t,r),i=Ope(e*o).pow_p_5_8,s=hr(e*n*i,r),a=hr(t*s*s,r),c=s,l=hr(s*J8,r),d=a===e,p=a===hr(-e,r),h=a===hr(-e*J8,r);if(d)s=c;if(p||h)s=l;if(z8(s,r))s=hr(-s,r);return{isValid:d||p,value:s}}var _P=W8(Rpe,{uvRatio:Cpe}),Q8=(()=>_P.Fp)();function Mpe(e){let{y:t}=e;return Q8.toBytes(Q8.div(SP+t,SP-t))}function Npe(e){let t=_P.Fp.BYTES;return Ui(e,t),X8(iP(e.subarray(0,t))).subarray(0,t)}function $pe(e){return K8(_P,iP,Object.assign({adjustScalarBytes:X8,toMontgomery:Mpe,toMontgomerySecret:Npe,zip215:!0},e))}var yd=$pe({});function $b(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=yd.utils.randomSecretKey();return{publicKey:yd.getPublicKey(e),privateKey:e}}function Lb(e){return ao(e.publicKey)}function Bb(e){return ao(e.privateKey)}function eF(e,t){return{publicKey:Cs(e),privateKey:Cs(t)}}function tF(e){return ao(Pb(e))}function rF(e,t,r,n){return`${e.toUpperCase()}
130
+ `}class KE{constructor(e=G4.stdin,t=G4.stdout,r){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=(n)=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=(n)=>{this.onerror?.(n)},this._readBuffer=new WE({maxBufferSize:r?.maxBufferSize})}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=H4(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var wb={name:"@0xmonaco/mcp-server",version:"1.1.2",type:"module",homepage:"https://docs.0xmonaco.com/sdk/typescript",description:"MCP server for the Monaco SDK",engines:{node:">=18"},bin:"./dist/bin.js",files:["dist"],scripts:{build:"bun build src/bin.ts --outdir dist --target node --format esm --minify",dev:"bun --watch src/bin.ts",start:"bun dist/bin.js",clean:"rm -rf dist",lint:"biome lint .",test:"bun test"},author:"@codebycarson",dependencies:{"@0xmonaco/core":"1.1.2","@0xmonaco/types":"1.1.2","@modelcontextprotocol/sdk":"^1.32.1","node-fetch":"^3.3.2",viem:"^2.57.10",ws:"^8.22.0",zod:"^4.6.7"},devDependencies:{"@types/bun":"latest","@types/ws":"^8.18.2"}};var Sb=["read","market-maker","full"],Fi=[{name:"search_docs",description:"Search the Monaco documentation for protocol, SDK, trading, and development guides.",category:"search",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pairs",description:"List trading pairs with optional filters (market type, base/quote token, active status).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trading_pair_by_symbol",description:"Look up a trading pair by symbol (e.g. `BTC/USDC`).",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_candlesticks",description:"Fetch OHLCV candlestick data for a trading pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_metadata",description:"Get tick size, minimum order size, and trading rules for a pair.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_screener",description:"Screen trading pairs with market stats (price, volume, change), filtered by market type, category, and active status.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_market_stats",description:"Get exchange-wide life-to-date cumulative volume and trade count across all markets.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trader_metrics",description:"Get public current long/short account counts, account shares and ratio, plus active-trader counts for a margin pair. Accounts are classified by net position across open risk buckets. Small cohorts are suppressed; activity counts include system user IDs on liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_trade_flow",description:"Get bounded UTC-aligned taker buy/sell quote-notional buckets and cumulative volume delta for a margin pair, including liquidation and ADL fills.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"list_liquidation_events",description:"List paginated public per-fill liquidation events, including public wallets and quote-asset notional using each event's captured mark.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_liquidation_metrics",description:"Get bounded UTC-aligned long/short liquidation totals; event counts represent persisted rows and notionals use each row's event-time mark.",category:"market",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_config",description:"Get a perpetual market's configuration (leverage limits, margin requirements, funding parameters).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_perp_market_summary",description:"Get a perpetual market's live summary (mark/index price, funding rate, open interest, 24h stats).",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_mark_price",description:"Get the current mark price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_index_price",description:"Get the current index (oracle) price for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_state",description:"Get the current funding rate and next funding time for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_open_interest",description:"Get the current one-sided LONG open interest (each contract counted once) for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_funding_history",description:"List historical funding-rate records for a perpetual market.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_all_funding_history",description:"List historical funding-rate records across all perpetual markets.",category:"perp",authMode:"public",sideEffect:"read-only"},{name:"get_orderbook",description:"Fetch a current orderbook snapshot with bids and asks.",category:"orderbook",authMode:"public",sideEffect:"read-only"},{name:"get_trades",description:"Fetch historical trades for a trading pair.",category:"trades",authMode:"public",sideEffect:"read-only"},{name:"place_limit_order",description:"Place a limit order with price, quantity, and time-in-force. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"place_market_order",description:"Place a market order — executes immediately inside a mandatory 1,000 bps protective price band, so it may partially fill or be rejected. The SDK supplies an idempotency key if omitted. Retain an explicit key to retry the same submission within 15 minutes of acceptance. Calling again without the original key is not idempotent; never retry an ambiguous failure with a new key. If the original key is unavailable, report the ambiguity.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"replace_order",description:"Modify an existing order's price and/or quantity. Not idempotent — an ambiguous failure (timeout/network error/5xx with no order) cannot be resolved from inside MCP, which has no order-stream tool; never retry, and report the ambiguity instead.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"cancel_order",description:"Cancel a single order by ID.",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_orders",description:"Cancel multiple orders by ID (non-atomic — a failed leg does not stop the others).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_cancel_all_orders",description:"Cancel all open orders, optionally filtered to a trading pair (unfiltered, it cancels your entire open-order book).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"batch_close_all_positions",description:"Close all open perpetual positions with market reduce-only orders (best-effort, optional pair-set and side filters).",category:"trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_orders",description:"List your orders with optional filters.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_order",description:"Get details for a specific order by ID.",category:"trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_positions",description:"List your perpetual positions with optional filters (margin account, trading pair, status).",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position",description:"Get details for a specific perpetual position by ID.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_risk",description:"Get liquidation price, margin ratio, and risk metrics for a perpetual position.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_history",description:"List historical (closed/reduced) perpetual position records with optional filters.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_position_pnl_history",description:"Get the PnL history time series for a perpetual position over an interval.",category:"positions",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"close_position",description:"Close a perpetual position with a market, limit, or IOC reduce order.",category:"positions",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_profile",description:"Fetch your core profile (address, username, account type, withdrawal status).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balances",description:"List token balances with pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_balance_by_asset",description:"Get balance for a specific asset.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_movements",description:"Fetch transaction and movement history with optional filters.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_user_trades",description:"List your own trade fills with optional filters and cursor pagination.",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_funding_payments",description:"List your perpetual funding payments with optional filters (trading pair, position, margin account).",category:"profile",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_summary",description:"Get your authoritative portfolio summary (equity, PnL, exposure) over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_performance",description:"Get your portfolio performance time series over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_realized_pnl",description:"Get your realized PnL breakdown over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_assets",description:"Get your per-asset portfolio allocation and balances over a period.",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_portfolio_margin",description:"Get your portfolio margin overview (collateral, maintenance margin, health).",category:"portfolio",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_margin_accounts",description:"List your margin accounts with optional filters (state, trading pair).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_summary",description:"Get your parent (cross) margin account summary.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_available_collateral",description:"Get available (unlocked) collateral for allocating to margin accounts or risk buckets.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_parent_margin_account_movements",description:"List collateral movements for your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_parent_margin_order_risk",description:"Preview the risk impact of a prospective order against your parent (cross) margin account (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"simulate_risk_bucket_order_risk",description:"Preview the risk impact of a prospective order for a new or existing risk bucket (read-only simulation).",category:"margin",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_collateral_to_parent_margin_account",description:"Move collateral from spot into your parent (cross) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_parent_margin_account",description:"Move collateral out of your parent (cross) margin account back to spot.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_risk_bucket",description:"Allocate collateral into an isolated or cross risk bucket.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_to_sub_account",description:"Move collateral from your default (parent) margin account into one of your margin sub-accounts.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"transfer_collateral_from_sub_account",description:"Move collateral from one of your margin sub-accounts back to your default (parent) margin account.",category:"margin",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_fee_schedule",description:"Get a trading pair's fee tier schedule: volume thresholds and maker/taker bps per tier (no credentials required).",category:"fees",authMode:"public",sideEffect:"read-only"},{name:"simulate_fees",description:"Simulate fees for an order before placing it.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_fee_tier",description:"Get your current fee tier, rolling 14-day volumes, and a pair's fee schedule.",category:"fees",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_approve",description:"Approve the vault contract to spend a token.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_deposit",description:"Deposit tokens into the vault (optional `target`: `spot` default, or `margin` to route into collateral).",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_withdraw",description:"Withdraw tokens from the vault.",category:"vault",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"vault_get_allowance",description:"Check current token allowance for the vault.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"vault_needs_approval",description:"Check whether an approval transaction is needed before depositing.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_pending_withdrawals",description:"List your pending withdrawals still awaiting on-chain root confirmation.",category:"vault",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"request_faucet",description:"Request test tokens for all trading pairs.",category:"faucet",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating",excludedOnMainnet:!0},{name:"get_faucet_info",description:"Check remaining faucet quota, next-request time, and recent mint history.",category:"faucet",authMode:"authenticated",capability:"read",sideEffect:"read-only",excludedOnMainnet:!0},{name:"get_trader_code_info",description:"Look up a trader code's details (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"check_trader_code_availability",description:"Public advisory check of whether a custom TraderCode handle is available (no credentials required).",category:"pitpass",authMode:"public",sideEffect:"read-only"},{name:"get_my_trader_code",description:"Fetch your own trader code.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"set_trader_code",description:"Claim or edit your custom (vanity) TraderCode handle.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"clear_trader_code",description:"Clear your custom TraderCode handle, reverting to the wallet-derived default.",category:"pitpass",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"get_rewards_balance",description:"Fetch your TraderCodes rewards-bucket balances across reward tokens.",category:"pitpass",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"transfer_rewards",description:"Move your earned TraderCodes rewards from the rewards bucket into your own tradeable balance (ledger-only).",category:"pitpass",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"list_lead_traders",description:"Public copy trading leaderboard: lead traders ranked by ROI, PnL, followers, allocated AUM, marked AUM or win rate over a stats window (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"get_lead_trader",description:"Public profile, follow summary and stats of one lead trader, by custom TraderCode handle (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_closed_trades",description:"Public list of a lead trader's closed trades, newest first (no credentials required).",category:"copy-trading",authMode:"public",sideEffect:"read-only"},{name:"list_lead_trader_open_positions",description:"Open positions of a lead trader you currently follow (followers only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_my_lead_trader",description:"Fetch your own lead trader profile, follow summary and stats.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_followers",description:"List your followers, as a lead trader.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_my_follows",description:"List your copy trading follows and their settings.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"get_follow",description:"Fetch one of your follows with its most recent skipped mirrors and its copy account's marked equity.",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"preview_follow",description:"Preview what following a lead trader with copyExisting would open: estimated margin and fees and how many positions would be copied (read-only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"list_follow_leader_positions",description:"Open positions of the lead trader one of your follows copies (live follows only).",category:"copy-trading",authMode:"authenticated",capability:"read",sideEffect:"read-only"},{name:"upsert_lead_trader",description:"Register as a lead trader, or edit your lead profile (profit share, bio, status, minimum allocation).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"upsert_follow",description:"Follow a lead trader (moves the allocation into a new copy account) or edit one of your follows.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"stop_follow",description:"Stop one of your follows: the leader's fills stop being mirrored.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_follow_positions",description:"Close one follow's copy positions at market and keep the follow (it keeps mirroring).",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"close_all_copy_positions",description:"Close the copy positions of all your follows at market and keep the follows.",category:"copy-trading",authMode:"authenticated",capability:"market-maker",sideEffect:"mutating"},{name:"add_follow_position_margin",description:"Add margin to one of your copy positions from the follow's copy account (lowers its leverage; your margin account is never touched; no reduction). Not idempotent — after a timeout, read the follow before retrying, or the amount may be added twice.",category:"copy-trading",authMode:"authenticated",capability:"full",sideEffect:"fund-movement"},{name:"get_pulse",description:"Get the latest market-pulse news feed: AI-synthesized, per-asset headlines with sentiment tags.",category:"pulse",authMode:"public",sideEffect:"read-only"}],NAe=Fi.map((e)=>e.name),V4=Fi.filter((e)=>e.authMode==="public").map((e)=>e.name),$Ae=Fi.filter((e)=>e.authMode==="authenticated"&&e.capability==="read").map((e)=>e.name),LAe=Fi.filter((e)=>e.authMode==="authenticated"&&e.capability==="market-maker").map((e)=>e.name),BAe=Fi.filter((e)=>e.authMode==="authenticated"&&e.capability==="full").map((e)=>e.name),zAe=Fi.filter((e)=>e.excludedOnMainnet).map((e)=>e.name),Z4=Fi.filter((e)=>e.sideEffect==="fund-movement").map((e)=>e.name);var jde=new Map(Fi.map((e)=>[e.name,e.sideEffect]));function W4(e){let t=jde.get(e);if(!t)return;let r=t==="read-only";return{readOnlyHint:r,destructiveHint:!r}}var K4={read:0,"market-maker":1,full:2},YE=V4,JE=Object.fromEntries(Fi.filter((e)=>e.authMode==="authenticated").map((e)=>[e.name,{capability:e.capability??"full",...e.sideEffect==="fund-movement"?{fundMovement:!0}:{},...e.excludedOnMainnet?{excludedOnMainnet:!0}:{}}])),Y4=Object.fromEntries(Object.entries(JE).map(([e,t])=>[e,t.capability])),UAe=new Set(Z4);function J4(e){let t=JE[e];if(!t)return"full";if(t.fundMovement)return"full";return t.capability}function Q4(e){return J4(e)==="read"}function X4(e,t){if(t.network==="mainnet"&&JE[e]?.excludedOnMainnet)return!1;if(t.deny.includes(e))return!1;if(YE.includes(e))return!0;if(!t.authenticated)return!1;if(t.allow.includes(e))return!0;return K4[t.capability]>=K4[J4(e)]}var Hde=new Set([...YE,...Object.keys(Y4)]),Gde={mainnet:"https://evm-rpc.sei-apis.com",development:"https://evm-rpc-testnet.sei-apis.com",staging:"https://evm-rpc-testnet.sei-apis.com",local:"http://localhost:8545"};function e8(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function pu(e=process.env){let t=e.MONACO_PRIVATE_KEY||null;if(t&&!t.startsWith("0x"))throw Error("MONACO_PRIVATE_KEY must start with '0x'.");let r=e.MONACO_CLIENT_ID||null;if(t&&!r)throw Error("MONACO_CLIENT_ID is required when MONACO_PRIVATE_KEY is set.");let n=["mainnet","development","staging","local"],o=e.MONACO_NETWORK;if(t&&!o)throw Error(`MONACO_NETWORK must be set explicitly (one of: ${n.join(", ")}) when MONACO_PRIVATE_KEY is configured. Refusing to default to mainnet for an authenticated session.`);let i=o||"mainnet";if(!n.includes(i))throw Error(`MONACO_NETWORK must be one of: ${n.join(", ")}.`);let s=i,a=e.MONACO_CAPABILITY;if(a&&!Sb.includes(a))throw Error(`MONACO_CAPABILITY must be one of: ${Sb.join(", ")}.`);let c=a||"read",l=e8(e.MONACO_TOOL_ALLOWLIST),d=e8(e.MONACO_TOOL_DENYLIST),p=[...l,...d].filter((y)=>!Hde.has(y)).length;if(p>0)throw Error(`${p} unknown tool name(s) in MONACO_TOOL_ALLOWLIST/MONACO_TOOL_DENYLIST. Check them against the documented tool list.`);let h=e.MONACO_RPC_URL||Gde[s],g=null;if(e.MONACO_DELEGATED_OWNER_USER_ID!==void 0){let y=e.MONACO_DELEGATED_OWNER_USER_ID.trim();if(!y)throw Error("MONACO_DELEGATED_OWNER_USER_ID must be a non-empty owner user id when set.");if(!t||!r)throw Error("MONACO_DELEGATED_OWNER_USER_ID requires MONACO_PRIVATE_KEY and MONACO_CLIENT_ID (the agent authenticates as itself before adopting the owner).");g=y}return{privateKey:t,clientId:r,network:s,seiRpcUrl:h,capability:c,allow:l,deny:d,delegatedOwnerUserId:g}}function Vde(e){return e.replace(/_([a-z])/g,(t,r)=>r.toUpperCase())}function Cr(e){if(e===null||e===void 0)return e;if(typeof e!=="object")return e;if(Array.isArray(e))return e.map((r)=>Cr(r));let t={};for(let[r,n]of Object.entries(e))t[Vde(r)]=typeof n==="object"&&n!==null?Cr(n):n;return t}function Tb(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var QE=(e)=>e?`"${e}" `:"";function jm(e,t=""){if(typeof e!=="number")throw TypeError(QE(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(QE(t)+"expected integer >= 0, got "+e);return e}function Ui(e,t,r=""){if(Tb(e)&&(t===void 0||e.length===t))return e;if(t!==void 0)jm(t,"length");let n=Tb(e),o=t!==void 0?` of length ${t}`:"",i=n?`length=${e.length}`:`type=${typeof e}`,s=QE(r)+"expected Uint8Array"+o+", got "+i;if(!n)throw TypeError(s);throw RangeError(s)}var Zde=(e,t)=>{if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},t8=(e,t)=>{Zde(e,t);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw TypeError(`"${t}.__proto__" is not allowed`)};function XE(e,t=!0){if(e.destroyed)throw Error("hash was destroyed");if(t&&e.finished)throw Error("digest() was already called")}function n8(e,t){Ui(e,void 0,"output");let r=t.outputLen;if(!(e.length>=r))throw RangeError('"output" expected length >= '+r)}function fd(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _b(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Yo(e,t){return e<<32-t|e>>>t}var o8=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Wde=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ao(e){if(Ui(e),o8)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Wde[e[r]];return t}function r8(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function Cs(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(o8)try{return Uint8Array.fromHex(e)}catch(o){if(o instanceof SyntaxError)throw RangeError(o.message);throw o}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=r8(e.charCodeAt(i)),a=r8(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function fu(e){if(typeof e!=="string")throw TypeError("string expected");let t=new TextEncoder().encode(e);try{return new Uint8Array(t)}finally{fd(t)}}function eP(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];Ui(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}function Kde(e,t,r="opts"){if(t8(e,"defaults"),t!==void 0)t8(t,r);return Object.assign(Object.create(null),e,t)}function tP(e,t={}){if(typeof e!=="function")throw TypeError('"hashCons" expected function, got type='+typeof e);t=Kde({},t,"info");let r=(o,i)=>e(i).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=(o)=>e(o),Object.assign(r,t),Object.freeze(r)}function i8(e=32){jm(e,"bytesLength");let t=typeof globalThis==="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!=="function")throw Error("crypto.getRandomValues must be defined");if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var rP=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var vb=(()=>BigInt(4294967295))(),s8=BigInt(32);function Yde(e,t=!1){if(t)return{h:Number(e&vb),l:Number(e>>s8&vb)};return{h:Number(e>>s8&vb)|0,l:Number(e&vb)|0}}function a8(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=Yde(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var Jde=(e)=>e/4294967296|0,Qde=(e)=>e>>>0;function c8(e,t,r,n){let o=Jde(r),i=Qde(r);e.setUint32(t,n?i:o,n),e.setUint32(t+4,n?o:i,n)}var nP=(e,t,r)=>e>>>r,oP=(e,t,r)=>e<<32-r|t>>>r,mu=(e,t,r)=>e>>>r|t<<32-r,hu=(e,t,r)=>e<<32-r|t>>>r,Hm=(e,t,r)=>e<<64-r|t>>>r-32,Gm=(e,t,r)=>e>>>r-32|t<<64-r;function qi(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/4294967296|0)|0,l:o|0}}var u8=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),l8=(e,t,r,n)=>t+r+n+(e/4294967296|0)|0,d8=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),p8=(e,t,r,n,o)=>t+r+n+o+(e/4294967296|0)|0,f8=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),m8=(e,t,r,n,o,i)=>t+r+n+o+i+(e/4294967296|0)|0;function h8(e,t,r){return e&t^~e&r}function g8(e,t,r){return e&t^e&r^t&r}class Eb{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=_b(this.buffer)}update(e){XE(this),Ui(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length,i=!1;for(let s=0;s<o;){let a=Math.min(n-this.pos,o-s);if(a===n){let c=_b(e);for(;n<=o-s;s+=n)this.process(c,s);i=!0;continue}if(r.set(s===0&&a===o?e:e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===n)this.process(t,0),this.pos=0,i=!0}if(this.length+=e.length,i)this.roundClean();return this}digestInto(e){XE(this),n8(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;if(t[i++]=128,t.fill(0,i),this.padOffset>n-i)this.process(r,0),t.fill(0);c8(r,n-8,this.length*8,o),this.process(r,0),this.roundClean();let s=e===t?r:_b(e),a=this.outputLen,c=a/4,l=this.get();if(a%4||c>l.length)throw Error("invalid outputLen");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneIntoMeta(e){let{buffer:t,length:r,finished:n,destroyed:o,pos:i}=this;if(e.destroyed=o,e.finished=n,e.length=r,e.pos=i,i)e.buffer.set(t);return e}clone(){return this._cloneInto()}}var y8=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var b8=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var epe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),oc=new Uint32Array(64);class x8 extends Eb{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1);this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)oc[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=oc[d-15],h=oc[d-2],g=Yo(p,7)^Yo(p,18)^p>>>3,y=Yo(h,17)^Yo(h,19)^h>>>10;oc[d]=y+oc[d-7]+g+oc[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let d=0;d<64;d++){let p=Yo(s,6)^Yo(s,11)^Yo(s,25),h=l+p+h8(s,a,c)+epe[d]+oc[d]|0,y=(Yo(r,2)^Yo(r,13)^Yo(r,22))+g8(r,n,o)|0;l=c,c=a,a=s,s=i+h|0,i=o,o=n,n=r,r=h+y|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,o,i,s,a,c,l)}roundClean(){fd(oc)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),fd(this.buffer)}}class w8 extends x8{constructor(){super(32,y8)}}var S8=(()=>a8(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e)=>BigInt(e))))(),tpe=(()=>S8[0])(),rpe=(()=>S8[1])(),ic=new Uint32Array(80),sc=new Uint32Array(80);class T8 extends Eb{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1);this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:o,Cl:i,Dh:s,Dl:a,Eh:c,El:l,Fh:d,Fl:p,Gh:h,Gl:g,Hh:y,Hl:b}=this;return[e,t,r,n,o,i,s,a,c,l,d,p,h,g,y,b]}set(e,t,r,n,o,i,s,a,c,l,d,p,h,g,y,b){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=o|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=p|0,this.Gh=h|0,this.Gl=g|0,this.Hh=y|0,this.Hl=b|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let v=0;v<16;v++,t+=4)ic[v]=e.getUint32(t),sc[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){let _=ic[v-15]|0,E=sc[v-15]|0,P=mu(_,E,1)^mu(_,E,8)^nP(_,E,7),A=hu(_,E,1)^hu(_,E,8)^oP(_,E,7),C=ic[v-2]|0,N=sc[v-2]|0,F=mu(C,N,19)^Hm(C,N,61)^nP(C,N,6),R=hu(C,N,19)^Gm(C,N,61)^oP(C,N,6),V=d8(A,R,sc[v-7],sc[v-16]),Z=p8(V,P,F,ic[v-7],ic[v-16]);ic[v]=Z|0,sc[v]=V|0}let{Ah:r,Al:n,Bh:o,Bl:i,Ch:s,Cl:a,Dh:c,Dl:l,Eh:d,El:p,Fh:h,Fl:g,Gh:y,Gl:b,Hh:T,Hl:S}=this;for(let v=0;v<80;v++){let _=mu(d,p,14)^mu(d,p,18)^Hm(d,p,41),E=hu(d,p,14)^hu(d,p,18)^Gm(d,p,41),P=d&h^~d&y,A=p&g^~p&b,C=f8(S,E,A,rpe[v],sc[v]),N=m8(C,T,_,P,tpe[v],ic[v]),F=C|0,R=mu(r,n,28)^Hm(r,n,34)^Hm(r,n,39),V=hu(r,n,28)^Gm(r,n,34)^Gm(r,n,39),Z=r&o^r&s^o&s,se=n&i^n&a^i&a;T=y|0,S=b|0,y=h|0,b=g|0,h=d|0,g=p|0,{h:d,l:p}=qi(c|0,l|0,N|0,F|0),c=s|0,l=a|0,s=o|0,a=i|0,o=r|0,i=n|0;let q=u8(F,V,se);r=l8(q,N,R,Z),n=q|0}({h:r,l:n}=qi(this.Ah|0,this.Al|0,r|0,n|0)),{h:o,l:i}=qi(this.Bh|0,this.Bl|0,o|0,i|0),{h:s,l:a}=qi(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l}=qi(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:p}=qi(this.Eh|0,this.El|0,d|0,p|0),{h,l:g}=qi(this.Fh|0,this.Fl|0,h|0,g|0),{h:y,l:b}=qi(this.Gh|0,this.Gl|0,y|0,b|0),{h:T,l:S}=qi(this.Hh|0,this.Hl|0,T|0,S|0),this.set(r,n,o,i,s,a,c,l,d,p,h,g,y,b,T,S)}roundClean(){fd(ic,sc)}destroy(){this.destroyed=!0,fd(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class _8 extends T8{constructor(){super(64,b8)}}var Pb=tP(()=>new w8,rP(1));var iP=tP(()=>new _8,rP(3));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ab(e,t,r=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let n=0;n<e.length;n++)r(e[n],`${t}[${n}]`);return e}var Bn=(e,t,r)=>Ui(e,t,r),sP=jm;function ac(e,t="object"){if(e===null||typeof e!=="object"||Array.isArray(e))throw TypeError(t==="object"?"expected valid options object":`"${t}" expected object, got type=${typeof e}`);return e}function gu(e,t){if(typeof e!=="function")throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}var E8=ao,aP=(...e)=>eP(...e),P8=(e)=>Cs(e),Vm=Tb,cP=(e)=>i8(e),Ib=BigInt(0),v8=BigInt(1),npe=(e)=>e?`"${e}" `:"";function Ms(e,t=""){if(typeof e!=="boolean")throw TypeError(npe(t)+"expected boolean, got type="+typeof e);return e}function ope(e){if(typeof e==="bigint"){if(!cc(e))throw RangeError("positive bigint expected, got "+e)}else sP(e);return e}function md(e,t=""){if(typeof e!=="number"){let r=t&&`"${t}" `;throw TypeError(r+"expected number, got type="+typeof e)}if(!Number.isSafeInteger(e)){let r=t&&`"${t}" `;throw RangeError(r+"expected safe integer, got "+e)}}function I8(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?Ib:BigInt("0x"+e)}function kb(e){return I8(ao(e))}function hd(e){return I8(ao(Zm(Ui(e)).reverse()))}function uP(e,t){if(jm(t),t===0)throw Error("zero output length is invalid");e=ope(e);let r=t*2,n=e.toString(16);if(n.length>r)throw RangeError("number is too large");return Cs(n.padStart(r,"0"))}function A8(e,t){return uP(e,t).reverse()}function Zm(e){return Uint8Array.from(Bn(e))}function cc(e){return typeof e==="bigint"&&Ib<=e}function lP(e,t,r){return cc(e)&&cc(t)&&cc(r)&&t<=e&&e<r}function dP(e,t,r,n){if(!lP(t,r,n))throw RangeError("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function pP(e){if(e<Ib)throw Error("expected non-negative bigint, got "+e);return e===Ib?0:e.toString(2).length}var k8=(e)=>(md(e,"n"),(v8<<BigInt(e))-v8);function uc(e,t={},r={},n="object"){ac(e,n),ac(t,"fields"),ac(r,"optFields");function o(s,a,c){let l=n==="object"?`param "${String(s)}"`:`"${n}.${String(s)}"`,d=e[s];if(!Object.hasOwn(e,s)&&(c?d!==void 0:a!=="function"))throw TypeError(`${l} is invalid: expected own property`);if(c&&d===void 0)return;let p=typeof d;if(p!==a||d===null)throw TypeError(`${l} is invalid: expected ${a}, got ${p}`)}let i=(s,a)=>Object.entries(s).forEach(([c,l])=>o(c,l,a));i(t,!1),i(r,!0)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Mr=BigInt(0),Wt=BigInt(1),yu=BigInt(2),C8=BigInt(3),mP=BigInt(4),M8=BigInt(5),ipe=BigInt(7),N8=BigInt(8),spe=BigInt(9),ape=BigInt(15),$8=BigInt(16),cpe=BigInt("0x10000000000000000");function hr(e,t){if(t<=Mr)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Mr?r:t+r}function upe(e,t,r){if(r<=Wt)throw Error("pow: expected modulus > 1, got "+r);if(typeof t!=="bigint")throw TypeError("invalid exponent: expected bigint, got "+typeof t);if(t<Mr)throw Error("invalid exponent, negatives unsupported");if(t===Mr)return Wt;if(t===Wt)return e;let n=e%r;if(n<Mr)n+=r;if(t<cpe){let a=Wt;while(t>Mr){if(t&Wt)a=a*n%r;n=n*n%r,t>>=Wt}return a}let o=[];while(t>Mr)o.push(Number(t&ape)),t>>=mP;let i=Array(16);i[0]=Wt,i[1]=n;for(let a=2;a<16;a++)i[a]=i[a-1]*n%r;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%r,s=s*s%r,s=s*s%r,s=s*s%r;let c=o[a];if(c!==0)s=s*i[c]%r}return s}function Jo(e,t,r){if(r<=Wt)throw Error("pow2: expected modulus > 1, got "+r);if(t<Mr)throw Error("pow2: expected non-negative exponent, got "+t);let n=e;while(t-- >Mr)n*=n,n%=r;return n}function R8(e,t){if(e===Mr)throw Error("invert: expected non-zero number");if(t<=Wt)throw Error("invert: expected modulus > 1, got "+t);let r=hr(e,t),n=t,o=Mr,i=Wt;while(r!==Mr){let a=n/r,c=n-r*a,l=o-i*a;n=r,r=c,o=i,i=l}if(n!==Wt)throw Error("invert: does not exist");return hr(o,t)}function hP(e,t,r){let n=e;if(!n.eql(n.sqr(t),r))throw Error("Cannot find square root")}function gP(e,t){if((e&Wt)===Mr)throw Error(t+": expected odd modulus, got "+e)}function L8(e,t){let r=e,n=(r.ORDER+Wt)/mP,o=r.pow(t,n);return hP(r,o,t),o}function lpe(e,t){let r=e,n=(r.ORDER-M8)/N8,o=r.mul(t,yu),i=r.pow(o,n),s=r.mul(t,i),a=r.mul(r.mul(s,yu),i),c=r.mul(s,r.sub(a,r.ONE));return hP(r,c,t),c}function dpe(e){let t=Ob(e),r=B8(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+ipe)/$8;return(a,c)=>{let l=a,d=l.pow(c,s),p=l.mul(d,n),h=l.mul(d,o),g=l.mul(d,i),y=l.eql(l.sqr(p),c),b=l.eql(l.sqr(h),c);d=l.cmov(d,p,y),p=l.cmov(g,h,b);let T=l.eql(l.sqr(p),c),S=l.cmov(d,p,T);return hP(l,S,c),S}}function B8(e){if(e<C8)throw Error("sqrt is not defined for small field");gP(e,"tonelliShanks");let t=e-Wt,r=0;while(t%yu===Mr)t/=yu,r++;let n=yu,o=Ob(e);while(Wm(o,n)===1)if(n++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return L8;let i=o.pow(n,t),s=(t+Wt)/yu;return function(c,l){let d=c;if(d.is0(l))return l;if(Wm(d,l)!==1)throw Error("Cannot find square root");let p=r,h=d.mul(d.ONE,i),g=d.pow(l,t),y=d.pow(l,s);while(!d.eql(g,d.ONE)){if(d.is0(g))throw Error("Cannot find square root: probably non-prime P");let b=1,T=d.sqr(g);while(!d.eql(T,d.ONE))if(b++,T=d.sqr(T),b===p)throw Error("Cannot find square root");let S=Wt<<BigInt(p-b-1),v=d.pow(h,S);p=b,h=d.sqr(v),g=d.mul(g,h),y=d.mul(y,v)}return y}}function ppe(e){if(gP(e,"Fp.sqrt"),e%mP===C8)return L8;if(e%N8===M8)return lpe;if(e%$8===spe)return dpe(e);return B8(e)}var z8=(e,t)=>(hr(e,t)&Wt)===Wt,fpe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gd(e){if(ac(e,"field"),typeof e.ORDER!=="bigint")throw TypeError('param "ORDER" is invalid: expected bigint, got '+typeof e.ORDER);md(e.BYTES,"BYTES"),md(e.BITS,"BITS");for(let t of fpe)gu(e[t],"field."+t);if(e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=Wt)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function Rb(e,t,r=!1){gd(e),Ab(t,"nums"),Ms(r,"passZero");let n=e,o=Array(t.length).fill(r?n.ZERO:void 0),i=t.reduce((a,c,l)=>{if(n.is0(c))return a;return o[l]=a,n.mul(a,c)},n.ONE),s=n.inv(i);return t.reduceRight((a,c,l)=>{if(n.is0(c))return a;return o[l]=n.mul(a,o[l]),n.mul(a,c)},s),o}function Wm(e,t){gd(e);let r=e;gP(r.ORDER,"FpLegendre");let n=(r.ORDER-Wt)/yu,o=r.pow(t,n),i=r.eql(o,r.ONE),s=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function mpe(e,t){if(t!==void 0)sP(t);if(e<=Mr)throw Error("invalid n length: expected positive n, got "+e);if(t!==void 0&&t<1)throw Error("invalid n length: expected positive bit length, got "+t);let r=pP(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${r})`);let n=t!==void 0?t:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var O8=new WeakMap;class fP{ORDER;BITS;BYTES;isLE;ZERO=Mr;ONE=Wt;_lengths;_mod;constructor(e,t={}){if(e<=Wt)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:n,nByteLength:o}=mpe(e,r);if(o>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,Object.freeze(this)}create(e){return hr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Mr<=e&&e<this.ORDER}is0(e){return e===Mr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Wt)===Wt}neg(e){return hr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return hr(e*e,this.ORDER)}add(e,t){return hr(e+t,this.ORDER)}sub(e,t){return hr(e-t,this.ORDER)}mul(e,t){return hr(e*t,this.ORDER)}pow(e,t){return upe(e,t,this.ORDER)}div(e,t){return hr(e*R8(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return R8(e,this.ORDER)}sqrt(e){let t=O8.get(this);if(!t)O8.set(this,t=ppe(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?A8(e,this.BYTES):uP(e,this.BYTES)}fromBytes(e,t=!1){Bn(e);let{_lengths:r,BYTES:n,isLE:o,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>n)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(n);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==n)throw Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let a=o?hd(e):kb(e);if(s)a=hr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Rb(this,e,!0)}cmov(e,t,r){return Ms(r,"condition"),r?t:e}}function Ob(e,t={}){return Object.freeze(fP.prototype),new fP(e,t)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var xP=BigInt(0),Km=BigInt(1),hpe=BigInt(4),yP=16,D8=128,gpe=5,F8=(()=>2147483648)();function Ym(e){let t=e;if(typeof t!=="function")throw TypeError('"Point" expected constructor, got type='+typeof e);gu(t.fromAffine,"Point.fromAffine"),gu(t.fromBytes,"Point.fromBytes"),gu(t.fromHex,"Point.fromHex"),ac(t.BASE,"Point.BASE"),ac(t.ZERO,"Point.ZERO"),gd(t.Fp),gd(t.Fn)}function q8(e,t){Ym(e),j8(t,e);let r=Rb(e.Fp,t.map((n)=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function ype(e,t,r=1){if(!Number.isSafeInteger(e)||e<r||e>t)throw Error("invalid window size, expected ["+r+".."+t+"], got W="+e)}function bpe(e,t){let r=e*(4*t+128);if(r>F8)throw Error("invalid window size: table would need ~"+Math.ceil(r/1048576)+" MiB, max "+F8/1048576+" MiB")}function xpe(e,t){if(e===void 0)return;gu(e,"randomBytes");try{let r=e(t);if(!Vm(r)||r.length!==t)return}catch{return}return e}function j8(e,t){Ab(e,"points"),e.forEach((r,n)=>{if(!(r instanceof t))throw Error("invalid point at index "+n)})}function wpe(e,t,r){if(!Array.isArray(e))throw Error("array of scalars expected");e.forEach((n,o)=>{if(!(r===void 0?t.isValid(n):cc(n)&&n<r))throw Error("invalid scalar at index "+o)})}var H8=new WeakMap;function bP(e){return H8.get(e)||1}function Spe(e,t){let r=e.double(),n=[e];for(let o=1;o<t;o++)n.push(n[o-1].add(r));return n}function Tpe(e,t){let r=2**t,n=r/2,o=BigInt(r-1),i=[];while(e>xP){let s=0;if(e&Km){if(s=Number(e&o),s>=n)s-=r;e-=BigInt(s)}i.push(s),e>>=Km}return i}function _pe(e,t,r){let n=2**t,o=n/2,i=BigInt(n-1),s=BigInt(t),a=[];for(let c=0;c<r;c++){let l=Number(e&i);if(e>>=s,l>o)l-=n,e+=Km;a.push(l)}if(e!==xP)throw Error("invalid wnaf");return a}function vpe(e,t,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=e;for(let i=n-1;i>=0;i--){if(i!==n-1)o=o.double();for(let s=0;s<r.length;s++){let a=r[s][i];if(a){let c=t[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}class wP{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Ym(e),this.randomBytes=xpe(t,yP),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let n=Math.ceil(r/t)+1,o=2**(t-1),i=[],s=e;for(let a=0;a<n;a++){let c=s;for(let l=0;l<o;l++)i.push(c),c=c.add(s);s=i[i.length-1].double()}return{W:t,bits:r,windows:n,comp:i}}wnafCachedCT(e,t){let{W:r,windows:n,comp:o}=e,i=2**(r-1),s=_pe(t,r,n),a=this.ZERO,c=this.BASE;for(let l=0;l<n;l++){let d=s[l],p=l*i,h=Math.abs(d)-1,g=o[p];for(let b=1;b<i;b++)g=b===h?o[p+b]:g;let y=g.negate();if(d===0)c=c.add(o[p]);else a=a.add(d<0?y:g)}return{p:a,f:c}}getWnafPrecomputes(e,t,r,n){let o=this.wnafPrecomputes.get(t),i=o?.find((s)=>s.W===e&&s.bits===r);if(!i){if(i=this.buildWnafTable(t,e,r),typeof n==="function")i={...i,comp:n(i.comp)};if(!o)o=[],this.wnafPrecomputes.set(t,o);o.push(i)}return i}assertPoint(e){if(!(e instanceof this.Point))throw TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!lP(t,Km,this.Point.Fn.ORDER))throw Error("invalid scalar")}runCT(e,t,r,n){let o=bP(e);if(o===1)return this.fixedWindowCT(e,t,r);return this.wnafCachedCT(this.getWnafPrecomputes(o,e,r,n),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw Error("randomBytes is required for scalar blinding");let n=this.Point.Fn.BITS+D8,o=this.randomBytes(yP);if(!Vm(o)||o.length!==yP)throw Error("randomBytes returned invalid byte array");o[0]=o[0]&63|128;let i=t+kb(o)*this.Point.Fn.ORDER;return this.runCT(e,i,n,r)}fixedWindowCT(e,t,r){let n=gpe,o=1<<n,i=k8(n),s=Array(o);s[0]=this.ZERO;for(let l=1;l<o;l++)s[l]=s[l-1].add(e);let a=Math.ceil(r/n),c=this.ZERO;for(let l=a-1;l>=0;l--){if(l!==a-1)for(let h=0;h<n;h++)c=c.double();let d=Number(t>>BigInt(l*n)&i),p=s[0];for(let h=1;h<o;h++)p=h===d?s[h]:p;c=c.add(p)}return{p:c,f:c}}shouldBlind(e,t){if(this.randomBytes===void 0)return!1;if(t===Km)return!0;if(e!==this.BASE)return!1;if(this.baseCanBeBlinded===void 0)this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0();return this.baseCanBeBlinded}mulSecret(e,t,r,n){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,n):this.mulCT(e,t,n)}mulUnsafe(e,t,r){if(this.assertPoint(e),!cc(t))throw Error("invalid scalar");let n=bP(e);if(n===1||t>=this.Point.Fn.ORDER)return Epe(this.Point,[e],[t],!0);let o=this.getWnafPrecomputes(n,e,this.bits,r);return this.wnafCachedCT(o,t).p}setWindowSize(e,t){this.assertPoint(e),ype(t,this.bits);let r=Math.ceil((this.bits+D8)/t)+1;bpe(r*2**(t-1),this.Point.Fp.BYTES),H8.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return bP(e)!==1}}function Epe(e,t,r,n=!1){if(Ym(e),j8(t,e),Ms(n,"allowOversized"),wpe(r,e.Fn,n?e.Fn.ORDER**hpe:void 0),t.length!==r.length)throw Error("arrays of points and scalars must have equal length");let o=t.map((s)=>Spe(s,4)),i=r.map((s)=>Tpe(s,4));return vpe(e.ZERO,o,i)}function U8(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return gd(t),t}else return Ob(e,{isLE:r})}function G8(e,t,r={},n){if(e!=="weierstrass"&&e!=="edwards")throw Error('expected curve type "weierstrass" or "edwards"');if(n===void 0)n=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);uc(r);for(let c of["p","n","h"]){let l=t[c];if(!(cc(l)&&l!==xP))throw Error(`CURVE.${c} must be positive bigint`)}let o=U8(t.p,r.Fp,n),i=U8(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}function V8(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Cb=BigInt(0),Mb=BigInt(1),Nb=BigInt(2),Ppe=BigInt(4),Z8=BigInt(8);function Ipe(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function W8(e,t={}){uc(t,{},{},"extraOpts");let r=t,n=G8("edwards",e,r,r.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;if(Wm(o,s.a)!==1)throw Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Wm(o,s.d)!==-1)throw Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");uc(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?cP:r.randomBytes,l=Nb<<BigInt(o.BYTES*8)-Mb;function d(v){if(!o.isOdd)throw Error("Field does not have .isOdd()");return o.isOdd(v)}let p=r.uvRatio===void 0?(v,_)=>{try{return{isValid:!0,value:o.sqrt(o.div(v,_))}}catch(E){return{isValid:!1,value:Cb}}}:r.uvRatio;if(!Ipe(o,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");let h=o.eql(s.a,o.neg(o.ONE))?(v)=>o.neg(v):o.eql(s.a,o.ONE)?(v)=>v:(v)=>o.mul(s.a,v);function g(v,_,E=!1){let P=E?Mb:Cb;return dP("coordinate "+v,_,P,l),_}function y(v){if(!(v instanceof b))throw Error("EdwardsPoint expected")}class b{static BASE=new b(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new b(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(v,_,E,P){this.X=g("x",v),this.Y=g("y",_),this.Z=g("z",E,!0),this.T=g("t",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){if(v instanceof b)throw Error("extended point not allowed");let{x:_,y:E}=v||{};return g("x",_),g("y",E),new b(_,E,o.ONE,o.mul(_,E))}static fromBytes(v,_=!1){let E=o.BYTES,{a:P,d:A}=s;v=Zm(Bn(v,E,"point")),Ms(_,"zip215");let C=Zm(v),N=v[E-1];C[E-1]=N&-129;let F=hd(C),R=_?l:o.ORDER;dP("point.y",F,Cb,R);let V=o.sqr(F),Z=o.sub(V,o.ONE),se=o.sub(o.mulN(A,V),P),{isValid:q,value:L}=p(Z,se);if(!q)throw Error("bad point: invalid y coordinate");let G=d(L),ae=(N&128)!==0;if(!_&&o.is0(L)&&ae)throw Error("bad point: x=0 and x_0=1");if(ae!==G)L=o.neg(L);return b.fromAffine({x:L,y:F})}static fromHex(v,_=!1){return b.fromBytes(P8(v),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=6,_=!0){if(S.setWindowSize(this,v),!_)this.multiply(Nb);return this}assertValidity(){let v=this,{a:_,d:E}=s;if(v.is0())throw Error("bad point: ZERO");let{X:P,Y:A,Z:C,T:N}=v,F=o.sqr(P),R=o.sqr(A),V=o.sqr(C),Z=o.sqr(V),se=o.mul(F,_),q=o.mul(o.add(se,R),V),L=o.add(Z,o.mul(E,o.mul(F,R)));if(!o.eql(q,L))throw Error("bad point: equation left != right (1)");let G=o.mul(P,A),ae=o.mul(C,N);if(!o.eql(G,ae))throw Error("bad point: equation left != right (2)")}equals(v){y(v);let{X:_,Y:E,Z:P}=this,{X:A,Y:C,Z:N}=v,F=o.mul(_,N),R=o.mul(A,P),V=o.mul(E,N),Z=o.mul(C,P);return o.eql(F,R)&&o.eql(V,Z)}is0(){return this.equals(b.ZERO)}negate(){return new b(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:v,Y:_,Z:E}=this,P=o.sqr(v),A=o.sqr(_),C=o.mul(o.sqr(E),Nb),N=h(P),F=o.addN(v,_),R=o.sub(o.subN(o.sqr(F),P),A),V=o.addN(N,A),Z=o.subN(V,C),se=o.subN(N,A),q=o.mul(R,Z),L=o.mul(V,se),G=o.mul(R,se),ae=o.mul(Z,V);return new b(q,L,ae,G)}add(v){y(v);let{d:_}=s,{X:E,Y:P,Z:A,T:C}=this,{X:N,Y:F,Z:R,T:V}=v,Z=o.mul(E,N),se=o.mul(P,F),q=o.mul(o.mulN(C,_),V),L=o.mul(A,R),G=o.sub(o.subN(o.mulN(o.addN(E,P),o.addN(N,F)),Z),se),ae=o.subN(L,q),we=o.addN(L,q),ye=o.sub(se,h(Z)),Me=o.mul(G,ae),bt=o.mul(we,ye),be=o.mul(G,ye),Pt=o.mul(ae,we);return new b(Me,bt,Pt,be)}subtract(v){return y(v),this.add(v.negate())}multiply(v){if(!i.isValidNot0(v))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:_,f:E}=S.mulSecret(this,v,a,T);return T([_,E])[0]}multiplyUnsafe(v){if(!i.isValid(v))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(v===Cb)return b.ZERO;if(this.is0()||v===Mb)return this;return S.mulUnsafe(this,v,T)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return S.mulUnsafe(this,s.n).is0()}toAffine(v){let _=this,E=v;if(E!=null&&typeof E!=="bigint")throw TypeError('"invertedZ" expected bigint, got type='+typeof E);let{X:P,Y:A,Z:C}=_,N=_.is0();if(E==null)E=N?o.create(Z8):o.inv(C);let F=o.mul(P,E),R=o.mul(A,E),V=o.mul(C,E);if(N)return{x:o.ZERO,y:o.ONE};if(!o.eql(V,o.ONE))throw Error("invZ was invalid");return{x:F,y:R}}clearCofactor(){if(a===Mb)return this;if(a===Nb)return this.double();if(a===Ppe)return this.double().double();if(a===Z8)return this.double().double().double();return this.multiplyUnsafe(a)}toBytes(){let{x:v,y:_}=this.toAffine(),E=o.toBytes(_);return E[E.length-1]|=d(v)?128:0,E}toHex(){return E8(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let T=(v)=>q8(b,v),S=new wP(b,c);if(S.bits>=6)b.BASE.precompute(6);return Object.freeze(b.prototype),Object.freeze(b),b}function K8(e,t,r={}){if(Ym(e),typeof t!=="function")throw Error('"hash" function param is required');let n=t,o=r;uc(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=e,l=n.outputLen,d=2*a.BYTES;if(l!==void 0){if(md(l,"hash.outputLen"),l!==d)throw Error(`hash.outputLen must be ${d}, got ${l}`)}let p=o.randomBytes===void 0?cP:o.randomBytes,{toMontgomery:h,toMontgomerySecret:g}=o,y=o.adjustScalarBytes===void 0?(q)=>q:o.adjustScalarBytes,b=o.domain===void 0?(q,L,G)=>{if(Ms(G,"phflag"),L.length||G)throw Error("Contexts/pre-hash are not supported");return q}:o.domain;function T(q){return c.create(hd(q))}function S(q){let L=F.secretKey;Bn(q,F.secretKey,"secretKey");let G=Bn(n(q),2*L,"hashedSecretKey"),ae=y(G.slice(0,L)),we=G.slice(L,2*L),ye=T(ae);return{head:ae,prefix:we,scalar:ye}}function v(q){let{head:L,prefix:G,scalar:ae}=S(q),we=s.multiply(ae),ye=we.toBytes();return{head:L,prefix:G,scalar:ae,point:we,pointBytes:ye}}function _(q){return v(q).pointBytes}function E(q=Uint8Array.of(),...L){let G=aP(...L);return T(n(b(G,Bn(q,void 0,"context"),!!i)))}function P(q,L,G={}){if(uc(G,{},{},"options"),q=Zm(Bn(q,void 0,"message")),i)q=i(q);let{prefix:ae,scalar:we,pointBytes:ye}=v(L),Me=E(G.context,ae,q),bt=s.multiply(Me).toBytes(),be=E(G.context,bt,ye,q),Pt=c.create(Me+be*we);if(!c.isValid(Pt))throw Error("sign failed: invalid s");let Ye=aP(bt,c.toBytes(Pt));return Bn(Ye,F.signature,"result")}let A={zip215:o.zip215};function C(q,L,G,ae=A){uc(ae);let{context:we}=ae,ye=ae.zip215===void 0?!!A.zip215:ae.zip215,Me=F.signature;if(q=Bn(q,Me,"signature"),L=Bn(L,void 0,"message"),G=Bn(G,F.publicKey,"publicKey"),ye!==void 0)Ms(ye,"zip215");if(i)L=i(L);let bt=Me/2,be=q.subarray(0,bt),Pt=hd(q.subarray(bt,Me)),Ye,rt,lr;try{Ye=e.fromBytes(G,ye),rt=e.fromBytes(be,ye),lr=s.multiplyUnsafe(Pt)}catch(Yr){return!1}if(!ye&&Ye.isSmallOrder())return!1;let En=E(we,be,G,L);return rt.add(Ye.multiplyUnsafe(En)).subtract(lr).clearCofactor().is0()}let N=a.BYTES,F={secretKey:N,publicKey:N,signature:2*N,seed:N};function R(q){return q=q===void 0?p(F.seed):q,Bn(q,F.seed,"seed")}function V(q){return Vm(q)&&q.length===F.secretKey}function Z(q,L){try{return!!e.fromBytes(q,L===void 0?A.zip215:L)}catch(G){return!1}}let se={getExtendedPublicKey:v,randomSecretKey:R,isValidSecretKey:V,isValidPublicKey:Z,toMontgomery(q){if(h===void 0)throw Error("Montgomery conversion is not supported for this curve");return h(e.fromBytes(q))},toMontgomerySecret(q){if(g===void 0)throw Error("Montgomery conversion is not supported for this curve");return g(q)}};return Object.freeze(F),Object.freeze(se),Object.freeze({keygen:V8(R,_),getPublicKey:_,sign:P,verify:C,utils:se,Point:e,lengths:F})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var SP=BigInt(1),Y8=BigInt(2);var Ape=BigInt(5),kpe=BigInt(8),TP=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Rpe=(()=>({p:TP,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:kpe,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Ope(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=TP,a=e*e%i*e%i,c=Jo(a,Y8,i)*a%i,l=Jo(c,SP,i)*e%i,d=Jo(l,Ape,i)*l%i,p=Jo(d,t,i)*d%i,h=Jo(p,r,i)*p%i,g=Jo(h,n,i)*h%i,y=Jo(g,o,i)*g%i,b=Jo(y,o,i)*g%i,T=Jo(b,t,i)*d%i;return{pow_p_5_8:Jo(T,Y8,i)*e%i,b2:a}}function X8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var J8=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Cpe(e,t){let r=TP,n=hr(t*t*t,r),o=hr(n*n*t,r),i=Ope(e*o).pow_p_5_8,s=hr(e*n*i,r),a=hr(t*s*s,r),c=s,l=hr(s*J8,r),d=a===e,p=a===hr(-e,r),h=a===hr(-e*J8,r);if(d)s=c;if(p||h)s=l;if(z8(s,r))s=hr(-s,r);return{isValid:d||p,value:s}}var _P=W8(Rpe,{uvRatio:Cpe}),Q8=(()=>_P.Fp)();function Mpe(e){let{y:t}=e;return Q8.toBytes(Q8.div(SP+t,SP-t))}function Npe(e){let t=_P.Fp.BYTES;return Ui(e,t),X8(iP(e.subarray(0,t))).subarray(0,t)}function $pe(e){return K8(_P,iP,Object.assign({adjustScalarBytes:X8,toMontgomery:Mpe,toMontgomerySecret:Npe,zip215:!0},e))}var yd=$pe({});function $b(){if(typeof globalThis.crypto?.getRandomValues!=="function")throw Error("Secure randomness (crypto.getRandomValues) is unavailable; cannot generate a session keypair.");let e=yd.utils.randomSecretKey();return{publicKey:yd.getPublicKey(e),privateKey:e}}function Lb(e){return ao(e.publicKey)}function Bb(e){return ao(e.privateKey)}function eF(e,t){return{publicKey:Cs(e),privateKey:Cs(t)}}function tF(e){return ao(Pb(e))}function rF(e,t,r,n){return`${e.toUpperCase()}
131
131
  ${t}
132
132
  ${r}
133
133
  ${n}`}function nF(e,t){return`WS-AUTH
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xmonaco/mcp-server",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "type": "module",
5
5
  "homepage": "https://docs.0xmonaco.com/sdk/typescript",
6
6
  "description": "MCP server for the Monaco SDK",
@@ -21,8 +21,8 @@
21
21
  },
22
22
  "author": "@codebycarson",
23
23
  "dependencies": {
24
- "@0xmonaco/core": "1.1.1",
25
- "@0xmonaco/types": "1.1.1",
24
+ "@0xmonaco/core": "1.1.2",
25
+ "@0xmonaco/types": "1.1.2",
26
26
  "@modelcontextprotocol/sdk": "^1.32.1",
27
27
  "node-fetch": "^3.3.2",
28
28
  "viem": "^2.57.10",