@reddb-io/red-skills 2.87.6 → 2.87.7

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 Ka(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]})??Ce(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}=Ga(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}=Ja(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function Bv(e,t){if(t.mapStrategy==="record")return Ka(e,t);let r=W(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ce(t),n=W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ce(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Wv(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 Jv(e){return e.target==="openAi"?void 0:{not:Ce({...e,currentPath:[...e.currentPath,"not"]})}}function Gv(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ki={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Xv(e,t){if(t.target==="openApi3")return Kv(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ki&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Ki[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 Kv(e,t)}var Kv=(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 Yv(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:Ki[e.innerType._def.typeName],nullable:!0}:{type:[Ki[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 Qv(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",of(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 eb(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=nO(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=rO(e,t);return s!==void 0&&(n.additionalProperties=s),n}function rO(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 nO(e){try{return e.isOptional()}catch{return!0}}var tb=(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:Ce(t)},r]}:Ce(t)};var rb=(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 nb(e,t){return W(e.type._def,t)}function ob(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 ib(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 sb(e){return{not:Ce(e)}}function ab(e){return Ce(e)}var cb=(e,t)=>W(e.innerType._def,t);var ub=(e,t,r)=>{switch(t){case E.ZodString:return Ga(e,r);case E.ZodNumber:return Qv(e,r);case E.ZodObject:return eb(e,r);case E.ZodBigInt:return Nv(e,r);case E.ZodBoolean:return Av();case E.ZodDate:return sf(e,r);case E.ZodUndefined:return sb(r);case E.ZodNull:return Gv(r);case E.ZodArray:return Dv(e,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return Xv(e,r);case E.ZodIntersection:return Fv(e,r);case E.ZodTuple:return ib(e,r);case E.ZodRecord:return Ka(e,r);case E.ZodLiteral:return Vv(e,r);case E.ZodEnum:return Uv(e);case E.ZodNativeEnum:return Wv(e);case E.ZodNullable:return Yv(e,r);case E.ZodOptional:return tb(e,r);case E.ZodMap:return Bv(e,r);case E.ZodSet:return ob(e,r);case E.ZodLazy:return()=>e.getter()._def;case E.ZodPromise:return nb(e,r);case E.ZodNaN:case E.ZodNever:return Jv(r);case E.ZodEffects:return Lv(e,r);case E.ZodAny:return Ce(r);case E.ZodUnknown:return ab(r);case E.ZodDefault:return qv(e,r);case E.ZodBranded:return Ja(e,r);case E.ZodReadonly:return cb(e,r);case E.ZodCatch:return Zv(e,r);case E.ZodPipeline:return rb(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!==jv)return a}if(n&&!r){let a=oO(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=ub(e,e.typeName,t),s=typeof i=="function"?W(i(),t):i;if(s&&iO(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var oO=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Wa(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`),Ce(t)):t.$refStrategy==="seen"?Ce(t):void 0}},iO=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var uf=(e,t)=>{let r=Iv(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)??Ce(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)??Ce(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 sO(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function lf(e,t){return Nt(e)?Od(e,{target:sO(t?.target),io:t?.pipeStrategy??"input"}):uf(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function df(e){let r=Wr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$a(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ff(e,t){let r=Br(e,t);if(!r.success)throw r.error;return r.data}var aO=6e4,Xa=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(Ea,r=>{this._oncancel(r)}),this.setNotificationHandler(Ca,r=>{this._onprogress(r)}),this.setRequestHandler(Oa,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ja,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(F.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ia,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,g=new q(d.error.code,d.error.message,d.error.data);l(g)}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 q(F.InvalidParams,`Task not found: ${i}`);if(!Gr(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Gr(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Jr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Da,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 q(F.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Aa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(F.InvalidParams,`Task not found: ${r.params.taskId}`);if(Gr(o.status))throw new q(F.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 q(F.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof q?o:new q(F.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),q.fromError(F.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),Li(i)||wv(i)?this._onresponse(i):Vd(i)?this._onrequest(i,s):bv(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=q.fromError(F.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?.[Jr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:F.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=yv(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,g)=>{if(s.signal.aborted)throw new q(F.ConnectionClosed,"Request was cancelled");let m={...g,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:F.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),Li(t))n(t);else{let s=new q(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(Li(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),Li(t))o(t);else{let s=q.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 q?s:new q(F.InternalError,String(s))}}return}let i;try{let s=await this.request(t,So,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new q(F.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Gr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new q(F.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(F.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 q?s:new q(F.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 g=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:g}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Jr]:c}});let p=T=>{this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(T)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(D=>this._onerror(new Error(`Failed to send cancellation: ${D}`)));let R=T instanceof q?T:new q(F.RequestTimeout,String(T));l(R)};this._responseHandlers.set(g,T=>{if(!n?.signal?.aborted){if(T instanceof Error)return l(T);try{let R=Br(r,T.result);R.success?u(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let y=n?.timeout??aO,v=()=>p(q.fromError(F.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(g,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let P=c?.taskId;if(P){let T=R=>{let D=this._responseHandlers.get(g);D?D(R):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,T),this._enqueueTaskMessage(P,{type:"request",message:m,timestamp:Date.now()}).catch(R=>{this._cleanupTimeout(g),l(R)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(T=>{this._cleanupTimeout(g),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},Na,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Sv,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||{},[Jr]: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||{},[Jr]: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||{},[Jr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=df(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=ff(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=df(t);this._notificationHandlers.set(n,o=>{let i=ff(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"&&Vd(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new q(F.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 q(F.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new q(F.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 q(F.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=Bi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Gr(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 q(F.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Gr(a.status))throw new q(F.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=Bi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Gr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function lb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function db(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];lb(s)&&lb(i)?r[o]={...s,...i}:r[o]=i}return r}var r0=Xs(Yp(),1),n0=Xs(t0(),1);function lN(){let e=new r0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,n0.default)(e),e}var Cc=class{constructor(t){this._ajv=t??lN()}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 jc=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(g=>g.type==="tool_use").map(g=>g.id)),d=new Set(i.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(l.size!==d.size||![...l].every(g=>d.has(g)))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},Gi,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},To,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 o0(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 i0(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 Xa{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ji.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 Cc,this.setRequestHandler(Wd,n=>this._oninitialize(n)),this.setNotificationHandler(Jd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(tf,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=Ji.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new jc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=db(this._capabilities,t)}setRequestHandler(t,r){let o=Wr(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Nt(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=Br(Po,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new q(F.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,g=await Promise.resolve(r(c,u));if(d.task){let p=Br(So,g);if(!p.success){let y=p.error instanceof Error?p.error.message:String(p.error);throw new q(F.InvalidParams,`Invalid task creation result: ${y}`)}return p.data}let m=Br(Ha,g);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new q(F.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){i0(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&o0(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:mv.includes(r)?r:Ud,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"},Ra)}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},rf,r):this.request({method:"sampling/createMessage",params:t},Gi,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},To,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},To,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new q(F.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof q?s:new q(F.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},nf,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 a0=Symbol.for("mcp.completable");function sm(e){return!!e&&typeof e=="object"&&a0 in e}function c0(e){return e[a0]?.complete}var s0;(function(e){e.Completable="McpCompletable"})(s0||(s0={}));var dN=/^[A-Za-z0-9._-]{1,128}$/;function fN(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"),!dN.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 pN(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 am(e){let t=fN(e);return pN(e,t.warnings),t.isValid}var Ic=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 Dc=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 Ic(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Va)),this.server.assertCanSetRequestHandler(on(Po)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Va,()=>({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=xo(r.inputSchema);return o?lf(o,{strictUnions:!0,pipeStrategy:"input"}):mN})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=xo(r.outputSchema);o&&(n.outputSchema=lf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Po,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new q(F.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new q(F.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 q(F.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new q(F.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 q&&n.code===F.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=xo(t.inputSchema)??t.inputSchema,s=await wa(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=xa(a);throw new q(F.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 q(F.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=xo(t.outputSchema),i=await wa(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=xa(s);throw new q(F.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(g=>setTimeout(g,l));let d=await n.taskStore.getTask(c);if(!d)throw new q(F.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(on(Ba)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ba,async t=>{switch(t.params.ref.type){case"ref/prompt":return Ev(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Ov(t),this.handleResourceCompletion(t,t.params.ref);default:throw new q(F.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new q(F.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new q(F.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ps;let i=Wr(n.argsSchema)?.[t.params.argument.name];if(!sm(i))return Ps;let s=c0(i);if(!s)return Ps;let a=await s(t.params.argument.value,t.params.context);return l0(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 Ps;throw new q(F.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Ps;let i=await o(t.params.argument.value,t.params.context);return l0(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Za)),this.server.assertCanSetRequestHandler(on(qa)),this.server.assertCanSetRequestHandler(on(La)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Za,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(qa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(La,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new q(F.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 q(F.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Ua)),this.server.assertCanSetRequestHandler(on(Fa)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ua,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?hN(r.argsSchema):void 0}))})),this.server.setRequestHandler(Fa,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new q(F.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new q(F.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=xo(n.argsSchema),i=await wa(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=xa(c);throw new q(F.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:Un(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=Un(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 vt?c._def?.innerType:c;return sm(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,u){am(t);let l={title:r,description:n,inputSchema:u0(o),outputSchema:u0(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"&&am(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=Un(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Un(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(cm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!cm(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 mN={type:"object",properties:{}};function d0(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function f0(e){return"_def"in e||"_zod"in e||d0(e)}function cm(e){return typeof e!="object"||e===null||f0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(d0)}function u0(e){if(e){if(cm(e))return Un(e);if(!f0(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function hN(e){let t=Wr(e);return t?Object.entries(t).map(([r,n])=>{let o=V_(n),i=H_(n);return{name:r,description:o,required:!i}}):[]}function on(e){let r=Wr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$a(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function l0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ps={completion:{values:[],hasMore:!1}};import m0 from"node:process";var Nc=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),gN(r)}clear(){this._buffer=void 0}};function gN(e){return xv.parse(JSON.parse(e))}function p0(e){return JSON.stringify(e)+`
53
- `}var Ac=class{constructor(t=m0.stdin,r=m0.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Nc,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=p0(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function h0(e){let t={app:e,version:yN(Bo("__RED_BUILD_VERSION__",()=>"2.87.6")??"0.0.0-dev"),gitSha:Bo("__RED_BUILD_GIT_SHA__",()=>"698c85881b043eb712d489860986832fb05c29cb")??"unknown",buildTime:Bo("__RED_BUILD_TIME__",()=>"2026-07-28T19:08:02-03:00")??"unknown",bundleAsset:Bo("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Bo("__REDDB_SDK_VERSION__",()=>""),n=Bo("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function yN(e){return e.startsWith("v")?e.slice(1):e}function g0(e){return`${e.app} ${e.version} ${e.gitSha}`}function Bo(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var um={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function y0(){let e=process.env.CODE_NAV_SERVERS;if(!e)return um;try{let t=JSON.parse(e),r={...um};for(let[n,o]of Object.entries(t))r[n]={...r[n]??{},...o};return r}catch(t){return process.stderr.write(`navigator: failed to parse CODE_NAV_SERVERS, using defaults: ${String(t)}
53
+ `}var Ac=class{constructor(t=m0.stdin,r=m0.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Nc,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=p0(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function h0(e){let t={app:e,version:yN(Bo("__RED_BUILD_VERSION__",()=>"2.87.7")??"0.0.0-dev"),gitSha:Bo("__RED_BUILD_GIT_SHA__",()=>"5b4f35b7513e6bfd5ef2269f9b7f5276704148d8")??"unknown",buildTime:Bo("__RED_BUILD_TIME__",()=>"2026-07-29T00:50:06-03:00")??"unknown",bundleAsset:Bo("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Bo("__REDDB_SDK_VERSION__",()=>""),n=Bo("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function yN(e){return e.startsWith("v")?e.slice(1):e}function g0(e){return`${e.app} ${e.version} ${e.gitSha}`}function Bo(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var um={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function y0(){let e=process.env.CODE_NAV_SERVERS;if(!e)return um;try{let t=JSON.parse(e),r={...um};for(let[n,o]of Object.entries(t))r[n]={...r[n]??{},...o};return r}catch(t){return process.stderr.write(`navigator: failed to parse CODE_NAV_SERVERS, using defaults: ${String(t)}
54
54
  `),um}}function _0(e){let t=new Map;for(let[r,n]of Object.entries(e))for(let o of n.extensions)t.set(o,r);return t}var hi=Xs(Zk(),1),ft=Xs(ny(),1);import{spawn as rA}from"node:child_process";import{readFile as nA}from"node:fs/promises";import{pathToFileURL as qk,fileURLToPath as oA}from"node:url";import{resolve as iA}from"node:path";var Bs=class{constructor(t,r){this.spec=t;this.rootPath=r}spec;rootPath;proc;conn;ready;openDocs=new Set;async ensureStarted(){return this.ready?this.ready:(this.ready=this.start(),this.ready)}async start(){let t=rA(this.spec.command,this.spec.args,{cwd:this.rootPath,stdio:["pipe","pipe","pipe"]});this.proc=t,await new Promise((i,s)=>{t.once("spawn",()=>i()),t.once("error",a=>s(new Error(`failed to spawn '${this.spec.command}': ${a.message}`)))}),t.stderr.on("data",i=>{process.stderr.write(`[${this.spec.command}] ${i.toString()}`)}),t.once("exit",()=>{try{this.conn?.dispose()}catch{}});let r=(0,hi.createProtocolConnection)(new hi.StreamMessageReader(t.stdout),new hi.StreamMessageWriter(t.stdin));this.conn=r,r.listen();let n=qk(this.rootPath).toString(),o={processId:process.pid,rootUri:n,workspaceFolders:[{uri:n,name:"workspace"}],capabilities:{textDocument:{definition:{linkSupport:!0},references:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},hover:{contentFormat:["markdown","plaintext"]}},workspace:{symbol:{}}}};await r.sendRequest(ft.InitializeRequest.type,o),await r.sendNotification(ft.InitializedNotification.type,{})}async ensureOpen(t){let r=iA(this.rootPath,t),n=qk(r).toString();if(this.openDocs.has(n))return n;let o=await nA(r,"utf8");return await this.conn.sendNotification(ft.DidOpenTextDocumentNotification.type,{textDocument:{uri:n,languageId:this.spec.languageId,version:1,text:o}}),this.openDocs.add(n),n}async definition(t,r,n){await this.ensureStarted();let o=await this.ensureOpen(t),i=await this.conn.sendRequest(ft.DefinitionRequest.type,{textDocument:{uri:o},position:{line:r,character:n}});return sA(i)}async references(t,r,n,o){await this.ensureStarted();let i=await this.ensureOpen(t);return await this.conn.sendRequest(ft.ReferencesRequest.type,{textDocument:{uri:i},position:{line:r,character:n},context:{includeDeclaration:o}})??[]}async documentSymbols(t){await this.ensureStarted();let r=await this.ensureOpen(t);return await this.conn.sendRequest(ft.DocumentSymbolRequest.type,{textDocument:{uri:r}})??[]}async hover(t,r,n){await this.ensureStarted();let o=await this.ensureOpen(t);return this.conn.sendRequest(ft.HoverRequest.type,{textDocument:{uri:o},position:{line:r,character:n}})}async workspaceSymbols(t){return await this.ensureStarted(),await this.conn.sendRequest(ft.WorkspaceSymbolRequest.type,{query:t})??[]}dispose(){try{this.conn?.dispose()}catch{}this.proc?.kill()}};function sA(e){return e?(Array.isArray(e)?e:[e]).map(r=>"targetUri"in r?{uri:r.targetUri,range:r.targetSelectionRange}:r):[]}function oy(e,t){try{let r=oA(e);return(r.startsWith(t)?r.slice(t.length).replace(/^[/\\]/,""):r)||r}catch{return e}}var Js=process.env.CODE_NAV_ROOT??process.cwd(),Ws=y0(),Lk=_0(Ws),gi=new Map;function ku(e){let t=aA(e),r=Lk.get(t);if(!r)throw new Error(`no language server configured for '${t}'. Configured extensions: ${[...Lk.keys()].join(", ")||"(none)"}.`);let n=gi.get(r);return n||(n=new Bs(Ws[r],Js),gi.set(r,n)),n}function cA(){for(let e of Object.keys(Ws))gi.has(e)||gi.set(e,new Bs(Ws[e],Js));return[...gi.values()]}function sy(e,t){return`${oy(e,Js)}:${t.start.line+1}:${t.start.character+1}`}var iy=h0("navigator"),yi=new Dc({name:"navigator",version:iy.version}),Pu={file:Fr.string().describe("Workspace-relative path to the source file."),line:Fr.number().int().describe("Zero-based line number."),character:Fr.number().int().describe("Zero-based character offset on the line.")};yi.registerTool("goto_definition",{title:"Go to definition",description:"Resolve the symbol at a file position to its definition(s). Returns file:line:column locations. Use this instead of grepping for a name.",inputSchema:Pu},async({file:e,line:t,character:r})=>{let n=await ku(e).definition(e,t,r);return n.length===0?_r("No definition found."):_r(n.map(o=>sy(o.uri,o.range)).join(`
55
55
  `))});yi.registerTool("find_references",{title:"Find references",description:"Find every reference to the symbol at a file position across the workspace. Semantic \u2014 matches the actual symbol, not text.",inputSchema:{...Pu,includeDeclaration:Fr.boolean().optional().describe("Include the declaration itself (default true).")}},async({file:e,line:t,character:r,includeDeclaration:n})=>{let o=await ku(e).references(e,t,r,n??!0);return o.length===0?_r("No references found."):_r(`${o.length} reference(s):
56
56
  `+o.map(i=>sy(i.uri,i.range)).join(`