@reddb-io/red-skills 3.0.2 → 3.0.4

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.
@@ -50,7 +50,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
50
50
  `:`[${n[c]}\r
51
51
  ]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!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 Ya(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??je(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===E.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Xa(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===E.ZodBranded&&e.keyType._def.type._def.typeName===E.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Ka(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function Kv(e,t){if(t.mapStrategy==="record")return Ya(e,t);let r=W(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||je(t),n=W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||je(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Xv(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 Yv(e){return e.target==="openAi"?void 0:{not:je({...e,currentPath:[...e.currentPath,"not"]})}}function Qv(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Yi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function tb(e,t){if(t.target==="openApi3")return eb(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Yi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Yi[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"];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 eb(e,t)}var eb=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>W(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 rb(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Yi[e.innerType._def.typeName],nullable:!0}:{type:[Yi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function nb(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",cf(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,t):ie(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,t):ie(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,t));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,t);break}return r}function ob(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 u=mO(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=W(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let s=pO(e,t);return s!==void 0&&(n.additionalProperties=s),n}function pO(e,t){if(e.catchall._def.typeName!=="ZodNever")return W(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 mO(e){try{return e.isOptional()}catch{return!0}}var ib=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return W(e.innerType._def,t);let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:je(t)},r]}:je(t)};var sb=(e,t)=>{if(t.pipeStrategy==="input")return W(e.in._def,t);if(t.pipeStrategy==="output")return W(e.out._def,t);let r=W(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=W(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function ab(e,t){return W(e.type._def,t)}function cb(e,t){let n={type:"array",uniqueItems:!0,items:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ie(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ie(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function ub(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:W(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function lb(e){return{not:je(e)}}function db(e){return je(e)}var fb=(e,t)=>W(e.innerType._def,t);var pb=(e,t,r)=>{switch(t){case E.ZodString:return Xa(e,r);case E.ZodNumber:return nb(e,r);case E.ZodObject:return ob(e,r);case E.ZodBigInt:return Lv(e,r);case E.ZodBoolean:return Fv();case E.ZodDate:return uf(e,r);case E.ZodUndefined:return lb(r);case E.ZodNull:return Qv(r);case E.ZodArray:return Zv(e,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return tb(e,r);case E.ZodIntersection:return Wv(e,r);case E.ZodTuple:return ub(e,r);case E.ZodRecord:return Ya(e,r);case E.ZodLiteral:return Jv(e,r);case E.ZodEnum:return Bv(e);case E.ZodNativeEnum:return Xv(e);case E.ZodNullable:return rb(e,r);case E.ZodOptional:return ib(e,r);case E.ZodMap:return Kv(e,r);case E.ZodSet:return cb(e,r);case E.ZodLazy:return()=>e.getter()._def;case E.ZodPromise:return ab(e,r);case E.ZodNaN:case E.ZodNever:return Yv(r);case E.ZodEffects:return Hv(e,r);case E.ZodAny:return je(r);case E.ZodUnknown:return db(r);case E.ZodDefault:return Vv(e,r);case E.ZodBranded:return Ka(e,r);case E.ZodReadonly:return fb(e,r);case E.ZodCatch:return Uv(e,r);case E.ZodPipeline:return sb(e,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(t)}};function W(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==Dv)return a}if(n&&!r){let a=hO(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=pb(e,e.typeName,t),s=typeof i=="function"?W(i(),t):i;if(s&&gO(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var hO=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ga(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),je(t)):t.$refStrategy==="seen"?je(t):void 0}},gO=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var ff=(e,t)=>{let r=qv(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??je(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=W(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??je(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),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}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),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."),a};function yO(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function pf(e,t){return At(e)?Id(e,{target:yO(t?.target),io:t?.pipeStrategy??"input"}):ff(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function mf(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ka(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function hf(e,t){let r=Wr(e,t);if(!r.success)throw r.error;return r.data}var _O=6e4,Qa=class{constructor(t){this._options=t,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(Ca,r=>{this._oncancel(r)}),this.setNotificationHandler(Ia,r=>{this._onprogress(r)}),this.setRequestHandler(ja,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Na,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(U.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Da,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,h=new Z(d.error.code,d.error.message,d.error.data);l(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new Z(U.InvalidParams,`Task not found: ${i}`);if(!Kr(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Kr(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Gr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Aa,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new Z(U.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Za,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(Kr(o.status))throw new Z(U.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Z(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof Z?o:new Z(U.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Z.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Ui(i)||kv(i)?this._onresponse(i):Wd(i)?this._onrequest(i,s):Sv(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[Gr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=wv(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,h)=>{if(s.signal.aborted)throw new Z(U.ConnectionClosed,"Request was cancelled");let m={...h,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});let p=m.relatedTask?.taskId??i;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ui(t))n(t);else{let s=new Z(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Ui(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Ui(t))o(t);else{let s=Z.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof Z?s:new Z(U.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Ro,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Z(U.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Kr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(U.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(U.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Z?s:new Z(U.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=T=>{l(T)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(T){d(T);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Gr]:c}});let p=T=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(T)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`)));let z=T instanceof Z?T:new Z(U.RequestTimeout,String(T));l(z)};this._responseHandlers.set(h,T=>{if(!n?.signal?.aborted){if(T instanceof Error)return l(T);try{let z=Wr(r,T.result);z.success?u(z.data):l(z.error)}catch(z){l(z)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let y=n?.timeout??_O,v=()=>p(Z.fromError(U.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(h,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let P=c?.taskId;if(P){let T=z=>{let M=this._responseHandlers.get(h);M?M(z):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,T),this._enqueueTaskMessage(P,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(h),l(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(T=>{this._cleanupTimeout(h),l(T)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ma,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},qa,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Rv,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Gr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Gr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Gr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=mf(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=hf(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=mf(t);this._notificationHandlers.set(n,o=>{let i=hf(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&Wd(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new Z(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new Z(U.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new Z(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new Z(U.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=Ji.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Kr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new Z(U.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Kr(a.status))throw new Z(U.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let u=Ji.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Kr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function mb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function hb(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];mb(s)&&mb(i)?r[o]={...s,...i}:r[o]=i}return r}var s$=Qs(tm(),1),a$=Qs(i$(),1);function w1(){let e=new s$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,a$.default)(e),e}var Ic=class{constructor(t){this._ajv=t??w1()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Nc=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(i.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==d.size||![...l].every(h=>d.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Xi,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},Oo,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function c$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function u$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Mc=class extends Qa{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ki.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ic,this.setRequestHandler(Kd,n=>this._oninitialize(n)),this.setNotificationHandler(Xd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(of,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=Ki.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Nc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=hb(this._capabilities,t)}setRequestHandler(t,r){let o=Jr(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(At(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=Wr(Eo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new Z(U.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,h=await Promise.resolve(r(c,u));if(d.task){let p=Wr(Ro,h);if(!p.success){let y=p.error instanceof Error?p.error.message:String(p.error);throw new Z(U.InvalidParams,`Invalid task creation result: ${y}`)}return p.data}let m=Wr(Wa,h);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new Z(U.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){u$(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&c$(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:_v.includes(r)?r:Hd,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"},Oa)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},sf,r):this.request({method:"sampling/createMessage",params:t},Xi,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},Oo,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Oo,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Z(U.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Z?s:new Z(U.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},af,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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 d$=Symbol.for("mcp.completable");function um(e){return!!e&&typeof e=="object"&&d$ in e}function f$(e){return e[d$]?.complete}var l$;(function(e){e.Completable="McpCompletable"})(l$||(l$={}));var x1=/^[A-Za-z0-9._-]{1,128}$/;function $1(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"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!x1.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 S1(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 lm(e){let t=$1(e);return S1(e,t.warnings),t.isValid}var Dc=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Ac=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Mc(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Dc(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Ba)),this.server.assertCanSetRequestHandler(sn(Eo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ba,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=Po(r.inputSchema);return o?pf(o,{strictUnions:!0,pipeStrategy:"input"}):k1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Po(r.outputSchema);o&&(n.outputSchema=pf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Eo,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new Z(U.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new Z(U.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new Z(U.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof Z&&n.code===U.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=Po(t.inputSchema)??t.inputSchema,s=await $a(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=Sa(a);throw new Z(U.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(U.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Po(t.outputSchema),i=await $a(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=Sa(s);throw new Z(U.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(h=>setTimeout(h,l));let d=await n.taskStore.getTask(c);if(!d)throw new Z(U.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(sn(Ja)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ja,async t=>{switch(t.params.ref.type){case"ref/prompt":return Iv(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Nv(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Z(U.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(U.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Rs;let i=Jr(n.argsSchema)?.[t.params.argument.name];if(!um(i))return Rs;let s=f$(i);if(!s)return Rs;let a=await s(t.params.argument.value,t.params.context);return m$(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Rs;throw new Z(U.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Rs;let i=await o(t.params.argument.value,t.params.context);return m$(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(La)),this.server.assertCanSetRequestHandler(sn(Fa)),this.server.assertCanSetRequestHandler(sn(Ua)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(La,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Fa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ua,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(U.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new Z(U.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Va)),this.server.assertCanSetRequestHandler(sn(Ha)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Va,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?P1(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ha,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new Z(U.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=Po(n.argsSchema),i=await $a(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=Sa(c);throw new Z(U.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==t&&(delete this._registeredResourceTemplates[t],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Vn(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Vn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let u=c instanceof bt?c._def?.innerType:c;return um(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,u){lm(t);let l={title:r,description:n,inputSchema:p$(o),outputSchema:p$(i),annotations:s,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&lm(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Vn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Vn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(dm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!dm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},u,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var k1={type:"object",properties:{}};function h$(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function g$(e){return"_def"in e||"_zod"in e||h$(e)}function dm(e){return typeof e!="object"||e===null||g$(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(h$)}function p$(e){if(e){if(dm(e))return Vn(e);if(!g$(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function P1(e){let t=Jr(e);return t?Object.entries(t).map(([r,n])=>{let o=J_(n),i=G_(n);return{name:r,description:o,required:!i}}):[]}function sn(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ka(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function m$(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Rs={completion:{values:[],hasMore:!1}};import _$ from"node:process";var qc=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
52
52
  `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),T1(r)}clear(){this._buffer=void 0}};function T1(e){return Pv.parse(JSON.parse(e))}function y$(e){return JSON.stringify(e)+`
53
- `}var Zc=class{constructor(t=_$.stdin,r=_$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new qc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new 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(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){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(t){return new Promise(r=>{let n=y$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function fm(e){let t={app:e,version:R1(Ko("__RED_BUILD_VERSION__",()=>"3.0.2")??"0.0.0-dev"),gitSha:Ko("__RED_BUILD_GIT_SHA__",()=>"77f6a6e5ac33113a7417bd6d761515ec213cd0dd")??"unknown",buildTime:Ko("__RED_BUILD_TIME__",()=>"2026-07-30T22:31:19-03:00")??"unknown",bundleAsset:Ko("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Ko("__REDDB_SDK_VERSION__",()=>""),n=Ko("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function R1(e){return e.startsWith("v")?e.slice(1):e}function v$(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ko(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var b$={"=":"data",":=":{to:"data",typed:!0},":":"meta"},z1=/^[a-z][a-z0-9+.-]*:\/\//i;function E1(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function O1(e=b$){return Object.entries(e).map(([t,r])=>E1(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function C1(e){return/^-\d+(\.\d+)?$/.test(e)}function zs(e){return!(!e||e.startsWith("-")&&!C1(e))}function Lc(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function w$(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>w$(r.trim())):e}function ro(e,t){switch(t){case"boolean":return j1(e);case"number":return I1(e);case"array":return e.split(",").map(r=>Lc(r.trim()));default:return e}}function j1(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function I1(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function an(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function N1(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function $e(e,t){return{type:e,value:t}}function M1(e){let t=[],r=A1(e);if(t.push($e("section-header","Usage:"),$e("text"," "),$e("usage-text",r),$e("newline",`
53
+ `}var Zc=class{constructor(t=_$.stdin,r=_$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new qc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new 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(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){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(t){return new Promise(r=>{let n=y$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function fm(e){let t={app:e,version:R1(Ko("__RED_BUILD_VERSION__",()=>"3.0.4")??"0.0.0-dev"),gitSha:Ko("__RED_BUILD_GIT_SHA__",()=>"93051f3eda65f6e0cd40c92339034c3e119295e4")??"unknown",buildTime:Ko("__RED_BUILD_TIME__",()=>"2026-07-31T00:19:51-03:00")??"unknown",bundleAsset:Ko("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Ko("__REDDB_SDK_VERSION__",()=>""),n=Ko("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function R1(e){return e.startsWith("v")?e.slice(1):e}function v$(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ko(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var b$={"=":"data",":=":{to:"data",typed:!0},":":"meta"},z1=/^[a-z][a-z0-9+.-]*:\/\//i;function E1(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function O1(e=b$){return Object.entries(e).map(([t,r])=>E1(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function C1(e){return/^-\d+(\.\d+)?$/.test(e)}function zs(e){return!(!e||e.startsWith("-")&&!C1(e))}function Lc(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function w$(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>w$(r.trim())):e}function ro(e,t){switch(t){case"boolean":return j1(e);case"number":return I1(e);case"array":return e.split(",").map(r=>Lc(r.trim()));default:return e}}function j1(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function I1(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function an(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function N1(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function $e(e,t){return{type:e,value:t}}function M1(e){let t=[],r=A1(e);if(t.push($e("section-header","Usage:"),$e("text"," "),$e("usage-text",r),$e("newline",`
54
54
  `),$e("newline",`
55
55
  `)),e.positional&&e.positional.length>0){t.push($e("section-header","Arguments:"),$e("newline",`
56
56
  `));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;t.push($e("indent"," "),$e("positional-name",`<${o}>`)),n.required||t.push($e("positional-optional"," (optional)")),t.push($e("newline",`