@magic5644/graph-it-live 1.9.5 → 1.9.6

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.
@@ -85,7 +85,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
85
85
  `:`[${o[c]}\r
86
86
  ]`;continue}r+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return r}function rl(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,r)=>({...o,[r]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===w.ZodString&&t.keyType._def.checks?.length){let{type:o,...r}=tl(t.keyType._def,e);return{...n,propertyNames:r}}else{if(t.keyType?._def.typeName===w.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===w.ZodBranded&&t.keyType._def.type._def.typeName===w.ZodString&&t.keyType._def.type._def.checks?.length){let{type:o,...r}=el(t.keyType._def,e);return{...n,propertyNames:r}}}return n}function n$(t,e){if(e.mapStrategy==="record")return rl(t,e);let n=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),o=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,o],minItems:2,maxItems:2}}}function o$(t){let e=t.values,o=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),r=Array.from(new Set(o.map(i=>typeof i)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:o}}function i$(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}function a$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ra={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function c$(t,e){if(e.target==="openApi3")return s$(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(o=>o._def.typeName in ra&&(!o._def.checks||!o._def.checks.length))){let o=n.reduce((r,i)=>{let a=ra[i._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:o.length>1?o:o[0]}}else if(n.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=n.reduce((r,i)=>{let a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(i._def.value===null)return[...r,"null"];default:return r}},[]);if(o.length===n.length){let r=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:r.length>1?r:r[0],enum:n.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(n.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((o,r)=>[...o,...r._def.values.filter(i=>!o.includes(i))],[])};return s$(t,e)}var s$=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,r)=>F(o._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(o=>!!o&&(!e.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return n.length?{anyOf:n}:void 0};function u$(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ra[t.innerType._def.typeName],nullable:!0}:{type:[ra[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let o=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function l$(t,e){let n={type:"number"};if(!t.checks)return n;for(let o of t.checks)switch(o.kind){case"int":n.type="integer",Wm(n,"type",o.message,e);break;case"min":e.target==="jsonSchema7"?o.inclusive?ie(n,"minimum",o.value,o.message,e):ie(n,"exclusiveMinimum",o.value,o.message,e):(o.inclusive||(n.exclusiveMinimum=!0),ie(n,"minimum",o.value,o.message,e));break;case"max":e.target==="jsonSchema7"?o.inclusive?ie(n,"maximum",o.value,o.message,e):ie(n,"exclusiveMaximum",o.value,o.message,e):(o.inclusive||(n.exclusiveMaximum=!0),ie(n,"maximum",o.value,o.message,e));break;case"multipleOf":ie(n,"multipleOf",o.value,o.message,e);break}return n}function d$(t,e){let n=e.target==="openAi",o={type:"object",properties:{}},r=[],i=t.shape();for(let s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=LT(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=F(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||r.push(s))}r.length&&(o.required=r);let a=MT(t,e);return a!==void 0&&(o.additionalProperties=a),o}function MT(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function LT(t){try{return t.isOptional()}catch{return!0}}var p$=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ke(e)},n]}:ke(e)};var f$=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let n=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),o=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,o].filter(r=>r!==void 0)}};function m$(t,e){return F(t.type._def,e)}function h$(t,e){let o={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(o,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(o,"maxItems",t.maxSize.value,t.maxSize.message,e),o}function g$(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,o)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((n,o)=>o===void 0?n:[...n,o],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,o)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${o}`]})).reduce((n,o)=>o===void 0?n:[...n,o],[])}}function v$(t){return{not:ke(t)}}function y$(t){return ke(t)}var _$=(t,e)=>F(t.innerType._def,e);var b$=(t,e,n)=>{switch(e){case w.ZodString:return tl(t,n);case w.ZodNumber:return l$(t,n);case w.ZodObject:return d$(t,n);case w.ZodBigInt:return Gb(t,n);case w.ZodBoolean:return Bb();case w.ZodDate:return Jm(t,n);case w.ZodUndefined:return v$(n);case w.ZodNull:return a$(n);case w.ZodArray:return Jb(t,n);case w.ZodUnion:case w.ZodDiscriminatedUnion:return c$(t,n);case w.ZodIntersection:return e$(t,n);case w.ZodTuple:return g$(t,n);case w.ZodRecord:return rl(t,n);case w.ZodLiteral:return t$(t,n);case w.ZodEnum:return Qb(t);case w.ZodNativeEnum:return o$(t);case w.ZodNullable:return u$(t,n);case w.ZodOptional:return p$(t,n);case w.ZodMap:return n$(t,n);case w.ZodSet:return h$(t,n);case w.ZodLazy:return()=>t.getter()._def;case w.ZodPromise:return m$(t,n);case w.ZodNaN:case w.ZodNever:return i$(n);case w.ZodEffects:return Yb(t,n);case w.ZodAny:return ke(n);case w.ZodUnknown:return y$(n);case w.ZodDefault:return Xb(t,n);case w.ZodBranded:return el(t,n);case w.ZodReadonly:return _$(t,n);case w.ZodCatch:return Kb(t,n);case w.ZodPipeline:return f$(t,n);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return(o=>{})(e)}};function F(t,e,n=!1){let o=e.seen.get(t);if(e.override){let s=e.override?.(t,e,o,n);if(s!==Vb)return s}if(o&&!n){let s=qT(o,e);if(s!==void 0)return s}let r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);let i=b$(t,t.typeName,e),a=typeof i=="function"?F(i(),e):i;if(a&&FT(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return r.jsonSchema=a,s}return r.jsonSchema=a,a}var qT=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Qu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,o)=>e.currentPath[o]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},FT=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var Km=(t,e)=>{let n=Wb(e),o=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:F(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??ke(n)}),{}):void 0,r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=F(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??ke(n),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(i.title=a),n.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[n.openAiAnyTypeName]||(o[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let s=r===void 0?o?{...i,[n.definitionPath]:o}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...o,[r]:i}};return n.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function VT(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Xm(t,e){return _t(t)?Gr(t,{target:VT(e?.target),io:e?.pipeStrategy??"input"}):Km(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ym(t){let n=kr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let o=tu(n);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function Qm(t,e){let n=xr(t,e);if(!n.success)throw n.error;return n.data}var HT=6e4,nl=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Cu,n=>{this._oncancel(n)}),this.setNotificationHandler(Uu,n=>{this._onprogress(n)}),this.setRequestHandler(Au,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Zu,async(n,o)=>{let r=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!r)throw new D(U.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(Lu,async(n,o)=>{let r=async()=>{let i=n.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,p=new D(d.error.code,d.error.message,d.error.data);l(p)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:o.requestId})}}let a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new D(U.InvalidParams,`Task not found: ${i}`);if(!zr(a.status))return await this._waitForTaskUpdate(i,o.signal),await r();if(zr(a.status)){let s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Sr]:{taskId:i}}}}return await r()};return await r()}),this.setRequestHandler(qu,async(n,o)=>{try{let{tasks:r,nextCursor:i}=await this._taskStore.listTasks(n.params?.cursor,o.sessionId);return{tasks:r,nextCursor:i,_meta:{}}}catch(r){throw new D(U.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(Vu,async(n,o)=>{try{let r=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!r)throw new D(U.InvalidParams,`Task not found: ${n.params.taskId}`);if(zr(r.status))throw new D(U.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(n.params.taskId);let i=await this._taskStore.getTask(n.params.taskId,o.sessionId);if(!i)throw new D(U.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...i}}catch(r){throw r instanceof D?r:new D(U.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,o,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,n),startTime:Date.now(),timeout:n,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let o=Date.now()-n.startTime;if(n.maxTotalTimeout&&o>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),D.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:o});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){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=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};let r=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{r?.(i,a),Ji(i)||jb(i)?this._onresponse(i):jm(i)?this._onrequest(i,a):Ob(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(let o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();let n=D.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let o of e.values())o(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(e,n){let o=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Sr]?.taskId;if(o===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},r?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):r?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=Tb(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,u={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(a.signal.aborted)throw new D(U.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let h=f.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,f)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>o(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},r?.sessionId):await r?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.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()},r?.sessionId):await r?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...o}=e.params,r=Number(n),i=this._progressHandlers.get(r);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(c){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(c);return}i(o)}_onresponse(e){let n=Number(e.id),o=this._requestResolvers.get(n);if(o){if(this._requestResolvers.delete(n),Ji(e))o(e);else{let a=new D(e.error.code,e.error.message,e.error.data);o(a)}return}let r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let i=!1;if(Ji(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,n))}}if(i||this._progressHandlers.delete(n),Ji(e))r(e);else{let a=D.fromError(e.error.code,e.error.message,e.error.data);r(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,o){let{task:r}=o??{};if(!r){try{yield{type:"result",result:await this.request(e,n,o)}}catch(a){yield{type:"error",error:a instanceof D?a:new D(U.InternalError,String(a))}}return}let i;try{let a=await this.request(e,co,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new D(U.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},zr(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},n,o)}:s.status==="failed"?yield{type:"error",error:new D(U.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new D(U.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},n,o)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof D?a:new D(U.InternalError,String(a))}}}request(e,n,o){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};return new Promise((u,l)=>{let d=M=>{l(M)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(M){d(M);return}o?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};o?.onprogress&&(this._progressHandlers.set(p,o.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Sr]:c}});let h=M=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(M)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`)));let C=M instanceof D?M:new D(U.RequestTimeout,String(M));l(C)};this._responseHandlers.set(p,M=>{if(!o?.signal?.aborted){if(M instanceof Error)return l(M);try{let C=xr(n,M.result);C.success?u(C.data):l(C.error)}catch(C){l(C)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});let y=o?.timeout??HT,$=()=>h(D.fromError(U.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,o?.maxTotalTimeout,$,o?.resetTimeoutOnProgress??!1);let I=c?.taskId;if(I){let M=C=>{let Z=this._responseHandlers.get(p);Z?Z(C):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,M),this._enqueueTaskMessage(I,{type:"request",message:f,timestamp:Date.now()}).catch(C=>{this._cleanupTimeout(p),l(C)})}else this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(M=>{this._cleanupTimeout(p),l(M)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Mu,n)}async getTaskResult(e,n,o){return this.request({method:"tasks/result",params:e},n,o)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Fu,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},Db,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let o=n?.relatedTask?.taskId;if(o){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Sr]:n.relatedTask}}};await this._enqueueTaskMessage(o,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Sr]:n.relatedTask}}}),this._transport?.send(s,n).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Sr]:n.relatedTask}}}),await this._transport.send(a,n)}setRequestHandler(e,n){let o=Ym(e);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(r,i)=>{let a=Qm(e,r);return Promise.resolve(n(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let o=Ym(e);this._notificationHandlers.set(o,r=>{let i=Qm(e,r);return Promise.resolve(n(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,o){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,o,r)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let o=await this._taskMessageQueue.dequeueAll(e,n);for(let r of o)if(r.type==="request"&&jm(r.message)){let i=r.message.id,a=this._requestResolvers.get(i);a?(a(new D(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let r=await this._taskStore?.getTask(e);r?.pollInterval&&(o=r.pollInterval)}catch{}return new Promise((r,i)=>{if(n.aborted){i(new D(U.InvalidRequest,"Request cancelled"));return}let a=setTimeout(r,o);n.addEventListener("abort",()=>{clearTimeout(a),i(new D(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await o.createTask(r,e.id,{method:e.method,params:e.params},n)},getTask:async r=>{let i=await o.getTask(r,n);if(!i)throw new D(U.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(r,i,a)=>{await o.storeTaskResult(r,i,a,n);let s=await o.getTask(r,n);if(s){let c=Yi.parse({method:"notifications/tasks/status",params:s});await this.notification(c),zr(s.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>o.getTaskResult(r,n),updateTaskStatus:async(r,i,a)=>{let s=await o.getTask(r,n);if(!s)throw new D(U.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(zr(s.status))throw new D(U.InvalidParams,`Cannot update task "${r}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(r,i,a,n);let c=await o.getTask(r,n);if(c){let u=Yi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),zr(c.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>o.listTasks(r,n)}}};function $$(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function x$(t,e){let n={...t};for(let o in e){let r=o,i=e[r];if(i===void 0)continue;let a=n[r];$$(a)&&$$(i)?n[r]={...a,...i}:n[r]=i}return n}var fw=sv(Zg(),1),mw=sv(pw(),1);function GN(){let t=new fw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,mw.default)(t),t}var Ul=class{constructor(e){this._ajv=e??GN()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return o=>n(o)?{valid:!0,data:o,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Zl=class{constructor(e){this._server=e}requestStream(e,n,o){return this._server.requestStream(e,n,o)}createMessageStream(e,n){let o=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!o?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],i=Array.isArray(r.content)?r.content:[r.content],a=i.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],u=c.some(l=>l.type==="tool_use");if(a){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(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))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:e},ta,n)}elicitInputStream(e,n){let o=this._server.getClientCapabilities(),r=e.mode??"form";switch(r){case"url":{if(!o?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!o?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=r==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},po,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,o){return this._server.getTaskResult({taskId:e},n,o)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function hw(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function gw(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ml=class extends nl{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ea.options.map((o,r)=>[o,r])),this.isMessageIgnored=(o,r)=>{let i=this._loggingLevels.get(r);return i?this.LOG_LEVEL_SEVERITY.get(o)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Ul,this.setRequestHandler(Dm,o=>this._oninitialize(o)),this.setNotificationHandler(Cm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Fm,async(o,r)=>{let i=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=o.params,s=ea.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Zl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=x$(this._capabilities,e)}setRequestHandler(e,n){let r=kr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let i;if(_t(r)){let s=r;i=s._zod?.def?.value??s.value}else{let s=r;i=s._def?.value??s.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let s=async(c,u)=>{let l=xr(lo,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new D(U.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let h=xr(co,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new D(U.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let f=xr(Xu,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new D(U.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);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 ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){gw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&hw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Sb.includes(n)?n:Em,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"},Du)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],r=Array.isArray(o.content)?o.content:[o.content],i=r.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(i){if(r.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(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(r.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 e.tools?this.request({method:"sampling/createMessage",params:e},Vm,n):this.request({method:"sampling/createMessage",params:e},ta,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let r=e;return this.request({method:"elicitation/create",params:r},po,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let r=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:r},po,n);if(i.action==="accept"&&i.content&&r.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(r.requestedSchema)(i.content);if(!s.valid)throw new D(U.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof D?a:new D(U.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return i}}}createElicitationCompletionNotifier(e,n){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:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Hm,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var yw=Symbol.for("mcp.completable");function Jg(t){return!!t&&typeof t=="object"&&yw in t}function _w(t){return t[yw]?.complete}var vw;(function(t){t.Completable="McpCompletable"})(vw||(vw={}));var BN=/^[A-Za-z0-9._-]{1,128}$/;function KN(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!BN.test(t)){let n=t.split("").filter(o=>!/[A-Za-z0-9._-]/.test(o)).filter((o,r,i)=>i.indexOf(o)===r);return e.push(`Tool name contains invalid characters: ${n.map(o=>`"${o}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function XN(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 Gg(t){let e=KN(t);return XN(t,e.warnings),e.isValid}var Ll=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,o){let r={taskSupport:"required",...n.execution};if(r.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,r,n._meta,o)}};var ql=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ml(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Ll(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Dr(Ku)),this.server.assertCanSetRequestHandler(Dr(lo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ku,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let o={name:e,title:n.title,description:n.description,inputSchema:(()=>{let r=Xn(n.inputSchema);return r?Xm(r,{strictUnions:!0,pipeStrategy:"input"}):YN})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let r=Xn(n.outputSchema);r&&(o.outputSchema=Xm(r,{strictUnions:!0,pipeStrategy:"output"}))}return o})})),this.server.setRequestHandler(lo,async(e,n)=>{try{let o=this._registeredTools[e.params.name];if(!o)throw new D(U.InvalidParams,`Tool ${e.params.name} not found`);if(!o.enabled)throw new D(U.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=o.execution?.taskSupport,a="createTask"in o.handler;if((i==="required"||i==="optional")&&!a)throw new D(U.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!r)throw new D(U.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!r&&a)return await this.handleAutomaticTaskPolling(o,e,n);let s=await this.validateToolInput(o,e.params.arguments,e.params.name),c=await this.executeToolHandler(o,s,n);return r||await this.validateToolOutput(o,c,e.params.name),c}catch(o){if(o instanceof D&&o.code===U.UrlElicitationRequired)throw o;return this.createToolError(o instanceof Error?o.message:String(o))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,o){if(!e.inputSchema)return;let i=Xn(e.inputSchema)??e.inputSchema,a=await Qc(i,n);if(!a.success){let s="error"in a?a.error:"Unknown error",c=eu(s);throw new D(U.InvalidParams,`Input validation error: Invalid arguments for tool ${o}: ${c}`)}return a.data}async validateToolOutput(e,n,o){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new D(U.InvalidParams,`Output validation error: Tool ${o} has an output schema but no structured content was provided`);let r=Xn(e.outputSchema),i=await Qc(r,n.structuredContent);if(!i.success){let a="error"in i?i.error:"Unknown error",s=eu(a);throw new D(U.InvalidParams,`Output validation error: Invalid structured content for tool ${o}: ${s}`)}}async executeToolHandler(e,n,o){let r=e.handler;if("createTask"in r){if(!o.taskStore)throw new Error("No task store provided.");let a={...o,taskStore:o.taskStore};if(e.inputSchema){let s=r;return await Promise.resolve(s.createTask(n,a))}else{let s=r;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=r;return await Promise.resolve(a(n,o))}else{let a=r;return await Promise.resolve(a(o))}}async handleAutomaticTaskPolling(e,n,o){if(!o.taskStore)throw new Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(e,n.params.arguments,n.params.name),i=e.handler,a={...o,taskStore:o.taskStore},s=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),c=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await o.taskStore.getTask(c);if(!d)throw new D(U.InternalError,`Task ${c} not found during polling`);u=d}return await o.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Dr(Yu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Yu,async e=>{switch(e.params.ref.type){case"ref/prompt":return Lb(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return qb(e),this.handleResourceCompletion(e,e.params.ref);default:throw new D(U.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let o=this._registeredPrompts[n.name];if(!o)throw new D(U.InvalidParams,`Prompt ${n.name} not found`);if(!o.enabled)throw new D(U.InvalidParams,`Prompt ${n.name} disabled`);if(!o.argsSchema)return ja;let i=kr(o.argsSchema)?.[e.params.argument.name];if(!Jg(i))return ja;let a=_w(i);if(!a)return ja;let s=await a(e.params.argument.value,e.params.context);return $w(s)}async handleResourceCompletion(e,n){let o=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===n.uri);if(!o){if(this._registeredResources[n.uri])return ja;throw new D(U.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=o.resourceTemplate.completeCallback(e.params.argument.name);if(!r)return ja;let i=await r(e.params.argument.value,e.params.context);return $w(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Dr(Hu)),this.server.assertCanSetRequestHandler(Dr(Wu)),this.server.assertCanSetRequestHandler(Dr(Ju)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Hu,async(e,n)=>{let o=Object.entries(this._registeredResources).filter(([i,a])=>a.enabled).map(([i,a])=>({uri:i,name:a.name,...a.metadata})),r=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let a=await i.resourceTemplate.listCallback(n);for(let s of a.resources)r.push({...i.metadata,...s})}return{resources:[...o,...r]}}),this.server.setRequestHandler(Wu,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,o])=>({name:n,uriTemplate:o.resourceTemplate.uriTemplate.toString(),...o.metadata}))})),this.server.setRequestHandler(Ju,async(e,n)=>{let o=new URL(e.params.uri),r=this._registeredResources[o.toString()];if(r){if(!r.enabled)throw new D(U.InvalidParams,`Resource ${o} disabled`);return r.readCallback(o,n)}for(let i of Object.values(this._registeredResourceTemplates)){let a=i.resourceTemplate.uriTemplate.match(o.toString());if(a)return i.readCallback(o,a,n)}throw new D(U.InvalidParams,`Resource ${o} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Dr(Gu)),this.server.assertCanSetRequestHandler(Dr(Bu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Gu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?QN(n.argsSchema):void 0}))})),this.server.setRequestHandler(Bu,async(e,n)=>{let o=this._registeredPrompts[e.params.name];if(!o)throw new D(U.InvalidParams,`Prompt ${e.params.name} not found`);if(!o.enabled)throw new D(U.InvalidParams,`Prompt ${e.params.name} disabled`);if(o.argsSchema){let r=Xn(o.argsSchema),i=await Qc(r,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=eu(c);throw new D(U.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=i.data,s=o.callback;return await Promise.resolve(s(a,n))}else{let r=o.callback;return await Promise.resolve(r(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...o){let r;typeof o[0]=="object"&&(r=o.shift());let i=o[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let a=this._createRegisteredResource(e,void 0,n,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,n,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,n,o,r){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,o.title,n,o,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,o.title,n,o,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,n,o,r,i){let a={name:e,title:n,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==o&&(delete this._registeredResources[o],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[o]=a,a}_createRegisteredResourceTemplate(e,n,o,r,i){let a={resourceTemplate:o,title:n,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=a)),typeof u.title<"u"&&(a.title=u.title),typeof u.template<"u"&&(a.resourceTemplate=u.template),typeof u.metadata<"u"&&(a.metadata=u.metadata),typeof u.callback<"u"&&(a.readCallback=u.callback),typeof u.enabled<"u"&&(a.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=o.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!o.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,n,o,r,i){let a={title:n,description:o,argsSchema:r===void 0?void 0:Br(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=Br(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(c=>{let u=c instanceof ao?c._def?.innerType:c;return Jg(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,n,o,r,i,a,s,c,u){Gg(e);let l={title:n,description:o,inputSchema:bw(r),outputSchema:bw(i),annotations:a,execution:s,_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!==e&&(typeof d.name=="string"&&Gg(d.name),delete this._registeredTools[e],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=Br(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Br(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[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let o,r,i,a;if(typeof n[0]=="string"&&(o=n.shift()),n.length>1){let c=n[0];if(Bg(c))r=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Bg(n[0])&&(a=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=n.shift()}}let s=n[0];return this._createRegisteredTool(e,void 0,o,r,i,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,n,o){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,r,i,a,s,c,{taskSupport:"forbidden"},u,o)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let o;typeof n[0]=="string"&&(o=n.shift());let r;n.length>1&&(r=n.shift());let i=n[0],a=this._createRegisteredPrompt(e,void 0,o,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,n,o){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=n,s=this._createRegisteredPrompt(e,r,i,a,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var YN={type:"object",properties:{}};function xw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function kw(t){return"_def"in t||"_zod"in t||xw(t)}function Bg(t){return typeof t!="object"||t===null||kw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(xw)}function bw(t){if(t){if(Bg(t))return Br(t);if(!kw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function QN(t){let e=kr(t);return e?Object.entries(e).map(([n,o])=>{let r=d_(o),i=p_(o);return{name:n,description:r,required:!i}}):[]}function Dr(t){let n=kr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let o=tu(n);if(typeof o=="string")return o;throw new Error("Schema method literal must be a string")}function $w(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ja={completion:{values:[],hasMore:!1}};import Sw from"node:process";var Fl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
87
87
  `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),eD(n)}clear(){this._buffer=void 0}};function eD(t){return Rb.parse(JSON.parse(t))}function ww(t){return JSON.stringify(t)+`
88
- `}var Vl=class{constructor(e=Sw.stdin,n=Sw.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Fl,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise(n=>{let o=ww(e);this._stdout.write(o)?n():this._stdout.once("drain",n)})}};import*as Na from"node:path";import{Worker as tD}from"node:worker_threads";var rD=Za("McpWorkerHost"),Hl=class{worker=null;workerPath;warmupTimeout;invokeTimeout;isReady=!1;isStarting=!1;pendingRequests=new Map;requestCounter=0;warmupProgressCallback=null;constructor(e){this.workerPath=e.workerPath,this.warmupTimeout=e.warmupTimeout??6e4,this.invokeTimeout=e.invokeTimeout??3e4}async start(e,n){if(this.worker)throw new Error("Worker already started");if(this.isStarting)throw new Error("Worker is already starting");return this.isStarting=!0,this.warmupProgressCallback=n??null,new Promise((o,r)=>{let i=setTimeout(()=>{this.dispose(),r(new Error(`Worker warmup timeout after ${this.warmupTimeout}ms`))},this.warmupTimeout);try{this.worker=new tD(this.workerPath),this.worker.on("message",a=>{this.handleMessage(a,o,i)}),this.worker.on("error",a=>{clearTimeout(i),this.isStarting=!1,this.dispose(),r(a)}),this.worker.on("exit",a=>{a!==0&&!this.isReady&&(clearTimeout(i),this.isStarting=!1,r(new Error(`Worker exited with code ${a}`))),this.cleanup()}),this.postMessage({type:"init",config:e})}catch(a){clearTimeout(i),this.isStarting=!1,this.dispose(),r(a)}})}handleMessage(e,n,o){switch(e.type){case"ready":o&&clearTimeout(o),this.isReady=!0,this.isStarting=!1,this.warmupProgressCallback=null,n?.({durationMs:e.warmupDuration,filesIndexed:e.indexedFiles});break;case"warmup-progress":this.warmupProgressCallback?.(e.processed,e.total,e.currentFile);break;case"result":this.resolveRequest(e.requestId,e.data);break;case"error":this.rejectRequest(e.requestId,new Error(e.error));break;case"file-invalidated":rD.debug("Cache invalidated:",e.event,e.filePath);break}}async invoke(e,n){if(!this.isReady||!this.worker)throw new Error("Worker not ready. Call start() first.");let o=this.generateRequestId();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o),i(new Error(`Tool invocation timeout after ${this.invokeTimeout}ms`))},this.invokeTimeout);this.pendingRequests.set(o,{resolve:r,reject:i,timeoutId:a}),this.postMessage({type:"invoke",requestId:o,tool:e,params:n})})}ready(){return this.isReady}dispose(){if(this.worker){try{this.postMessage({type:"shutdown"})}catch{}this.worker.terminate().catch(()=>{})}this.cleanup()}cleanup(){for(let[e,n]of this.pendingRequests)clearTimeout(n.timeoutId),n.reject(new Error("Worker terminated")),this.pendingRequests.delete(e);this.worker=null,this.isReady=!1,this.isStarting=!1,this.warmupProgressCallback=null}postMessage(e){if(!this.worker)throw new Error("Worker not initialized");this.worker.postMessage(e)}generateRequestId(){return`req_${++this.requestCounter}_${Date.now()}`}resolveRequest(e,n){let o=this.pendingRequests.get(e);o&&(clearTimeout(o.timeoutId),this.pendingRequests.delete(e),o.resolve(n))}rejectRequest(e,n){let o=this.pendingRequests.get(e);o&&(clearTimeout(o.timeoutId),this.pendingRequests.delete(e),o.reject(n))}};function Kg(t){return t.replaceAll("\\",String.raw`\\`).replaceAll(",",String.raw`\,`).replaceAll("[",String.raw`\[`).replaceAll("]",String.raw`\]`).replaceAll("|",String.raw`\|`)}function zw(t,e){if(t==null)return"";if(Array.isArray(t))return t.map(o=>zw(o,e)).join("|");if(typeof t=="object"){let o=JSON.stringify(t);return e.escapeValues?Kg(o):o}if(typeof t=="string")return e.escapeValues?Kg(t):t;let n=String(t);return e.escapeValues?Kg(n):n}function Iw(t,e={}){let n={objectName:e.objectName??"data",escapeValues:e.escapeValues??!0};if(t.length===0)return`${n.objectName}()
88
+ `}var Vl=class{constructor(e=Sw.stdin,n=Sw.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Fl,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}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 e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}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(e){return new Promise(n=>{let o=ww(e);this._stdout.write(o)?n():this._stdout.once("drain",n)})}};import*as Na from"node:path";import{Worker as tD}from"node:worker_threads";var rD=Za("McpWorkerHost"),Hl=class{worker=null;workerPath;warmupTimeout;invokeTimeout;isReady=!1;isStarting=!1;pendingRequests=new Map;requestCounter=0;warmupProgressCallback=null;constructor(e){this.workerPath=e.workerPath,this.warmupTimeout=e.warmupTimeout??6e4,this.invokeTimeout=e.invokeTimeout??3e4}async start(e,n){if(this.worker)throw new Error("Worker already started");if(this.isStarting)throw new Error("Worker is already starting");return this.isStarting=!0,this.warmupProgressCallback=n??null,new Promise((o,r)=>{let i=setTimeout(()=>{this.dispose(),r(new Error(`Worker warmup timeout after ${this.warmupTimeout}ms`))},this.warmupTimeout);try{this.worker=new tD(this.workerPath),this.worker.on("message",a=>{this.handleMessage(a,o,i)}),this.worker.on("error",a=>{clearTimeout(i),this.isStarting=!1,this.dispose(),r(a)}),this.worker.on("exit",a=>{a!==0&&!this.isReady&&(clearTimeout(i),this.isStarting=!1,r(new Error(`Worker exited with code ${a}`))),this.cleanup()}),this.postMessage({type:"init",config:e})}catch(a){clearTimeout(i),this.isStarting=!1,this.dispose(),r(a)}})}handleMessage(e,n,o){switch(e.type){case"ready":o&&clearTimeout(o),this.isReady=!0,this.isStarting=!1,this.warmupProgressCallback=null,n?.({durationMs:e.warmupDuration,filesIndexed:e.indexedFiles});break;case"warmup-progress":this.warmupProgressCallback?.(e.processed,e.total,e.currentFile);break;case"result":this.resolveRequest(e.requestId,e.data);break;case"error":this.rejectRequest(e.requestId,new Error(e.error));break;case"file-invalidated":rD.debug("Cache invalidated:",e.event,e.filePath);break}}async invoke(e,n){if(!this.isReady||!this.worker)throw new Error("Worker not ready. Call start() first.");let o=this.generateRequestId();return new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o),i(new Error(`Tool invocation timeout after ${this.invokeTimeout}ms`))},this.invokeTimeout);this.pendingRequests.set(o,{resolve:r,reject:i,timeoutId:a}),this.postMessage({type:"invoke",requestId:o,tool:e,params:n})})}ready(){return this.isReady}async dispose(){if(!this.worker){this.cleanup();return}this.isReady=!1;let e=this.worker;this.worker=null;let n=new Promise(r=>{e.once("exit",()=>r())});try{e.postMessage({type:"shutdown"})}catch{}let o=5e3;await Promise.race([n,new Promise((r,i)=>setTimeout(()=>i(new Error("Worker shutdown timeout")),o))]).catch(async()=>{await e.terminate().catch(()=>{})}),this.cleanup()}cleanup(){for(let[e,n]of this.pendingRequests)clearTimeout(n.timeoutId),n.reject(new Error("Worker terminated")),this.pendingRequests.delete(e);this.worker=null,this.isReady=!1,this.isStarting=!1,this.warmupProgressCallback=null}postMessage(e){if(!this.worker)throw new Error("Worker not initialized");this.worker.postMessage(e)}generateRequestId(){return`req_${++this.requestCounter}_${Date.now()}`}resolveRequest(e,n){let o=this.pendingRequests.get(e);o&&(clearTimeout(o.timeoutId),this.pendingRequests.delete(e),o.resolve(n))}rejectRequest(e,n){let o=this.pendingRequests.get(e);o&&(clearTimeout(o.timeoutId),this.pendingRequests.delete(e),o.reject(n))}};function Kg(t){return t.replaceAll("\\",String.raw`\\`).replaceAll(",",String.raw`\,`).replaceAll("[",String.raw`\[`).replaceAll("]",String.raw`\]`).replaceAll("|",String.raw`\|`)}function zw(t,e){if(t==null)return"";if(Array.isArray(t))return t.map(o=>zw(o,e)).join("|");if(typeof t=="object"){let o=JSON.stringify(t);return e.escapeValues?Kg(o):o}if(typeof t=="string")return e.escapeValues?Kg(t):t;let n=String(t);return e.escapeValues?Kg(n):n}function Iw(t,e={}){let n={objectName:e.objectName??"data",escapeValues:e.escapeValues??!0};if(t.length===0)return`${n.objectName}()
89
89
  `;let o=t[0];if(typeof o!="object"||o===null||Array.isArray(o))throw new Error("TOON format requires an array of objects");let r=Object.keys(o),i=`${n.objectName}(${r.join(",")})`,a=t.map(s=>{if(typeof s!="object"||s===null||Array.isArray(s))throw new Error("All items must be objects");return`[${r.map(u=>{let l=s[u];return zw(l,n)}).join(",")}]`});return[i,...a].join(`
90
90
  `)}function Tw(t,e){let n=Math.ceil(t.length/4),o=Math.ceil(e.length/4),r=n-o,i=r/n*100;return{jsonTokens:n,toonTokens:o,savings:r,savingsPercent:i}}var nD=Za("responseFormatter");function H(t,e){let n;if(e==="toon"){let o=iD(t.data,sD(t));n=o.content,o.tokenSavings&&(n+=`
91
91
 
@@ -100,13 +100,13 @@ ${JSON.stringify(t,null,2)}
100
100
  `)?e:`${e}
101
101
  `),!!nv)try{dD();let o=`[${new Date().toISOString()}] ${e}
102
102
  `;rt.appendFileSync(Bl,o)}catch{}}nv?(J("[McpServer] ===== PROCESS STARTING (DEBUG MODE) ====="),J("[McpServer] Node version:",process.version),J("[McpServer] PID:",process.pid),J("[McpServer] cwd:",process.cwd()),J("[McpServer] argv:",JSON.stringify(process.argv)),J("[McpServer] Environment vars:"),J(" WORKSPACE_ROOT:",process.env.WORKSPACE_ROOT??"(not set)"),J(" TSCONFIG_PATH:",process.env.TSCONFIG_PATH??"(not set)"),J(" EXCLUDE_NODE_MODULES:",process.env.EXCLUDE_NODE_MODULES??"(not set)"),J(" MAX_DEPTH:",process.env.MAX_DEPTH??"(not set)")):process.stderr.write(`[McpServer] Starting (debug logging disabled - set DEBUG_MCP=true to enable)
103
- `);var we={workspaceRoot:process.env.WORKSPACE_ROOT??"",extensionPath:process.env.EXTENSION_PATH,tsConfigPath:process.env.TSCONFIG_PATH,excludeNodeModules:process.env.EXCLUDE_NODE_MODULES!=="false",maxDepth:Number.parseInt(process.env.MAX_DEPTH??"50",10)};we.workspaceRoot&&(we.workspaceRoot.includes("${")||we.workspaceRoot.includes("$("))&&(J("[McpServer] WARNING: WORKSPACE_ROOT contains unresolved variable:",we.workspaceRoot),J("[McpServer] Workspace not set - use graphitlive_set_workspace tool to configure"),we.workspaceRoot="");if(!we.workspaceRoot){let t=process.cwd();t==="/"||t===""?J("[McpServer] No workspace configured - use graphitlive_set_workspace tool to set workspace"):(we.workspaceRoot=t,J("[McpServer] WORKSPACE_ROOT not set, using current working directory:",we.workspaceRoot))}we.workspaceRoot&&!rt.existsSync(we.workspaceRoot)&&(J("[McpServer] WARNING: WORKSPACE_ROOT path does not exist:",we.workspaceRoot),J("[McpServer] Use graphitlive_set_workspace tool to configure a valid workspace"),we.workspaceRoot="");function ir(){return we.workspaceRoot}var Te=Re(["json","markdown","toon"]).default("toon"),pD=z({total:re(),limit:re(),offset:re(),hasMore:be()}),fD=z({executionTimeMs:re(),toolVersion:v(),timestamp:v(),workspaceRoot:v()}),Pe=z({success:be(),data:Iu(),metadata:fD,pagination:pD.optional(),error:v().optional()}),ze=new ql({name:"graph-it-live",version:Oo}),tt=null,Kl=!1,Ro=null,Gl=null;function rv(){Kl=!1,Ro=null,Gl=null}async function ov(){if(Kl&&!tt?.ready()&&(J("[McpServer] Worker was initialized but is no longer ready \u2014 auto-recovering"),tt&&(tt.dispose(),tt=null),rv()),!Kl){if(Gl&&(J("[McpServer] Previous init failed, allowing retry"),rv()),Ro!==null)return J("[McpServer] Waiting for existing initialization..."),Ro;Ro=mD();try{await Ro}catch(t){throw Gl=t instanceof Error?t:new Error(String(t)),Ro=null,Gl}}}async function mD(){let t=Na.join(__dirname,"mcpWorker.js");J(`[McpServer] __dirname: ${__dirname}`),J(`[McpServer] Worker path: ${t}`);try{await(await import("node:fs/promises")).access(t),J("[McpServer] Worker file exists: true")}catch{throw J("[McpServer] Worker file exists: false - THIS IS THE PROBLEM!"),new Error(`Worker file not found at ${t}`)}tt=new Hl({workerPath:t,warmupTimeout:12e4,invokeTimeout:6e4}),J("[McpServer] Starting worker with warmup...");try{let e=await tt.start({rootDir:ir(),tsConfigPath:we.tsConfigPath,extensionPath:we.extensionPath,excludeNodeModules:we.excludeNodeModules,maxDepth:we.maxDepth},(n,o,r)=>{J(`[McpServer] Warmup progress: ${n}/${o} - ${r??""}`)});J(`[McpServer] Worker ready: ${e.filesIndexed} files indexed in ${e.durationMs}ms`),Kl=!0}catch(e){throw J(`[McpServer] Worker initialization failed: ${e}`),e}}async function je(t,e){if(!tt?.ready())return Ra("Worker not ready",0,ir());let n=Date.now();try{let o=await tt.invoke(t,e),r=Date.now()-n;return Qg(o,r,ir())}catch(o){let r=Date.now()-n,i=o instanceof Error?o.message:"Unknown error";return Ra(i,r,ir())}}async function Oe(){try{return await ov(),{error:!1}}catch(t){let e=t instanceof Error?t.message:"Worker initialization failed";return J(`[McpServer] Tool call failed - worker init error: ${e}`),{error:!0,response:Ra(e,0,ir())}}}function tv(t,e,n,o){return{success:!1,data:{success:!1,workspacePath:t,filesIndexed:0,indexingTimeMs:Date.now()-o,previousWorkspace:e||void 0,message:n},error:n,metadata:{executionTimeMs:Date.now()-o,toolVersion:Oo,timestamp:new Date().toISOString(),workspaceRoot:t}}}function hD(t){return rt.existsSync(t)?rt.statSync(t).isDirectory()?null:`Path is not a directory: ${t}`:`Path does not exist: ${t}`}function gD(t,e){if(!t)return{resolvedPath:void 0,error:null};let n=Na.isAbsolute(t)?t:Na.join(e,t);if(!rt.existsSync(n))return{resolvedPath:void 0,error:`tsConfigPath does not exist: ${n}`};if(!rt.statSync(n).isFile())return{resolvedPath:void 0,error:`tsConfigPath is not a file: ${n}`};try{Bw(n,e)}catch(r){return{resolvedPath:void 0,error:r instanceof Error?r.message:"Invalid tsConfigPath"}}return{resolvedPath:n,error:null}}ze.registerTool("graphitlive_set_workspace",{title:"Set Workspace Directory",description:`USE THIS TOOL FIRST when working with a new project or when the workspace hasn't been configured yet. This tool MUST be called before any other graphitlive tools if no workspace is set.
103
+ `);var we={workspaceRoot:process.env.WORKSPACE_ROOT??"",extensionPath:process.env.EXTENSION_PATH,tsConfigPath:process.env.TSCONFIG_PATH,excludeNodeModules:process.env.EXCLUDE_NODE_MODULES!=="false",maxDepth:Number.parseInt(process.env.MAX_DEPTH??"50",10)};we.workspaceRoot&&(we.workspaceRoot.includes("${")||we.workspaceRoot.includes("$("))&&(J("[McpServer] WARNING: WORKSPACE_ROOT contains unresolved variable:",we.workspaceRoot),J("[McpServer] Workspace not set - use graphitlive_set_workspace tool to configure"),we.workspaceRoot="");if(!we.workspaceRoot){let t=process.cwd();t==="/"||t===""?J("[McpServer] No workspace configured - use graphitlive_set_workspace tool to set workspace"):(we.workspaceRoot=t,J("[McpServer] WORKSPACE_ROOT not set, using current working directory:",we.workspaceRoot))}we.workspaceRoot&&!rt.existsSync(we.workspaceRoot)&&(J("[McpServer] WARNING: WORKSPACE_ROOT path does not exist:",we.workspaceRoot),J("[McpServer] Use graphitlive_set_workspace tool to configure a valid workspace"),we.workspaceRoot="");function ir(){return we.workspaceRoot}var Te=Re(["json","markdown","toon"]).default("toon"),pD=z({total:re(),limit:re(),offset:re(),hasMore:be()}),fD=z({executionTimeMs:re(),toolVersion:v(),timestamp:v(),workspaceRoot:v()}),Pe=z({success:be(),data:Iu(),metadata:fD,pagination:pD.optional(),error:v().optional()}),ze=new ql({name:"graph-it-live",version:Oo}),tt=null,Kl=!1,Ro=null,Gl=null;function rv(){Kl=!1,Ro=null,Gl=null}async function ov(){if(Kl&&!tt?.ready()&&(J("[McpServer] Worker was initialized but is no longer ready \u2014 auto-recovering"),tt&&(await tt.dispose(),tt=null),rv()),!Kl){if(Gl&&(J("[McpServer] Previous init failed, allowing retry"),rv()),Ro!==null)return J("[McpServer] Waiting for existing initialization..."),Ro;Ro=mD();try{await Ro}catch(t){throw Gl=t instanceof Error?t:new Error(String(t)),Ro=null,Gl}}}async function mD(){let t=Na.join(__dirname,"mcpWorker.js");J(`[McpServer] __dirname: ${__dirname}`),J(`[McpServer] Worker path: ${t}`);try{await(await import("node:fs/promises")).access(t),J("[McpServer] Worker file exists: true")}catch{throw J("[McpServer] Worker file exists: false - THIS IS THE PROBLEM!"),new Error(`Worker file not found at ${t}`)}tt=new Hl({workerPath:t,warmupTimeout:12e4,invokeTimeout:6e4}),J("[McpServer] Starting worker with warmup...");try{let e=await tt.start({rootDir:ir(),tsConfigPath:we.tsConfigPath,extensionPath:we.extensionPath,excludeNodeModules:we.excludeNodeModules,maxDepth:we.maxDepth},(n,o,r)=>{J(`[McpServer] Warmup progress: ${n}/${o} - ${r??""}`)});J(`[McpServer] Worker ready: ${e.filesIndexed} files indexed in ${e.durationMs}ms`),Kl=!0}catch(e){throw J(`[McpServer] Worker initialization failed: ${e}`),e}}async function je(t,e){if(!tt?.ready())return Ra("Worker not ready",0,ir());let n=Date.now();try{let o=await tt.invoke(t,e),r=Date.now()-n;return Qg(o,r,ir())}catch(o){let r=Date.now()-n,i=o instanceof Error?o.message:"Unknown error";return Ra(i,r,ir())}}async function Oe(){try{return await ov(),{error:!1}}catch(t){let e=t instanceof Error?t.message:"Worker initialization failed";return J(`[McpServer] Tool call failed - worker init error: ${e}`),{error:!0,response:Ra(e,0,ir())}}}function tv(t,e,n,o){return{success:!1,data:{success:!1,workspacePath:t,filesIndexed:0,indexingTimeMs:Date.now()-o,previousWorkspace:e||void 0,message:n},error:n,metadata:{executionTimeMs:Date.now()-o,toolVersion:Oo,timestamp:new Date().toISOString(),workspaceRoot:t}}}function hD(t){return rt.existsSync(t)?rt.statSync(t).isDirectory()?null:`Path is not a directory: ${t}`:`Path does not exist: ${t}`}function gD(t,e){if(!t)return{resolvedPath:void 0,error:null};let n=Na.isAbsolute(t)?t:Na.join(e,t);if(!rt.existsSync(n))return{resolvedPath:void 0,error:`tsConfigPath does not exist: ${n}`};if(!rt.statSync(n).isFile())return{resolvedPath:void 0,error:`tsConfigPath is not a file: ${n}`};try{Bw(n,e)}catch(r){return{resolvedPath:void 0,error:r instanceof Error?r.message:"Invalid tsConfigPath"}}return{resolvedPath:n,error:null}}ze.registerTool("graphitlive_set_workspace",{title:"Set Workspace Directory",description:`USE THIS TOOL FIRST when working with a new project or when the workspace hasn't been configured yet. This tool MUST be called before any other graphitlive tools if no workspace is set.
104
104
 
105
105
  WHY: Graph-It-Live needs to know which project directory to analyze. Without a workspace configured, all other tools will fail. This tool sets the project root and initializes the dependency index for fast queries.
106
106
 
107
107
  RETURNS: Confirmation of the new workspace path and the number of files indexed. After calling this, all other graphItLive tools will work on the specified project.
108
108
 
109
- EXAMPLE: If analyzing a project at "/Users/me/my-app", call this tool with workspacePath="/Users/me/my-app"`,inputSchema:Ow.extend({response_format:Te.describe("Output format: 'json', 'markdown', or 'toon' (Token-Oriented Object Notation for reduced token usage) (default: toon - RECOMMENDED for 30-60% token savings)")}),outputSchema:Pe,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({workspacePath:t,tsConfigPath:e,excludeNodeModules:n,maxDepth:o,response_format:r})=>{let i=Date.now(),a=ir(),s=r??"json";J(`[McpServer] setWorkspace called with: ${t}`);let c=hD(t);if(c)return H(tv(t,a,c,i),s);let{resolvedPath:u,error:l}=gD(e,t);if(l)return H(tv(t,a,l,i),s);we.workspaceRoot=t,u!==void 0&&(we.tsConfigPath=u),n!==void 0&&(we.excludeNodeModules=n),o!==void 0&&(we.maxDepth=o),J(`[McpServer] Workspace updated to: ${t}`),tt&&(J("[McpServer] Disposing previous worker..."),tt.dispose(),tt=null),rv();try{await ov();let d=Date.now()-i,p=0,f=tt;f?.ready()&&(p=(await f.invoke("get_index_status",{})).cacheSize);let h={success:!0,data:{success:!0,workspacePath:t,filesIndexed:p,indexingTimeMs:d,previousWorkspace:a||void 0,message:`Workspace set to ${t}. Indexed ${p} files in ${d}ms.`},metadata:{executionTimeMs:d,toolVersion:Oo,timestamp:new Date().toISOString(),workspaceRoot:t}};return J(`[McpServer] Workspace configured successfully: ${p} files indexed`),H(h,s)}catch(d){let p=d instanceof Error?d.message:"Unknown error during initialization";return J(`[McpServer] setWorkspace failed: ${p}`),H(tv(t,a,`Failed to initialize workspace: ${p}`,i),s)}});ze.registerTool("graphitlive_analyze_dependencies",{title:"Analyze File Dependencies",description:`USE THIS TOOL WHEN the user asks about a file's imports, dependencies, or what modules a specific file uses. Examples: "What does this file import?", "Show me the dependencies of src/utils.ts", "What modules does this component rely on?"
109
+ EXAMPLE: If analyzing a project at "/Users/me/my-app", call this tool with workspacePath="/Users/me/my-app"`,inputSchema:Ow.extend({response_format:Te.describe("Output format: 'json', 'markdown', or 'toon' (Token-Oriented Object Notation for reduced token usage) (default: toon - RECOMMENDED for 30-60% token savings)")}),outputSchema:Pe,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({workspacePath:t,tsConfigPath:e,excludeNodeModules:n,maxDepth:o,response_format:r})=>{let i=Date.now(),a=ir(),s=r??"json";J(`[McpServer] setWorkspace called with: ${t}`);let c=hD(t);if(c)return H(tv(t,a,c,i),s);let{resolvedPath:u,error:l}=gD(e,t);if(l)return H(tv(t,a,l,i),s);we.workspaceRoot=t,u!==void 0&&(we.tsConfigPath=u),n!==void 0&&(we.excludeNodeModules=n),o!==void 0&&(we.maxDepth=o),J(`[McpServer] Workspace updated to: ${t}`),tt&&(J("[McpServer] Disposing previous worker..."),await tt.dispose(),tt=null),rv();try{await ov();let d=Date.now()-i,p=0,f=tt;f?.ready()&&(p=(await f.invoke("get_index_status",{})).cacheSize);let h={success:!0,data:{success:!0,workspacePath:t,filesIndexed:p,indexingTimeMs:d,previousWorkspace:a||void 0,message:`Workspace set to ${t}. Indexed ${p} files in ${d}ms.`},metadata:{executionTimeMs:d,toolVersion:Oo,timestamp:new Date().toISOString(),workspaceRoot:t}};return J(`[McpServer] Workspace configured successfully: ${p} files indexed`),H(h,s)}catch(d){let p=d instanceof Error?d.message:"Unknown error during initialization";return J(`[McpServer] setWorkspace failed: ${p}`),H(tv(t,a,`Failed to initialize workspace: ${p}`,i),s)}});ze.registerTool("graphitlive_analyze_dependencies",{title:"Analyze File Dependencies",description:`USE THIS TOOL WHEN the user asks about a file's imports, dependencies, or what modules a specific file uses. Examples: "What does this file import?", "Show me the dependencies of src/utils.ts", "What modules does this component rely on?"
110
110
 
111
111
  WHY: As an AI, you cannot see import statements or module relationships without parsing the actual source code. This tool provides the ground truth by analyzing real import/export statements on disk. Without it, you would have to guess dependencies and risk hallucinating non-existent relationships.
112
112
 
@@ -482,4 +482,4 @@ RETURNS:
482
482
  - filesWithDeadCode: Number of files containing unused exports
483
483
  - totalUnusedSymbols: Sum of all unused exported symbols found
484
484
  - entries[]: Per-file list with filePath, relativePath, unusedCount, unusedSymbols[]
485
- - analysisTimeMs: Wall-clock time for the scan`,inputSchema:Gw.extend({response_format:Te.describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}),outputSchema:Pe,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({scopePath:t,maxFiles:e,response_format:n})=>{let o=await Oe(),r=n??"toon";if(o.error)return H(o.response,r);let i=await je("scan_dead_code",{scopePath:t,maxFiles:e});return H(i,r)});async function vD(){J("[McpServer] Graph-It-Live MCP Server starting..."),J(`[McpServer] Workspace: ${ir()||"(not configured - use graphitlive_set_workspace)"}`),J(`[McpServer] TSConfig: ${we.tsConfigPath??"auto-detect"}`),J(`[McpServer] Exclude node_modules: ${we.excludeNodeModules}`),J(`[McpServer] Max depth: ${we.maxDepth}`);let t=new Vl;await ze.connect(t),J("[McpServer] MCP Server connected via stdio"),ov().catch(e=>{J(`[McpServer] Background warmup failed: ${e}`)}),process.on("SIGINT",()=>{J("[McpServer] Received SIGINT, shutting down..."),tt?.dispose(),process.exit(0)}),process.on("SIGTERM",()=>{J("[McpServer] Received SIGTERM, shutting down..."),tt?.dispose(),process.exit(0)})}vD().catch(t=>{J(`[McpServer] Fatal error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});
485
+ - analysisTimeMs: Wall-clock time for the scan`,inputSchema:Gw.extend({response_format:Te.describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}),outputSchema:Pe,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({scopePath:t,maxFiles:e,response_format:n})=>{let o=await Oe(),r=n??"toon";if(o.error)return H(o.response,r);let i=await je("scan_dead_code",{scopePath:t,maxFiles:e});return H(i,r)});async function vD(){J("[McpServer] Graph-It-Live MCP Server starting..."),J(`[McpServer] Workspace: ${ir()||"(not configured - use graphitlive_set_workspace)"}`),J(`[McpServer] TSConfig: ${we.tsConfigPath??"auto-detect"}`),J(`[McpServer] Exclude node_modules: ${we.excludeNodeModules}`),J(`[McpServer] Max depth: ${we.maxDepth}`);let t=new Vl;await ze.connect(t),J("[McpServer] MCP Server connected via stdio"),ov().catch(e=>{J(`[McpServer] Background warmup failed: ${e}`)}),process.on("SIGINT",()=>{J("[McpServer] Received SIGINT, shutting down..."),tt?.dispose().then(()=>process.exit(0)).catch(()=>process.exit(0))}),process.on("SIGTERM",()=>{J("[McpServer] Received SIGTERM, shutting down..."),tt?.dispose().then(()=>process.exit(0)).catch(()=>process.exit(0))})}vD().catch(t=>{J(`[McpServer] Fatal error: ${t instanceof Error?t.message:String(t)}`),process.exit(1)});