@netlify/agent-runner-cli 1.147.0 → 1.148.0

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.
@@ -76,5 +76,5 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
76
76
  `:`[${i[c]}\r
77
77
  ]`;continue}r+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return r}function Eu(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((i,r)=>({...i,[r]:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??_e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===w.ZodString&&t.keyType._def.checks?.length){let{type:i,...r}=ju(t.keyType._def,e);return{...n,propertyNames:r}}else{if(t.keyType?._def.typeName===w.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===w.ZodBranded&&t.keyType._def.type._def.typeName===w.ZodString&&t.keyType._def.type._def.checks?.length){let{type:i,...r}=Tu(t.keyType._def,e);return{...n,propertyNames:r}}}return n}function p$(t,e){if(e.mapStrategy==="record")return Eu(t,e);let n=q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||_e(e),i=q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||_e(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,i],minItems:2,maxItems:2}}}function f$(t){let e=t.values,i=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),r=Array.from(new Set(i.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:i}}function m$(t){return t.target==="openAi"?void 0:{not:_e({...t,currentPath:[...t.currentPath,"not"]})}}function h$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Co={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function v$(t,e){if(e.target==="openApi3")return g$(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(i=>i._def.typeName in Co&&(!i._def.checks||!i._def.checks.length))){let i=n.reduce((r,o)=>{let a=Co[o._def.typeName];return a&&!r.includes(a)?[...r,a]:r},[]);return{type:i.length>1?i:i[0]}}else if(n.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){let i=n.reduce((r,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...r,a];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];default:return r}},[]);if(i.length===n.length){let r=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:r.length>1?r:r[0],enum:n.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(n.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((i,r)=>[...i,...r._def.values.filter(o=>!i.includes(o))],[])};return g$(t,e)}var g$=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((i,r)=>q(i._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(i=>!!i&&(!e.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return n.length?{anyOf:n}:void 0};function y$(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:Co[t.innerType._def.typeName],nullable:!0}:{type:[Co[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let i=q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}let n=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function _$(t,e){let n={type:"number"};if(!t.checks)return n;for(let i of t.checks)switch(i.kind){case"int":n.type="integer",fm(n,"type",i.message,e);break;case"min":e.target==="jsonSchema7"?i.inclusive?te(n,"minimum",i.value,i.message,e):te(n,"exclusiveMinimum",i.value,i.message,e):(i.inclusive||(n.exclusiveMinimum=!0),te(n,"minimum",i.value,i.message,e));break;case"max":e.target==="jsonSchema7"?i.inclusive?te(n,"maximum",i.value,i.message,e):te(n,"exclusiveMaximum",i.value,i.message,e):(i.inclusive||(n.exclusiveMaximum=!0),te(n,"maximum",i.value,i.message,e));break;case"multipleOf":te(n,"multipleOf",i.value,i.message,e);break}return n}function $$(t,e){let n=e.target==="openAi",i={type:"object",properties:{}},r=[],o=t.shape();for(let s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=wI(c);u&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=q(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||r.push(s))}r.length&&(i.required=r);let a=kI(t,e);return a!==void 0&&(i.additionalProperties=a),i}function kI(t,e){if(t.catchall._def.typeName!=="ZodNever")return q(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 wI(t){try{return t.isOptional()}catch{return!0}}var b$=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return q(t.innerType._def,e);let n=q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:_e(e)},n]}:_e(e)};var x$=(t,e)=>{if(e.pipeStrategy==="input")return q(t.in._def,e);if(e.pipeStrategy==="output")return q(t.out._def,e);let n=q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),i=q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,i].filter(r=>r!==void 0)}};function k$(t,e){return q(t.type._def,e)}function w$(t,e){let i={type:"array",uniqueItems:!0,items:q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&te(i,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&te(i,"maxItems",t.maxSize.value,t.maxSize.message,e),i}function S$(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,i)=>q(n._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[]),additionalItems:q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,i)=>q(n._def,{...e,currentPath:[...e.currentPath,"items",`${i}`]})).reduce((n,i)=>i===void 0?n:[...n,i],[])}}function z$(t){return{not:_e(t)}}function I$(t){return _e(t)}var P$=(t,e)=>q(t.innerType._def,e);var T$=(t,e,n)=>{switch(e){case w.ZodString:return ju(t,n);case w.ZodNumber:return _$(t,n);case w.ZodObject:return $$(t,n);case w.ZodBigInt:return n$(t,n);case w.ZodBoolean:return i$();case w.ZodDate:return mm(t,n);case w.ZodUndefined:return z$(n);case w.ZodNull:return h$(n);case w.ZodArray:return r$(t,n);case w.ZodUnion:case w.ZodDiscriminatedUnion:return v$(t,n);case w.ZodIntersection:return u$(t,n);case w.ZodTuple:return S$(t,n);case w.ZodRecord:return Eu(t,n);case w.ZodLiteral:return l$(t,n);case w.ZodEnum:return c$(t);case w.ZodNativeEnum:return f$(t);case w.ZodNullable:return y$(t,n);case w.ZodOptional:return b$(t,n);case w.ZodMap:return p$(t,n);case w.ZodSet:return w$(t,n);case w.ZodLazy:return()=>t.getter()._def;case w.ZodPromise:return k$(t,n);case w.ZodNaN:case w.ZodNever:return m$(n);case w.ZodEffects:return s$(t,n);case w.ZodAny:return _e(n);case w.ZodUnknown:return I$(n);case w.ZodDefault:return a$(t,n);case w.ZodBranded:return Tu(t,n);case w.ZodReadonly:return P$(t,n);case w.ZodCatch:return o$(t,n);case w.ZodPipeline:return x$(t,n);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return(i=>{})(e)}};function q(t,e,n=!1){let i=e.seen.get(t);if(e.override){let s=e.override?.(t,e,i,n);if(s!==Q_)return s}if(i&&!n){let s=SI(i,e);if(s!==void 0)return s}let r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);let o=T$(t,t.typeName,e),a=typeof o=="function"?q(o(),e):o;if(a&&zI(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return r.jsonSchema=a,s}return r.jsonSchema=a,a}var SI=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Pu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,i)=>e.currentPath[i]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),_e(e)):e.$refStrategy==="seen"?_e(e):void 0}},zI=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var vm=(t,e)=>{let n=t$(e),i=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:q(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??_e(n)}),{}):void 0,r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=q(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??_e(n),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),n.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[n.openAiAnyTypeName]||(i[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let s=r===void 0?i?{...o,[n.definitionPath]:i}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...i,[r]:o}};return n.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function II(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ym(t,e){return st(t)?Rr(t,{target:II(e?.target),io:e?.pipeStrategy??"input"}):vm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function _m(t){let n=lr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Ec(n);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function $m(t,e){let n=ur(t,e);if(!n.success)throw n.error;return n.data}var PI=6e4,Ou=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(du,n=>{this._oncancel(n)}),this.setNotificationHandler(fu,n=>{this._onprogress(n)}),this.setRequestHandler(pu,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(mu,async(n,i)=>{let r=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!r)throw new D(A.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(gu,async(n,i)=>{let r=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,p=new D(d.error.code,d.error.message,d.error.data);l(p)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}let a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new D(A.InvalidParams,`Task not found: ${o}`);if(!fr(a.status))return await this._waitForTaskUpdate(o,i.signal),await r();if(fr(a.status)){let s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[pr]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(vu,async(n,i)=>{try{let{tasks:r,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,i.sessionId);return{tasks:r,nextCursor:o,_meta:{}}}catch(r){throw new D(A.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(_u,async(n,i)=>{try{let r=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!r)throw new D(A.InvalidParams,`Task not found: ${n.params.taskId}`);if(fr(r.status))throw new D(A.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,i.sessionId);if(!o)throw new D(A.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(r){throw r instanceof D?r:new D(A.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,i,r,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,n),startTime:Date.now(),timeout:n,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:r})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let i=Date.now()-n.startTime;if(n.maxTotalTimeout&&i>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),D.fromError(A.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:i});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};let r=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{r?.(o,a),jo(o)||L_(o)?this._onresponse(o):Qf(o)?this._onrequest(o,a):M_(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(let i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();let n=D.fromError(A.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let i of e.values())i(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,n){let i=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,o=e.params?._meta?.[pr]?.taskId;if(i===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:A.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},r?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):r?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=U_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,u={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(a.signal.aborted)throw new D(A.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let h=f.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,f)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>i(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},r?.sessionId):await r?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:A.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},r?.sessionId):await r?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...i}=e.params,r=Number(n),o=this._progressHandlers.get(r);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),s=this._timeoutInfo.get(r);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(c){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(c);return}o(i)}_onresponse(e){let n=Number(e.id),i=this._requestResolvers.get(n);if(i){if(this._requestResolvers.delete(n),jo(e))i(e);else{let a=new D(e.error.code,e.error.message,e.error.data);i(a)}return}let r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(jo(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,n))}}if(o||this._progressHandlers.delete(n),jo(e))r(e);else{let a=D.fromError(e.error.code,e.error.message,e.error.data);r(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,i){let{task:r}=i??{};if(!r){try{yield{type:"result",result:await this.request(e,n,i)}}catch(a){yield{type:"error",error:a instanceof D?a:new D(A.InternalError,String(a))}}return}let o;try{let a=await this.request(e,Gn,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new D(A.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},fr(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)}:s.status==="failed"?yield{type:"error",error:new D(A.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new D(A.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,i)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof D?a:new D(A.InternalError,String(a))}}}request(e,n,i){let{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{let d=M=>{l(M)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(M){d(M);return}i?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};i?.onprogress&&(this._progressHandlers.set(p,i.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[pr]:c}});let h=M=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(M)}},{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));let Z=M instanceof D?M:new D(A.RequestTimeout,String(M));l(Z)};this._responseHandlers.set(p,M=>{if(!i?.signal?.aborted){if(M instanceof Error)return l(M);try{let Z=ur(n,M.result);Z.success?u(Z.data):l(Z.error)}catch(Z){l(Z)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});let y=i?.timeout??PI,b=()=>h(D.fromError(A.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(p,y,i?.maxTotalTimeout,b,i?.resetTimeoutOnProgress??!1);let z=c?.taskId;if(z){let M=Z=>{let C=this._responseHandlers.get(p);C?C(Z):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,M),this._enqueueTaskMessage(z,{type:"request",message:f,timestamp:Date.now()}).catch(Z=>{this._cleanupTimeout(p),l(Z)})}else this._transport.send(f,{relatedRequestId:r,resumptionToken:o,onresumptiontoken:a}).catch(M=>{this._cleanupTimeout(p),l(M)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},hu,n)}async getTaskResult(e,n,i){return this.request({method:"tasks/result",params:e},n,i)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},yu,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},F_,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let i=n?.relatedTask?.taskId;if(i){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[pr]:n.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[pr]:n.relatedTask}}}),this._transport?.send(s,n).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[pr]:n.relatedTask}}}),await this._transport.send(a,n)}setRequestHandler(e,n){let i=_m(e);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(r,o)=>{let a=$m(e,r);return Promise.resolve(n(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let i=_m(e);this._notificationHandlers.set(i,r=>{let o=$m(e,r);return Promise.resolve(n(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,i,r)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let i=await this._taskMessageQueue.dequeueAll(e,n);for(let r of i)if(r.type==="request"&&Qf(r.message)){let o=r.message.id,a=this._requestResolvers.get(o);a?(a(new D(A.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let i=this._options?.defaultTaskPollInterval??1e3;try{let r=await this._taskStore?.getTask(e);r?.pollInterval&&(i=r.pollInterval)}catch{}return new Promise((r,o)=>{if(n.aborted){o(new D(A.InvalidRequest,"Request cancelled"));return}let a=setTimeout(r,i);n.addEventListener("abort",()=>{clearTimeout(a),o(new D(A.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await i.createTask(r,e.id,{method:e.method,params:e.params},n)},getTask:async r=>{let o=await i.getTask(r,n);if(!o)throw new D(A.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(r,o,a)=>{await i.storeTaskResult(r,o,a,n);let s=await i.getTask(r,n);if(s){let c=Do.parse({method:"notifications/tasks/status",params:s});await this.notification(c),fr(s.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>i.getTaskResult(r,n),updateTaskStatus:async(r,o,a)=>{let s=await i.getTask(r,n);if(!s)throw new D(A.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(fr(s.status))throw new D(A.InvalidParams,`Cannot update task "${r}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(r,o,a,n);let c=await i.getTask(r,n);if(c){let u=Do.parse({method:"notifications/tasks/status",params:c});await this.notification(u),fr(c.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>i.listTasks(r,n)}}};function j$(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function E$(t,e){let n={...t};for(let i in e){let r=i,o=e[r];if(o===void 0)continue;let a=n[r];j$(a)&&j$(o)?n[r]={...a,...o}:n[r]=o}return n}var xk=$g(ag(),1),kk=$g(bk(),1);function E4(){let t=new xk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,kk.default)(t),t}var fl=class{constructor(e){this._ajv=e??E4()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var ml=class{constructor(e){this._server=e}requestStream(e,n,i){return this._server.requestStream(e,n,i)}createMessageStream(e,n){let i=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!i?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],a=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],u=c.some(l=>l.type==="tool_use");if(a){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ao,n)}elicitInputStream(e,n){let i=this._server.getClientCapabilities(),r=e.mode??"form";switch(r){case"url":{if(!i?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!i?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=r==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Xn,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,i){return this._server.getTaskResult({taskId:e},n,i)}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 wk(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Sk(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var hl=class extends Ou{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Uo.options.map((i,r)=>[i,r])),this.isMessageIgnored=(i,r)=>{let o=this._loggingLevels.get(r);return o?this.LOG_LEVEL_SEVERITY.get(i)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new fl,this.setRequestHandler(rm,i=>this._oninitialize(i)),this.setNotificationHandler(nm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(lm,async(i,r)=>{let o=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=i.params,s=Uo.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ml(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=E$(this._capabilities,e)}setRequestHandler(e,n){let r=lr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let o;if(st(r)){let s=r;o=s._zod?.def?.value??s.value}else{let s=r;o=s._def?.value??s.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(c,u)=>{let l=ur(Wn,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new D(A.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let h=ur(Gn,p);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new D(A.InvalidParams,`Invalid task creation result: ${y}`)}return h.data}let f=ur(zu,p);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new D(A.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Sk(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&wk(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:R_.includes(n)?n:Xf,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"},lu)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],r=Array.isArray(i.content)?i.content:[i.content],o=r.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(o){if(r.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(r.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},dm,n):this.request({method:"sampling/createMessage",params:e},Ao,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let r=e;return this.request({method:"elicitation/create",params:r},Xn,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let r=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:r},Xn,n);if(o.action==="accept"&&o.content&&r.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(r.requestedSchema)(o.content);if(!s.valid)throw new D(A.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof D?a:new D(A.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},pm,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Ik=Symbol.for("mcp.completable");function mg(t){return!!t&&typeof t=="object"&&Ik in t}function Pk(t){return t[Ik]?.complete}var zk;(function(t){t.Completable="McpCompletable"})(zk||(zk={}));var O4=/^[A-Za-z0-9._-]{1,128}$/;function N4(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!O4.test(t)){let n=t.split("").filter(i=>!/[A-Za-z0-9._-]/.test(i)).filter((i,r,o)=>o.indexOf(i)===r);return e.push(`Tool name contains invalid characters: ${n.map(i=>`"${i}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function R4(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function hg(t){let e=N4(t);return R4(t,e.warnings),e.isValid}var gl=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,i){let r={taskSupport:"required",...n.execution};if(r.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,r,n._meta,i)}};var vl=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new hl(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new gl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(xr(Su)),this.server.assertCanSetRequestHandler(xr(Wn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Su,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let i={name:e,title:n.title,description:n.description,inputSchema:(()=>{let r=Un(n.inputSchema);return r?ym(r,{strictUnions:!0,pipeStrategy:"input"}):D4})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let r=Un(n.outputSchema);r&&(i.outputSchema=ym(r,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(Wn,async(e,n)=>{try{let i=this._registeredTools[e.params.name];if(!i)throw new D(A.InvalidParams,`Tool ${e.params.name} not found`);if(!i.enabled)throw new D(A.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,o=i.execution?.taskSupport,a="createTask"in i.handler;if((o==="required"||o==="optional")&&!a)throw new D(A.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!r)throw new D(A.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!r&&a)return await this.handleAutomaticTaskPolling(i,e,n);let s=await this.validateToolInput(i,e.params.arguments,e.params.name),c=await this.executeToolHandler(i,s,n);return r||await this.validateToolOutput(i,c,e.params.name),c}catch(i){if(i instanceof D&&i.code===A.UrlElicitationRequired)throw i;return this.createToolError(i instanceof Error?i.message:String(i))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,i){if(!e.inputSchema)return;let o=Un(e.inputSchema)??e.inputSchema,a=await Tc(o,n);if(!a.success){let s="error"in a?a.error:"Unknown error",c=jc(s);throw new D(A.InvalidParams,`Input validation error: Invalid arguments for tool ${i}: ${c}`)}return a.data}async validateToolOutput(e,n,i){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new D(A.InvalidParams,`Output validation error: Tool ${i} has an output schema but no structured content was provided`);let r=Un(e.outputSchema),o=await Tc(r,n.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=jc(a);throw new D(A.InvalidParams,`Output validation error: Invalid structured content for tool ${i}: ${s}`)}}async executeToolHandler(e,n,i){let r=e.handler;if("createTask"in r){if(!i.taskStore)throw new Error("No task store provided.");let a={...i,taskStore:i.taskStore};if(e.inputSchema){let s=r;return await Promise.resolve(s.createTask(n,a))}else{let s=r;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=r;return await Promise.resolve(a(n,i))}else{let a=r;return await Promise.resolve(a(i))}}async handleAutomaticTaskPolling(e,n,i){if(!i.taskStore)throw new Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(e,n.params.arguments,n.params.name),o=e.handler,a={...i,taskStore:i.taskStore},s=r?await Promise.resolve(o.createTask(r,a)):await Promise.resolve(o.createTask(a)),c=s.task.taskId,u=s.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await i.taskStore.getTask(c);if(!d)throw new D(A.InternalError,`Task ${c} not found during polling`);u=d}return await i.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(xr(Iu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Iu,async e=>{switch(e.params.ref.type){case"ref/prompt":return W_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return X_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new D(A.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let i=this._registeredPrompts[n.name];if(!i)throw new D(A.InvalidParams,`Prompt ${n.name} not found`);if(!i.enabled)throw new D(A.InvalidParams,`Prompt ${n.name} disabled`);if(!i.argsSchema)return ha;let o=lr(i.argsSchema)?.[e.params.argument.name];if(!mg(o))return ha;let a=Pk(o);if(!a)return ha;let s=await a(e.params.argument.value,e.params.context);return jk(s)}async handleResourceCompletion(e,n){let i=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===n.uri);if(!i){if(this._registeredResources[n.uri])return ha;throw new D(A.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=i.resourceTemplate.completeCallback(e.params.argument.name);if(!r)return ha;let o=await r(e.params.argument.value,e.params.context);return jk(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(xr($u)),this.server.assertCanSetRequestHandler(xr(bu)),this.server.assertCanSetRequestHandler(xr(xu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler($u,async(e,n)=>{let i=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),r=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(n);for(let s of a.resources)r.push({...o.metadata,...s})}return{resources:[...i,...r]}}),this.server.setRequestHandler(bu,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,i])=>({name:n,uriTemplate:i.resourceTemplate.uriTemplate.toString(),...i.metadata}))})),this.server.setRequestHandler(xu,async(e,n)=>{let i=new URL(e.params.uri),r=this._registeredResources[i.toString()];if(r){if(!r.enabled)throw new D(A.InvalidParams,`Resource ${i} disabled`);return r.readCallback(i,n)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(i.toString());if(a)return o.readCallback(i,a,n)}throw new D(A.InvalidParams,`Resource ${i} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(xr(ku)),this.server.assertCanSetRequestHandler(xr(wu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ku,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?Z4(n.argsSchema):void 0}))})),this.server.setRequestHandler(wu,async(e,n)=>{let i=this._registeredPrompts[e.params.name];if(!i)throw new D(A.InvalidParams,`Prompt ${e.params.name} not found`);if(!i.enabled)throw new D(A.InvalidParams,`Prompt ${e.params.name} disabled`);if(i.argsSchema){let r=Un(i.argsSchema),o=await Tc(r,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=jc(c);throw new D(A.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let a=o.data,s=i.callback;return await Promise.resolve(s(a,n))}else{let r=i.callback;return await Promise.resolve(r(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...i){let r;typeof i[0]=="object"&&(r=i.shift());let o=i[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let a=this._createRegisteredResource(e,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,n,i,r){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(e,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,i.title,n,i,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,n,i,r,o){let a={name:e,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==i&&(delete this._registeredResources[i],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[i]=a,a}_createRegisteredResourceTemplate(e,n,i,r,o){let a={resourceTemplate:i,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=a)),typeof u.title<"u"&&(a.title=u.title),typeof u.template<"u"&&(a.resourceTemplate=u.template),typeof u.metadata<"u"&&(a.metadata=u.metadata),typeof u.callback<"u"&&(a.readCallback=u.callback),typeof u.enabled<"u"&&(a.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=i.uriTemplate.variableNames;return Array.isArray(s)&&s.some(u=>!!i.completeCallback(u))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,n,i,r,o){let a={title:n,description:i,argsSchema:r===void 0?void 0:Dr(r),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=Dr(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(c=>{let u=c instanceof Hn?c._def?.innerType:c;return mg(u)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,n,i,r,o,a,s,c,u){hg(e);let l={title:n,description:i,inputSchema:Tk(r),outputSchema:Tk(o),annotations:a,execution:s,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&hg(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=Dr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Dr(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 i,r,o,a;if(typeof n[0]=="string"&&(i=n.shift()),n.length>1){let c=n[0];if(gg(c))r=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!gg(n[0])&&(a=n.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=n.shift()}}let s=n[0];return this._createRegisteredTool(e,void 0,i,r,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,n,i){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:r,description:o,inputSchema:a,outputSchema:s,annotations:c,_meta:u}=n;return this._createRegisteredTool(e,r,o,a,s,c,{taskSupport:"forbidden"},u,i)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let i;typeof n[0]=="string"&&(i=n.shift());let r;n.length>1&&(r=n.shift());let o=n[0],a=this._createRegisteredPrompt(e,void 0,i,r,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,n,i){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:r,description:o,argsSchema:a}=n,s=this._createRegisteredPrompt(e,r,o,a,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var D4={type:"object",properties:{}};function Ek(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Ok(t){return"_def"in t||"_zod"in t||Ek(t)}function gg(t){return typeof t!="object"||t===null||Ok(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ek)}function Tk(t){if(t){if(gg(t))return Dr(t);if(!Ok(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Z4(t){let e=lr(t);return e?Object.entries(e).map(([n,i])=>{let r=_y(i),o=$y(i);return{name:n,description:r,required:!o}}):[]}function xr(t){let n=lr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Ec(n);if(typeof i=="string")return i;throw new Error("Schema method literal must be a string")}function jk(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ha={completion:{values:[],hasMore:!1}};import Rk from"process";var yl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
78
78
  `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),U4(n)}clear(){this._buffer=void 0}};function U4(t){return q_.parse(JSON.parse(t))}function Nk(t){return JSON.stringify(t)+`
79
- `}var _l=class{constructor(e=Rk.stdin,n=Rk.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new yl,this._started=!1,this._ondata=i=>{this._readBuffer.append(i),this.processReadBuffer()},this._onerror=i=>{this.onerror?.(i)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let i=Nk(e);this._stdout.write(i)?n():this._stdout.once("drain",n)})}};var vg={questions:rt.array(rt.object({question:rt.string(),header:rt.string().optional().describe('Very short topic label rendered as a tag above the question, max ~12 characters (e.g. "Framework")'),multiSelect:rt.boolean().optional(),options:rt.array(rt.object({label:rt.string(),description:rt.string().optional()})).optional()})).min(1).max(4)},BC=rt.object(vg);var Dk=new vl({name:"netlify_interactions",version:"1.0.0"});Dk.registerTool("ask",{description:"Ask the user one or more clarifying multiple-choice questions and pause until they answer. Use this instead of guessing when a decision materially changes the work. The process pauses as soon as you call it; do not call it more than once or continue working after calling it.",inputSchema:vg},()=>new Promise(()=>{}));var Zk=()=>process.exit(0);process.stdin.on("close",Zk);process.stdin.on("end",Zk);await Dk.connect(new _l);
79
+ `}var _l=class{constructor(e=Rk.stdin,n=Rk.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new yl,this._started=!1,this._ondata=i=>{this._readBuffer.append(i),this.processReadBuffer()},this._onerror=i=>{this.onerror?.(i)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(n=>{let i=Nk(e);this._stdout.write(i)?n():this._stdout.once("drain",n)})}};var vg={questions:rt.array(rt.object({question:rt.string(),header:rt.string().optional().describe('Very short topic label rendered as a tag above the question, max ~12 characters (e.g. "Framework")'),multiSelect:rt.boolean().optional(),options:rt.array(rt.object({label:rt.string(),description:rt.string().optional()})).optional()})).min(1).max(3)},BC=rt.object(vg);var Dk=new vl({name:"netlify_interactions",version:"1.0.0"});Dk.registerTool("ask",{description:"Ask the user one or more clarifying multiple-choice questions and pause until they answer. Use this instead of guessing when a decision materially changes the work. The process pauses as soon as you call it; do not call it more than once or continue working after calling it.",inputSchema:vg},()=>new Promise(()=>{}));var Zk=()=>process.exit(0);process.stdin.on("close",Zk);process.stdin.on("end",Zk);await Dk.connect(new _l);
80
80
  //# sourceMappingURL=interactions-mcp-server.js.map
@@ -1,10 +1,14 @@
1
1
  ---
2
2
  name: asking-questions
3
- description: When the request is ambiguous or a choice would materially change the outcome and only the user can decide, ask them with the `ask` tool instead of guessing or asking in plain text. Calling it pauses the process until they answer.
3
+ description:
4
+ When the request is ambiguous or a choice would materially change the outcome and only the user can decide, ask them
5
+ with the `ask` tool instead of guessing or asking in plain text. Calling it pauses the process until they answer.
4
6
  ---
5
7
 
6
8
  # Asking the user questions
7
9
 
8
10
  When a decision is genuinely the user's to make and would change what you build, ask rather than assume.
9
11
 
10
- Use the `ask` tool: pass one to four questions, each with a short `header`, the `question` text, and `options` when there is a clear set of choices. Calling it pauses the process until the user answers, so ask everything you need in a single call and stop. A plain-text question does not reach the user.
12
+ Use the `ask` tool: pass one to three questions, each with a short `header`, the `question` text, and `options` when
13
+ there is a clear set of choices. Calling it pauses the process until the user answers, so ask everything you need in a
14
+ single call and stop. A plain-text question does not reach the user.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netlify/agent-runner-cli",
3
3
  "type": "module",
4
- "version": "1.147.0",
4
+ "version": "1.148.0",
5
5
  "description": "CLI tool for running Netlify agents",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",