@rayburst/cc 3.1.0 → 3.1.2

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.
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Always-on product context for Claude Code — features, acceptance criteria, and board cards injected automatically.",
9
- "version": "3.1.0"
9
+ "version": "3.1.2"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "rayburst",
14
14
  "source": "./",
15
15
  "description": "Always-on product context for Claude Code. Automatically injects your Rayburst Product Requirement Registry (features, Gherkin acceptance criteria, board cards) into every coding session.",
16
- "version": "3.1.0",
16
+ "version": "3.1.2",
17
17
  "author": {
18
18
  "name": "Rayburst"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rayburst",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "description": "Always-on product context for Claude Code. Automatically injects feature atlas and acceptance criteria into every coding session — no slash commands needed.",
5
5
  "author": {
6
6
  "name": "Rayburst",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rayburst/cc",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "type": "module",
5
5
  "description": "Always-on product context for Claude Code. Automatically injects feature atlas and acceptance criteria into every coding session.",
6
6
  "author": {
package/server.bundle.mjs CHANGED
@@ -39,4 +39,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
39
39
  ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}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 o}function gs(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===$.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??fe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===$.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=hs(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===$.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===$.ZodBranded&&t.keyType._def.type._def.typeName===$.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ms(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function bf(t,e){if(e.mapStrategy==="record")return gs(t,e);let r=M(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||fe(e),n=M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||fe(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function xf(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function $f(t){return t.target==="openAi"?void 0:{not:fe({...t,currentPath:[...t.currentPath,"not"]})}}function wf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var qn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Sf(t,e){if(e.target==="openApi3")return kf(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in qn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=qn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return kf(t,e)}var kf=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>M(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function zf(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:qn[t.innerType._def.typeName],nullable:!0}:{type:[qn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=M(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Tf(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Cc(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?G(r,"minimum",n.value,n.message,e):G(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),G(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?G(r,"maximum",n.value,n.message,e):G(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),G(r,"maximum",n.value,n.message,e));break;case"multipleOf":G(r,"multipleOf",n.value,n.message,e);break}return r}function Pf(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=Xx(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=M(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=Yx(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Yx(t,e){if(t.catchall._def.typeName!=="ZodNever")return M(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 Xx(t){try{return t.isOptional()}catch{return!0}}var Ef=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return M(t.innerType._def,e);let r=M(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:fe(e)},r]}:fe(e)};var If=(t,e)=>{if(e.pipeStrategy==="input")return M(t.in._def,e);if(e.pipeStrategy==="output")return M(t.out._def,e);let r=M(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=M(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Rf(t,e){return M(t.type._def,e)}function Of(t,e){let n={type:"array",uniqueItems:!0,items:M(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&G(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&G(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Zf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:M(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>M(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Nf(t){return{not:fe(t)}}function jf(t){return fe(t)}var Cf=(t,e)=>M(t.innerType._def,e);var Af=(t,e,r)=>{switch(e){case $.ZodString:return hs(t,r);case $.ZodNumber:return Tf(t,r);case $.ZodObject:return Pf(t,r);case $.ZodBigInt:return df(t,r);case $.ZodBoolean:return pf();case $.ZodDate:return Ac(t,r);case $.ZodUndefined:return Nf(r);case $.ZodNull:return wf(r);case $.ZodArray:return lf(t,r);case $.ZodUnion:case $.ZodDiscriminatedUnion:return Sf(t,r);case $.ZodIntersection:return _f(t,r);case $.ZodTuple:return Zf(t,r);case $.ZodRecord:return gs(t,r);case $.ZodLiteral:return yf(t,r);case $.ZodEnum:return gf(t);case $.ZodNativeEnum:return xf(t);case $.ZodNullable:return zf(t,r);case $.ZodOptional:return Ef(t,r);case $.ZodMap:return bf(t,r);case $.ZodSet:return Of(t,r);case $.ZodLazy:return()=>t.getter()._def;case $.ZodPromise:return Rf(t,r);case $.ZodNaN:case $.ZodNever:return $f(r);case $.ZodEffects:return hf(t,r);case $.ZodAny:return fe(r);case $.ZodUnknown:return jf(r);case $.ZodDefault:return mf(t,r);case $.ZodBranded:return ms(t,r);case $.ZodReadonly:return Cf(t,r);case $.ZodCatch:return ff(t,r);case $.ZodPipeline:return If(t,r);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(n=>{})(e)}};function M(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==af)return a}if(n&&!r){let a=Qx(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Af(t,t.typeName,e),i=typeof s=="function"?M(s(),e):s;if(i&&e$(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Qx=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:fs(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),fe(e)):e.$refStrategy==="seen"?fe(e):void 0}},e$=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var qc=(t,e)=>{let r=uf(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:M(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??fe(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=M(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??fe(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function t$(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Lc(t,e){return Ke(t)?uc(t,{target:t$(e?.target),io:e?.pipeStrategy??"input"}):qc(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Uc(t){let r=Mt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Vo(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Vc(t,e){let r=At(t,e);if(!r.success)throw r.error;return r.data}var r$=6e4,_s=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(Wo,r=>{this._oncancel(r)}),this.setNotificationHandler(Xo,r=>{this._onprogress(r)}),this.setRequestHandler(Yo,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Qo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new R(N.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ts,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,h=new R(d.error.code,d.error.message,d.error.data);l(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new R(N.InvalidParams,`Task not found: ${s}`);if(!qt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(qt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Dt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(rs,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new R(N.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(os,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new R(N.InvalidParams,`Task not found: ${r.params.taskId}`);if(qt(o.status))throw new R(N.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new R(N.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof R?o:new R(N.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),R.fromError(N.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.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 r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Rn(s)||Kp(s)?this._onresponse(s):$c(s)?this._onrequest(s,i):Bp(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=R.fromError(N.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Dt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:N.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Fp(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,h)=>{if(i.signal.aborted)throw new R(N.ConnectionClosed,"Request was cancelled");let f={...h,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let p=f.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:N.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Rn(e))n(e);else{let i=new R(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Rn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Rn(e))o(e);else{let i=R.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof R?i:new R(N.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Fr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new R(N.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},qt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new R(N.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new R(N.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof R?i:new R(N.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=x=>{l(x)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(x){d(x);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:h}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Dt]:c}});let p=x=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(E=>this._onerror(new Error(`Failed to send cancellation: ${E}`)));let w=x instanceof R?x:new R(N.RequestTimeout,String(x));l(w)};this._responseHandlers.set(h,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let w=At(r,x.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let m=n?.timeout??r$,_=()=>p(R.fromError(N.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(h,m,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let x=w=>{let E=this._responseHandlers.get(h);E?E(w):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,x),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(h),l(w)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>{this._cleanupTimeout(h),l(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},es,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ns,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Yp,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Dt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.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 a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Dt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Dt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Uc(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Vc(e,o);return Promise.resolve(r(i,s))})}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,r){let n=Uc(e);this._notificationHandlers.set(n,o=>{let s=Vc(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&$c(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new R(N.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new R(N.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new R(N.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new R(N.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Cn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),qt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new R(N.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(qt(a.status))throw new R(N.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Cn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),qt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Mf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Df(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Mf(i)&&Mf(s)?r[o]={...i,...s}:r[o]=s}return r}var Sg=Vl(Pl(),1),zg=Vl(kg(),1);function Bz(){let t=new Sg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,zg.default)(t),t}var Qs=class{constructor(e){this._ajv=e??Bz()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var ei=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(s.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==d.size||![...l].every(h=>d.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Dn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Br,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Tg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Pg(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var ti=class extends _s{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Mn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Qs,this.setRequestHandler(Sc,n=>this._oninitialize(n)),this.setNotificationHandler(zc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Zc,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Mn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ei(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Df(this._capabilities,e)}setRequestHandler(e,r){let o=Mt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Ke(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=At(Jr,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new R(N.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,h=await Promise.resolve(r(c,u));if(d.task){let p=At(Fr,h);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new R(N.InvalidParams,`Invalid task creation result: ${m}`)}return p.data}let f=At(ds,h);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new R(N.InvalidParams,`Invalid tools/call result: ${p}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}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){Pg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Tg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Lp.includes(r)?r:bc,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"},Go)}async createMessage(e,r){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 n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Nc,r):this.request({method:"sampling/createMessage",params:e},Dn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Br,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Br,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new R(N.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof R?i:new R(N.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},jc,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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 Ig=Symbol.for("mcp.completable");function Cl(t){return!!t&&typeof t=="object"&&Ig in t}function Rg(t){return t[Ig]?.complete}var Eg;(function(t){t.Completable="McpCompletable"})(Eg||(Eg={}));var Kz=/^[A-Za-z0-9._-]{1,128}$/;function Gz(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"),!Kz.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Wz(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Al(t){let e=Gz(t);return Wz(t,e.warnings),e.isValid}var ri=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var ni=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ti(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ri(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Gt(ls)),this.server.assertCanSetRequestHandler(Gt(Jr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ls,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Ur(r.inputSchema);return o?Lc(o,{strictUnions:!0,pipeStrategy:"input"}):Yz})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Ur(r.outputSchema);o&&(n.outputSchema=Lc(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Jr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new R(N.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new R(N.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new R(N.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new R(N.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof R&&n.code===N.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Ur(e.inputSchema)??e.inputSchema,i=await Lo(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Uo(a);throw new R(N.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new R(N.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Ur(e.outputSchema),s=await Lo(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Uo(i);throw new R(N.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(h=>setTimeout(h,l));let d=await n.taskStore.getTask(c);if(!d)throw new R(N.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Gt(ps)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ps,async e=>{switch(e.params.ref.type){case"ref/prompt":return nf(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return of(e),this.handleResourceCompletion(e,e.params.ref);default:throw new R(N.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new R(N.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new R(N.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return _o;let s=Mt(n.argsSchema)?.[e.params.argument.name];if(!Cl(s))return _o;let i=Rg(s);if(!i)return _o;let a=await i(e.params.argument.value,e.params.context);return Zg(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return _o;throw new R(N.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return _o;let s=await o(e.params.argument.value,e.params.context);return Zg(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Gt(ss)),this.server.assertCanSetRequestHandler(Gt(is)),this.server.assertCanSetRequestHandler(Gt(as)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ss,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(is,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(as,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new R(N.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new R(N.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Gt(cs)),this.server.assertCanSetRequestHandler(Gt(us)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(cs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Xz(r.argsSchema):void 0}))})),this.server.setRequestHandler(us,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new R(N.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new R(N.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Ur(n.argsSchema),s=await Lo(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Uo(c);throw new R(N.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:vr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=vr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof je?c._def?.innerType:c;return Cl(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Al(e);let l={title:r,description:n,inputSchema:Og(o),outputSchema:Og(s),annotations:i,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"&&Al(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=vr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=vr(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,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Ml(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Ml(r[0])&&(i=r.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`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Yz={type:"object",properties:{}};function Ng(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function jg(t){return"_def"in t||"_zod"in t||Ng(t)}function Ml(t){return typeof t!="object"||t===null||jg(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ng)}function Og(t){if(t){if(Ml(t))return vr(t);if(!jg(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Xz(t){let e=Mt(t);return e?Object.entries(e).map(([r,n])=>{let o=_p(n),s=yp(n);return{name:r,description:o,required:!s}}):[]}function Gt(t){let r=Mt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Vo(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Zg(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var _o={completion:{values:[],hasMore:!1}};import Ag from"node:process";var oi=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
40
40
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Qz(r)}clear(){this._buffer=void 0}};function Qz(t){return Gp.parse(JSON.parse(t))}function Cg(t){return JSON.stringify(t)+`
41
41
  `}var si=class{constructor(e=Ag.stdin,r=Ag.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new oi,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let 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(r=>{let n=Cg(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{readFileSync as Mg,existsSync as Dg}from"node:fs";import{resolve as qg}from"node:path";var Dl=class{config;requestId=0;constructor(e){this.config=e}async call(e,r={}){let o={jsonrpc:"2.0",id:++this.requestId,method:"tools/call",params:{name:e,arguments:r}},s={"Content-Type":"application/json",Accept:"application/json, text/event-stream",Authorization:`Bearer ${this.config.apiKey}`};this.config.agentId&&(s["X-Agent-Id"]=this.config.agentId);let i=await fetch(this.config.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o)});if(!i.ok){let u=await i.text().catch(()=>"");throw new Error(`Rayburst API error ${i.status}: ${u||i.statusText}`)}if((i.headers.get("content-type")??"").includes("text/event-stream")){let u=await i.text();return this.parseSSE(u)}let c=await i.json();if(c.error)throw new Error(`MCP error: ${c.error.message??JSON.stringify(c.error)}`);return c.result??c}parseSSE(e){let r=e.split(`
42
- `),n=null;for(let o of r)o.startsWith("data: ")&&(n=o.slice(6));if(!n)throw new Error("No data in SSE response");try{let o=JSON.parse(n);if(o.error)throw new Error(`MCP error: ${o.error.message??JSON.stringify(o.error)}`);return o.result??o}catch(o){throw o instanceof SyntaxError?new Error(`Failed to parse SSE data: ${n}`):o}}async ping(){try{let e={"Content-Type":"application/json",Accept:"application/json, text/event-stream",Authorization:`Bearer ${this.config.apiKey}`};return this.config.agentId&&(e["X-Agent-Id"]=this.config.agentId),(await fetch(this.config.apiUrl,{method:"POST",headers:e,body:JSON.stringify({jsonrpc:"2.0",id:++this.requestId,method:"initialize",params:{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"rayburst-cc",version:"2.0.0"}}})})).ok}catch{return!1}}};function eT(){try{let t=process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=qg(t,".claude","rb-config.md");if(!Dg(e))return null;let n=Mg(e,"utf-8").match(/-\s*API Key:\s*(.+)/i);return n?n[1].trim():null}catch{return null}}function tT(){try{let t=process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=qg(t,".claude","rb-config.md");if(!Dg(e))return null;let n=Mg(e,"utf-8").match(/-\s*API URL:\s*(.+)/i);return n?n[1].trim():null}catch{return null}}function Lg(){let t=process.env.RAYBURST_API_KEY||eT(),e=process.env.RAYBURST_API_URL||tT()||"https://api.rayburst.app/api/v1/mcp",r=process.env.RAYBURST_AGENT_ID;if(!t)throw new Error("Rayburst API key not found. Run /rb:init to configure, or set RAYBURST_API_KEY.");return new Dl({apiUrl:e,apiKey:t,agentId:r})}function Ug(t,e){t.tool("rb_ping","Check connection to the Rayburst API",{},async()=>{let r=await e.ping();return{content:[{type:"text",text:JSON.stringify(r?{status:"ok",message:"Connected to Rayburst API"}:{status:"error",message:"Failed to connect to Rayburst API"})}]}})}var ql=k.enum(["draft","active","completed","archived"]);function Vg(t,e){t.tool("rb_list_features","List features with optional filters",{projectId:k.string().optional().describe("Filter by project ID"),status:ql.optional().describe("Filter by status"),search:k.string().optional().describe("Search by title/description"),tagIds:k.array(k.string()).optional().describe("Filter by tag IDs"),limit:k.number().min(1).max(100).default(50).describe("Max results"),offset:k.number().min(0).default(0).describe("Pagination offset")},async r=>{let n=await e.call("list_features",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_get_feature","Get a feature by ID with its acceptance criteria",{featureId:k.string().describe("Feature UUID")},async r=>{let n=await e.call("get_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_create_feature","Create a new feature with title and acceptance criteria",{title:k.string().min(1).max(200).describe("Feature title (noun phrase)"),description:k.string().optional().describe("Feature description"),projectIds:k.array(k.string()).describe("Project IDs to link"),status:ql.default("draft").describe("Initial status")},async r=>{let n=await e.call("create_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_update_feature","Update an existing feature",{featureId:k.string().describe("Feature UUID"),title:k.string().min(1).max(200).optional().describe("New title"),description:k.string().optional().describe("New description"),status:ql.optional().describe("New status"),projectIds:k.array(k.string()).optional().describe("Updated project IDs"),tagIds:k.array(k.string()).optional().describe("Updated tag IDs")},async r=>{let n=await e.call("update_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_delete_feature","Delete a feature permanently",{featureId:k.string().describe("Feature UUID")},async r=>{let n=await e.call("delete_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var Fg=k.enum(["draft","pending","pass","fail","blocked","skipped","deprecated"]),Hg=k.enum(["manual","browser","code-review"]);function Jg(t,e){t.tool("rb_add_criterion","Add an acceptance criterion to a feature",{featureId:k.string().describe("Feature UUID"),title:k.string().max(200).optional().describe("Short criterion title"),description:k.string().min(1).max(2e3).describe("Criterion description (Gherkin Given/When/Then preferred)"),status:Fg.default("pending").describe("Initial status"),validationMethod:Hg.default("manual").describe("How this criterion is validated"),allowCodeReviewFallback:k.boolean().optional().describe("Allow code review as fallback validation"),validationNotes:k.string().max(5e3).optional().describe("Notes for validators"),tagIds:k.array(k.string()).optional().describe("Tag IDs to assign")},async r=>{let n=await e.call("add_criterion",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_update_criterion","Update an existing acceptance criterion",{featureId:k.string().describe("Feature UUID"),criterionId:k.string().describe("Criterion UUID"),title:k.string().max(200).nullable().optional().describe("New title"),description:k.string().min(1).max(2e3).optional().describe("New description"),status:Fg.optional().describe("New status"),validationMethod:Hg.optional().describe("New validation method"),allowCodeReviewFallback:k.boolean().optional(),validationNotes:k.string().max(5e3).nullable().optional(),tagIds:k.array(k.string()).optional()},async r=>{let n=await e.call("update_criterion",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_delete_criterion","Delete an acceptance criterion from a feature",{featureId:k.string().describe("Feature UUID"),criterionId:k.string().describe("Criterion UUID")},async r=>{let n=await e.call("delete_criterion",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var Bg=k.enum(["draft","ready","in-progress","validation","done"]);function Kg(t,e){t.tool("rb_list_projects","List all projects in the organization",{search:k.string().optional().describe("Search by project name or description"),limit:k.number().int().min(1).max(100).optional().describe("Max results (default 50)")},async r=>{let n=await e.call("list_projects",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_boards","List all boards in the organization",{},async()=>{let r=await e.call("list_boards",{});return{content:[{type:"text",text:JSON.stringify(r)}]}}),t.tool("rb_list_cards","List all cards on a board",{boardId:k.string().describe("Board UUID")},async r=>{let n=await e.call("list_cards",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_get_card","Get a card with its roles, todos, and dependencies",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("get_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_create_card","Create a new card on a board",{boardId:k.string().describe("Board UUID"),columnId:k.string().optional().describe("Column UUID"),title:k.string().min(1).max(200).describe("Card title"),description:k.string().max(2e3).optional().describe("Card description"),status:Bg.default("draft").describe("Initial status")},async r=>{let n=await e.call("create_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_update_card","Update a card's title or description",{cardId:k.string().describe("Card UUID"),title:k.string().min(1).max(200).optional().describe("New title"),description:k.string().max(2e3).optional().describe("New description")},async r=>{let n=await e.call("update_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_move_card","Move a card to a new status column",{cardId:k.string().describe("Card UUID"),status:Bg.describe("Target status"),afterCardId:k.string().nullable().optional().describe("Card to place after (null for top)")},async r=>{let n=await e.call("move_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_card_features","List features linked to a card",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("list_card_features",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_card_todos","List implementation todos on a card",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("list_card_todos",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_card_roles","List role assignments on a card",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("list_card_roles",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}function Gg(t,e){t.tool("rb_link_feature_to_feature","Create a typed link between two features",{sourceFeatureId:k.string().describe("Source feature UUID"),targetFeatureId:k.string().describe("Target feature UUID"),linkType:k.enum(["depends_on","implements","extends","related_to"]).optional().describe("Relationship type")},async r=>{let n=await e.call("link_feature_to_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_feature_links","List all feature-to-feature links for a feature",{featureId:k.string().describe("Feature UUID")},async r=>{let n=await e.call("list_feature_links",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var rT=k.object({criterionId:k.string().describe("Criterion UUID"),status:k.enum(["pass","fail","blocked","skipped"]).describe("Result status"),notes:k.string().optional().describe("Validation notes")});function Wg(t,e){t.tool("rb_submit_validation","Submit a validation report for a card or feature",{cardId:k.string().optional().describe("Card UUID (provide cardId OR featureId)"),featureId:k.string().optional().describe("Feature UUID (provide cardId OR featureId)"),results:k.array(rT).min(1).describe("Per-criterion validation results"),overallComment:k.string().optional().describe("Summary comment")},async r=>{let n=await e.call("submit_validation",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var nT=k.enum(["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"]);function Yg(t,e){t.tool("rb_list_tags","List all tags in the organization",{},async()=>{let r=await e.call("list_tags",{});return{content:[{type:"text",text:JSON.stringify(r)}]}}),t.tool("rb_create_tag","Create a new tag",{name:k.string().min(1).max(50).describe("Tag name"),color:nT.describe("Tag color")},async r=>{let n=await e.call("create_tag",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}function Xg(t,e){t.tool("rb_add_comment","Add a comment to a card",{cardId:k.string().describe("Card UUID"),content:k.string().min(1).max(5e3).describe("Comment text (markdown)")},async r=>{let n=await e.call("add_comment",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var bt=new ni({name:"rayburst",version:"3.1.0"}),Wt=new Proxy({},{get(t,e){return Lg()[e]}});Ug(bt,Wt);Vg(bt,Wt);Jg(bt,Wt);Kg(bt,Wt);Gg(bt,Wt);Wg(bt,Wt);Yg(bt,Wt);Xg(bt,Wt);var Qg=async()=>{try{await bt.close()}catch{}process.exit(0)};process.on("SIGINT",Qg);process.on("SIGTERM",Qg);var oT=new si;await bt.connect(oT);
42
+ `),n=null;for(let o of r)o.startsWith("data: ")&&(n=o.slice(6));if(!n)throw new Error("No data in SSE response");try{let o=JSON.parse(n);if(o.error)throw new Error(`MCP error: ${o.error.message??JSON.stringify(o.error)}`);return o.result??o}catch(o){throw o instanceof SyntaxError?new Error(`Failed to parse SSE data: ${n}`):o}}async ping(){try{let e={"Content-Type":"application/json",Accept:"application/json, text/event-stream",Authorization:`Bearer ${this.config.apiKey}`};return this.config.agentId&&(e["X-Agent-Id"]=this.config.agentId),(await fetch(this.config.apiUrl,{method:"POST",headers:e,body:JSON.stringify({jsonrpc:"2.0",id:++this.requestId,method:"initialize",params:{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"rayburst-cc",version:"2.0.0"}}})})).ok}catch{return!1}}};function eT(){try{let t=process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=qg(t,".claude","rb-config.md");if(!Dg(e))return null;let n=Mg(e,"utf-8").match(/-\s*API Key:\s*(.+)/i);return n?n[1].trim():null}catch{return null}}function tT(){try{let t=process.env.CLAUDE_PROJECT_DIR||process.cwd(),e=qg(t,".claude","rb-config.md");if(!Dg(e))return null;let n=Mg(e,"utf-8").match(/-\s*API URL:\s*(.+)/i);return n?n[1].trim():null}catch{return null}}function Lg(){let t=process.env.RAYBURST_API_KEY||eT(),e=process.env.RAYBURST_API_URL||tT()||"https://api.rayburst.app/api/v1/mcp",r=process.env.RAYBURST_AGENT_ID;if(!t)throw new Error("Rayburst API key not found. Run /rb:init to configure, or set RAYBURST_API_KEY.");return new Dl({apiUrl:e,apiKey:t,agentId:r})}function Ug(t,e){t.tool("rb_ping","Check connection to the Rayburst API",{},async()=>{let r=await e.ping();return{content:[{type:"text",text:JSON.stringify(r?{status:"ok",message:"Connected to Rayburst API"}:{status:"error",message:"Failed to connect to Rayburst API"})}]}})}var ql=k.enum(["draft","active","completed","archived"]);function Vg(t,e){t.tool("rb_list_features","List features with optional filters",{projectId:k.string().optional().describe("Filter by project ID"),status:ql.optional().describe("Filter by status"),search:k.string().optional().describe("Search by title/description"),tagIds:k.array(k.string()).optional().describe("Filter by tag IDs"),limit:k.number().min(1).max(100).default(50).describe("Max results"),offset:k.number().min(0).default(0).describe("Pagination offset")},async r=>{let n=await e.call("list_features",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_get_feature","Get a feature by ID with its acceptance criteria",{featureId:k.string().describe("Feature UUID")},async r=>{let n=await e.call("get_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_create_feature","Create a new feature with title and acceptance criteria",{title:k.string().min(1).max(200).describe("Feature title (noun phrase)"),description:k.string().optional().describe("Feature description"),projectIds:k.array(k.string()).describe("Project IDs to link"),status:ql.default("draft").describe("Initial status")},async r=>{let n=await e.call("create_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_update_feature","Update an existing feature",{featureId:k.string().describe("Feature UUID"),title:k.string().min(1).max(200).optional().describe("New title"),description:k.string().optional().describe("New description"),status:ql.optional().describe("New status"),projectIds:k.array(k.string()).optional().describe("Updated project IDs"),tagIds:k.array(k.string()).optional().describe("Updated tag IDs")},async r=>{let n=await e.call("update_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_delete_feature","Delete a feature permanently",{featureId:k.string().describe("Feature UUID")},async r=>{let n=await e.call("delete_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var Fg=k.enum(["draft","pending","pass","fail","blocked","skipped","deprecated"]),Hg=k.enum(["manual","browser","code-review"]);function Jg(t,e){t.tool("rb_add_criterion","Add an acceptance criterion to a feature",{featureId:k.string().describe("Feature UUID"),title:k.string().max(200).optional().describe("Short criterion title"),description:k.string().min(1).max(2e3).describe("Criterion description (Gherkin Given/When/Then preferred)"),status:Fg.default("pending").describe("Initial status"),validationMethod:Hg.default("manual").describe("How this criterion is validated"),allowCodeReviewFallback:k.boolean().optional().describe("Allow code review as fallback validation"),validationNotes:k.string().max(5e3).optional().describe("Notes for validators"),tagIds:k.array(k.string()).optional().describe("Tag IDs to assign")},async r=>{let n=await e.call("add_criterion",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_update_criterion","Update an existing acceptance criterion",{featureId:k.string().describe("Feature UUID"),criterionId:k.string().describe("Criterion UUID"),title:k.string().max(200).nullable().optional().describe("New title"),description:k.string().min(1).max(2e3).optional().describe("New description"),status:Fg.optional().describe("New status"),validationMethod:Hg.optional().describe("New validation method"),allowCodeReviewFallback:k.boolean().optional(),validationNotes:k.string().max(5e3).nullable().optional(),tagIds:k.array(k.string()).optional()},async r=>{let n=await e.call("update_criterion",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_delete_criterion","Delete an acceptance criterion from a feature",{featureId:k.string().describe("Feature UUID"),criterionId:k.string().describe("Criterion UUID")},async r=>{let n=await e.call("delete_criterion",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var Bg=k.enum(["draft","ready","in-progress","validation","done"]);function Kg(t,e){t.tool("rb_list_projects","List all projects in the organization",{search:k.string().optional().describe("Search by project name or description"),limit:k.number().int().min(1).max(100).optional().describe("Max results (default 50)")},async r=>{let n=await e.call("list_projects",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_boards","List all boards in the organization",{},async()=>{let r=await e.call("list_boards",{});return{content:[{type:"text",text:JSON.stringify(r)}]}}),t.tool("rb_list_cards","List all cards on a board",{boardId:k.string().describe("Board UUID")},async r=>{let n=await e.call("list_cards",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_get_card","Get a card with its roles, todos, and dependencies",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("get_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_create_card","Create a new card on a board",{boardId:k.string().describe("Board UUID"),columnId:k.string().optional().describe("Column UUID"),title:k.string().min(1).max(200).describe("Card title"),description:k.string().max(2e3).optional().describe("Card description"),status:Bg.default("draft").describe("Initial status")},async r=>{let n=await e.call("create_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_update_card","Update a card's title or description",{cardId:k.string().describe("Card UUID"),title:k.string().min(1).max(200).optional().describe("New title"),description:k.string().max(2e3).optional().describe("New description")},async r=>{let n=await e.call("update_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_move_card","Move a card to a new status column",{cardId:k.string().describe("Card UUID"),status:Bg.describe("Target status"),afterCardId:k.string().nullable().optional().describe("Card to place after (null for top)")},async r=>{let n=await e.call("move_card",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_card_features","List features linked to a card",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("list_card_features",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_card_todos","List implementation todos on a card",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("list_card_todos",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_card_roles","List role assignments on a card",{cardId:k.string().describe("Card UUID")},async r=>{let n=await e.call("list_card_roles",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}function Gg(t,e){t.tool("rb_link_feature_to_feature","Create a typed link between two features",{sourceFeatureId:k.string().describe("Source feature UUID"),targetFeatureId:k.string().describe("Target feature UUID"),linkType:k.enum(["depends_on","implements","extends","related_to"]).optional().describe("Relationship type")},async r=>{let n=await e.call("link_feature_to_feature",r);return{content:[{type:"text",text:JSON.stringify(n)}]}}),t.tool("rb_list_feature_links","List all feature-to-feature links for a feature",{featureId:k.string().describe("Feature UUID")},async r=>{let n=await e.call("list_feature_links",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var rT=k.object({criterionId:k.string().describe("Criterion UUID"),status:k.enum(["pass","fail","blocked","skipped"]).describe("Result status"),notes:k.string().optional().describe("Validation notes")});function Wg(t,e){t.tool("rb_submit_validation","Submit a validation report for a card or feature",{cardId:k.string().optional().describe("Card UUID (provide cardId OR featureId)"),featureId:k.string().optional().describe("Feature UUID (provide cardId OR featureId)"),results:k.array(rT).min(1).describe("Per-criterion validation results"),overallComment:k.string().optional().describe("Summary comment")},async r=>{let n=await e.call("submit_validation",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var nT=k.enum(["gray","red","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"]);function Yg(t,e){t.tool("rb_list_tags","List all tags in the organization",{},async()=>{let r=await e.call("list_tags",{});return{content:[{type:"text",text:JSON.stringify(r)}]}}),t.tool("rb_create_tag","Create a new tag",{name:k.string().min(1).max(50).describe("Tag name"),color:nT.describe("Tag color")},async r=>{let n=await e.call("create_tag",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}function Xg(t,e){t.tool("rb_add_comment","Add a comment to a card",{cardId:k.string().describe("Card UUID"),content:k.string().min(1).max(5e3).describe("Comment text (markdown)")},async r=>{let n=await e.call("add_comment",r);return{content:[{type:"text",text:JSON.stringify(n)}]}})}var bt=new ni({name:"rayburst",version:"3.1.2"}),Wt=new Proxy({},{get(t,e){return Lg()[e]}});Ug(bt,Wt);Vg(bt,Wt);Jg(bt,Wt);Kg(bt,Wt);Gg(bt,Wt);Wg(bt,Wt);Yg(bt,Wt);Xg(bt,Wt);var Qg=async()=>{try{await bt.close()}catch{}process.exit(0)};process.on("SIGINT",Qg);process.on("SIGTERM",Qg);var oT=new si;await bt.connect(oT);
@@ -102,49 +102,49 @@ Store as `project_url`.
102
102
 
103
103
  ---
104
104
 
105
- ### Step 5: Select Board
105
+ ### Step 5: Select Projects
106
106
 
107
- List available boards:
107
+ List available projects in the organization:
108
108
 
109
109
  ```
110
- mcp__plugin_rayburst_rayburst__rb_list_boards()
110
+ mcp__plugin_rayburst_rayburst__rb_list_projects()
111
111
  ```
112
112
 
113
- Display them numbered and ask the user to pick:
113
+ Display them numbered and let the user pick one or more:
114
114
 
115
115
  ```
116
- Available boards:
117
- 1. Rayburst MVP (23578fa2-...)
118
- 2. Rayburst Business (e07dae77-...)
116
+ Available projects:
117
+ 1. My App Frontend (a1b2c3d4-...) — local
118
+ 2. My App API (e5f6a7b8-...) — github
119
+ 3. Landing Page (c9d0e1f2-...) — manual
119
120
 
120
- Select a board number:
121
+ Select project(s) for this workspace (comma-separated numbers, or Enter to skip):
122
+ e.g. 1,2
121
123
  ```
122
124
 
123
- Store the selected `board_id` and `board_slug`.
125
+ Store selected project IDs and names as `projects` list. If only one is selected, store it. If multiple, store all.
124
126
 
125
127
  ---
126
128
 
127
- ### Step 6: Select Projects
129
+ ### Step 6: Select Board
128
130
 
129
- List available projects in the organization:
131
+ List available boards:
130
132
 
131
133
  ```
132
- mcp__plugin_rayburst_rayburst__rb_list_projects()
134
+ mcp__plugin_rayburst_rayburst__rb_list_boards()
133
135
  ```
134
136
 
135
- Display them numbered and let the user pick one or more:
137
+ Display them numbered and ask the user to pick:
136
138
 
137
139
  ```
138
- Available projects:
139
- 1. Rayburst Frontend (231165df-...) — local
140
- 2. Rayburst API (7805dae1-...) — github
141
- 3. Marketing Site (a1b2c3d4-...) — manual
140
+ Available boards:
141
+ 1. Rayburst MVP (23578fa2-...)
142
+ 2. Rayburst Business (e07dae77-...)
142
143
 
143
- Select project(s) for this workspace (comma-separated numbers, or Enter to skip):
144
- e.g. 1,2
144
+ Select a board number:
145
145
  ```
146
146
 
147
- Store selected project IDs and names as `projects` list. If only one is selected, store it. If multiple, store all.
147
+ Store the selected `board_id` and `board_slug`.
148
148
 
149
149
  ---
150
150
 
@@ -194,14 +194,14 @@ Write the complete `.claude/rb-config.md` (overwriting the minimal one from Step
194
194
  ## Project URL
195
195
  <project_url>
196
196
 
197
- ## Board
198
- - ID: <board_id>
199
- - Slug: <board_slug>
200
-
201
197
  ## Projects
202
198
  - <project_name_1>: <project_id_1>
203
199
  - <project_name_2>: <project_id_2>
204
200
 
201
+ ## Board
202
+ - ID: <board_id>
203
+ - Slug: <board_slug>
204
+
205
205
  ## Users
206
206
 
207
207
  ### <description_1>