@wp-playground/mcp 3.1.35 → 3.1.38

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.
package/index.cjs CHANGED
@@ -42,7 +42,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
42
42
  ]))`;continue}else if(r[u]==="$"){s+=`($|(?=[\r
43
43
  ]))`;continue}}if(n.s&&r[u]==="."){s+=o?`${r[u]}\r
44
44
  `:`[${r[u]}\r
45
- ]`;continue}s+=r[u],r[u]==="\\"?i=!0:o&&r[u]==="]"?o=!1:!o&&r[u]==="["&&(o=!0)}try{new RegExp(s)}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 s}function eo(t,e){var r,s,i,o,a,c;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"&&((r=t.keyType)==null?void 0:r._def.typeName)===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((u,l)=>({...u,[l]:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",l]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const n={type:"object",additionalProperties:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(((s=t.keyType)==null?void 0:s._def.typeName)===k.ZodString&&((i=t.keyType._def.checks)!=null&&i.length)){const{type:u,...l}=Xi(t.keyType._def,e);return{...n,propertyNames:l}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===k.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&((c=t.keyType._def.type._def.checks)!=null&&c.length)){const{type:u,...l}=Yi(t.keyType._def,e);return{...n,propertyNames:l}}}return n}function zh(t,e){if(e.mapStrategy==="record")return eo(t,e);const n=W(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),r=W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function $h(t){const e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),s=Array.from(new Set(r.map(i=>typeof i)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Ph(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}function Rh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const sn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Nh(t,e){if(e.target==="openApi3")return hs(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in sn&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,i)=>{const o=sn[i._def.typeName];return o&&!s.includes(o)?[...s,o]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,i)=>{const o=typeof i._def.value;switch(o){case"string":case"number":case"boolean":return[...s,o];case"bigint":return[...s,"integer"];case"object":if(i._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((i,o,a)=>a.indexOf(i)===o);return{type:s.length>1?s:s[0],enum:n.reduce((i,o)=>i.includes(o._def.value)?i:[...i,o._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(i=>!r.includes(i))],[])};return hs(t,e)}const hs=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>W(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Eh(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:sn[t.innerType._def.typeName],nullable:!0}:{type:[sn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=W(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Ch(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",Gi(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?K(n,"minimum",r.value,r.message,e):K(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),K(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?K(n,"maximum",r.value,r.message,e):K(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),K(n,"maximum",r.value,r.message,e));break;case"multipleOf":K(n,"multipleOf",r.value,r.message,e);break}return n}function Ih(t,e){const n=e.target==="openAi",r={type:"object",properties:{}},s=[],i=t.shape();for(const a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=xh(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=W(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,u||s.push(a))}s.length&&(r.required=s);const o=Oh(t,e);return o!==void 0&&(r.additionalProperties=o),r}function Oh(t,e){if(t.catchall._def.typeName!=="ZodNever")return W(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 xh(t){try{return t.isOptional()}catch{return!0}}const Zh=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return W(t.innerType._def,e);const n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ke(e)},n]}:ke(e)},Ah=(t,e)=>{if(e.pipeStrategy==="input")return W(t.in._def,e);if(e.pipeStrategy==="output")return W(t.out._def,e);const n=W(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=W(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function jh(t,e){return W(t.type._def,e)}function Mh(t,e){const r={type:"array",uniqueItems:!0,items:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&K(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&K(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function Lh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:W(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Dh(t){return{not:ke(t)}}function qh(t){return ke(t)}const Fh=(t,e)=>W(t.innerType._def,e),Uh=(t,e,n)=>{switch(e){case k.ZodString:return Xi(t,n);case k.ZodNumber:return Ch(t,n);case k.ZodObject:return Ih(t,n);case k.ZodBigInt:return hh(t,n);case k.ZodBoolean:return mh();case k.ZodDate:return Qi(t,n);case k.ZodUndefined:return Dh(n);case k.ZodNull:return Rh(n);case k.ZodArray:return fh(t,n);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Nh(t,n);case k.ZodIntersection:return wh(t,n);case k.ZodTuple:return Lh(t,n);case k.ZodRecord:return eo(t,n);case k.ZodLiteral:return kh(t,n);case k.ZodEnum:return vh(t);case k.ZodNativeEnum:return $h(t);case k.ZodNullable:return Eh(t,n);case k.ZodOptional:return Zh(t,n);case k.ZodMap:return zh(t,n);case k.ZodSet:return Mh(t,n);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return jh(t,n);case k.ZodNaN:case k.ZodNever:return Ph(n);case k.ZodEffects:return yh(t,n);case k.ZodAny:return ke(n);case k.ZodUnknown:return qh(n);case k.ZodDefault:return _h(t,n);case k.ZodBranded:return Yi(t,n);case k.ZodReadonly:return Fh(t,n);case k.ZodCatch:return ph(t,n);case k.ZodPipeline:return Ah(t,n);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(r=>{})()}};function W(t,e,n=!1){var a;const r=e.seen.get(t);if(e.override){const c=(a=e.override)==null?void 0:a.call(e,t,e,r,n);if(c!==uh)return c}if(r&&!n){const c=Vh(r,e);if(c!==void 0)return c}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const i=Uh(t,t.typeName,e),o=typeof i=="function"?W(i(),e):i;if(o&&Hh(t,e,o),e.postProcess){const c=e.postProcess(o,t,e);return s.jsonSchema=o,c}return s.jsonSchema=o,o}const Vh=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ki(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},Hh=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Jh=(t,e)=>{const n=dh(e);let r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??ke(n)}),{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,i=W(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??ke(n),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(i.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=s===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:i}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 Bh(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ms(t,e){return Ze(t)?Eu(t,{target:Bh(e==null?void 0:e.target),io:(e==null?void 0:e.pipeStrategy)??"input"}):Jh(t,{strictUnions:(e==null?void 0:e.strictUnions)??!0,pipeStrategy:(e==null?void 0:e.pipeStrategy)??"input"})}function ps(t){const e=Ot(t),n=e==null?void 0:e.method;if(!n)throw new Error("Schema is missing a method literal");const r=Wi(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function gs(t,e){const n=wt(t,e);if(!n.success)throw n.error;return n.data}const Wh=6e4;class Gh{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(ar,n=>{this._oncancel(n)}),this.setNotificationHandler(ur,n=>{this._onprogress(n)}),this.setRequestHandler(cr,n=>({})),this._taskStore=e==null?void 0:e.taskStore,this._taskMessageQueue=e==null?void 0:e.taskMessageQueue,this._taskStore&&(this.setRequestHandler(lr,async(n,r)=>{const s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new C(x.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(fr,async(n,r)=>{const s=async()=>{var a;const i=n.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(i,r.sessionId);){if(c.type==="response"||c.type==="error"){const u=c.message,l=u.id,d=this._requestResolvers.get(l);if(d)if(this._requestResolvers.delete(l),c.type==="response")d(u);else{const p=u,m=new C(p.error.code,p.error.message,p.error.data);d(m)}else{const p=c.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await((a=this._transport)==null?void 0:a.send(c.message,{relatedRequestId:r.requestId}))}}const o=await this._taskStore.getTask(i,r.sessionId);if(!o)throw new C(x.InvalidParams,`Task not found: ${i}`);if(!Ke(o.status))return await this._waitForTaskUpdate(i,r.signal),await s();if(Ke(o.status)){const c=await this._taskStore.getTaskResult(i,r.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[Ye]:{taskId:i}}}}return await s()};return await s()}),this.setRequestHandler(hr,async(n,r)=>{var s;try{const{tasks:i,nextCursor:o}=await this._taskStore.listTasks((s=n.params)==null?void 0:s.cursor,r.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new C(x.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(pr,async(n,r)=>{try{const s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new C(x.InvalidParams,`Task not found: ${n.params.taskId}`);if(Ke(s.status))throw new C(x.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);const i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new C(x.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...i}}catch(s){throw s instanceof C?s:new C(x.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const n=this._requestHandlerAbortControllers.get(e.params.requestId);n==null||n.abort(e.params.reason)}_setupTimeout(e,n,r,s,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(e){const n=this._timeoutInfo.get(e);if(!n)return!1;const r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),C.fromError(x.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){const n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var i,o,a;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;const n=(i=this.transport)==null?void 0:i.onclose;this._transport.onclose=()=>{n==null||n(),this._onclose()};const r=(o=this.transport)==null?void 0:o.onerror;this._transport.onerror=c=>{r==null||r(c),this._onerror(c)};const s=(a=this._transport)==null?void 0:a.onmessage;this._transport.onmessage=(c,u)=>{s==null||s(c,u),Lt(c)||Wl(c)?this._onresponse(c):Br(c)?this._onrequest(c,u):Bl(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var r;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const s of this._requestHandlerAbortControllers.values())s.abort();this._requestHandlerAbortControllers.clear();const n=C.fromError(x.ConnectionClosed,"Connection closed");this._transport=void 0,(r=this.onclose)==null||r.call(this);for(const s of e.values())s(n)}_onerror(e){var n;(n=this.onerror)==null||n.call(this,e)}_onnotification(e){const n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){var l,d,p,m;const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,i=(p=(d=(l=e.params)==null?void 0:l._meta)==null?void 0:d[Ye])==null?void 0:p.taskId;if(r===void 0){const S={jsonrpc:"2.0",id:e.id,error:{code:x.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:S,timestamp:Date.now()},s==null?void 0:s.sessionId).catch(T=>this._onerror(new Error(`Failed to enqueue error response: ${T}`))):s==null||s.send(S).catch(T=>this._onerror(new Error(`Failed to send an error response: ${T}`)));return}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const a=Jl(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s==null?void 0:s.sessionId):void 0,u={signal:o.signal,sessionId:s==null?void 0:s.sessionId,_meta:(m=e.params)==null?void 0:m._meta,sendNotification:async S=>{if(o.signal.aborted)return;const T={relatedRequestId:e.id};i&&(T.relatedTask={taskId:i}),await this.notification(S,T)},sendRequest:async(S,T,j)=>{var Z;if(o.signal.aborted)throw new C(x.ConnectionClosed,"Request was cancelled");const y={...j,relatedRequestId:e.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});const v=((Z=y.relatedTask)==null?void 0:Z.taskId)??i;return v&&c&&await c.updateTaskStatus(v,"input_required"),await this.request(S,T,y)},authInfo:n==null?void 0:n.authInfo,requestId:e.id,requestInfo:n==null?void 0:n.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a==null?void 0:a.ttl,closeSSEStream:n==null?void 0:n.closeSSEStream,closeStandaloneSSEStream:n==null?void 0:n.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async S=>{if(o.signal.aborted)return;const T={result:S,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:T,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(T))},async S=>{if(o.signal.aborted)return;const T={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(S.code)?S.code:x.InternalError,message:S.message??"Internal error",...S.data!==void 0&&{data:S.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:T,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(T))}).catch(S=>this._onerror(new Error(`Failed to send response: ${S}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:n,...r}=e.params,s=Number(n),i=this._progressHandlers.get(s);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),o(c);return}i(r)}_onresponse(e){const n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Lt(e))r(e);else{const o=new C(e.error.code,e.error.message,e.error.data);r(o)}return}const s=this._responseHandlers.get(n);if(s===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(Lt(e)&&e.result&&typeof e.result=="object"){const o=e.result;if(o.task&&typeof o.task=="object"){const a=o.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,n))}}if(i||this._progressHandlers.delete(n),Lt(e))s(e);else{const o=C.fromError(e.error.code,e.error.message,e.error.data);s(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}async*requestStream(e,n,r){var o,a;const{task:s}=r??{};if(!s){try{yield{type:"result",result:await this.request(e,n,r)}}catch(c){yield{type:"error",error:c instanceof C?c:new C(x.InternalError,String(c))}}return}let i;try{const c=await this.request(e,gn,r);if(c.task)i=c.task.taskId,yield{type:"taskCreated",task:c.task};else throw new C(x.InternalError,"Task creation did not return a task");for(;;){const u=await this.getTask({taskId:i},r);if(yield{type:"taskStatus",task:u},Ke(u.status)){u.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},n,r)}:u.status==="failed"?yield{type:"error",error:new C(x.InternalError,`Task ${i} failed`)}:u.status==="cancelled"&&(yield{type:"error",error:new C(x.InternalError,`Task ${i} was cancelled`)});return}if(u.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},n,r)};return}const l=u.pollInterval??((o=this._options)==null?void 0:o.defaultTaskPollInterval)??1e3;await new Promise(d=>setTimeout(d,l)),(a=r==null?void 0:r.signal)==null||a.throwIfAborted()}}catch(c){yield{type:"error",error:c instanceof C?c:new C(x.InternalError,String(c))}}}request(e,n,r){const{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{var v,Z,R,te,ue;const d=G=>{l(G)};if(!this._transport){d(new Error("Not connected"));return}if(((v=this._options)==null?void 0:v.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(G){d(G);return}(Z=r==null?void 0:r.signal)==null||Z.throwIfAborted();const p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};r!=null&&r.onprogress&&(this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...((R=e.params)==null?void 0:R._meta)||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...((te=m.params)==null?void 0:te._meta)||{},[Ye]:c}});const S=G=>{var fe;this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),(fe=this._transport)==null||fe.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(G)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(Je=>this._onerror(new Error(`Failed to send cancellation: ${Je}`)));const _e=G instanceof C?G:new C(x.RequestTimeout,String(G));l(_e)};this._responseHandlers.set(p,G=>{var _e;if(!((_e=r==null?void 0:r.signal)!=null&&_e.aborted)){if(G instanceof Error)return l(G);try{const fe=wt(n,G.result);fe.success?u(fe.data):l(fe.error)}catch(fe){l(fe)}}}),(ue=r==null?void 0:r.signal)==null||ue.addEventListener("abort",()=>{var G;S((G=r==null?void 0:r.signal)==null?void 0:G.reason)});const T=(r==null?void 0:r.timeout)??Wh,j=()=>S(C.fromError(x.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(p,T,r==null?void 0:r.maxTotalTimeout,j,(r==null?void 0:r.resetTimeoutOnProgress)??!1);const y=c==null?void 0:c.taskId;if(y){const G=_e=>{const fe=this._responseHandlers.get(p);fe?fe(_e):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,G),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(_e=>{this._cleanupTimeout(p),l(_e)})}else this._transport.send(m,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(G=>{this._cleanupTimeout(p),l(G)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},dr,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},mr,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},dd,n)}async notification(e,n){var a,c,u,l;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=(a=n==null?void 0:n.relatedTask)==null?void 0:a.taskId;if(r){const d={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((c=e.params)==null?void 0:c._meta)||{},[Ye]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:d,timestamp:Date.now()});return}if((((u=this._options)==null?void 0:u.debouncedNotificationMethods)??[]).includes(e.method)&&!e.params&&!(n!=null&&n.relatedRequestId)&&!(n!=null&&n.relatedTask)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var p,m;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let d={...e,jsonrpc:"2.0"};n!=null&&n.relatedTask&&(d={...d,params:{...d.params,_meta:{...((p=d.params)==null?void 0:p._meta)||{},[Ye]:n.relatedTask}}}),(m=this._transport)==null||m.send(d,n).catch(S=>this._onerror(S))});return}let o={...e,jsonrpc:"2.0"};n!=null&&n.relatedTask&&(o={...o,params:{...o.params,_meta:{...((l=o.params)==null?void 0:l._meta)||{},[Ye]:n.relatedTask}}}),await this._transport.send(o,n)}setRequestHandler(e,n){const r=ps(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,i)=>{const o=gs(e,s);return Promise.resolve(n(o,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){const r=ps(e);this._notificationHandlers.set(r,s=>{const i=gs(e,s);return Promise.resolve(n(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=(i=this._options)==null?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,s)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,n);for(const s of r)if(s.type==="request"&&Br(s.message)){const i=s.message.id,o=this._requestResolvers.get(i);o?(o(new C(x.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){var s,i;let r=((s=this._options)==null?void 0:s.defaultTaskPollInterval)??1e3;try{const o=await((i=this._taskStore)==null?void 0:i.getTask(e));o!=null&&o.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,a)=>{if(n.aborted){a(new C(x.InvalidRequest,"Request cancelled"));return}const c=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(c),a(new C(x.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await r.createTask(s,e.id,{method:e.method,params:e.params},n)},getTask:async s=>{const i=await r.getTask(s,n);if(!i)throw new C(x.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(s,i,o)=>{await r.storeTaskResult(s,i,o,n);const a=await r.getTask(s,n);if(a){const c=Bt.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ke(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>r.getTaskResult(s,n),updateTaskStatus:async(s,i,o)=>{const a=await r.getTask(s,n);if(!a)throw new C(x.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Ke(a.status))throw new C(x.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(s,i,o,n);const c=await r.getTask(s,n);if(c){const u=Bt.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ke(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}function _s(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Kh(t,e){const n={...t};for(const r in e){const s=r,i=e[s];if(i===void 0)continue;const o=n[s];_s(o)&&_s(i)?n[s]={...o,...i}:n[s]=i}return n}function Yh(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Vn={exports:{}},to={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(A,q){return{validate:A,compare:q}}t.fullFormats={date:e(i,o),time:e(c(!0),u),"date-time":e(p(!0),m),"iso-time":e(c(),l),"iso-date-time":e(p(),S),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:Je,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:Z,int32:{type:"number",validate:ue},int64:{type:"number",validate:G},float:{type:"number",validate:_e},double:{type:"number",validate:_e},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,m),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,S),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function n(A){return A%4===0&&(A%100!==0||A%400===0)}const r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(A){const q=r.exec(A);if(!q)return!1;const ae=+q[1],F=+q[2],Te=+q[3];return F>=1&&F<=12&&Te>=1&&Te<=(F===2&&n(ae)?29:s[F])}function o(A,q){if(A&&q)return A>q?1:A<q?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(A){return function(ae){const F=a.exec(ae);if(!F)return!1;const Te=+F[1],Be=+F[2],We=+F[3],_n=F[4],xt=F[5]==="-"?-1:1,Zt=+(F[6]||0),pt=+(F[7]||0);if(Zt>23||pt>59||A&&!_n)return!1;if(Te<=23&&Be<=59&&We<60)return!0;const Ge=Be-pt*xt,O=Te-Zt*xt-(Ge<0?1:0);return(O===23||O===-1)&&(Ge===59||Ge===-1)&&We<61}}function u(A,q){if(!(A&&q))return;const ae=new Date("2020-01-01T"+A).valueOf(),F=new Date("2020-01-01T"+q).valueOf();if(ae&&F)return ae-F}function l(A,q){if(!(A&&q))return;const ae=a.exec(A),F=a.exec(q);if(ae&&F)return A=ae[1]+ae[2]+ae[3],q=F[1]+F[2]+F[3],A>q?1:A<q?-1:0}const d=/t|\s/i;function p(A){const q=c(A);return function(F){const Te=F.split(d);return Te.length===2&&i(Te[0])&&q(Te[1])}}function m(A,q){if(!(A&&q))return;const ae=new Date(A).valueOf(),F=new Date(q).valueOf();if(ae&&F)return ae-F}function S(A,q){if(!(A&&q))return;const[ae,F]=A.split(d),[Te,Be]=q.split(d),We=o(ae,Te);if(We!==void 0)return We||u(F,Be)}const T=/\/|:/,j=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function y(A){return T.test(A)&&j.test(A)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Z(A){return v.lastIndex=0,v.test(A)}const R=-2147483648,te=2**31-1;function ue(A){return Number.isInteger(A)&&A<=te&&A>=R}function G(A){return Number.isInteger(A)}function _e(){return!0}const fe=/[^\\]\\Z/;function Je(A){if(fe.test(A))return!1;try{return new RegExp(A),!0}catch{return!1}}})(to);var no={},zr={},on={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class r extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((Z,R)=>`${Z}${R}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((Z,R)=>(R instanceof n&&(Z[R.str]=(Z[R.str]||0)+1),Z),{})}}t._Code=r,t.nil=new r("");function s(y,...v){const Z=[y[0]];let R=0;for(;R<v.length;)a(Z,v[R]),Z.push(y[++R]);return new r(Z)}t._=s;const i=new r("+");function o(y,...v){const Z=[m(y[0])];let R=0;for(;R<v.length;)Z.push(i),a(Z,v[R]),Z.push(i,m(y[++R]));return c(Z),new r(Z)}t.str=o;function a(y,v){v instanceof r?y.push(...v._items):v instanceof n?y.push(v):y.push(d(v))}t.addCodeArg=a;function c(y){let v=1;for(;v<y.length-1;){if(y[v]===i){const Z=u(y[v-1],y[v+1]);if(Z!==void 0){y.splice(v-1,3,Z);continue}y[v++]="+"}v++}}function u(y,v){if(v==='""')return y;if(y==='""')return v;if(typeof y=="string")return v instanceof n||y[y.length-1]!=='"'?void 0:typeof v!="string"?`${y.slice(0,-1)}${v}"`:v[0]==='"'?y.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(y instanceof n))return`"${y}${v.slice(1)}`}function l(y,v){return v.emptyStr()?y:y.emptyStr()?v:o`${y}${v}`}t.strConcat=l;function d(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:m(Array.isArray(y)?y.join(","):y)}function p(y){return new r(m(y))}t.stringify=p;function m(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=m;function S(y){return typeof y=="string"&&t.IDENTIFIER.test(y)?new r(`.${y}`):s`[${y}]`}t.getProperty=S;function T(y){if(typeof y=="string"&&t.IDENTIFIER.test(y))return new r(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}t.getEsmExportName=T;function j(y){return new r(y.toString())}t.regexpCode=j})(on);var Hn={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=on;class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var r;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(r=t.UsedValueState||(t.UsedValueState={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class s{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=s;class i extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=i;const o=(0,e._)`\n`;class a extends s{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?o:e.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:m}=p,S=(d=l.key)!==null&&d!==void 0?d:l.ref;let T=this._values[m];if(T){const v=T.get(S);if(v)return v}else T=this._values[m]=new Map;T.set(S,p);const j=this._scope[m]||(this._scope[m]=[]),y=j.length;return j[y]=l.ref,p.setValue(l,{property:m,itemIndex:y}),p}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=e.nil;for(const S in u){const T=u[S];if(!T)continue;const j=d[S]=d[S]||new Map;T.forEach(y=>{if(j.has(y))return;j.set(y,r.Started);let v=l(y);if(v){const Z=this.opts.es5?t.varKinds.var:t.varKinds.const;m=(0,e._)`${m}${Z} ${y} = ${v};${this.opts._n}`}else if(v=p==null?void 0:p(y))m=(0,e._)`${m}${v}${this.opts._n}`;else throw new n(y);j.set(y,r.Completed)})}return m}}t.ValueScope=a})(Hn);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=on,n=Hn;var r=on;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}});var s=Hn;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class i{optimizeNodes(){return this}optimizeNames(f,h){return this}}class o extends i{constructor(f,h,b){super(),this.varKind=f,this.name=h,this.rhs=b}render({es5:f,_n:h}){const b=f?n.varKinds.var:this.varKind,D=this.rhs===void 0?"":` = ${this.rhs}`;return`${b} ${this.name}${D};`+h}optimizeNames(f,h){if(f[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,f,h)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends i{constructor(f,h,b){super(),this.lhs=f,this.rhs=h,this.sideEffects=b}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,h){if(!(this.lhs instanceof e.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,f,h),this}get names(){const f=this.lhs instanceof e.Name?{}:{...this.lhs.names};return ae(f,this.rhs)}}class c extends a{constructor(f,h,b,D){super(f,b,D),this.op=h}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends i{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class p extends i{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,h){return this.code=F(this.code,f,h),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class m extends i{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((h,b)=>h+b.render(f),"")}optimizeNodes(){const{nodes:f}=this;let h=f.length;for(;h--;){const b=f[h].optimizeNodes();Array.isArray(b)?f.splice(h,1,...b):b?f[h]=b:f.splice(h,1)}return f.length>0?this:void 0}optimizeNames(f,h){const{nodes:b}=this;let D=b.length;for(;D--;){const H=b[D];H.optimizeNames(f,h)||(Te(f,H.names),b.splice(D,1))}return b.length>0?this:void 0}get names(){return this.nodes.reduce((f,h)=>q(f,h.names),{})}}class S extends m{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class T extends m{}class j extends S{}j.kind="else";class y extends S{constructor(f,h){super(h),this.condition=f}render(f){let h=`if(${this.condition})`+super.render(f);return this.else&&(h+="else "+this.else.render(f)),h}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let h=this.else;if(h){const b=h.optimizeNodes();h=this.else=Array.isArray(b)?new j(b):b}if(h)return f===!1?h instanceof y?h:h.nodes:this.nodes.length?this:new y(Be(f),h instanceof y?[h]:h.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,h){var b;if(this.else=(b=this.else)===null||b===void 0?void 0:b.optimizeNames(f,h),!!(super.optimizeNames(f,h)||this.else))return this.condition=F(this.condition,f,h),this}get names(){const f=super.names;return ae(f,this.condition),this.else&&q(f,this.else.names),f}}y.kind="if";class v extends S{}v.kind="for";class Z extends v{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,h){if(super.optimizeNames(f,h))return this.iteration=F(this.iteration,f,h),this}get names(){return q(super.names,this.iteration.names)}}class R extends v{constructor(f,h,b,D){super(),this.varKind=f,this.name=h,this.from=b,this.to=D}render(f){const h=f.es5?n.varKinds.var:this.varKind,{name:b,from:D,to:H}=this;return`for(${h} ${b}=${D}; ${b}<${H}; ${b}++)`+super.render(f)}get names(){const f=ae(super.names,this.from);return ae(f,this.to)}}class te extends v{constructor(f,h,b,D){super(),this.loop=f,this.varKind=h,this.name=b,this.iterable=D}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,h){if(super.optimizeNames(f,h))return this.iterable=F(this.iterable,f,h),this}get names(){return q(super.names,this.iterable.names)}}class ue extends S{constructor(f,h,b){super(),this.name=f,this.args=h,this.async=b}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}ue.kind="func";class G extends m{render(f){return"return "+super.render(f)}}G.kind="return";class _e extends S{render(f){let h="try"+super.render(f);return this.catch&&(h+=this.catch.render(f)),this.finally&&(h+=this.finally.render(f)),h}optimizeNodes(){var f,h;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(h=this.finally)===null||h===void 0||h.optimizeNodes(),this}optimizeNames(f,h){var b,D;return super.optimizeNames(f,h),(b=this.catch)===null||b===void 0||b.optimizeNames(f,h),(D=this.finally)===null||D===void 0||D.optimizeNames(f,h),this}get names(){const f=super.names;return this.catch&&q(f,this.catch.names),this.finally&&q(f,this.finally.names),f}}class fe extends S{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}fe.kind="catch";class Je extends S{render(f){return"finally"+super.render(f)}}Je.kind="finally";class A{constructor(f,h={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...h,_n:h.lines?`
45
+ ]`;continue}s+=r[u],r[u]==="\\"?i=!0:o&&r[u]==="]"?o=!1:!o&&r[u]==="["&&(o=!0)}try{new RegExp(s)}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 s}function eo(t,e){var r,s,i,o,a,c;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"&&((r=t.keyType)==null?void 0:r._def.typeName)===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((u,l)=>({...u,[l]:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",l]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const n={type:"object",additionalProperties:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(((s=t.keyType)==null?void 0:s._def.typeName)===k.ZodString&&((i=t.keyType._def.checks)!=null&&i.length)){const{type:u,...l}=Xi(t.keyType._def,e);return{...n,propertyNames:l}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===k.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(((a=t.keyType)==null?void 0:a._def.typeName)===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&((c=t.keyType._def.type._def.checks)!=null&&c.length)){const{type:u,...l}=Yi(t.keyType._def,e);return{...n,propertyNames:l}}}return n}function zh(t,e){if(e.mapStrategy==="record")return eo(t,e);const n=W(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),r=W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function $h(t){const e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),s=Array.from(new Set(r.map(i=>typeof i)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Ph(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}function Rh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const sn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Nh(t,e){if(e.target==="openApi3")return hs(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in sn&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((s,i)=>{const o=sn[i._def.typeName];return o&&!s.includes(o)?[...s,o]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((s,i)=>{const o=typeof i._def.value;switch(o){case"string":case"number":case"boolean":return[...s,o];case"bigint":return[...s,"integer"];case"object":if(i._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===n.length){const s=r.filter((i,o,a)=>a.indexOf(i)===o);return{type:s.length>1?s:s[0],enum:n.reduce((i,o)=>i.includes(o._def.value)?i:[...i,o._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(i=>!r.includes(i))],[])};return hs(t,e)}const hs=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>W(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Eh(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:sn[t.innerType._def.typeName],nullable:!0}:{type:[sn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=W(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Ch(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",Gi(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?K(n,"minimum",r.value,r.message,e):K(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),K(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?K(n,"maximum",r.value,r.message,e):K(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),K(n,"maximum",r.value,r.message,e));break;case"multipleOf":K(n,"multipleOf",r.value,r.message,e);break}return n}function Ih(t,e){const n=e.target==="openAi",r={type:"object",properties:{}},s=[],i=t.shape();for(const a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=xh(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=W(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(r.properties[a]=l,u||s.push(a))}s.length&&(r.required=s);const o=Oh(t,e);return o!==void 0&&(r.additionalProperties=o),r}function Oh(t,e){if(t.catchall._def.typeName!=="ZodNever")return W(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 xh(t){try{return t.isOptional()}catch{return!0}}const Zh=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return W(t.innerType._def,e);const n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ke(e)},n]}:ke(e)},Ah=(t,e)=>{if(e.pipeStrategy==="input")return W(t.in._def,e);if(e.pipeStrategy==="output")return W(t.out._def,e);const n=W(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=W(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}};function jh(t,e){return W(t.type._def,e)}function Mh(t,e){const r={type:"array",uniqueItems:!0,items:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&K(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&K(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function Lh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:W(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function Dh(t){return{not:ke(t)}}function qh(t){return ke(t)}const Fh=(t,e)=>W(t.innerType._def,e),Uh=(t,e,n)=>{switch(e){case k.ZodString:return Xi(t,n);case k.ZodNumber:return Ch(t,n);case k.ZodObject:return Ih(t,n);case k.ZodBigInt:return hh(t,n);case k.ZodBoolean:return mh();case k.ZodDate:return Qi(t,n);case k.ZodUndefined:return Dh(n);case k.ZodNull:return Rh(n);case k.ZodArray:return fh(t,n);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Nh(t,n);case k.ZodIntersection:return wh(t,n);case k.ZodTuple:return Lh(t,n);case k.ZodRecord:return eo(t,n);case k.ZodLiteral:return kh(t,n);case k.ZodEnum:return vh(t);case k.ZodNativeEnum:return $h(t);case k.ZodNullable:return Eh(t,n);case k.ZodOptional:return Zh(t,n);case k.ZodMap:return zh(t,n);case k.ZodSet:return Mh(t,n);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return jh(t,n);case k.ZodNaN:case k.ZodNever:return Ph(n);case k.ZodEffects:return yh(t,n);case k.ZodAny:return ke(n);case k.ZodUnknown:return qh(n);case k.ZodDefault:return _h(t,n);case k.ZodBranded:return Yi(t,n);case k.ZodReadonly:return Fh(t,n);case k.ZodCatch:return ph(t,n);case k.ZodPipeline:return Ah(t,n);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(r=>{})()}};function W(t,e,n=!1){var a;const r=e.seen.get(t);if(e.override){const c=(a=e.override)==null?void 0:a.call(e,t,e,r,n);if(c!==uh)return c}if(r&&!n){const c=Vh(r,e);if(c!==void 0)return c}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const i=Uh(t,t.typeName,e),o=typeof i=="function"?W(i(),e):i;if(o&&Hh(t,e,o),e.postProcess){const c=e.postProcess(o,t,e);return s.jsonSchema=o,c}return s.jsonSchema=o,o}const Vh=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ki(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},Hh=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Jh=(t,e)=>{const n=dh(e);let r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??ke(n)}),{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,i=W(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??ke(n),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(i.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=s===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:i}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 Bh(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ms(t,e){return Ze(t)?Eu(t,{target:Bh(e==null?void 0:e.target),io:(e==null?void 0:e.pipeStrategy)??"input"}):Jh(t,{strictUnions:(e==null?void 0:e.strictUnions)??!0,pipeStrategy:(e==null?void 0:e.pipeStrategy)??"input"})}function ps(t){const e=Ot(t),n=e==null?void 0:e.method;if(!n)throw new Error("Schema is missing a method literal");const r=Wi(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function gs(t,e){const n=wt(t,e);if(!n.success)throw n.error;return n.data}const Wh=6e4;class Gh{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(ar,n=>{this._oncancel(n)}),this.setNotificationHandler(ur,n=>{this._onprogress(n)}),this.setRequestHandler(cr,n=>({})),this._taskStore=e==null?void 0:e.taskStore,this._taskMessageQueue=e==null?void 0:e.taskMessageQueue,this._taskStore&&(this.setRequestHandler(lr,async(n,r)=>{const s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new C(x.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(fr,async(n,r)=>{const s=async()=>{var a;const i=n.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(i,r.sessionId);){if(c.type==="response"||c.type==="error"){const u=c.message,l=u.id,d=this._requestResolvers.get(l);if(d)if(this._requestResolvers.delete(l),c.type==="response")d(u);else{const p=u,m=new C(p.error.code,p.error.message,p.error.data);d(m)}else{const p=c.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await((a=this._transport)==null?void 0:a.send(c.message,{relatedRequestId:r.requestId}))}}const o=await this._taskStore.getTask(i,r.sessionId);if(!o)throw new C(x.InvalidParams,`Task not found: ${i}`);if(!Ke(o.status))return await this._waitForTaskUpdate(i,r.signal),await s();if(Ke(o.status)){const c=await this._taskStore.getTaskResult(i,r.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[Ye]:{taskId:i}}}}return await s()};return await s()}),this.setRequestHandler(hr,async(n,r)=>{var s;try{const{tasks:i,nextCursor:o}=await this._taskStore.listTasks((s=n.params)==null?void 0:s.cursor,r.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new C(x.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(pr,async(n,r)=>{try{const s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new C(x.InvalidParams,`Task not found: ${n.params.taskId}`);if(Ke(s.status))throw new C(x.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);const i=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!i)throw new C(x.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...i}}catch(s){throw s instanceof C?s:new C(x.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const n=this._requestHandlerAbortControllers.get(e.params.requestId);n==null||n.abort(e.params.reason)}_setupTimeout(e,n,r,s,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:s})}_resetTimeout(e){const n=this._timeoutInfo.get(e);if(!n)return!1;const r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),C.fromError(x.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){const n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var i,o,a;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;const n=(i=this.transport)==null?void 0:i.onclose;this._transport.onclose=()=>{n==null||n(),this._onclose()};const r=(o=this.transport)==null?void 0:o.onerror;this._transport.onerror=c=>{r==null||r(c),this._onerror(c)};const s=(a=this._transport)==null?void 0:a.onmessage;this._transport.onmessage=(c,u)=>{s==null||s(c,u),Lt(c)||Wl(c)?this._onresponse(c):Br(c)?this._onrequest(c,u):Bl(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var r;const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const s of this._requestHandlerAbortControllers.values())s.abort();this._requestHandlerAbortControllers.clear();const n=C.fromError(x.ConnectionClosed,"Connection closed");this._transport=void 0,(r=this.onclose)==null||r.call(this);for(const s of e.values())s(n)}_onerror(e){var n;(n=this.onerror)==null||n.call(this,e)}_onnotification(e){const n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){var l,d,p,m;const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,i=(p=(d=(l=e.params)==null?void 0:l._meta)==null?void 0:d[Ye])==null?void 0:p.taskId;if(r===void 0){const S={jsonrpc:"2.0",id:e.id,error:{code:x.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:S,timestamp:Date.now()},s==null?void 0:s.sessionId).catch(T=>this._onerror(new Error(`Failed to enqueue error response: ${T}`))):s==null||s.send(S).catch(T=>this._onerror(new Error(`Failed to send an error response: ${T}`)));return}const o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);const a=Jl(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s==null?void 0:s.sessionId):void 0,u={signal:o.signal,sessionId:s==null?void 0:s.sessionId,_meta:(m=e.params)==null?void 0:m._meta,sendNotification:async S=>{if(o.signal.aborted)return;const T={relatedRequestId:e.id};i&&(T.relatedTask={taskId:i}),await this.notification(S,T)},sendRequest:async(S,T,j)=>{var Z;if(o.signal.aborted)throw new C(x.ConnectionClosed,"Request was cancelled");const y={...j,relatedRequestId:e.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});const v=((Z=y.relatedTask)==null?void 0:Z.taskId)??i;return v&&c&&await c.updateTaskStatus(v,"input_required"),await this.request(S,T,y)},authInfo:n==null?void 0:n.authInfo,requestId:e.id,requestInfo:n==null?void 0:n.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a==null?void 0:a.ttl,closeSSEStream:n==null?void 0:n.closeSSEStream,closeStandaloneSSEStream:n==null?void 0:n.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async S=>{if(o.signal.aborted)return;const T={result:S,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:T,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(T))},async S=>{if(o.signal.aborted)return;const T={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(S.code)?S.code:x.InternalError,message:S.message??"Internal error",...S.data!==void 0&&{data:S.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:T,timestamp:Date.now()},s==null?void 0:s.sessionId):await(s==null?void 0:s.send(T))}).catch(S=>this._onerror(new Error(`Failed to send response: ${S}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:n,...r}=e.params,s=Number(n),i=this._progressHandlers.get(s);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&o&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),o(c);return}i(r)}_onresponse(e){const n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Lt(e))r(e);else{const o=new C(e.error.code,e.error.message,e.error.data);r(o)}return}const s=this._responseHandlers.get(n);if(s===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(Lt(e)&&e.result&&typeof e.result=="object"){const o=e.result;if(o.task&&typeof o.task=="object"){const a=o.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,n))}}if(i||this._progressHandlers.delete(n),Lt(e))s(e);else{const o=C.fromError(e.error.code,e.error.message,e.error.data);s(o)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)==null?void 0:e.close())}async*requestStream(e,n,r){var o,a;const{task:s}=r??{};if(!s){try{yield{type:"result",result:await this.request(e,n,r)}}catch(c){yield{type:"error",error:c instanceof C?c:new C(x.InternalError,String(c))}}return}let i;try{const c=await this.request(e,gn,r);if(c.task)i=c.task.taskId,yield{type:"taskCreated",task:c.task};else throw new C(x.InternalError,"Task creation did not return a task");for(;;){const u=await this.getTask({taskId:i},r);if(yield{type:"taskStatus",task:u},Ke(u.status)){u.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},n,r)}:u.status==="failed"?yield{type:"error",error:new C(x.InternalError,`Task ${i} failed`)}:u.status==="cancelled"&&(yield{type:"error",error:new C(x.InternalError,`Task ${i} was cancelled`)});return}if(u.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},n,r)};return}const l=u.pollInterval??((o=this._options)==null?void 0:o.defaultTaskPollInterval)??1e3;await new Promise(d=>setTimeout(d,l)),(a=r==null?void 0:r.signal)==null||a.throwIfAborted()}}catch(c){yield{type:"error",error:c instanceof C?c:new C(x.InternalError,String(c))}}}request(e,n,r){const{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{var v,Z,R,te,ue;const d=G=>{l(G)};if(!this._transport){d(new Error("Not connected"));return}if(((v=this._options)==null?void 0:v.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(G){d(G);return}(Z=r==null?void 0:r.signal)==null||Z.throwIfAborted();const p=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:p};r!=null&&r.onprogress&&(this._progressHandlers.set(p,r.onprogress),m.params={...e.params,_meta:{...((R=e.params)==null?void 0:R._meta)||{},progressToken:p}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...((te=m.params)==null?void 0:te._meta)||{},[Ye]:c}});const S=G=>{var fe;this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),(fe=this._transport)==null||fe.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(G)}},{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(Je=>this._onerror(new Error(`Failed to send cancellation: ${Je}`)));const _e=G instanceof C?G:new C(x.RequestTimeout,String(G));l(_e)};this._responseHandlers.set(p,G=>{var _e;if(!((_e=r==null?void 0:r.signal)!=null&&_e.aborted)){if(G instanceof Error)return l(G);try{const fe=wt(n,G.result);fe.success?u(fe.data):l(fe.error)}catch(fe){l(fe)}}}),(ue=r==null?void 0:r.signal)==null||ue.addEventListener("abort",()=>{var G;S((G=r==null?void 0:r.signal)==null?void 0:G.reason)});const T=(r==null?void 0:r.timeout)??Wh,j=()=>S(C.fromError(x.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(p,T,r==null?void 0:r.maxTotalTimeout,j,(r==null?void 0:r.resetTimeoutOnProgress)??!1);const y=c==null?void 0:c.taskId;if(y){const G=_e=>{const fe=this._responseHandlers.get(p);fe?fe(_e):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,G),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(_e=>{this._cleanupTimeout(p),l(_e)})}else this._transport.send(m,{relatedRequestId:s,resumptionToken:i,onresumptiontoken:o}).catch(G=>{this._cleanupTimeout(p),l(G)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},dr,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},mr,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},dd,n)}async notification(e,n){var a,c,u,l;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=(a=n==null?void 0:n.relatedTask)==null?void 0:a.taskId;if(r){const d={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...((c=e.params)==null?void 0:c._meta)||{},[Ye]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:d,timestamp:Date.now()});return}if((((u=this._options)==null?void 0:u.debouncedNotificationMethods)??[]).includes(e.method)&&!e.params&&!(n!=null&&n.relatedRequestId)&&!(n!=null&&n.relatedTask)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var p,m;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let d={...e,jsonrpc:"2.0"};n!=null&&n.relatedTask&&(d={...d,params:{...d.params,_meta:{...((p=d.params)==null?void 0:p._meta)||{},[Ye]:n.relatedTask}}}),(m=this._transport)==null||m.send(d,n).catch(S=>this._onerror(S))});return}let o={...e,jsonrpc:"2.0"};n!=null&&n.relatedTask&&(o={...o,params:{...o.params,_meta:{...((l=o.params)==null?void 0:l._meta)||{},[Ye]:n.relatedTask}}}),await this._transport.send(o,n)}setRequestHandler(e,n){const r=ps(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,i)=>{const o=gs(e,s);return Promise.resolve(n(o,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){const r=ps(e);this._notificationHandlers.set(r,s=>{const i=gs(e,s);return Promise.resolve(n(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const s=(i=this._options)==null?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,s)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,n);for(const s of r)if(s.type==="request"&&Br(s.message)){const i=s.message.id,o=this._requestResolvers.get(i);o?(o(new C(x.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){var s,i;let r=((s=this._options)==null?void 0:s.defaultTaskPollInterval)??1e3;try{const o=await((i=this._taskStore)==null?void 0:i.getTask(e));o!=null&&o.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,a)=>{if(n.aborted){a(new C(x.InvalidRequest,"Request cancelled"));return}const c=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(c),a(new C(x.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await r.createTask(s,e.id,{method:e.method,params:e.params},n)},getTask:async s=>{const i=await r.getTask(s,n);if(!i)throw new C(x.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(s,i,o)=>{await r.storeTaskResult(s,i,o,n);const a=await r.getTask(s,n);if(a){const c=Bt.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ke(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>r.getTaskResult(s,n),updateTaskStatus:async(s,i,o)=>{const a=await r.getTask(s,n);if(!a)throw new C(x.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Ke(a.status))throw new C(x.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(s,i,o,n);const c=await r.getTask(s,n);if(c){const u=Bt.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ke(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}function _s(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Kh(t,e){const n={...t};for(const r in e){const s=r,i=e[s];if(i===void 0)continue;const o=n[s];_s(o)&&_s(i)?n[s]={...o,...i}:n[s]=i}return n}function Yh(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Vn={exports:{}},to={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatNames=t.fastFormats=t.fullFormats=void 0;function e(A,q){return{validate:A,compare:q}}t.fullFormats={date:e(i,o),time:e(c(!0),u),"date-time":e(p(!0),m),"iso-time":e(c(),l),"iso-date-time":e(p(),S),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:Je,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:Z,int32:{type:"number",validate:ue},int64:{type:"number",validate:G},float:{type:"number",validate:_e},double:{type:"number",validate:_e},password:!0,binary:!0},t.fastFormats={...t.fullFormats,date:e(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,m),"iso-time":e(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":e(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,S),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},t.formatNames=Object.keys(t.fullFormats);function n(A){return A%4===0&&(A%100!==0||A%400===0)}const r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(A){const q=r.exec(A);if(!q)return!1;const ae=+q[1],F=+q[2],Te=+q[3];return F>=1&&F<=12&&Te>=1&&Te<=(F===2&&n(ae)?29:s[F])}function o(A,q){if(A&&q)return A>q?1:A<q?-1:0}const a=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(A){return function(ae){const F=a.exec(ae);if(!F)return!1;const Te=+F[1],Be=+F[2],We=+F[3],_n=F[4],xt=F[5]==="-"?-1:1,Zt=+(F[6]||0),pt=+(F[7]||0);if(Zt>23||pt>59||A&&!_n)return!1;if(Te<=23&&Be<=59&&We<60)return!0;const Ge=Be-pt*xt,O=Te-Zt*xt-(Ge<0?1:0);return(O===23||O===-1)&&(Ge===59||Ge===-1)&&We<61}}function u(A,q){if(!(A&&q))return;const ae=new Date("2020-01-01T"+A).valueOf(),F=new Date("2020-01-01T"+q).valueOf();if(ae&&F)return ae-F}function l(A,q){if(!(A&&q))return;const ae=a.exec(A),F=a.exec(q);if(ae&&F)return A=ae[1]+ae[2]+ae[3],q=F[1]+F[2]+F[3],A>q?1:A<q?-1:0}const d=/t|\s/i;function p(A){const q=c(A);return function(F){const Te=F.split(d);return Te.length===2&&i(Te[0])&&q(Te[1])}}function m(A,q){if(!(A&&q))return;const ae=new Date(A).valueOf(),F=new Date(q).valueOf();if(ae&&F)return ae-F}function S(A,q){if(!(A&&q))return;const[ae,F]=A.split(d),[Te,Be]=q.split(d),We=o(ae,Te);if(We!==void 0)return We||u(F,Be)}const T=/\/|:/,j=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function y(A){return T.test(A)&&j.test(A)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Z(A){return v.lastIndex=0,v.test(A)}const R=-2147483648,te=2**31-1;function ue(A){return Number.isInteger(A)&&A<=te&&A>=R}function G(A){return Number.isInteger(A)}function _e(){return!0}const fe=/[^\\]\\Z/;function Je(A){if(fe.test(A))return!1;try{return new RegExp(A),!0}catch{return!1}}})(to);var no={},zr={},on={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class r extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((Z,R)=>`${Z}${R}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((Z,R)=>(R instanceof n&&(Z[R.str]=(Z[R.str]||0)+1),Z),{})}}t._Code=r,t.nil=new r("");function s(y,...v){const Z=[y[0]];let R=0;for(;R<v.length;)a(Z,v[R]),Z.push(y[++R]);return new r(Z)}t._=s;const i=new r("+");function o(y,...v){const Z=[m(y[0])];let R=0;for(;R<v.length;)Z.push(i),a(Z,v[R]),Z.push(i,m(y[++R]));return c(Z),new r(Z)}t.str=o;function a(y,v){v instanceof r?y.push(...v._items):v instanceof n?y.push(v):y.push(d(v))}t.addCodeArg=a;function c(y){let v=1;for(;v<y.length-1;){if(y[v]===i){const Z=u(y[v-1],y[v+1]);if(Z!==void 0){y.splice(v-1,3,Z);continue}y[v++]="+"}v++}}function u(y,v){if(v==='""')return y;if(y==='""')return v;if(typeof y=="string")return v instanceof n||y[y.length-1]!=='"'?void 0:typeof v!="string"?`${y.slice(0,-1)}${v}"`:v[0]==='"'?y.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(y instanceof n))return`"${y}${v.slice(1)}`}function l(y,v){return v.emptyStr()?y:y.emptyStr()?v:o`${y}${v}`}t.strConcat=l;function d(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:m(Array.isArray(y)?y.join(","):y)}function p(y){return new r(m(y))}t.stringify=p;function m(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=m;function S(y){return typeof y=="string"&&t.IDENTIFIER.test(y)?new r(`.${y}`):s`[${y}]`}t.getProperty=S;function T(y){if(typeof y=="string"&&t.IDENTIFIER.test(y))return new r(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}t.getEsmExportName=T;function j(y){return new r(y.toString())}t.regexpCode=j})(on);var Hn={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=on;class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var r;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(r||(t.UsedValueState=r={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class s{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=s;class i extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=i;const o=(0,e._)`\n`;class a extends s{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?o:e.nil}}get(){return this._scope}name(u){return new i(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:m}=p,S=(d=l.key)!==null&&d!==void 0?d:l.ref;let T=this._values[m];if(T){const v=T.get(S);if(v)return v}else T=this._values[m]=new Map;T.set(S,p);const j=this._scope[m]||(this._scope[m]=[]),y=j.length;return j[y]=l.ref,p.setValue(l,{property:m,itemIndex:y}),p}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,d)}_reduceValues(u,l,d={},p){let m=e.nil;for(const S in u){const T=u[S];if(!T)continue;const j=d[S]=d[S]||new Map;T.forEach(y=>{if(j.has(y))return;j.set(y,r.Started);let v=l(y);if(v){const Z=this.opts.es5?t.varKinds.var:t.varKinds.const;m=(0,e._)`${m}${Z} ${y} = ${v};${this.opts._n}`}else if(v=p==null?void 0:p(y))m=(0,e._)`${m}${v}${this.opts._n}`;else throw new n(y);j.set(y,r.Completed)})}return m}}t.ValueScope=a})(Hn);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=on,n=Hn;var r=on;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}});var s=Hn;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return s.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return s.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return s.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return s.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class i{optimizeNodes(){return this}optimizeNames(f,h){return this}}class o extends i{constructor(f,h,b){super(),this.varKind=f,this.name=h,this.rhs=b}render({es5:f,_n:h}){const b=f?n.varKinds.var:this.varKind,D=this.rhs===void 0?"":` = ${this.rhs}`;return`${b} ${this.name}${D};`+h}optimizeNames(f,h){if(f[this.name.str])return this.rhs&&(this.rhs=F(this.rhs,f,h)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends i{constructor(f,h,b){super(),this.lhs=f,this.rhs=h,this.sideEffects=b}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,h){if(!(this.lhs instanceof e.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=F(this.rhs,f,h),this}get names(){const f=this.lhs instanceof e.Name?{}:{...this.lhs.names};return ae(f,this.rhs)}}class c extends a{constructor(f,h,b,D){super(f,b,D),this.op=h}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends i{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class p extends i{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,h){return this.code=F(this.code,f,h),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class m extends i{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((h,b)=>h+b.render(f),"")}optimizeNodes(){const{nodes:f}=this;let h=f.length;for(;h--;){const b=f[h].optimizeNodes();Array.isArray(b)?f.splice(h,1,...b):b?f[h]=b:f.splice(h,1)}return f.length>0?this:void 0}optimizeNames(f,h){const{nodes:b}=this;let D=b.length;for(;D--;){const H=b[D];H.optimizeNames(f,h)||(Te(f,H.names),b.splice(D,1))}return b.length>0?this:void 0}get names(){return this.nodes.reduce((f,h)=>q(f,h.names),{})}}class S extends m{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class T extends m{}class j extends S{}j.kind="else";class y extends S{constructor(f,h){super(h),this.condition=f}render(f){let h=`if(${this.condition})`+super.render(f);return this.else&&(h+="else "+this.else.render(f)),h}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let h=this.else;if(h){const b=h.optimizeNodes();h=this.else=Array.isArray(b)?new j(b):b}if(h)return f===!1?h instanceof y?h:h.nodes:this.nodes.length?this:new y(Be(f),h instanceof y?[h]:h.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,h){var b;if(this.else=(b=this.else)===null||b===void 0?void 0:b.optimizeNames(f,h),!!(super.optimizeNames(f,h)||this.else))return this.condition=F(this.condition,f,h),this}get names(){const f=super.names;return ae(f,this.condition),this.else&&q(f,this.else.names),f}}y.kind="if";class v extends S{}v.kind="for";class Z extends v{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,h){if(super.optimizeNames(f,h))return this.iteration=F(this.iteration,f,h),this}get names(){return q(super.names,this.iteration.names)}}class R extends v{constructor(f,h,b,D){super(),this.varKind=f,this.name=h,this.from=b,this.to=D}render(f){const h=f.es5?n.varKinds.var:this.varKind,{name:b,from:D,to:H}=this;return`for(${h} ${b}=${D}; ${b}<${H}; ${b}++)`+super.render(f)}get names(){const f=ae(super.names,this.from);return ae(f,this.to)}}class te extends v{constructor(f,h,b,D){super(),this.loop=f,this.varKind=h,this.name=b,this.iterable=D}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,h){if(super.optimizeNames(f,h))return this.iterable=F(this.iterable,f,h),this}get names(){return q(super.names,this.iterable.names)}}class ue extends S{constructor(f,h,b){super(),this.name=f,this.args=h,this.async=b}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}ue.kind="func";class G extends m{render(f){return"return "+super.render(f)}}G.kind="return";class _e extends S{render(f){let h="try"+super.render(f);return this.catch&&(h+=this.catch.render(f)),this.finally&&(h+=this.finally.render(f)),h}optimizeNodes(){var f,h;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(h=this.finally)===null||h===void 0||h.optimizeNodes(),this}optimizeNames(f,h){var b,D;return super.optimizeNames(f,h),(b=this.catch)===null||b===void 0||b.optimizeNames(f,h),(D=this.finally)===null||D===void 0||D.optimizeNames(f,h),this}get names(){const f=super.names;return this.catch&&q(f,this.catch.names),this.finally&&q(f,this.finally.names),f}}class fe extends S{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}fe.kind="catch";class Je extends S{render(f){return"finally"+super.render(f)}}Je.kind="finally";class A{constructor(f,h={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...h,_n:h.lines?`
46
46
  `:""},this._extScope=f,this._scope=new n.Scope({parent:f}),this._nodes=[new T]}toString(){return this._root.render(this.opts)}name(f){return this._scope.name(f)}scopeName(f){return this._extScope.name(f)}scopeValue(f,h){const b=this._extScope.value(f,h);return(this._values[b.prefix]||(this._values[b.prefix]=new Set)).add(b),b}getScopeValue(f,h){return this._extScope.getValue(f,h)}scopeRefs(f){return this._extScope.scopeRefs(f,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(f,h,b,D){const H=this._scope.toName(h);return b!==void 0&&D&&(this._constants[H.str]=b),this._leafNode(new o(f,H,b)),H}const(f,h,b){return this._def(n.varKinds.const,f,h,b)}let(f,h,b){return this._def(n.varKinds.let,f,h,b)}var(f,h,b){return this._def(n.varKinds.var,f,h,b)}assign(f,h,b){return this._leafNode(new a(f,h,b))}add(f,h){return this._leafNode(new c(f,t.operators.ADD,h))}code(f){return typeof f=="function"?f():f!==e.nil&&this._leafNode(new p(f)),this}object(...f){const h=["{"];for(const[b,D]of f)h.length>1&&h.push(","),h.push(b),(b!==D||this.opts.es5)&&(h.push(":"),(0,e.addCodeArg)(h,D));return h.push("}"),new e._Code(h)}if(f,h,b){if(this._blockNode(new y(f)),h&&b)this.code(h).else().code(b).endIf();else if(h)this.code(h).endIf();else if(b)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(f){return this._elseNode(new y(f))}else(){return this._elseNode(new j)}endIf(){return this._endBlockNode(y,j)}_for(f,h){return this._blockNode(f),h&&this.code(h).endFor(),this}for(f,h){return this._for(new Z(f),h)}forRange(f,h,b,D,H=this.opts.es5?n.varKinds.var:n.varKinds.let){const de=this._scope.toName(f);return this._for(new R(H,de,h,b),()=>D(de))}forOf(f,h,b,D=n.varKinds.const){const H=this._scope.toName(f);if(this.opts.es5){const de=h instanceof e.Name?h:this.var("_arr",h);return this.forRange("_i",0,(0,e._)`${de}.length`,io=>{this.var(H,(0,e._)`${de}[${io}]`),b(H)})}return this._for(new te("of",D,H,h),()=>b(H))}forIn(f,h,b,D=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(f,(0,e._)`Object.keys(${h})`,b);const H=this._scope.toName(f);return this._for(new te("in",D,H,h),()=>b(H))}endFor(){return this._endBlockNode(v)}label(f){return this._leafNode(new u(f))}break(f){return this._leafNode(new l(f))}return(f){const h=new G;if(this._blockNode(h),this.code(f),h.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(G)}try(f,h,b){if(!h&&!b)throw new Error('CodeGen: "try" without "catch" and "finally"');const D=new _e;if(this._blockNode(D),this.code(f),h){const H=this.name("e");this._currNode=D.catch=new fe(H),h(H)}return b&&(this._currNode=D.finally=new Je,this.code(b)),this._endBlockNode(fe,Je)}throw(f){return this._leafNode(new d(f))}block(f,h){return this._blockStarts.push(this._nodes.length),f&&this.code(f).endBlock(h),this}endBlock(f){const h=this._blockStarts.pop();if(h===void 0)throw new Error("CodeGen: not in self-balancing block");const b=this._nodes.length-h;if(b<0||f!==void 0&&b!==f)throw new Error(`CodeGen: wrong number of nodes: ${b} vs ${f} expected`);return this._nodes.length=h,this}func(f,h=e.nil,b,D){return this._blockNode(new ue(f,h,b)),D&&this.code(D).endFunc(),this}endFunc(){return this._endBlockNode(ue)}optimize(f=1){for(;f-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(f){return this._currNode.nodes.push(f),this}_blockNode(f){this._currNode.nodes.push(f),this._nodes.push(f)}_endBlockNode(f,h){const b=this._currNode;if(b instanceof f||h&&b instanceof h)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${h?`${f.kind}/${h.kind}`:f.kind}"`)}_elseNode(f){const h=this._currNode;if(!(h instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=h.else=f,this}get _root(){return this._nodes[0]}get _currNode(){const f=this._nodes;return f[f.length-1]}set _currNode(f){const h=this._nodes;h[h.length-1]=f}}t.CodeGen=A;function q(O,f){for(const h in f)O[h]=(O[h]||0)+(f[h]||0);return O}function ae(O,f){return f instanceof e._CodeOrName?q(O,f.names):O}function F(O,f,h){if(O instanceof e.Name)return b(O);if(!D(O))return O;return new e._Code(O._items.reduce((H,de)=>(de instanceof e.Name&&(de=b(de)),de instanceof e._Code?H.push(...de._items):H.push(de),H),[]));function b(H){const de=h[H.str];return de===void 0||f[H.str]!==1?H:(delete f[H.str],de)}function D(H){return H instanceof e._Code&&H._items.some(de=>de instanceof e.Name&&f[de.str]===1&&h[de.str]!==void 0)}}function Te(O,f){for(const h in f)O[h]=(O[h]||0)-(f[h]||0)}function Be(O){return typeof O=="boolean"||typeof O=="number"||O===null?!O:(0,e._)`!${Ge(O)}`}t.not=Be;const We=pt(t.operators.AND);function _n(...O){return O.reduce(We)}t.and=_n;const xt=pt(t.operators.OR);function Zt(...O){return O.reduce(xt)}t.or=Zt;function pt(O){return(f,h)=>f===e.nil?h:h===e.nil?f:(0,e._)`${Ge(f)} ${O} ${Ge(h)}`}function Ge(O){return O instanceof e.Name?O:(0,e._)`(${O})`}})(zr);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.formatLimitDefinition=void 0;const e=zs,n=zr,r=n.operators,s={formatMaximum:{okStr:"<=",ok:r.LTE,fail:r.GT},formatMinimum:{okStr:">=",ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},i={message:({keyword:a,schemaCode:c})=>(0,n.str)`should be ${s[a].okStr} ${c}`,params:({keyword:a,schemaCode:c})=>(0,n._)`{comparison: ${s[a].okStr}, limit: ${c}}`};t.formatLimitDefinition={keyword:Object.keys(s),type:"string",schemaType:"string",$data:!0,error:i,code(a){const{gen:c,data:u,schemaCode:l,keyword:d,it:p}=a,{opts:m,self:S}=p;if(!m.validateFormats)return;const T=new e.KeywordCxt(p,S.RULES.all.format.definition,"format");T.$data?j():y();function j(){const Z=c.scopeValue("formats",{ref:S.formats,code:m.code.formats}),R=c.const("fmt",(0,n._)`${Z}[${T.schemaCode}]`);a.fail$data((0,n.or)((0,n._)`typeof ${R} != "object"`,(0,n._)`${R} instanceof RegExp`,(0,n._)`typeof ${R}.compare != "function"`,v(R)))}function y(){const Z=T.schema,R=S.formats[Z];if(!R||R===!0)return;if(typeof R!="object"||R instanceof RegExp||typeof R.compare!="function")throw new Error(`"${d}": format "${Z}" does not define "compare" function`);const te=c.scopeValue("formats",{key:Z,ref:R,code:m.code.formats?(0,n._)`${m.code.formats}${(0,n.getProperty)(Z)}`:void 0});a.fail$data(v(te))}function v(Z){return(0,n._)`${Z}.compare(${u}, ${l}) ${s[d].fail} 0`}},dependencies:["format"]};const o=a=>(a.addKeyword(t.formatLimitDefinition),a);t.default=o})(no);(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});const n=to,r=no,s=zr,i=new s.Name("fullFormats"),o=new s.Name("fastFormats"),a=(u,l={keywords:!0})=>{if(Array.isArray(l))return c(u,l,n.fullFormats,i),u;const[d,p]=l.mode==="fast"?[n.fastFormats,o]:[n.fullFormats,i],m=l.formats||n.formatNames;return c(u,m,d,p),l.keywords&&(0,r.default)(u),u};a.get=(u,l="full")=>{const p=(l==="fast"?n.fastFormats:n.fullFormats)[u];if(!p)throw new Error(`Unknown format "${u}"`);return p};function c(u,l,d,p){var m,S;(m=(S=u.opts.code).formats)!==null&&m!==void 0||(S.formats=(0,s._)`require("ajv-formats/dist/formats").${p}`);for(const T of l)u.addFormat(T,d[T])}t.exports=e=a,Object.defineProperty(e,"__esModule",{value:!0}),e.default=a})(Vn,Vn.exports);var Qh=Vn.exports;const Xh=Yh(Qh);function em(){const t=new zs({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return Xh(t),t}class tm{constructor(e){this._ajv=e??em()}getValidator(e){const n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}class nm{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){var s;const r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!((s=r==null?void 0:r.sampling)!=null&&s.tools))throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const i=e.messages[e.messages.length-1],o=Array.isArray(i.content)?i.content:[i.content],a=o.some(d=>d.type==="tool_result"),c=e.messages.length>1?e.messages[e.messages.length-2]:void 0,u=c?Array.isArray(c.content)?c.content:[c.content]:[],l=u.some(d=>d.type==="tool_use");if(a){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){const d=new Set(u.filter(m=>m.type==="tool_use").map(m=>m.id)),p=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==p.size||![...d].every(m=>p.has(m)))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},Sr,n)}elicitInputStream(e,n){var o,a;const r=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!((o=r==null?void 0:r.elicitation)!=null&&o.url))throw new Error("Client does not support url elicitation.");break}case"form":{if(!((a=r==null?void 0:r.elicitation)!=null&&a.form))throw new Error("Client does not support form elicitation.");break}}const i=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},Yt,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}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 rm(t,e,n){var r;if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!((r=t.tools)!=null&&r.call))throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break}}function sm(t,e,n){var r,s;if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!((r=t.sampling)!=null&&r.createMessage))throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!((s=t.elicitation)!=null&&s.create))throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break}}class im extends Gh{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Gt.options.map((r,s)=>[r,s])),this.isMessageIgnored=(r,s)=>{const i=this._loggingLevels.get(s);return i?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=(n==null?void 0:n.capabilities)??{},this._instructions=n==null?void 0:n.instructions,this._jsonSchemaValidator=(n==null?void 0:n.jsonSchemaValidator)??new tm,this.setRequestHandler(Zi,r=>this._oninitialize(r)),this.setNotificationHandler(Ai,()=>{var r;return(r=this.oninitialized)==null?void 0:r.call(this)}),this._capabilities.logging&&this.setRequestHandler(Fi,async(r,s)=>{var c;const i=s.sessionId||((c=s.requestInfo)==null?void 0:c.headers["mcp-session-id"])||void 0,{level:o}=r.params,a=Gt.safeParse(o);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new nm(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Kh(this._capabilities,e)}setRequestHandler(e,n){var a;const r=Ot(e),s=r==null?void 0:r.method;if(!s)throw new Error("Schema is missing a method literal");let i;if(Ze(s)){const c=s,u=(a=c._zod)==null?void 0:a.def;i=(u==null?void 0:u.value)??c.value}else{const c=s,u=c._def;i=(u==null?void 0:u.value)??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){const c=async(u,l)=>{const d=wt(Wt,u);if(!d.success){const T=d.error instanceof Error?d.error.message:String(d.error);throw new C(x.InvalidParams,`Invalid tools/call request: ${T}`)}const{params:p}=d.data,m=await Promise.resolve(n(u,l));if(p.task){const T=wt(gn,m);if(!T.success){const j=T.error instanceof Error?T.error.message:String(T.error);throw new C(x.InvalidParams,`Invalid task creation result: ${j}`)}return T.data}const S=wt(kr,m);if(!S.success){const T=S.error instanceof Error?S.error.message:String(S.error);throw new C(x.InvalidParams,`Invalid tools/call result: ${T}`)}return S.data};return super.setRequestHandler(e,c)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){var n,r,s;switch(e){case"sampling/createMessage":if(!((n=this._clientCapabilities)!=null&&n.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!((r=this._clientCapabilities)!=null&&r.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!((s=this._clientCapabilities)!=null&&s.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){var n,r;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(!((r=(n=this._clientCapabilities)==null?void 0:n.elicitation)!=null&&r.url))throw new Error(`Client does not support URL elicitation (required for ${e})`);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}}assertTaskCapability(e){var n,r;sm((r=(n=this._clientCapabilities)==null?void 0:n.tasks)==null?void 0:r.requests,e,"Client")}assertTaskHandlerCapability(e){var n;this._capabilities&&rm((n=this._capabilities.tasks)==null?void 0:n.requests,e,"Server")}async _oninitialize(e){const n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ul.includes(n)?n:Ni,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"},or)}async createMessage(e,n){var r,s;if((e.tools||e.toolChoice)&&!((s=(r=this._clientCapabilities)==null?void 0:r.sampling)!=null&&s.tools))throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){const i=e.messages[e.messages.length-1],o=Array.isArray(i.content)?i.content:[i.content],a=o.some(d=>d.type==="tool_result"),c=e.messages.length>1?e.messages[e.messages.length-2]:void 0,u=c?Array.isArray(c.content)?c.content:[c.content]:[],l=u.some(d=>d.type==="tool_use");if(a){if(o.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){const d=new Set(u.filter(m=>m.type==="tool_use").map(m=>m.id)),p=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==p.size||![...d].every(m=>p.has(m)))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},Ui,n):this.request({method:"sampling/createMessage",params:e},Sr,n)}async elicitInput(e,n){var s,i,o,a;switch(e.mode??"form"){case"url":{if(!((i=(s=this._clientCapabilities)==null?void 0:s.elicitation)!=null&&i.url))throw new Error("Client does not support url elicitation.");const c=e;return this.request({method:"elicitation/create",params:c},Yt,n)}case"form":{if(!((a=(o=this._clientCapabilities)==null?void 0:o.elicitation)!=null&&a.form))throw new Error("Client does not support form elicitation.");const c=e.mode==="form"?e:{...e,mode:"form"},u=await this.request({method:"elicitation/create",params:c},Yt,n);if(u.action==="accept"&&u.content&&c.requestedSchema)try{const d=this._jsonSchemaValidator.getValidator(c.requestedSchema)(u.content);if(!d.valid)throw new C(x.InvalidParams,`Elicitation response content does not match requested schema: ${d.errorMessage}`)}catch(l){throw l instanceof C?l:new C(x.InternalError,`Error validating elicitation response: ${l instanceof Error?l.message:String(l)}`)}return u}}}createElicitationCompletionNotifier(e,n){var r,s;if(!((s=(r=this._clientCapabilities)==null?void 0:r.elicitation)!=null&&s.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},Vi,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"})}}const ro=Symbol.for("mcp.completable");function ys(t){return!!t&&typeof t=="object"&&ro in t}function om(t){const e=t[ro];return e==null?void 0:e.complete}var vs;(function(t){t.Completable="McpCompletable"})(vs||(vs={}));const am=/^[A-Za-z0-9._-]{1,128}$/;function cm(t){const 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"),!am.test(t)){const n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,s,i)=>i.indexOf(r)===s);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function um(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(const 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 bs(t){const e=cm(t);return um(t,e.warnings),e.isValid}class lm{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){const s={taskSupport:"required",...n.execution};if(s.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,s,n._meta,r)}}class dm{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 im(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new lm(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Le(Zn)),this.server.assertCanSetRequestHandler(Le(Wt)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Zn,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{const r={name:e,title:n.title,description:n.description,inputSchema:(()=>{const s=gt(n.inputSchema);return s?ms(s,{strictUnions:!0,pipeStrategy:"input"}):fm})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){const s=gt(n.outputSchema);s&&(r.outputSchema=ms(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Wt,async(e,n)=>{var r;try{const s=this._registeredTools[e.params.name];if(!s)throw new C(x.InvalidParams,`Tool ${e.params.name} not found`);if(!s.enabled)throw new C(x.InvalidParams,`Tool ${e.params.name} disabled`);const i=!!e.params.task,o=(r=s.execution)==null?void 0:r.taskSupport,a="createTask"in s.handler;if((o==="required"||o==="optional")&&!a)throw new C(x.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!i)throw new C(x.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!i&&a)return await this.handleAutomaticTaskPolling(s,e,n);const c=await this.validateToolInput(s,e.params.arguments,e.params.name),u=await this.executeToolHandler(s,c,n);return i||await this.validateToolOutput(s,u,e.params.name),u}catch(s){if(s instanceof C&&s.code===x.UrlElicitationRequired)throw s;return this.createToolError(s instanceof Error?s.message:String(s))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;const i=gt(e.inputSchema)??e.inputSchema,o=await kn(i,n);if(!o.success){const a="error"in o?o.error:"Unknown error",c=Sn(a);throw new C(x.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return o.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new C(x.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);const s=gt(e.outputSchema),i=await kn(s,n.structuredContent);if(!i.success){const o="error"in i?i.error:"Unknown error",a=Sn(o);throw new C(x.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){const s=e.handler;if("createTask"in s){if(!r.taskStore)throw new Error("No task store provided.");const o={...r,taskStore:r.taskStore};if(e.inputSchema){const a=s;return await Promise.resolve(a.createTask(n,o))}else{const a=s;return await Promise.resolve(a.createTask(o))}}if(e.inputSchema){const o=s;return await Promise.resolve(o(n,r))}else{const o=s;return await Promise.resolve(o(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");const s=await this.validateToolInput(e,n.params.arguments,n.params.name),i=e.handler,o={...r,taskStore:r.taskStore},a=s?await Promise.resolve(i.createTask(s,o)):await Promise.resolve(i.createTask(o)),c=a.task.taskId;let u=a.task;const l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));const d=await r.taskStore.getTask(c);if(!d)throw new C(x.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Le(An)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(An,async e=>{switch(e.params.ref.type){case"ref/prompt":return yf(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return vf(e),this.handleResourceCompletion(e,e.params.ref);default:throw new C(x.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){const r=this._registeredPrompts[n.name];if(!r)throw new C(x.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new C(x.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return _t;const s=Ot(r.argsSchema),i=s==null?void 0:s[e.params.argument.name];if(!ys(i))return _t;const o=om(i);if(!o)return _t;const a=await o(e.params.argument.value,e.params.context);return ks(a)}async handleResourceCompletion(e,n){const r=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return _t;throw new C(x.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return _t;const i=await s(e.params.argument.value,e.params.context);return ks(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Le(En)),this.server.assertCanSetRequestHandler(Le(Cn)),this.server.assertCanSetRequestHandler(Le(In)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(En,async(e,n)=>{const r=Object.entries(this._registeredResources).filter(([i,o])=>o.enabled).map(([i,o])=>({uri:i,name:o.name,...o.metadata})),s=[];for(const i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;const o=await i.resourceTemplate.listCallback(n);for(const a of o.resources)s.push({...i.metadata,...a})}return{resources:[...r,...s]}}),this.server.setRequestHandler(Cn,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(In,async(e,n)=>{const r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new C(x.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,n)}for(const i of Object.values(this._registeredResourceTemplates)){const o=i.resourceTemplate.uriTemplate.match(r.toString());if(o)return i.readCallback(r,o,n)}throw new C(x.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Le(On)),this.server.assertCanSetRequestHandler(Le(xn)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(On,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?mm(n.argsSchema):void 0}))})),this.server.setRequestHandler(xn,async(e,n)=>{const r=this._registeredPrompts[e.params.name];if(!r)throw new C(x.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new C(x.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){const s=gt(r.argsSchema),i=await kn(s,e.params.arguments);if(!i.success){const c="error"in i?i.error:"Unknown error",u=Sn(c);throw new C(x.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}const o=i.data,a=r.callback;return await Promise.resolve(a(o,n))}else{const s=r.callback;return await Promise.resolve(s(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let s;typeof r[0]=="object"&&(s=r.shift());const i=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);const o=this._createRegisteredResource(e,void 0,n,s,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,void 0,n,s,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,n,r,s){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);const i=this._createRegisteredResource(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const i=this._createRegisteredResourceTemplate(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,n,r,s,i){const o={name:e,title:n,metadata:s,readCallback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==r&&(delete this._registeredResources[r],a.uri&&(this._registeredResources[a.uri]=o)),typeof a.name<"u"&&(o.name=a.name),typeof a.title<"u"&&(o.title=a.title),typeof a.metadata<"u"&&(o.metadata=a.metadata),typeof a.callback<"u"&&(o.readCallback=a.callback),typeof a.enabled<"u"&&(o.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=o,o}_createRegisteredResourceTemplate(e,n,r,s,i){const o={resourceTemplate:r,title:n,metadata:s,readCallback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=o)),typeof u.title<"u"&&(o.title=u.title),typeof u.template<"u"&&(o.resourceTemplate=u.template),typeof u.metadata<"u"&&(o.metadata=u.metadata),typeof u.callback<"u"&&(o.readCallback=u.callback),typeof u.enabled<"u"&&(o.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;const a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,n,r,s,i){const o={title:n,description:r,argsSchema:s===void 0?void 0:st(s),callback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=o)),typeof a.title<"u"&&(o.title=a.title),typeof a.description<"u"&&(o.description=a.description),typeof a.argsSchema<"u"&&(o.argsSchema=st(a.argsSchema)),typeof a.callback<"u"&&(o.callback=a.callback),typeof a.enabled<"u"&&(o.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,s&&Object.values(s).some(c=>{var l;const u=c instanceof uo.ZodOptional?(l=c._def)==null?void 0:l.innerType:c;return ys(u)})&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,n,r,s,i,o,a,c,u){bs(e);const l={title:n,description:r,inputSchema:ws(s),outputSchema:ws(i),annotations:o,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!==e&&(typeof d.name=="string"&&bs(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=st(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=st(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 r,s,i,o;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){const c=n[0];Jn(c)?(s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Jn(n[0])&&(o=n.shift())):typeof c=="object"&&c!==null&&(o=n.shift())}const a=n[0];return this._createRegisteredTool(e,void 0,r,s,i,o,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:s,description:i,inputSchema:o,outputSchema:a,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,s,i,o,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let s;n.length>1&&(s=n.shift());const i=n[0],o=this._createRegisteredPrompt(e,void 0,r,s,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:s,description:i,argsSchema:o}=n,a=this._createRegisteredPrompt(e,s,i,o,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}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()}}const fm={type:"object",properties:{}};function so(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function hm(t){return"_def"in t||"_zod"in t||so(t)}function Jn(t){return typeof t!="object"||t===null||hm(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(so)}function ws(t){if(t)return Jn(t)?st(t):t}function mm(t){const e=Ot(t);return e?Object.entries(e).map(([n,r])=>{const s=ah(r),i=ch(r);return{name:n,description:s,required:!i}}):[]}function Le(t){const e=Ot(t),n=e==null?void 0:e.method;if(!n)throw new Error("Schema is missing a method literal");const r=Wi(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function ks(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const _t={completion:{values:[],hasMore:!1}},Ss=lo.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:yn&&yn.tagName.toUpperCase()==="SCRIPT"&&yn.src||new URL("index.cjs",document.baseURI).href);let Bn;try{Bn=Ss("./package.json").version}catch{Bn=Ss("../package.json").version}function pm(){return new dm({name:"wordpress-playground",version:Bn,description:`Use this server when you need a live WordPress environment without any local setup. WordPress Playground runs entirely in the user's browser tab via WebAssembly — no PHP, MySQL, or server required. You are automatically authenticated as an admin user.
47
47
 
48
48
  PREREQUISITE: Call playground_list_sites first. If no browser is connected, call playground_get_website_url to get the exact URL and ask the user to open it.