@reddb-io/red-skills 2.55.2 → 2.55.3

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.
@@ -74,7 +74,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
74
74
  `:`[${n[c]}\r
75
75
  ]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function uc(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===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=cc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ac(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function C_(t,e){if(e.mapStrategy==="record")return uc(t,e);let r=Q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Be(e),n=Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function O_(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function N_(t){return t.target==="openAi"?void 0:{not:Be({...t,currentPath:[...t.currentPath,"not"]})}}function j_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var is={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function M_(t,e){if(e.target==="openApi3")return D_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in is&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=is[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return D_(t,e)}var D_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Q(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 A_(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:is[t.innerType._def.typeName],nullable:!0}:{type:[is[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function q_(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",gf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?he(r,"minimum",n.value,n.message,e):he(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),he(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?he(r,"maximum",n.value,n.message,e):he(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),he(r,"maximum",n.value,n.message,e));break;case"multipleOf":he(r,"multipleOf",n.value,n.message,e);break}return r}function Z_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let l=Mz(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let f=Q(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});f!==void 0&&(n.properties[a]=f,l||o.push(a))}o.length&&(n.required=o);let s=Dz(t,e);return s!==void 0&&(n.additionalProperties=s),n}function Dz(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 Mz(t){try{return t.isOptional()}catch{return!0}}var L_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Q(t.innerType._def,e);let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Be(e)},r]}:Be(e)};var F_=(t,e)=>{if(e.pipeStrategy==="input")return Q(t.in._def,e);if(e.pipeStrategy==="output")return Q(t.out._def,e);let r=Q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function U_(t,e){return Q(t.type._def,e)}function V_(t,e){let n={type:"array",uniqueItems:!0,items:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&he(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&he(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function H_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function B_(t){return{not:Be(t)}}function W_(t){return Be(t)}var J_=(t,e)=>Q(t.innerType._def,e);var K_=(t,e,r)=>{switch(e){case D.ZodString:return cc(t,r);case D.ZodNumber:return q_(t,r);case D.ZodObject:return Z_(t,r);case D.ZodBigInt:return $_(t,r);case D.ZodBoolean:return k_();case D.ZodDate:return yf(t,r);case D.ZodUndefined:return B_(r);case D.ZodNull:return j_(r);case D.ZodArray:return x_(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return M_(t,r);case D.ZodIntersection:return z_(t,r);case D.ZodTuple:return H_(t,r);case D.ZodRecord:return uc(t,r);case D.ZodLiteral:return E_(t,r);case D.ZodEnum:return R_(t);case D.ZodNativeEnum:return O_(t);case D.ZodNullable:return A_(t,r);case D.ZodOptional:return L_(t,r);case D.ZodMap:return C_(t,r);case D.ZodSet:return V_(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return U_(t,r);case D.ZodNaN:case D.ZodNever:return N_(r);case D.ZodEffects:return P_(t,r);case D.ZodAny:return Be(r);case D.ZodUnknown:return W_(r);case D.ZodDefault:return T_(t,r);case D.ZodBranded:return ac(t,r);case D.ZodReadonly:return J_(t,r);case D.ZodCatch:return S_(t,r);case D.ZodPipeline:return F_(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}};function Q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==v_)return a}if(n&&!r){let a=Az(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=K_(t,t.typeName,e),s=typeof i=="function"?Q(i(),e):i;if(s&&qz(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var Az=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sc(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`),Be(e)):e.$refStrategy==="seen"?Be(e):void 0}},qz=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var bf=(t,e)=>{let r=w_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,f])=>({...c,[l]:Q(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Be(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Be(r),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Zz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function wf(t,e){return Kt(t)?Fd(t,{target:Zz(e?.target),io:e?.pipeStrategy??"input"}):bf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function xf(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $f(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var Lz=6e4,lc=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(Ua,r=>{this._oncancel(r)}),this.setNotificationHandler(Ha,r=>{this._onprogress(r)}),this.setRequestHandler(Va,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ba,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ja,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,f=this._requestResolvers.get(l);if(f)if(this._requestResolvers.delete(l),a.type==="response")f(c);else{let p=c,w=new B(p.error.code,p.error.message,p.error.data);f(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new B(G.InvalidParams,`Task not found: ${i}`);if(!cn(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(cn(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[an]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Ka,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new B(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Xa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(cn(o.status))throw new B(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new B(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof B?o:new B(G.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,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,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),B.fromError(G.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=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Gi(i)||a_(i)?this._onresponse(i):tf(i)?this._onrequest(i,s):s_(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let 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=B.fromError(G.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,i=e.params?._meta?.[an]?.taskId;if(n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(f).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=n_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};i&&(p.relatedTask={taskId:i}),await this.notification(f,p)},sendRequest:async(f,p,w)=>{if(s.signal.aborted)throw new B(G.ConnectionClosed,"Request was cancelled");let b={...w,relatedRequestId:e.id};i&&!b.relatedTask&&(b.relatedTask={taskId:i});let g=b.relatedTask?.taskId??i;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(f,p,b)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async f=>{if(s.signal.aborted)return;let p={result:f,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async f=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:G.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Gi(e))n(e);else{let s=new B(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Gi(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Gi(e))o(e);else{let s=B.fromError(e.error.code,e.error.message,e.error.data);o(s)}}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(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}return}let i;try{let s=await this.request(e,jo,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new B(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},cn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new B(G.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(G.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,f)=>{let p=O=>{f(O)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(O){p(O);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(b.params={...b.params,task:a}),c&&(b.params={...b.params,_meta:{...b.params?._meta||{},[an]:c}});let g=O=>{this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(O)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`)));let z=O instanceof B?O:new B(G.RequestTimeout,String(O));f(z)};this._responseHandlers.set(w,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return f(O);try{let z=on(r,O.result);z.success?l(z.data):f(z.error)}catch(z){f(z)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let x=n?.timeout??Lz,S=()=>g(B.fromError(G.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(w,x,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let N=c?.taskId;if(N){let O=z=>{let Z=this._responseHandlers.get(w);Z?Z(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,O),this._enqueueTaskMessage(N,{type:"request",message:b,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),f(z)})}else this._transport.send(b,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(O=>{this._cleanupTimeout(w),f(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Wa,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},Ga,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},l_,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||{},[an]: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||{},[an]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[an]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=xf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=$f(e,o);return Promise.resolve(r(s,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=xf(e);this._notificationHandlers.set(n,o=>{let i=$f(e,o);return Promise.resolve(r(i))})}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"&&tf(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new B(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,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,i)=>{if(r.aborted){i(new B(G.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new B(G.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 i=await n.getTask(o,r);if(!i)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=ts.parse({method:"notifications/tasks/status",params:a});await this.notification(c),cn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new B(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(cn(a.status))throw new B(G.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=ts.parse({method:"notifications/tasks/status",params:c});await this.notification(l),cn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function G_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X_(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let s=r[o];G_(s)&&G_(i)?r[o]={...s,...i}:r[o]=i}return r}var Fw=la(um(),1),Uw=la(Lw(),1);function Vj(){let t=new Fw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Uw.default)(t),t}var Hc=class{constructor(e){this._ajv=e??Vj()}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 Bc=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],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(f=>f.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]:[],l=c.some(f=>f.type==="tool_use");if(s){if(i.some(f=>f.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let f=new Set(c.filter(w=>w.type==="tool_use").map(w=>w.id)),p=new Set(i.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(f.size!==p.size||![...f].every(w=>p.has(w)))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},os,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 i=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},Ao,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 Vw(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 Hw(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 Wc=class extends lc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ns.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Hc,this.setRequestHandler(of,n=>this._oninitialize(n)),this.setNotificationHandler(sf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(pf,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=ns.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Bc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=X_(this._capabilities,e)}setRequestHandler(e,r){let o=sn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Kt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,l)=>{let f=on(Mo,c);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new B(G.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:p}=f.data,w=await Promise.resolve(r(c,l));if(p.task){let g=on(jo,w);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new B(G.InvalidParams,`Invalid task creation result: ${x}`)}return g.data}let b=on(oc,w);if(!b.success){let g=b.error instanceof Error?b.error.message:String(b.error);throw new B(G.InvalidParams,`Invalid tools/call result: ${g}`)}return b.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){Hw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Vw(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:e_.includes(r)?r:Qd,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"},Fa)}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],i=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(l=>l.type==="tool_use");if(i){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(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==f.size||![...l].every(p=>f.has(p)))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},mf,r):this.request({method:"sampling/createMessage",params:e},os,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},Ao,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"},i=await this.request({method:"elicitation/create",params:o},Ao,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new B(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof B?s:new B(G.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}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},hf,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 Ww=Symbol.for("mcp.completable");function ym(t){return!!t&&typeof t=="object"&&Ww in t}function Jw(t){return t[Ww]?.complete}var Bw;(function(t){t.Completable="McpCompletable"})(Bw||(Bw={}));var Hj=/^[A-Za-z0-9._-]{1,128}$/;function Bj(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"),!Hj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.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 Wj(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 _m(t){let e=Bj(t);return Wj(t,e.warnings),e.isValid}var Jc=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 Kc=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 Wc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Jc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(nc)),this.server.assertCanSetRequestHandler(yn(Mo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(nc,()=>({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=Oo(r.inputSchema);return o?wf(o,{strictUnions:!0,pipeStrategy:"input"}):Jj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Oo(r.outputSchema);o&&(n.outputSchema=wf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Mo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new B(G.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new B(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)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 B&&n.code===G.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 i=Oo(e.inputSchema)??e.inputSchema,s=await Na(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=ja(a);throw new B(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Oo(e.outputSchema),i=await Na(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ja(s);throw new B(G.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 s={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(e.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(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),i=e.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,f=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(w=>setTimeout(w,f));let p=await n.taskStore.getTask(c);if(!p)throw new B(G.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(yn(ic)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ic,async e=>{switch(e.params.ref.type){case"ref/prompt":return g_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return y_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return js;let i=sn(n.argsSchema)?.[e.params.argument.name];if(!ym(i))return js;let s=Jw(i);if(!s)return js;let a=await s(e.params.argument.value,e.params.context);return Gw(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return js;throw new B(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return js;let i=await o(e.params.argument.value,e.params.context);return Gw(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(Ya)),this.server.assertCanSetRequestHandler(yn(Qa)),this.server.assertCanSetRequestHandler(yn(ec)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ya,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Qa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ec,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(G.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new B(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(tc)),this.server.assertCanSetRequestHandler(yn(rc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(tc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Kj(r.argsSchema):void 0}))})),this.server.setRequestHandler(rc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Oo(n.argsSchema),i=await Na(o,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=ja(c);throw new B(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,void 0,r,o,i);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,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,n.title,r,n,o);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,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,n,o,i){let s={name:e,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(e,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Qn(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Qn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,o&&Object.values(o).some(c=>{let l=c instanceof zt?c._def?.innerType:c;return ym(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,r,n,o,i,s,a,c,l){_m(e);let f={title:r,description:n,inputSchema:Kw(o),outputSchema:Kw(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>f.update({enabled:!1}),enable:()=>f.update({enabled:!0}),remove:()=>f.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&_m(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=f)),typeof p.title<"u"&&(f.title=p.title),typeof p.description<"u"&&(f.description=p.description),typeof p.paramsSchema<"u"&&(f.inputSchema=Qn(p.paramsSchema)),typeof p.outputSchema<"u"&&(f.outputSchema=Qn(p.outputSchema)),typeof p.callback<"u"&&(f.handler=p.callback),typeof p.annotations<"u"&&(f.annotations=p.annotations),typeof p._meta<"u"&&(f._meta=p._meta),typeof p.enabled<"u"&&(f.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=f,this.setToolRequestHandlers(),this.sendToolListChanged(),f}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(vm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!vm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,i,s,{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:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,i,s,a,c,{taskSupport:"forbidden"},l,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 i=r[0],s=this._createRegisteredPrompt(e,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(e,o,i,s,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 Jj={type:"object",properties:{}};function Xw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Yw(t){return"_def"in t||"_zod"in t||Xw(t)}function vm(t){return typeof t!="object"||t===null||Yw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Xw)}function Kw(t){if(t){if(vm(t))return Qn(t);if(!Yw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Kj(t){let e=sn(t);return e?Object.entries(e).map(([r,n])=>{let o=Ey(n),i=Iy(n);return{name:r,description:o,required:!i}}):[]}function yn(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Gw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var js={completion:{values:[],hasMore:!1}};import ex from"node:process";var Gc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
76
76
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Gj(r)}clear(){this._buffer=void 0}};function Gj(t){return c_.parse(JSON.parse(t))}function Qw(t){return JSON.stringify(t)+`
77
- `}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,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=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.55.2")??"0.0.0-dev"),gitSha:ni("__RED_BUILD_GIT_SHA__",()=>"c2bbfd6d644ae033e4d5d012f98a7e0a9407a76c")??"unknown",buildTime:ni("__RED_BUILD_TIME__",()=>"2026-07-13T23:33:42-03:00")??"unknown",bundleAsset:ni("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=ni("__REDDB_SDK_VERSION__",()=>""),n=ni("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function Xj(t){return t.startsWith("v")?t.slice(1):t}function rx(t){return`${t.app} ${t.version} ${t.gitSha}`}function ni(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var bm={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function nx(){let t=process.env.CODE_NAV_SERVERS;if(!t)return bm;try{let e=JSON.parse(t),r={...bm};for(let[n,o]of Object.entries(e))r[n]={...r[n]??{},...o};return r}catch(e){return process.stderr.write(`code-nav: failed to parse CODE_NAV_SERVERS, using defaults: ${String(e)}
77
+ `}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,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=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.55.3")??"0.0.0-dev"),gitSha:ni("__RED_BUILD_GIT_SHA__",()=>"15be4622f2ef4c460ff55365d4731f90d6f2d570")??"unknown",buildTime:ni("__RED_BUILD_TIME__",()=>"2026-07-13T23:50:13-03:00")??"unknown",bundleAsset:ni("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=ni("__REDDB_SDK_VERSION__",()=>""),n=ni("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function Xj(t){return t.startsWith("v")?t.slice(1):t}function rx(t){return`${t.app} ${t.version} ${t.gitSha}`}function ni(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var bm={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function nx(){let t=process.env.CODE_NAV_SERVERS;if(!t)return bm;try{let e=JSON.parse(t),r={...bm};for(let[n,o]of Object.entries(e))r[n]={...r[n]??{},...o};return r}catch(e){return process.stderr.write(`code-nav: failed to parse CODE_NAV_SERVERS, using defaults: ${String(e)}
78
78
  `),bm}}function ox(t){let e=new Map;for(let[r,n]of Object.entries(t))for(let o of n.extensions)e.set(o,r);return e}var $i=la(jk(),1),xt=la(Jh(),1);import{spawn as t1}from"node:child_process";import{readFile as r1}from"node:fs/promises";import{pathToFileURL as Dk,fileURLToPath as n1}from"node:url";import{resolve as o1}from"node:path";var Hs=class{constructor(e,r){this.spec=e;this.rootPath=r}spec;rootPath;proc;conn;ready;openDocs=new Set;async ensureStarted(){return this.ready?this.ready:(this.ready=this.start(),this.ready)}async start(){let e=t1(this.spec.command,this.spec.args,{cwd:this.rootPath,stdio:["pipe","pipe","pipe"]});this.proc=e,await new Promise((i,s)=>{e.once("spawn",()=>i()),e.once("error",a=>s(new Error(`failed to spawn '${this.spec.command}': ${a.message}`)))}),e.stderr.on("data",i=>{process.stderr.write(`[${this.spec.command}] ${i.toString()}`)}),e.once("exit",()=>{try{this.conn?.dispose()}catch{}});let r=(0,$i.createProtocolConnection)(new $i.StreamMessageReader(e.stdout),new $i.StreamMessageWriter(e.stdin));this.conn=r,r.listen();let n=Dk(this.rootPath).toString(),o={processId:process.pid,rootUri:n,workspaceFolders:[{uri:n,name:"workspace"}],capabilities:{textDocument:{definition:{linkSupport:!0},references:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},hover:{contentFormat:["markdown","plaintext"]}},workspace:{symbol:{}}}};await r.sendRequest(xt.InitializeRequest.type,o),await r.sendNotification(xt.InitializedNotification.type,{})}async ensureOpen(e){let r=o1(this.rootPath,e),n=Dk(r).toString();if(this.openDocs.has(n))return n;let o=await r1(r,"utf8");return await this.conn.sendNotification(xt.DidOpenTextDocumentNotification.type,{textDocument:{uri:n,languageId:this.spec.languageId,version:1,text:o}}),this.openDocs.add(n),n}async definition(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e),i=await this.conn.sendRequest(xt.DefinitionRequest.type,{textDocument:{uri:o},position:{line:r,character:n}});return i1(i)}async references(e,r,n,o){await this.ensureStarted();let i=await this.ensureOpen(e);return await this.conn.sendRequest(xt.ReferencesRequest.type,{textDocument:{uri:i},position:{line:r,character:n},context:{includeDeclaration:o}})??[]}async documentSymbols(e){await this.ensureStarted();let r=await this.ensureOpen(e);return await this.conn.sendRequest(xt.DocumentSymbolRequest.type,{textDocument:{uri:r}})??[]}async hover(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e);return this.conn.sendRequest(xt.HoverRequest.type,{textDocument:{uri:o},position:{line:r,character:n}})}async workspaceSymbols(e){return await this.ensureStarted(),await this.conn.sendRequest(xt.WorkspaceSymbolRequest.type,{query:e})??[]}dispose(){try{this.conn?.dispose()}catch{}this.proc?.kill()}};function i1(t){return t?(Array.isArray(t)?t:[t]).map(r=>"targetUri"in r?{uri:r.targetUri,range:r.targetSelectionRange}:r):[]}function Kh(t,e){try{let r=n1(t);return(r.startsWith(e)?r.slice(e.length).replace(/^[/\\]/,""):r)||r}catch{return t}}var Ws=process.env.CODE_NAV_ROOT??process.cwd(),Bs=nx(),Mk=ox(Bs),ki=new Map;function Au(t){let e=s1(t),r=Mk.get(e);if(!r)throw new Error(`no language server configured for '${e}'. Configured extensions: ${[...Mk.keys()].join(", ")||"(none)"}.`);let n=ki.get(r);return n||(n=new Hs(Bs[r],Ws),ki.set(r,n)),n}function a1(){for(let t of Object.keys(Bs))ki.has(t)||ki.set(t,new Hs(Bs[t],Ws));return[...ki.values()]}function Xh(t,e){return`${Kh(t,Ws)}:${e.start.line+1}:${e.start.character+1}`}var Gh=tx("code-nav"),Si=new Kc({name:"code-nav",version:Gh.version}),qu={file:tn.string().describe("Workspace-relative path to the source file."),line:tn.number().int().describe("Zero-based line number."),character:tn.number().int().describe("Zero-based character offset on the line.")};Si.registerTool("goto_definition",{title:"Go to definition",description:"Resolve the symbol at a file position to its definition(s). Returns file:line:column locations. Use this instead of grepping for a name.",inputSchema:qu},async({file:t,line:e,character:r})=>{let n=await Au(t).definition(t,e,r);return n.length===0?Cr("No definition found."):Cr(n.map(o=>Xh(o.uri,o.range)).join(`
79
79
  `))});Si.registerTool("find_references",{title:"Find references",description:"Find every reference to the symbol at a file position across the workspace. Semantic \u2014 matches the actual symbol, not text.",inputSchema:{...qu,includeDeclaration:tn.boolean().optional().describe("Include the declaration itself (default true).")}},async({file:t,line:e,character:r,includeDeclaration:n})=>{let o=await Au(t).references(t,e,r,n??!0);return o.length===0?Cr("No references found."):Cr(`${o.length} reference(s):
80
80
  `+o.map(i=>Xh(i.uri,i.range)).join(`
@@ -830,7 +830,7 @@ requeued to ready-for-agent${e.activeBlocker?` (cleared active blocker: ${e.acti
830
830
  `)},I)}catch(k){return process.stderr.write(`[afk] respond failed: ${k instanceof Error?k.message:String(k)}
831
831
  `),1}return r.write(`Respond #${o}: ${v.action}${v.verb?` (/dev ${v.verb})`:""}.
832
832
  `),0}FC();function Oxr(e){let t=e.indexOf("--runner"),r=t>=0?e[t+1]:void 0;return r==="opencode"?"opencode":r==="claude"?"claude":"codex"}function Nxr(e){let t=JP(void 0,{runner:e});return JSON.stringify(e==="codex"||e==="opencode"?{systemMessage:t}:{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:t}})}async function lpt(e){let t=Oxr(e),r=JP(void 0,{runner:t});return process.stdout.write(e.includes("--hook")?Nxr(t):r),e.includes("--hook")&&process.stdout.write(`
833
- `),0}import{existsSync as EEr,readFileSync as bEr,statSync as Bye}from"node:fs";import{join as vpt,basename as SEr}from"node:path";function jY(e){let t={app:e,version:Pxr(HR("__RED_BUILD_VERSION__",()=>"2.55.2")??"0.0.0-dev"),gitSha:HR("__RED_BUILD_GIT_SHA__",()=>"c2bbfd6d644ae033e4d5d012f98a7e0a9407a76c")??"unknown",buildTime:HR("__RED_BUILD_TIME__",()=>"2026-07-13T23:33:42-03:00")??"unknown",bundleAsset:HR("__RED_BUNDLE_ASSET__",()=>"dev.bundle.min.mjs")??"unknown"},r=HR("__REDDB_SDK_VERSION__",()=>""),n=HR("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Pxr(e){return e.startsWith("v")?e.slice(1):e}function dpt(e){return`${e.app} ${e.version} ${e.gitSha}`}function HR(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function zY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.floor(e/1e3)}k`:String(e)}function mpt(e){let t=(r,n)=>{let o=(Math.round(r*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${n}`};return e>=1e9?t(e/1e9,"B"):e>=1e6?t(e/1e6,"M"):e>=1e3?t(e/1e3,"k"):String(e>0?e:0)}function qY(e){if(e>=100)return e.toFixed(0);if(e>=10)return e.toFixed(1);if(e>=1)return e.toFixed(2);let t=Math.max(2,Math.ceil(-Math.log10(e))+2);return e.toFixed(t)}function Mxr(e){let t=Number.isFinite(e)&&e>0?e:0;return t===0?"0":t>=1e9?`${qY(t/1e9)}B`:t>=1e6?`${qY(t/1e6)}M`:t>=1e3?`${qY(t/1e3)}k`:qY(t)}function Fxr(e){let t=Math.max(0,Math.floor(e));return t<1e3?String(t):t<1e6?`${(Math.floor(t/100)/10).toFixed(1)}k`:Mxr(t)}function hpt(e){let t=e.toLowerCase();for(let r of["opus","sonnet","haiku","fable"])if(t.includes(r))return r;return e}function Lxr(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60);if(r<60)return`${r}m${t%60}s`;let n=Math.floor(r/60);return n<24?`${n}h${r%60}m`:`${Math.floor(n/24)}d${n%24}h`}function WR(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let r=Math.floor(t/60),n=t%60;return n>0?`${r}h${n}m`:`${r}h`}function fpt(e){let t=e.basename;if(e.branch){let r=e.branch;return r.length>28&&(r=`${r.slice(0,27)}\u2026`),`${t} (${r})`}return e.detachedSha?`${t} (detached ${e.detachedSha})`:t}function Uxr(e){return!e||!e.model?null:e.effort?`${e.model}\xB7${e.effort}`:e.model}function ppt(e){if(!e)return null;let t=e.contextTokens;if(t===void 0||t===0)return null;let r=zY(t);return e.contextPercent===void 0?r:`${r} ${Math.round(e.contextPercent)}%`}function $xr(e){if(!e||e.workers<=0)return[];let t=[],r=(i,s)=>{t.push({label:i,value:s,suffix:""})};if(e.workers>0&&r("wrk=",String(e.workers)),e.sourceCounts&&e.sourceCounts.length>0)for(let{origin:i,count:s}of e.sourceCounts)r(`${i}=`,String(s));let n=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";if(e.queue>0&&t.push({label:"rdy=",value:String(e.queue),suffix:n}),e.human>0){let i=n&&e.queue===0?n:"";t.push({label:"hmn=",value:String(e.human),suffix:i})}e.blocked>0&&r("blk=",String(e.blocked));let o=[];return e.added>0&&o.push(`+${e.added}`),e.removed>0&&o.push(`-${e.removed}`),o.length&&r("loc=",e.locIsPeak?`~${o.join(" ")}`:o.join(" ")),e.waiting!==void 0&&e.waiting>0&&r("wai=",String(e.waiting)),e.tokens!==void 0&&e.tokens>0&&r("tok=",zY(e.tokens)),e.costUsd!==void 0&&e.costUsd>0&&r("usd=",e.costUsd.toFixed(2)),e.issues.forEach((i,s)=>{let a=e.phases?.[s],c=e.aliveMs?.[s],u=a?`\xB7${a}`:"";c!==void 0&&c>0&&(u+=`\xB7${Lxr(c)}`),t.push({label:"#",value:String(i),suffix:u})}),t}function Hxr(e){if(!e)return null;let t=[];return e.usage5h!==void 0&&t.push(`5h=${Math.round(e.usage5h)}%`),e.usage7d!==void 0&&t.push(`7d=${Math.round(e.usage7d)}%`),t.length?t.join(" "):null}function Wxr(e){if(!e)return null;let t=[],r=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(`prs=${e.openPrs}${r}`),e.todayPrs&&e.todayPrs>0){let o=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(`cpr=${e.todayPrs}${o}`)}if(e.openIssues&&e.openIssues>0){let o=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(`iss=${e.openIssues}${o}`)}let n=[];return e.localAdded&&e.localAdded>0&&n.push(`+${e.localAdded}`),e.localRemoved&&e.localRemoved>0&&n.push(`-${e.localRemoved}`),n.length&&t.push(`loc=${n.join(" ")}`),t.length?t.join(" "):null}function jxr(e){if(!e||!e.openIssues||e.openIssues<=0)return null;let t=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";return`iss=${e.openIssues}${t}`}function _ye(e){if(!e)return null;let t=e.runner||"?",r=Math.max(0,Math.floor(e.busy)),n=Math.max(0,Math.floor(e.total)),o=Math.max(0,Math.floor(e.queue)),i=[`flt=${t} ${r}/${n} busy`,`q=${o}`];return e.parked!==void 0&&e.parked>0&&i.push(`park=${Math.floor(e.parked)}`),i.join(" \xB7 ")}function GY(e){return e?e.state==="ready"?`rsp=\u2193${Fxr(e.tokensSavedToday)}`:e.state==="warming"?"rsp=\u2026":"rsp=!":null}function qxr(e){let t=$xr(e);return t.length===0?null:t.map(r=>`${r.label}${r.value}${r.suffix}`).join(" ")}function gpt(e,t="full"){if(t==="short"){let l=[fpt(e.project)],d=ppt(e.claude);d!==null&&l.push(`ctx=${d}`);let f=jxr(e.repo);f!==null&&l.push(f);let p=GY(e.rsp);return p!==null&&l.push(p),l.join(" \xB7 ")}let r=[fpt(e.project)],n=Uxr(e.claude);n!==null&&r.push(n);let o=ppt(e.claude);o!==null&&r.push(o);let i=Hxr(e.claude);i!==null&&r.push(i);let s=Wxr(e.repo);s!==null&&r.push(s);let a=_ye(e.fleet);a!==null&&r.push(a);let c=GY(e.rsp);c!==null&&r.push(c);let u=qxr(e.afk);return u!==null&&r.push(u),r.join(" \xB7 ")}var Gxr="\x1B[48;2;114;47;55m",zxr="\x1B[48;2;88;36;42m",xpt="\x1B[49m",WC="\x1B[38;2;255;255;255m",Ept="\x1B[38;2;255;214;214m",bpt="\x1B[39m",jC="\x1B[38;2;224;138;148m",mM="\x1B[38;2;201;150;158m",Vxr="\x1B[38;2;96;214;128m",Yxr="\x1B[38;2;255;95;95m",Jxr="\x1B[38;2;240;200;120m",Spt="\x1B[1m",Cpt="\x1B[22m",wpt="\x1B[0m",Kxr=28,Zxr=" ",VY=["workerId","run","org","iss","phase","elapsed","loc","tks","tls","rsn","txt"],Xxr=["workerId","iss","phase","elapsed"],eEr=new Set(["requeue"]),tEr=new Set(["gate","push-pr","merge","cascade"]),rEr=e=>e.replace(/\x1b\[[0-9;]*m/g,"");function Ipt(e){return rEr(e).length}function nEr(e,t){return e+" ".repeat(Math.max(0,t-Ipt(e)))}var Wx=(e,t)=>`${Ept}${e}=${bpt}${t}${jC}`;function oEr(e,t){let r=[];return e&&e>0&&r.push(`+${e}`),t&&t>0&&r.push(`-${t}`),r.length?r.join(" "):null}function iEr(e){return e.runner==="claude"&&e.tokens===0?"\u2014":mpt(e.tokens)}function sEr(e,t=!0){let r="";if(e.branch){let o=e.branch.length>Kxr?`${e.branch.slice(0,27)}\u2026`:e.branch;r=` ${mM}(${o})${WC}`}else e.detachedSha&&(r=` ${mM}(detached ${e.detachedSha})${WC}`);let n=t&&e.version?` ${mM}v${e.version}${WC}`:"";return`${Jxr}\xBB${WC} ${Spt}${e.basename}${Cpt}${r}${n}`}function aEr(e){return!e||!e.model?null:e.effort?`${e.model}${mM}\xB7${WC}${e.effort}`:e.model}function Apt(e){if(!e||!e.contextTokens)return null;let t=zY(e.contextTokens),r=e.contextPercent===void 0?t:`${t} ${Math.round(e.contextPercent)}%`;return Wx("ctx",r)}function cEr(e){if(!e)return[];let t=[];return e.usage5h!==void 0&&t.push(Wx("5h",`${Math.round(e.usage5h)}%`)),e.usage7d!==void 0&&t.push(Wx("7d",`${Math.round(e.usage7d)}%`)),t}function uEr(e){if(!e)return[];let t=[],r=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(Wx("prs",String(e.openPrs))+r),e.todayPrs&&e.todayPrs>0){let n=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(Wx("cpr",String(e.todayPrs))+n)}if(e.openIssues&&e.openIssues>0){let n=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(Wx("iss",String(e.openIssues))+n)}return t}function lEr(e){if(!e)return[];let t=oEr(e.localAdded,e.localRemoved);return t?[Wx("loc",t)]:[]}function dEr(e){let t=_ye(e);return t?[t]:[]}function ypt(e){let t=GY(e);return!e||!t?[]:e.state==="ready"?[`${Vxr}${t}${jC}`]:e.state==="error"?[`${Yxr}${t}${jC}`]:[`${mM}${t}${jC}`]}function fEr(e,t,r,n,o="full",i){let s=`${zxr}${WC} ${sEr(e,o==="full")} `,a=aEr(t);o==="full"&&a!==null&&(s+=`${Gxr}${WC} ${a} `),s+=`${xpt}${jC}`;let c=o==="short"?[Apt(t),r&&r.openIssues&&r.openIssues>0?Wx("iss",String(r.openIssues))+(r.cacheAgeS!==void 0?` (${WR(r.cacheAgeS)})`:""):null,...ypt(i)].filter(u=>u!==null):[Apt(t),...cEr(t),...uEr(r),...lEr(r),...dEr(n),...ypt(i)].filter(u=>u!==null);return c.length&&(s+=` ${c.join(" ")}`),`${s}${wpt}`}function pEr(e,t){return[e,t].filter(Boolean).join("\xB7")}function mEr(e,t){let r=fft(e,t),n=[r.runner,r.model?hpt(r.model):void 0,r.effort].filter(s=>!!s).join(" "),o=tEr.has(r.phase),i=o||r.origin!==void 0&&eEr.has(r.origin);return{workerId:r.workerId,run:`run=${n}`,org:`org=${o?"landing":r.origin||"afk"}`,iss:r.issue===null?"":`iss=${String(r.issue)}`,phase:r.issue===null?"":pEr(r.phase,r.activity),elapsed:r.elapsed,loc:i?"":`loc=${dM(r.added,r.removed)}`,tks:i?"":`tks=${iEr(r)}`,tls:i?"":`tls=${String(r.tools)}`,rsn:i?"":`rsn=${String(r.reasoning)}`,txt:i?"":`txt=${String(r.text)}`}}function hEr(e,t=VY){let r=Object.fromEntries(VY.map(n=>[n,0]));for(let n of e)for(let o of t)r[o]=Math.max(r[o],Ipt(n[o]));return r}function gEr(e,t){if(e==="workerId")return`${Spt}${t}${Cpt}`;let r=t.indexOf("=");return r>0?`${Ept}${t.slice(0,r+1)}${bpt}${t.slice(r+1)}${jC}`:t}function AEr(e,t,r=VY){let n=r.map(o=>gEr(o,nEr(e[o],t[o])));return`${xpt}${jC}${n.join(Zxr)}${wpt}`}function yEr(e,t,r="full"){let n=e.map(s=>mEr(s,t)),o=r==="short"?Xxr:VY,i=hEr(n,o);return n.map(s=>AEr(s,i,o))}function xEr(e,t={}){let r=t.preset??"full",n=[fEr(e.project,e.claude,e.repo,e.fleet,r,e.rsp)],o=t.now??0;return n.push(...yEr(t.workers??[],o,r)),n.join(`
833
+ `),0}import{existsSync as EEr,readFileSync as bEr,statSync as Bye}from"node:fs";import{join as vpt,basename as SEr}from"node:path";function jY(e){let t={app:e,version:Pxr(HR("__RED_BUILD_VERSION__",()=>"2.55.3")??"0.0.0-dev"),gitSha:HR("__RED_BUILD_GIT_SHA__",()=>"15be4622f2ef4c460ff55365d4731f90d6f2d570")??"unknown",buildTime:HR("__RED_BUILD_TIME__",()=>"2026-07-13T23:50:13-03:00")??"unknown",bundleAsset:HR("__RED_BUNDLE_ASSET__",()=>"dev.bundle.min.mjs")??"unknown"},r=HR("__REDDB_SDK_VERSION__",()=>""),n=HR("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Pxr(e){return e.startsWith("v")?e.slice(1):e}function dpt(e){return`${e.app} ${e.version} ${e.gitSha}`}function HR(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function zY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.floor(e/1e3)}k`:String(e)}function mpt(e){let t=(r,n)=>{let o=(Math.round(r*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${n}`};return e>=1e9?t(e/1e9,"B"):e>=1e6?t(e/1e6,"M"):e>=1e3?t(e/1e3,"k"):String(e>0?e:0)}function qY(e){if(e>=100)return e.toFixed(0);if(e>=10)return e.toFixed(1);if(e>=1)return e.toFixed(2);let t=Math.max(2,Math.ceil(-Math.log10(e))+2);return e.toFixed(t)}function Mxr(e){let t=Number.isFinite(e)&&e>0?e:0;return t===0?"0":t>=1e9?`${qY(t/1e9)}B`:t>=1e6?`${qY(t/1e6)}M`:t>=1e3?`${qY(t/1e3)}k`:qY(t)}function Fxr(e){let t=Math.max(0,Math.floor(e));return t<1e3?String(t):t<1e6?`${(Math.floor(t/100)/10).toFixed(1)}k`:Mxr(t)}function hpt(e){let t=e.toLowerCase();for(let r of["opus","sonnet","haiku","fable"])if(t.includes(r))return r;return e}function Lxr(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60);if(r<60)return`${r}m${t%60}s`;let n=Math.floor(r/60);return n<24?`${n}h${r%60}m`:`${Math.floor(n/24)}d${n%24}h`}function WR(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let r=Math.floor(t/60),n=t%60;return n>0?`${r}h${n}m`:`${r}h`}function fpt(e){let t=e.basename;if(e.branch){let r=e.branch;return r.length>28&&(r=`${r.slice(0,27)}\u2026`),`${t} (${r})`}return e.detachedSha?`${t} (detached ${e.detachedSha})`:t}function Uxr(e){return!e||!e.model?null:e.effort?`${e.model}\xB7${e.effort}`:e.model}function ppt(e){if(!e)return null;let t=e.contextTokens;if(t===void 0||t===0)return null;let r=zY(t);return e.contextPercent===void 0?r:`${r} ${Math.round(e.contextPercent)}%`}function $xr(e){if(!e||e.workers<=0)return[];let t=[],r=(i,s)=>{t.push({label:i,value:s,suffix:""})};if(e.workers>0&&r("wrk=",String(e.workers)),e.sourceCounts&&e.sourceCounts.length>0)for(let{origin:i,count:s}of e.sourceCounts)r(`${i}=`,String(s));let n=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";if(e.queue>0&&t.push({label:"rdy=",value:String(e.queue),suffix:n}),e.human>0){let i=n&&e.queue===0?n:"";t.push({label:"hmn=",value:String(e.human),suffix:i})}e.blocked>0&&r("blk=",String(e.blocked));let o=[];return e.added>0&&o.push(`+${e.added}`),e.removed>0&&o.push(`-${e.removed}`),o.length&&r("loc=",e.locIsPeak?`~${o.join(" ")}`:o.join(" ")),e.waiting!==void 0&&e.waiting>0&&r("wai=",String(e.waiting)),e.tokens!==void 0&&e.tokens>0&&r("tok=",zY(e.tokens)),e.costUsd!==void 0&&e.costUsd>0&&r("usd=",e.costUsd.toFixed(2)),e.issues.forEach((i,s)=>{let a=e.phases?.[s],c=e.aliveMs?.[s],u=a?`\xB7${a}`:"";c!==void 0&&c>0&&(u+=`\xB7${Lxr(c)}`),t.push({label:"#",value:String(i),suffix:u})}),t}function Hxr(e){if(!e)return null;let t=[];return e.usage5h!==void 0&&t.push(`5h=${Math.round(e.usage5h)}%`),e.usage7d!==void 0&&t.push(`7d=${Math.round(e.usage7d)}%`),t.length?t.join(" "):null}function Wxr(e){if(!e)return null;let t=[],r=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(`prs=${e.openPrs}${r}`),e.todayPrs&&e.todayPrs>0){let o=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(`cpr=${e.todayPrs}${o}`)}if(e.openIssues&&e.openIssues>0){let o=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(`iss=${e.openIssues}${o}`)}let n=[];return e.localAdded&&e.localAdded>0&&n.push(`+${e.localAdded}`),e.localRemoved&&e.localRemoved>0&&n.push(`-${e.localRemoved}`),n.length&&t.push(`loc=${n.join(" ")}`),t.length?t.join(" "):null}function jxr(e){if(!e||!e.openIssues||e.openIssues<=0)return null;let t=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";return`iss=${e.openIssues}${t}`}function _ye(e){if(!e)return null;let t=e.runner||"?",r=Math.max(0,Math.floor(e.busy)),n=Math.max(0,Math.floor(e.total)),o=Math.max(0,Math.floor(e.queue)),i=[`flt=${t} ${r}/${n} busy`,`q=${o}`];return e.parked!==void 0&&e.parked>0&&i.push(`park=${Math.floor(e.parked)}`),i.join(" \xB7 ")}function GY(e){return e?e.state==="ready"?`rsp=\u2193${Fxr(e.tokensSavedToday)}`:e.state==="warming"?"rsp=\u2026":"rsp=!":null}function qxr(e){let t=$xr(e);return t.length===0?null:t.map(r=>`${r.label}${r.value}${r.suffix}`).join(" ")}function gpt(e,t="full"){if(t==="short"){let l=[fpt(e.project)],d=ppt(e.claude);d!==null&&l.push(`ctx=${d}`);let f=jxr(e.repo);f!==null&&l.push(f);let p=GY(e.rsp);return p!==null&&l.push(p),l.join(" \xB7 ")}let r=[fpt(e.project)],n=Uxr(e.claude);n!==null&&r.push(n);let o=ppt(e.claude);o!==null&&r.push(o);let i=Hxr(e.claude);i!==null&&r.push(i);let s=Wxr(e.repo);s!==null&&r.push(s);let a=_ye(e.fleet);a!==null&&r.push(a);let c=GY(e.rsp);c!==null&&r.push(c);let u=qxr(e.afk);return u!==null&&r.push(u),r.join(" \xB7 ")}var Gxr="\x1B[48;2;114;47;55m",zxr="\x1B[48;2;88;36;42m",xpt="\x1B[49m",WC="\x1B[38;2;255;255;255m",Ept="\x1B[38;2;255;214;214m",bpt="\x1B[39m",jC="\x1B[38;2;224;138;148m",mM="\x1B[38;2;201;150;158m",Vxr="\x1B[38;2;96;214;128m",Yxr="\x1B[38;2;255;95;95m",Jxr="\x1B[38;2;240;200;120m",Spt="\x1B[1m",Cpt="\x1B[22m",wpt="\x1B[0m",Kxr=28,Zxr=" ",VY=["workerId","run","org","iss","phase","elapsed","loc","tks","tls","rsn","txt"],Xxr=["workerId","iss","phase","elapsed"],eEr=new Set(["requeue"]),tEr=new Set(["gate","push-pr","merge","cascade"]),rEr=e=>e.replace(/\x1b\[[0-9;]*m/g,"");function Ipt(e){return rEr(e).length}function nEr(e,t){return e+" ".repeat(Math.max(0,t-Ipt(e)))}var Wx=(e,t)=>`${Ept}${e}=${bpt}${t}${jC}`;function oEr(e,t){let r=[];return e&&e>0&&r.push(`+${e}`),t&&t>0&&r.push(`-${t}`),r.length?r.join(" "):null}function iEr(e){return e.runner==="claude"&&e.tokens===0?"\u2014":mpt(e.tokens)}function sEr(e,t=!0){let r="";if(e.branch){let o=e.branch.length>Kxr?`${e.branch.slice(0,27)}\u2026`:e.branch;r=` ${mM}(${o})${WC}`}else e.detachedSha&&(r=` ${mM}(detached ${e.detachedSha})${WC}`);let n=t&&e.version?` ${mM}v${e.version}${WC}`:"";return`${Jxr}\xBB${WC} ${Spt}${e.basename}${Cpt}${r}${n}`}function aEr(e){return!e||!e.model?null:e.effort?`${e.model}${mM}\xB7${WC}${e.effort}`:e.model}function Apt(e){if(!e||!e.contextTokens)return null;let t=zY(e.contextTokens),r=e.contextPercent===void 0?t:`${t} ${Math.round(e.contextPercent)}%`;return Wx("ctx",r)}function cEr(e){if(!e)return[];let t=[];return e.usage5h!==void 0&&t.push(Wx("5h",`${Math.round(e.usage5h)}%`)),e.usage7d!==void 0&&t.push(Wx("7d",`${Math.round(e.usage7d)}%`)),t}function uEr(e){if(!e)return[];let t=[],r=e.cacheAgeS!==void 0?` (${WR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(Wx("prs",String(e.openPrs))+r),e.todayPrs&&e.todayPrs>0){let n=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(Wx("cpr",String(e.todayPrs))+n)}if(e.openIssues&&e.openIssues>0){let n=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(Wx("iss",String(e.openIssues))+n)}return t}function lEr(e){if(!e)return[];let t=oEr(e.localAdded,e.localRemoved);return t?[Wx("loc",t)]:[]}function dEr(e){let t=_ye(e);return t?[t]:[]}function ypt(e){let t=GY(e);return!e||!t?[]:e.state==="ready"?[`${Vxr}${t}${jC}`]:e.state==="error"?[`${Yxr}${t}${jC}`]:[`${mM}${t}${jC}`]}function fEr(e,t,r,n,o="full",i){let s=`${zxr}${WC} ${sEr(e,o==="full")} `,a=aEr(t);o==="full"&&a!==null&&(s+=`${Gxr}${WC} ${a} `),s+=`${xpt}${jC}`;let c=o==="short"?[Apt(t),r&&r.openIssues&&r.openIssues>0?Wx("iss",String(r.openIssues))+(r.cacheAgeS!==void 0?` (${WR(r.cacheAgeS)})`:""):null,...ypt(i)].filter(u=>u!==null):[Apt(t),...cEr(t),...uEr(r),...lEr(r),...dEr(n),...ypt(i)].filter(u=>u!==null);return c.length&&(s+=` ${c.join(" ")}`),`${s}${wpt}`}function pEr(e,t){return[e,t].filter(Boolean).join("\xB7")}function mEr(e,t){let r=fft(e,t),n=[r.runner,r.model?hpt(r.model):void 0,r.effort].filter(s=>!!s).join(" "),o=tEr.has(r.phase),i=o||r.origin!==void 0&&eEr.has(r.origin);return{workerId:r.workerId,run:`run=${n}`,org:`org=${o?"landing":r.origin||"afk"}`,iss:r.issue===null?"":`iss=${String(r.issue)}`,phase:r.issue===null?"":pEr(r.phase,r.activity),elapsed:r.elapsed,loc:i?"":`loc=${dM(r.added,r.removed)}`,tks:i?"":`tks=${iEr(r)}`,tls:i?"":`tls=${String(r.tools)}`,rsn:i?"":`rsn=${String(r.reasoning)}`,txt:i?"":`txt=${String(r.text)}`}}function hEr(e,t=VY){let r=Object.fromEntries(VY.map(n=>[n,0]));for(let n of e)for(let o of t)r[o]=Math.max(r[o],Ipt(n[o]));return r}function gEr(e,t){if(e==="workerId")return`${Spt}${t}${Cpt}`;let r=t.indexOf("=");return r>0?`${Ept}${t.slice(0,r+1)}${bpt}${t.slice(r+1)}${jC}`:t}function AEr(e,t,r=VY){let n=r.map(o=>gEr(o,nEr(e[o],t[o])));return`${xpt}${jC}${n.join(Zxr)}${wpt}`}function yEr(e,t,r="full"){let n=e.map(s=>mEr(s,t)),o=r==="short"?Xxr:VY,i=hEr(n,o);return n.map(s=>AEr(s,i,o))}function xEr(e,t={}){let r=t.preset??"full",n=[fEr(e.project,e.claude,e.repo,e.fleet,r,e.rsp)],o=t.now??0;return n.push(...yEr(t.workers??[],o,r)),n.join(`
834
834
  `)}function kpt(e,t,r={}){let n=r.preset??"full";return t?xEr(e,r):gpt(e,n)}bo();LP();function CEr(e){return new Promise(t=>{if(e.isTTY){t("");return}let r="",n=!1,o=()=>{n||(n=!0,t(r))};e.setEncoding("utf8"),e.on("data",i=>{r+=i}),e.on("end",o),e.on("error",o),e.on("close",o)})}function wEr(e){if(!e.trim())return{};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function IEr(e){try{return Bye(e).isDirectory()}catch{return!1}}function kEr(e,t,r){if(e&&IEr(e))return e;let n=t.workspace?.project_dir||t.workspace?.current_dir||t.cwd;return n||r}function vEr(e){let t=vpt(e,".red","config.yaml");if(!EEr(t))return!0;let r=Sr(t,{warn:()=>{}});return!(Pe(r,"statusline")==="false"||Pe(r,"afk.statusline")==="false")}function YY(e){return e==="full"||e==="short"?e:void 0}function REr(e){return YY(Pe(e,"plugins.dev.statusline.preset"))??YY(Pe(e,"dev.statusline.preset"))??YY(Pe(e,"afk.statusline.preset"))??YY(Pe(e,"statusline.preset"))??"full"}var _Er=15e3;function BEr(e){try{let t=JSON.parse(bEr(e,"utf8"));if(typeof t=="object"&&t!==null&&t.version===1&&typeof t.tokens_saved_today=="number"&&typeof t.updated_at=="string")return t}catch{}}function TEr(e,t,r){try{return t-Bye(e).mtimeMs<=r}catch{return!1}}function DEr(e){try{return Bye(e),!0}catch{return!1}}function Rpt(e){let t=Date.parse(e);if(Number.isFinite(t))return new Date(t).toISOString().slice(0,10)}function QEr(e,t){return Rpt(e.updated_at)!==new Date(t).toISOString().slice(0,10)?0:Math.max(0,Math.floor(e.tokens_saved_today))}function OEr(e,t){if(Rpt(e.updated_at)===new Date(t).toISOString().slice(0,10)&&typeof e.dollars_saved_today_usd=="number")return Math.max(0,e.dollars_saved_today_usd)}async function NEr(e,t=process.env){if(!DAe(e,t).enabled)return;let n=DR(e),o=Date.now(),i=BEr(n.summaryPath);if(i)return{state:"ready",tokensSavedToday:QEr(i,o),dollarsSavedTodayUsd:OEr(i,o)};if(TEr(n.wakeLockPath,o,_Er))return{state:"warming"};if(DEr(n.wakeLockPath))return{state:"error"}}async function PEr(e){let t={cwd:e},r=jY("dev").version,n={basename:SEr(e),version:r},o=await CP(t);if(o)return{...n,branch:o};let i=await yg(t);return i?{...n,detachedSha:i}:n}function MEr(e){let t=e.model?.display_name,r=e.effort?.level,n=e.context_window?.total_input_tokens,o=e.context_window?.used_percentage,i=e.rate_limits?.five_hour?.used_percentage,s=e.rate_limits?.seven_day?.used_percentage;if(!(t===void 0&&n===void 0&&i===void 0&&s===void 0))return{model:t||void 0,effort:r||void 0,contextTokens:n,contextPercent:o,usage5h:i,usage7d:s}}async function _pt(e,t=process.cwd(),r=process.stdout,n=process.stdin){if(e.includes("--legend"))return r.write(`${MY()}
835
835
  `),0;let o=e[0],i=await CEr(n),s=wEr(i),a=kEr(o,s,t);if(!vEr(a))return 0;let c=await PEr(a),u=MEr(s),l={root:a,repo:bR(a),remote:"origin"},d=Sr(vpt(a,".red","config.yaml"),{warn:()=>{}}),f=REr(d),p=$4(process.env,B=>Pe(d,B)),g=`origin/${await pf({issueBody:""},{readLockedBranch:()=>wg(Qx(a)),configLockedBranch:Pe(d,"dev.lock.branch"),configTrunk:Pe(d,"dev.trunk"),fetchIssueBody:async()=>{}})}`,[A,E,y,b,w]=await Promise.all([Zat(l,p,g),Yat(l,p).then(B=>B??void 0),Jat(l),Kat(l),NEr(a)]),I=!process.env.NO_COLOR,v=Number.parseInt(process.env.COLUMNS??"",10),k=Math.floor(Date.now()/1e3),R=kpt({project:c,claude:u,repo:A,fleet:y,afk:E,rsp:w},I,{columns:Number.isFinite(v)&&v>0?v:void 0,workers:b,now:k,preset:f});return r.write(`${R}
836
836
  `),0}async function Bpt(e,t=process.cwd()){let r=e[0]??t,n="",o="";for(let i=1;i<e.length;i+=1){let s=e[i];s==="--repo"?n=e[++i]??"":s==="--lock"&&(o=e[++i]??"")}return await Vat(r,n||bR(r),o||void 0),0}iw();import{spawn as qpt}from"node:child_process";import{existsSync as Dye,openSync as zpt,closeSync as GEr,writeFileSync as Vpt,writeSync as zEr,rmSync as Qye,renameSync as VEr}from"node:fs";import{join as qC}from"node:path";import{existsSync as FEr,readdirSync as hM,readFileSync as JY,statSync as Opt}from"node:fs";import{join as fs}from"node:path";nu();Kd();function LEr(e,t){return fs(e,`afk-supervisor-slot-${t}.log`)}function UEr(e){let t;try{t=JY(e,"utf8")}catch{return[]}let r=[],n=new Set;for(let o of t.split(`
@@ -6563,7 +6563,7 @@ Usage:
6563
6563
  ${n} archive --candidate <json> [--root <dir>] [--archive-dir <rel>]
6564
6564
  ${n} restore <name> [--root <dir>] [--archive-dir <rel>]`}function fx(n){return ANn(typeof n.root=="string"?n.root:process.cwd())}function Xot(n){return typeof n["archive-dir"]=="string"?n["archive-dir"]:void 0}async function vj(n){let a=await Co(n);return a?a.mode!=="graph"?{ok:!1,message:`curate: skill telemetry needs graph mode (this project is "${a.mode}") \u2014 run \`${ywe}\``}:sZ(a)?{ok:!0}:{ok:!1,message:`curate: skill telemetry is not enabled here \u2014 run \`${ywe}\``}:{ok:!1,message:`curate: memory is not initialized here \u2014 run \`${ywe}\``}}function xNn(){let n=kNn(LNn(import.meta.url));return n.includes("dist/curate-skill")||n.endsWith("dist/curate-skill")?vot(n,"..","cli.js"):vot(n,"..","cli.ts")}async function zNn(n,a){let i=["curate","skills","--json"];a!==void 0&&i.push("--stale-days",String(a));let d=xNn(),h=d.endsWith(".ts")?Rot(process.execPath,["--import","tsx",d,...i,"--root",n],{encoding:"utf8"}):Rot(process.execPath,[d,...i,"--root",n],{encoding:"utf8"}),y=h.status??1;if(y!==0)throw new Error(`memory curate skills exited ${y}`);return Vot(h.stdout??"")}function ONn(n){return typeof n.flags["stale-days"]=="string"?Number(n.flags["stale-days"]):void 0}async function fot(n,a){return(a.loadCuratorReport??zNn)(fx(n.flags),ONn(n))}async function UNn(n){let a=fx(n.flags),i=await vj(a);return i.ok?(console.log("curate: skill telemetry is enabled \u2014 ready to curate"),0):(console.error(i.message),2)}async function MNn(n,a){let i=fx(n.flags),d=await vj(i);if(!d.ok)return console.error(d.message),2;let b;try{b=await fot(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{candidates:h,byCategory:y,filtered:w}=Vwe(b);return console.log(JSON.stringify({candidates:h,byCategory:y,filtered:w,totals:{totalSkills:b.totalSkills,curatableSkills:b.curatableSkills,readOnlySkills:b.readOnlySkills}},null,2)),0}async function BNn(n,a){let i=fx(n.flags),d=await vj(i);if(!d.ok)return console.error(d.message),2;let b;try{b=await fot(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{byCategory:h}=Vwe(b);if(gwe(h)===0)return console.error("curate: no candidates \u2014 no issue filed"),0;let y=typeof n.flags.label=="string"?n.flags.label:void 0,w=await yot({byCategory:h,totals:{totalSkills:b.totalSkills,curatableSkills:b.curatableSkills,readOnlySkills:b.readOnlySkills},generatedAt:b.generatedAt},{cwd:i,label:y});return console.log(`curate: filed background issue \u2014 ${w.output||w.title}`),0}async function SNn(n){let a=fx(n.flags),i=await vj(a);if(!i.ok)return console.error(i.message),2;let d=n.flags.candidate;if(typeof d!="string")return console.error("curate archive: --candidate <json> is required"),2;let b;try{b=JSON.parse(d)}catch(y){return console.error(`curate archive: invalid --candidate JSON: ${y.message}`),2}let h=await Not(b,{rootDir:a,archiveDir:Xot(n.flags)});return h.ok?(console.log(`curate: archived "${h.receipt.name}" \u2192 ${h.receipt.archiveRoot} (${h.receipt.files.length} file(s), manifest at ${h.receipt.manifestPath})`),0):(console.error(`curate archive: refused \u2014 ${h.rejection.reason}: ${h.rejection.detail}`),3)}async function TNn(n){let a=fx(n.flags),i=await vj(a);if(!i.ok)return console.error(i.message),2;let d=n.positional[0];if(!d)return console.error("curate restore: skill name is required"),2;let b=await Yot(d,{rootDir:a,archiveDir:Xot(n.flags)});return console.log(`curate: restored "${b.name}" \u2192 ${b.restoredRoot} (${b.files.length} file(s) hash-verified)`),0}async function wot(n,a={}){switch(n.command){case"check":return UNn(n);case"list":return MNn(n,a);case"background":return BNn(n,a);case"archive":return SNn(n);case"restore":return TNn(n);case void 0:case"--help":case"-h":return console.log(Fot(a.usageCommand)),0;default:return console.error(`unknown curate subcommand: ${n.command}
6565
6565
 
6566
- ${Fot(a.usageCommand)}`),2}}function Hot(n){let a={app:n,version:jNn(wx("__RED_BUILD_VERSION__",()=>"2.55.2")??"0.0.0-dev"),gitSha:wx("__RED_BUILD_GIT_SHA__",()=>"c2bbfd6d644ae033e4d5d012f98a7e0a9407a76c")??"unknown",buildTime:wx("__RED_BUILD_TIME__",()=>"2026-07-13T23:33:42-03:00")??"unknown",bundleAsset:wx("__RED_BUNDLE_ASSET__",()=>"memory.bundle.min.mjs")??"unknown"},i=wx("__REDDB_SDK_VERSION__",()=>"1.23.1"),d=wx("__REDDB_BINARY_TAG__",()=>"v1.23.1");return i&&(a.reddbSdkVersion=i),d&&(a.reddbBinaryTag=d),a}function jNn(n){return n.startsWith("v")?n.slice(1):n}function Qot(n){return`${n.app} ${n.version} ${n.gitSha}`}function wx(n,a){try{let i=a();return typeof i=="string"&&i.length>0?i:void 0}catch{return process.env[n.replace(/^__|__$/g,"")]}}var Eot=`memory \u2014 governed operational memory for code agents
6566
+ ${Fot(a.usageCommand)}`),2}}function Hot(n){let a={app:n,version:jNn(wx("__RED_BUILD_VERSION__",()=>"2.55.3")??"0.0.0-dev"),gitSha:wx("__RED_BUILD_GIT_SHA__",()=>"15be4622f2ef4c460ff55365d4731f90d6f2d570")??"unknown",buildTime:wx("__RED_BUILD_TIME__",()=>"2026-07-13T23:50:13-03:00")??"unknown",bundleAsset:wx("__RED_BUNDLE_ASSET__",()=>"memory.bundle.min.mjs")??"unknown"},i=wx("__REDDB_SDK_VERSION__",()=>"1.23.1"),d=wx("__REDDB_BINARY_TAG__",()=>"v1.23.1");return i&&(a.reddbSdkVersion=i),d&&(a.reddbBinaryTag=d),a}function jNn(n){return n.startsWith("v")?n.slice(1):n}function Qot(n){return`${n.app} ${n.version} ${n.gitSha}`}function wx(n,a){try{let i=a();return typeof i=="string"&&i.length>0?i:void 0}catch{return process.env[n.replace(/^__|__$/g,"")]}}var Eot=`memory \u2014 governed operational memory for code agents
6567
6567
 
6568
6568
  Common workflows:
6569
6569
  remember one fact memory store "Decision: ..."
@@ -25,8 +25,8 @@ var yc=Object.defineProperty;var S=(e,t)=>()=>(e&&(t=e(e=0)),t);var D=(e,t)=>{fo
25
25
 
26
26
  `)){let l=u.split(`
27
27
  `).find(d=>d.startsWith("data: "));l&&(yield JSON.parse(l.slice(6)))}}watchPrefix(t,n={}){return this.watch(`${t}.*`,n)}}});function Zl(e,t,n){let{waitMs:r,group:i=null,count:s=null}=n??{};if(!Number.isInteger(r)||r<0)throw new h("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let o=ae(e),a=ae(t),c=i!=null?` GROUP ${ae(i)}`:"",u=s!=null?mr(s):"";return`QUEUE READ ${o}${c} CONSUMER ${a}${u} WAIT ${r}ms`}function ae(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new h("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function mr(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new h("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function ed(e){if(!Number.isInteger(e))throw new h("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function td(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new h("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${ed(e.priority)}`),e.key!=null&&(t+=` KEY ${pr(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${pr(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function nd(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?pr(e):JSON.stringify(e)}function pr(e){return`'${String(e).replace(/'/g,"''")}'`}function fr(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Rt,gr=S(()=>{he();Rt=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${ae(t)}`})}push(t,n,r={}){let i=td(r);return this.client.call("query",{sql:`QUEUE PUSH ${ae(t)} ${nd(n)}${i}`})}async pop(t,n){let r=await this.client.call("query",{sql:`QUEUE POP ${ae(t)}${mr(n)}`});return fr(r)}async peek(t,n){let r=await this.client.call("query",{sql:`QUEUE PEEK ${ae(t)}${mr(n)}`});return fr(r)}async len(t){let n=await this.client.call("query",{sql:`QUEUE LEN ${ae(t)}`});return Number(n?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${ae(t)}`})}async readWait(t,n,r={}){let i=Zl(t,n,r),s=await this.client.call("query",{sql:i});return fr(s)}}});function Xs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new h("INVALID_ARGUMENT",`${t} must be an object`)}function rd(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new h("INVALID_ARGUMENT","limit must be a positive integer");return e}function cn(e){return String(e).split(".").map(Zs).join(".")}function Zs(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new h("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function id(e){return eo(JSON.stringify(e))}function sd(e){return JSON.stringify(e)}function od(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?id(e):eo(e)}function eo(e){return`'${String(e).replace(/'/g,"''")}'`}var Et,yr=S(()=>{he();Et=class{constructor(t){this.db=t}async insert(t,n){Xs(n,"documents.insert document"),await this.ensureCollection(t);let r=await this.db.query(`INSERT INTO ${cn(t)} DOCUMENT VALUES (${sd(n)}) RETURNING *`),i=r.rows?.[0];if(!i||i.rid==null)throw new h("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:r.affected??1,rid:i.rid,item:i}}async get(t,n){let r=await this.db.get(t,n);if(!r.entity)throw new h("NOT_FOUND",`document ${String(n)} was not found`);return r.entity}async list(t,n={}){let r=rd(n.limit),i=n.orderBy??n.order_by??"rid ASC",s=n.filter?` WHERE ${String(n.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${cn(t)}${s} ORDER BY ${i} LIMIT ${r}`)).rows??[]}}async patch(t,n,r){Xs(r,"documents.patch patch");let i=Object.entries(r);if(i.length===0)throw new h("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of i)if(c.includes("/"))throw new h("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let s=i.map(([c,u])=>`${Zs(c)} = ${od(u)}`).join(", "),a=(await this.db.query(`UPDATE ${cn(t)} SET ${s} WHERE rid = $1 RETURNING *`,n)).rows?.[0];if(!a)throw new h("NOT_FOUND",`document ${String(n)} was not found`);return a}async delete(t,n){let i=(await this.db.delete(t,n)).affected??0;return{affected:i,deleted:i>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${cn(t)}`)}catch(n){if(!String(n?.message??"").includes("already exists"))throw n}}}});function ad(e,t){if(t.secretRef){let{collection:n,key:r}=t.secretRef;return`SECRET_REF(vault, ${we(n)}.${we(r)})`}return ud(e)}function cd(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function we(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function ud(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):to(e)}function to(e){return`'${String(e).replace(/'/g,"''")}'`}var kt,hr=S(()=>{kt=class{constructor(t,n="red.config"){this.client=t,this.collection=n}put(t,n,r={}){cd(r,"config");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(to).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${we(i)} ${we(t)} = ${ad(n,r)}${s}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${we(r)} ${we(t)}`})}resolve(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${we(r)} ${we(t)}`})}}});function ld(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function Qe(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function dd(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):no(e)}function no(e){return`'${String(e).replace(/'/g,"''")}'`}var St,wr=S(()=>{St=class{constructor(t,n="red.vault"){this.client=t,this.collection=n}put(t,n,r={}){ld(r,"vault");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(no).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${Qe(i)}.${Qe(t)} = ${dd(n)}${s}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${Qe(r)}.${Qe(t)}`})}unseal(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${Qe(r)}.${Qe(t)}`})}}});async function io(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(fd)}async function so(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${pd(t)}`)).rows??[]).some(r=>r.name===String(t))}function fd(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function ro(e){return String(e).split(".").map(md).join(".")}function md(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new h("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function pd(e){return`'${String(e).replace(/'/g,"''")}'`}var vt,br=S(()=>{he();vt=class e{constructor(t,n,r=null,i=[],s=[]){this.db=t,this.collection=n,this.columns=r,this.whereClauses=i,this.params=s}select(...t){let n=t.length===1&&Array.isArray(t[0])?t[0]:t,r=n.length===1&&n[0]==="*"?null:n;return new e(this.db,this.collection,r!=null&&r.length>0?r:null,this.whereClauses,this.params)}where(t,...n){if(typeof t!="string"||t.trim().length===0)throw new h("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...r])}async run(){let t=this.columns==null?"*":this.columns.map(ro).join(", "),n=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(o=>`(${o})`).join(" AND ")}`:"",r=`SELECT ${t} FROM ${ro(this.collection)}${n}`,s=(this.params.length>0?await this.db.query(r,this.params):await this.db.query(r)).rows??[];return this.columns==null?s:s.map(o=>{let a={};for(let c of this.columns)a[c]=o[c];return a})}}});async function uo(e,t={}){let n=or(e);if(Sd(n),n.kind==="embedded"){let r=kd(n,t.auth);if(r.token||r.username)throw new h("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let i=Ed(n),s=t.binary??Ks(),o=await qs(s,i),a=new an(o);return await a.call("version",{}),new Rr(a,{transport:"embedded"})}}function ao(e){return hd(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:bd(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&Rd(e)?{$uuid:e}:e}function hd(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new h("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new h("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new h("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function wd(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(ao):e.map(ao)}function bd(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function _d(e){if(typeof Buffer<"u"){let r=Buffer.from(e,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Rd(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function un(e){if(Array.isArray(e))return e.map(un);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return _d(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let r=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(r/1000000n))}}let n={};for(let[r,i]of Object.entries(e))n[r]=un(i);return n}return e}function Ed(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function kd(e,t){let n={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return n;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");n.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");n.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");n.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");n.password=t.password}return t.loginUrl!=null&&(n.loginUrl=t.loginUrl),n}function Sd(e){if(e.kind!=="embedded")throw new h("EMBEDDED_ONLY",gd)}function Er(){return new h(oo,`${oo}: nested transactions are not supported on one connection`)}function lo(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function vd(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new h("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${co} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function Td(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new h("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${co} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new h("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}var gd,yd,co,oo,ln,_r,Rr,fo=S(()=>{Vs();zs();he();ar();cr();dr();gr();yr();hr();wr();br();cr();dr();gr();yr();hr();wr();br();ar();gd="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",yd="1.0",co="1.0.9",oo="NESTED_TX_NOT_SUPPORTED";ln=class{constructor(t){this.db=t}query(t,...n){return this.db.query(t,...n)}execute(t,...n){return this.db.execute(t,...n)}insert(t,n){return this.db.insert(t,n)}bulkInsert(t,n){return this.db.bulkInsert(t,n)}async transaction(){throw Er()}},_r=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Er();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new h("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new h("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new h("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let n=await t(new ln(this.db));return await this.commit(),n}catch(n){if(this.active)try{await this.rollback()}catch(r){lo(n,r)}throw n}}},Rr=class{constructor(t,n={}){this.client=t,this.transport=n.transport??null,this.helperSpecVersion=yd,this.cache=new _t(t,this.transport),this.queue=new Rt(t),this.queues=this.queue,this.documents=new Et(this);let r=new Ye(t);this.kv=Object.assign((i="kv_default")=>new Ye(t,i),{put:r.put.bind(r),invalidateTags:r.invalidateTags.bind(r),watch:r.watch.bind(r),watchPrefix:r.watchPrefix.bind(r)}),this.config=(i="red.config")=>new kt(t,i),this.vault=(i="red.vault")=>new St(t,i),this.inTransaction=!1}query(t,...n){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new h("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let r=wd(n);return r==null?this.client.call("query",{sql:t}).then(un):this.client.call("query",{sql:t,params:r}).then(un)}execute(t,...n){return this.query(t,...n)}async insert(t,n){let r=await this.client.call("insert",{collection:t,payload:n});return vd(r,"insert")}async bulkInsert(t,n){if(Array.isArray(n)&&n.length===0)return{affected:0,rids:[],ids:[]};let r=await this.client.call("bulk_insert",{collection:t,payloads:n});return Td(r,n.length)}tx(){return new _r(this)}async transaction(t){if(this.inTransaction)throw Er();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let n=!1;try{await this.query("BEGIN"),n=!0;let r=await t(new ln(this));return await this.query("COMMIT"),r}catch(r){if(n)try{await this.query("ROLLBACK")}catch(i){lo(r,i)}throw r}finally{this.inTransaction=!1}}exists(t){return so(this,t)}list(){return io(this)}from(t){return new vt(this,t)}get(t,n){return this.client.call("get",{collection:t,id:String(n)})}delete(t,n){return this.client.call("delete",{collection:t,id:String(n)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,n){return this.client.call("auth.login",{username:t,password:n})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,n){return this.client.call("auth.change_password",{current_password:t,new_password:n})}createApiKey({username:t,role:n}={}){return this.client.call("auth.create_api_key",{username:t,role:n})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}}});var xr={};D(xr,{DEFAULT_RSP_BYTE_BUDGET:()=>oe,DEFAULT_RSP_TTL_DAYS:()=>se,RSP_ELISION_COLLECTION:()=>L,RspElisionStore:()=>Tt});import{createHash as yo}from"node:crypto";import{existsSync as xd}from"node:fs";import{mkdir as Od,readFile as vr,readdir as ho,rename as Pd,writeFile as Dd}from"node:fs/promises";import{homedir as $d}from"node:os";import{basename as Tr,dirname as wo,join as Xe}from"node:path";import{fileURLToPath as Id}from"node:url";function mo(e,t){return`el:${yo("sha256").update("rsp-elision-v1\0").update(e).update("\0").update(JSON.stringify({command:t.command,loss:t.loss})).digest("hex").slice(0,12)}`}function ce(e){return`record:${e.slice(3)}`}function Ie(e){return`expired:${e.slice(3)}`}function kr(){return"index:v1"}function xt(e){return/^el:[a-f0-9]{12}$/.test(e)}function Ad(e){if(!et(e))throw new Error("memory recall payload must be an object");let t=e.query;if(typeof t!="string"||t.trim()==="")throw new Error("memory recall query is required");let n=typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:10;return{query:t,limit:n,options:{includeSuperseded:e.includeSuperseded===!0,scope:et(e.scope)?e.scope:void 0,ranking:et(e.ranking)?e.ranking:void 0}}}function Nd(e){if(!et(e))throw new Error("memory ingest payload must be an object");let t=e.cwd;if(typeof t!="string"||t.trim()==="")throw new Error("memory ingest cwd is required");let n=typeof e.maxFiles=="number"&&Number.isFinite(e.maxFiles)?e.maxFiles:void 0,r=Array.isArray(e.ignore)?e.ignore.filter(i=>typeof i=="string"):void 0;return{cwd:t,maxFiles:n,ignore:r}}function et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bd(e){return et(e)?typeof e.key=="string"&&e.key.trim()!==""?{key:e.key,value:dn(e.value)}:typeof e.record_key=="string"&&e.record_key.trim()!==""?{key:e.record_key,value:dn(e.value)}:Ze(e)?{key:ce(e.handle),value:e}:fn(e)&&typeof e.handle=="string"&&xt(e.handle)?{key:Ie(e.handle),value:e}:null:null}function dn(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}async function Ld(e,t,n){let r=[],i=new Set([".git","node_modules",".red",...n]);async function s(o){if(r.length>=t)return;let a=await ho(o,{withFileTypes:!0}).catch(()=>[]);for(let c of a){if(r.length>=t)return;if(i.has(c.name))continue;let u=Xe(o,c.name);c.isDirectory()?await s(u):c.isFile()&&/\.(md|mdx|txt|ts|tsx|js|jsx|json|yaml|yml|toml|rs|go|py|sql)$/i.test(c.name)&&r.push(u)}}return await s(e),r}function Cd(e,t){let n=Number(e.red_entity_id??e.rid);if(!Number.isFinite(n))return null;let r=e.properties??e.PROPERTIES,i=et(r)?r:{},s=String(e.label??e.LABEL??i.title??`memory-${n}`),o=String(e.node_type??e.NODE_TYPE??"concept"),a=String(i.content??i.summary??i.title??s),c=`${s} ${a}`.toLowerCase(),u=t.filter(l=>c.includes(l));return u.length===0&&t.length>0?null:{id:String(n),rid:n,label:s,node_type:o,score:u.length||1,excerpt:a.slice(0,500)}}function po(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Ze(e){return be(e)?e.collection===L&&typeof e.handle=="string"&&xt(e.handle)&&typeof e.original=="string"&&e.original_encoding==="base64"&&typeof e.original_bytes=="number"&&typeof e.command=="string"&&typeof e.created_at=="string"&&typeof e.expires_at=="string"&&Md(e.loss):!1}function Sr(e){return!be(e)||e.version!==1||!Array.isArray(e.records)?!1:e.records.every(t=>be(t)&&typeof t.handle=="string"&&xt(t.handle)&&typeof t.key=="string"&&typeof t.bytes=="number"&&typeof t.command=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string")}function fn(e){return be(e)&&e.status==="expired"&&typeof e.expired_at=="string"&&typeof e.command=="string"}function Md(e){return be(e)&&typeof e.level=="string"&&typeof e.bytes_elided=="number"}function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function jd(e){try{let t=await vr(e,"utf8");if(t.trim()==="")return go();let n=JSON.parse(t);if(qd(n))return n}catch(t){if(t.code==="ENOENT"){let n=go();return await _o(e,n),n}throw t}throw new Error("rsp elision store is unreadable")}async function Ud(e){try{let t=await vr(e);return bo(e)?e:Gd(t)?Fd(e):e}catch(t){if(t.code==="ENOENT")return e;throw t}}function Gd(e){return e.subarray(0,8).toString("ascii")==="RDBSBLK1"}function Fd(e){return Tr(e)==="red.rdb"?Xe(wo(e),"tmp","rsp-elisions.json"):`${e}.json`}function bo(e){return Tr(e)==="red-skills.rdb"}async function Jd(){if(process.env.REDDB_BIN)return;let e=process.env.RED_SKILLS_CACHE_DIR??(process.env.XDG_CACHE_HOME?Xe(process.env.XDG_CACHE_HOME,"red-skills","bundles"):Xe($d(),".cache","red-skills","bundles")),t=Xe(e,"reddb"),n;try{n=await ho(t)}catch{return}n.sort().reverse();for(let r of n){let i=Xe(t,r,process.platform==="win32"?"red.exe":"red");if(xd(i)){process.env.REDDB_BIN=i;return}}}async function _o(e,t){await Od(wo(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await Dd(n,`${JSON.stringify(t)}
28
- `,"utf8"),await Pd(n,e)}function go(){return{version:1,records:{},tombstones:{},index:{version:1,records:[]}}}function qd(e){return be(e)&&e.version===1&&be(e.records)&&Object.values(e.records).every(Ze)&&be(e.tombstones)&&Object.values(e.tombstones).every(fn)&&Sr(e.index)}function Vd(e){if(!e.startsWith("file://"))throw new Error("rsp elision store requires a file:// URI");return Id(e)}var L,Tt,mn=S(()=>{"use strict";fo();K();L="rsp_elisions_v1",Tt=class e{constructor(t,n){this.opts=n;this.path=t}document;db;path;static async open(t){if(process.env.RSP_FAIL_IF_STORE_OPEN==="1"&&!t.allowResidentOpen)throw new Error("RSP_FAIL_IF_STORE_OPEN blocked store open");let n=Vd(t.uri),r=await Ud(n),i=new e(r,{uri:t.uri,ttlDays:po(t.ttlDays,se),byteBudget:po(t.byteBudget,oe),now:t.now??(()=>new Date)});return bo(r)?(await Jd(),i.db=await uo(`file://${r}`),await i.ensureRedDbCollections(),await i.ensureRedDbStore()):i.document=await jd(i.path),i}async close(){await this.db?.close()}redDb(){return this.db}async mint(t,n){if(this.db)return await this.mintRedDb(t,n);let r=Buffer.from(t),i=this.opts.now(),s=i.toISOString(),o=new Date(i.getTime()+this.opts.ttlDays*24*60*60*1e3).toISOString(),a=mo(r,n),c=ce(a),u={collection:L,handle:a,original:r.toString("base64"),original_encoding:"base64",original_bytes:r.length,command:n.command,created_at:s,expires_at:o,loss:n.loss};return delete this.document.tombstones[Ie(a)],this.document.records[c]=u,this.upsertIndex({handle:a,key:c,bytes:r.length,command:n.command,created_at:s,expires_at:o}),this.prune(),await this.flush(),a}async get(t){if(this.db)return await this.getRedDb(t);if(!xt(t))return null;let n=this.tombstone(t);if(n)return n;let r=this.document.records[ce(t)];if(!Ze(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return this.expireEntry({handle:r.handle,key:ce(r.handle),bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at},r.expires_at),await this.flush(),s}let i=this.readOriginal(r);return i?{collection:L,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss}:null}async stats(){if(this.db)return await this.statsRedDb();this.prune(),await this.flush();let n=this.readIndex().records;return{records:n.length,bytes:n.reduce((r,i)=>r+i.bytes,0),oldest:n.reduce((r,i)=>r==null||i.created_at<r?i.created_at:r,null),budget:this.opts.byteBudget}}readIndex(){return this.document.index}writeIndex(t){this.document.index=t}upsertIndex(t){let r=this.readIndex().records.filter(i=>i.handle!==t.handle);r.push(t),this.writeIndex({version:1,records:r})}prune(){let t=this.opts.now().getTime(),n=new Date(t).toISOString(),r=this.readIndex(),i=[];for(let o of r.records)Date.parse(o.expires_at)<=t?this.expireEntry(o,o.expires_at):i.push(o);let s=i.reduce((o,a)=>o+a.bytes,0);for(i.sort((o,a)=>o.created_at.localeCompare(a.created_at));s>this.opts.byteBudget&&i.length>0;){let o=i.shift();s-=o.bytes,this.expireEntry(o,n)}this.writeIndex({version:1,records:i})}expireEntry(t,n){delete this.document.records[t.key],this.document.tombstones[Ie(t.handle)]={status:"expired",expired_at:n,command:t.command}}tombstone(t){let n=this.document.tombstones[Ie(t)];return fn(n)?n:null}readOriginal(t){return t.original?Buffer.from(t.original,"base64"):null}async flush(){await _o(this.path,this.document)}kv(){if(!this.db)throw new Error("rsp RedDB store is not open");return this.db.kv(L)}async kvGet(t){let n=await this.kv().get(t);if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}async ensureRedDbStore(){let t=await this.readRedDbIndex();await this.writeRedDbIndex(t)}async ensureRedDbCollections(){if(!this.db)throw new Error("rsp RedDB store is not open");let t=(await this.db.list()).find(r=>r.name===L);if(!t){await this.db.query(`CREATE KV IF NOT EXISTS ${L}`);return}if(t.model==="kv")return;if(t.model!=="table")throw new Error(`cannot self-heal elision collection ${L}: unsupported model ${t.model}`);let n=await this.readLegacyElisionTableRows();await this.db.query(`DROP TABLE ${L}`),await this.db.query(`CREATE KV IF NOT EXISTS ${L}`);for(let r of n)await this.kv().put(r.key,r.value);await this.ensureMigratedRedDbIndex(n)}async readLegacyElisionTableRows(){if(!this.db)throw new Error("rsp RedDB store is not open");let t=await this.db.query(`SELECT * FROM ${L}`),n=[];for(let r of t.rows){let i=Bd(r);i&&n.push(i)}return n}async ensureMigratedRedDbIndex(t){if(t.some(i=>i.key===kr()&&Sr(dn(i.value))))return;let r=t.map(i=>{let s=dn(i.value);return Ze(s)?{handle:s.handle,key:ce(s.handle),bytes:s.original_bytes,command:s.command,created_at:s.created_at,expires_at:s.expires_at}:null}).filter(i=>i!=null);await this.writeRedDbIndex({version:1,records:r})}async mintRedDb(t,n){let r=Buffer.from(t),i=this.opts.now(),s=i.toISOString(),o=new Date(i.getTime()+this.opts.ttlDays*24*60*60*1e3).toISOString(),a=mo(r,n),c=ce(a),u={collection:L,handle:a,original:r.toString("base64"),original_encoding:"base64",original_bytes:r.length,command:n.command,created_at:s,expires_at:o,loss:n.loss};await this.kv().delete(Ie(a)),await this.kv().put(c,u);let d=(await this.readRedDbIndex()).records.filter(m=>m.handle!==a);return d.push({handle:a,key:c,bytes:r.length,command:n.command,created_at:s,expires_at:o}),await this.pruneRedDb({version:1,records:d}),await this.assertRedDbMintPersisted(a,r.length),a}async getRedDb(t){if(!xt(t))return null;let n=await this.kvGet(Ie(t));if(fn(n))return n;let r=await this.kvGet(ce(t));if(!Ze(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return await this.expireRedDbEntry({handle:r.handle,key:ce(r.handle),bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at},r.expires_at),s}let i=this.readOriginal(r);return i?{collection:L,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss}:null}async statsRedDb(){let t=await this.pruneRedDb(await this.readRedDbIndex());return{records:t.records.length,bytes:t.records.reduce((n,r)=>n+r.bytes,0),oldest:t.records.reduce((n,r)=>n==null||r.created_at<n?r.created_at:n,null),budget:this.opts.byteBudget}}async memory(t,n){if(!this.db)throw new Error("resident memory operations require the shared RedDB store");if(await this.ensureMemoryGraphStore(),t==="recall"){let r=Ad(n);return await this.memoryRecallRedDb(r.query,r.limit)}if(t==="ingest"){let r=Nd(n);return await this.memoryIngestRedDb(r)}throw new Error(`unsupported memory action: ${t}`)}async ensureMemoryGraphStore(){if(!this.db)throw new Error("rsp RedDB store is not open");await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_nodes"),await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_edges")}async memoryIngestRedDb(t){if(!this.db)throw new Error("rsp RedDB store is not open");let n=await Ld(t.cwd,t.maxFiles??200,t.ignore??[]),r=0;for(let i of n){let o=(await vr(i,"utf8").catch(()=>"")).trim();if(!o)continue;let a=Tr(i),c=yo("sha256").update("resident-memory-v1\0").update(i).update("\0").update(o).digest("hex");if(await this.db.kv("memory_kv").get(`resident-node-hash:${c}`)!=null)continue;let u=Date.now(),l={title:a,content:o,source:i,confidence:"EXTRACTED",hash:c,project:"default",scope:"project",importance:1,tier:"durable",provenance_tier:"oracle",created_at:u,updated_at:u,accessed_at:u,access_count:0,provenance:{source_kind:"system",writer:"rsp-resident",confidence:"EXTRACTED",evidence:[i],created_at:u,updated_at:u}},d=await this.db.query("INSERT INTO memory_nodes NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *",a,"concept",c,l),m=Number(d.rows[0]?.red_entity_id??d.rows[0]?.rid);Number.isFinite(m)&&await this.db.kv("memory_kv").put(`resident-node-hash:${c}`,m),r+=1}return{files:n.length,nodes:r,edges:0,docs:n.length,added:r,updated:0,skipped:n.length-r,stale:0,semantic:{enabled:!1,nodes:0,edges:0,token_cost:{input:0,output:0}},durationMs:0}}async memoryRecallRedDb(t,n){if(!this.db)throw new Error("rsp RedDB store is not open");let r=await this.db.query("SELECT * FROM memory_nodes"),i=t.toLowerCase().split(/\s+/).filter(Boolean),s=r.rows.map(o=>Cd(o,i)).filter(o=>o!=null).sort((o,a)=>a.score-o.score).slice(0,Math.max(1,Math.min(100,n)));return{hits:s,context_md:s.map(o=>`- memory_nodes:${o.rid} ${o.label}: ${o.excerpt}`).join(`
29
- `),diagnostics:{vector:{status:"unavailable",candidates:0,contributed:0,reason:"resident-basic-recall"}}}}async readRedDbIndex(){let t=await this.kvGet(kr());return Sr(t)?t:{version:1,records:[]}}async writeRedDbIndex(t){await this.kv().put(kr(),t)}async pruneRedDb(t){let n=this.opts.now().getTime(),r=new Date(n).toISOString(),i=[];for(let a of t.records)Date.parse(a.expires_at)<=n?await this.expireRedDbEntry(a,a.expires_at):i.push(a);let s=i.reduce((a,c)=>a+c.bytes,0);for(i.sort((a,c)=>a.created_at.localeCompare(c.created_at));s>this.opts.byteBudget&&i.length>0;){let a=i.shift();s-=a.bytes,await this.expireRedDbEntry(a,r)}let o={version:1,records:i};return await this.writeRedDbIndex(o),o}async expireRedDbEntry(t,n){await this.kv().delete(t.key),await this.kv().put(Ie(t.handle),{status:"expired",expired_at:n,command:t.command})}async assertRedDbMintPersisted(t,n){let r=await this.kvGet(ce(t));if(!Ze(r))throw new Error(`rsp resident failed to persist elision record ${t}`);let s=(await this.readRedDbIndex()).records.find(o=>o.handle===t);if(!s||s.bytes!==n)throw new Error(`rsp resident failed to persist elision index ${t}`)}}});var Oo={};D(Oo,{REPO_STORE_PATH:()=>Pr,mergeRspBlock:()=>vo,provisionRspRepoStore:()=>Zd});import{constants as Wd}from"node:fs";import{access as Hd,copyFile as Kd,mkdir as Ro,readFile as zd,writeFile as Eo}from"node:fs/promises";import{dirname as Yd,join as pn,resolve as Qd}from"node:path";async function Zd(e,t={}){let n=Qd(e),r=pn(n,".red"),i=pn(r,"config.yaml"),s=pn(n,Pr);await Ro(r,{recursive:!0}),await Ro(Yd(s),{recursive:!0});let o="";try{o=await zd(i,"utf8")}catch(m){if(m.code!=="ENOENT")throw m}let a=vo(o,{enabled:!0,ttlDays:t.ttlDays??se,byteBudget:t.byteBudget??oe,heavyGitByteThreshold:t.heavyGitByteThreshold??ie}),c=a!==o;c&&await Eo(i,a,"utf8");let u=!await So(s),l=!1;if(u){let m=pn(n,Xd);if(await So(m))await Kd(m,s),l=!0;else{let{RspElisionStore:b}=await Promise.resolve().then(()=>(mn(),xr)),_=process.env.REDDB_BIN;try{await(await b.open({uri:`file://${s}`,ttlDays:t.ttlDays??se,byteBudget:t.byteBudget??oe,allowResidentOpen:!0})).close()}finally{_===void 0?delete process.env.REDDB_BIN:process.env.REDDB_BIN=_}}}let d=ef(a,Pr);return d!==a&&await Eo(i,d,"utf8"),{configPath:i,storePath:s,configChanged:c||d!==a,storeCreated:u,memoryStoreMigrated:l}}function vo(e,t){let n=["rsp:",` enabled: ${t.enabled?"true":"false"}`,` ttlDays: ${Or(t.ttlDays,se)}`,` byteBudget: ${Or(t.byteBudget,oe)}`,` heavyGitByteThreshold: ${Or(t.heavyGitByteThreshold,ie)}`],r=e===""?[]:e.replace(/\n+$/,"").split(`
28
+ `,"utf8"),await Pd(n,e)}function go(){return{version:1,records:{},tombstones:{},index:{version:1,records:[]}}}function qd(e){return be(e)&&e.version===1&&be(e.records)&&Object.values(e.records).every(Ze)&&be(e.tombstones)&&Object.values(e.tombstones).every(fn)&&Sr(e.index)}function Vd(e){if(!e.startsWith("file://"))throw new Error("rsp elision store requires a file:// URI");return Id(e)}var L,Tt,mn=S(()=>{"use strict";fo();K();L="rsp_elisions_v1",Tt=class e{constructor(t,n){this.opts=n;this.path=t}document;db;path;dirty=!1;static async open(t){if(process.env.RSP_FAIL_IF_STORE_OPEN==="1"&&!t.allowResidentOpen)throw new Error("RSP_FAIL_IF_STORE_OPEN blocked store open");let n=Vd(t.uri),r=await Ud(n),i=new e(r,{uri:t.uri,ttlDays:po(t.ttlDays,se),byteBudget:po(t.byteBudget,oe),now:t.now??(()=>new Date)});return bo(r)?(await Jd(),i.db=await uo(`file://${r}`),await i.ensureRedDbCollections(),await i.ensureRedDbStore()):i.document=await jd(i.path),i}async close(){await this.db?.close()}redDb(){return this.db}async mint(t,n){if(this.db)return await this.mintRedDb(t,n);let r=Buffer.from(t),i=this.opts.now(),s=i.toISOString(),o=new Date(i.getTime()+this.opts.ttlDays*24*60*60*1e3).toISOString(),a=mo(r,n),c=ce(a),u={collection:L,handle:a,original:r.toString("base64"),original_encoding:"base64",original_bytes:r.length,command:n.command,created_at:s,expires_at:o,loss:n.loss};return delete this.document.tombstones[Ie(a)],this.document.records[c]=u,this.upsertIndex({handle:a,key:c,bytes:r.length,command:n.command,created_at:s,expires_at:o}),this.prune(),await this.flush(),a}async get(t){if(this.db)return await this.getRedDb(t);if(!xt(t))return null;let n=this.tombstone(t);if(n)return n;let r=this.document.records[ce(t)];if(!Ze(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return this.expireEntry({handle:r.handle,key:ce(r.handle),bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at},r.expires_at),await this.flush(),s}let i=this.readOriginal(r);return i?{collection:L,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss}:null}async stats(){if(this.db)return await this.statsRedDb();this.prune(),await this.flush();let n=this.readIndex().records;return{records:n.length,bytes:n.reduce((r,i)=>r+i.bytes,0),oldest:n.reduce((r,i)=>r==null||i.created_at<r?i.created_at:r,null),budget:this.opts.byteBudget}}readIndex(){return this.document.index}writeIndex(t){this.document.index=t}upsertIndex(t){let r=this.readIndex().records.filter(i=>i.handle!==t.handle);r.push(t),this.writeIndex({version:1,records:r}),this.dirty=!0}prune(){let t=this.opts.now().getTime(),n=new Date(t).toISOString(),r=this.readIndex(),i=[];for(let o of r.records)Date.parse(o.expires_at)<=t?this.expireEntry(o,o.expires_at):i.push(o);let s=i.reduce((o,a)=>o+a.bytes,0);for(i.sort((o,a)=>o.created_at.localeCompare(a.created_at));s>this.opts.byteBudget&&i.length>0;){let o=i.shift();s-=o.bytes,this.expireEntry(o,n)}i.length<r.records.length&&this.writeIndex({version:1,records:i})}expireEntry(t,n){delete this.document.records[t.key],this.document.tombstones[Ie(t.handle)]={status:"expired",expired_at:n,command:t.command},this.dirty=!0}tombstone(t){let n=this.document.tombstones[Ie(t)];return fn(n)?n:null}readOriginal(t){return t.original?Buffer.from(t.original,"base64"):null}async flush(){this.dirty&&(await _o(this.path,this.document),this.dirty=!1)}kv(){if(!this.db)throw new Error("rsp RedDB store is not open");return this.db.kv(L)}async kvGet(t){let n=await this.kv().get(t);if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}async ensureRedDbStore(){let t=await this.readRedDbIndex();await this.writeRedDbIndex(t)}async ensureRedDbCollections(){if(!this.db)throw new Error("rsp RedDB store is not open");let t=(await this.db.list()).find(r=>r.name===L);if(!t){await this.db.query(`CREATE KV IF NOT EXISTS ${L}`);return}if(t.model==="kv")return;if(t.model!=="table")throw new Error(`cannot self-heal elision collection ${L}: unsupported model ${t.model}`);let n=await this.readLegacyElisionTableRows();await this.db.query(`DROP TABLE ${L}`),await this.db.query(`CREATE KV IF NOT EXISTS ${L}`);for(let r of n)await this.kv().put(r.key,r.value);await this.ensureMigratedRedDbIndex(n)}async readLegacyElisionTableRows(){if(!this.db)throw new Error("rsp RedDB store is not open");let t=await this.db.query(`SELECT * FROM ${L}`),n=[];for(let r of t.rows){let i=Bd(r);i&&n.push(i)}return n}async ensureMigratedRedDbIndex(t){if(t.some(i=>i.key===kr()&&Sr(dn(i.value))))return;let r=t.map(i=>{let s=dn(i.value);return Ze(s)?{handle:s.handle,key:ce(s.handle),bytes:s.original_bytes,command:s.command,created_at:s.created_at,expires_at:s.expires_at}:null}).filter(i=>i!=null);await this.writeRedDbIndex({version:1,records:r})}async mintRedDb(t,n){let r=Buffer.from(t),i=this.opts.now(),s=i.toISOString(),o=new Date(i.getTime()+this.opts.ttlDays*24*60*60*1e3).toISOString(),a=mo(r,n),c=ce(a),u={collection:L,handle:a,original:r.toString("base64"),original_encoding:"base64",original_bytes:r.length,command:n.command,created_at:s,expires_at:o,loss:n.loss};await this.kv().delete(Ie(a)),await this.kv().put(c,u);let d=(await this.readRedDbIndex()).records.filter(m=>m.handle!==a);return d.push({handle:a,key:c,bytes:r.length,command:n.command,created_at:s,expires_at:o}),await this.pruneRedDb({version:1,records:d},!0),await this.assertRedDbMintPersisted(a,r.length),a}async getRedDb(t){if(!xt(t))return null;let n=await this.kvGet(Ie(t));if(fn(n))return n;let r=await this.kvGet(ce(t));if(!Ze(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return await this.expireRedDbEntry({handle:r.handle,key:ce(r.handle),bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at},r.expires_at),s}let i=this.readOriginal(r);return i?{collection:L,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss}:null}async statsRedDb(){let t=await this.pruneRedDb(await this.readRedDbIndex());return{records:t.records.length,bytes:t.records.reduce((n,r)=>n+r.bytes,0),oldest:t.records.reduce((n,r)=>n==null||r.created_at<n?r.created_at:n,null),budget:this.opts.byteBudget}}async memory(t,n){if(!this.db)throw new Error("resident memory operations require the shared RedDB store");if(await this.ensureMemoryGraphStore(),t==="recall"){let r=Ad(n);return await this.memoryRecallRedDb(r.query,r.limit)}if(t==="ingest"){let r=Nd(n);return await this.memoryIngestRedDb(r)}throw new Error(`unsupported memory action: ${t}`)}async ensureMemoryGraphStore(){if(!this.db)throw new Error("rsp RedDB store is not open");await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_nodes"),await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_edges")}async memoryIngestRedDb(t){if(!this.db)throw new Error("rsp RedDB store is not open");let n=await Ld(t.cwd,t.maxFiles??200,t.ignore??[]),r=0;for(let i of n){let o=(await vr(i,"utf8").catch(()=>"")).trim();if(!o)continue;let a=Tr(i),c=yo("sha256").update("resident-memory-v1\0").update(i).update("\0").update(o).digest("hex");if(await this.db.kv("memory_kv").get(`resident-node-hash:${c}`)!=null)continue;let u=Date.now(),l={title:a,content:o,source:i,confidence:"EXTRACTED",hash:c,project:"default",scope:"project",importance:1,tier:"durable",provenance_tier:"oracle",created_at:u,updated_at:u,accessed_at:u,access_count:0,provenance:{source_kind:"system",writer:"rsp-resident",confidence:"EXTRACTED",evidence:[i],created_at:u,updated_at:u}},d=await this.db.query("INSERT INTO memory_nodes NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *",a,"concept",c,l),m=Number(d.rows[0]?.red_entity_id??d.rows[0]?.rid);Number.isFinite(m)&&await this.db.kv("memory_kv").put(`resident-node-hash:${c}`,m),r+=1}return{files:n.length,nodes:r,edges:0,docs:n.length,added:r,updated:0,skipped:n.length-r,stale:0,semantic:{enabled:!1,nodes:0,edges:0,token_cost:{input:0,output:0}},durationMs:0}}async memoryRecallRedDb(t,n){if(!this.db)throw new Error("rsp RedDB store is not open");let r=await this.db.query("SELECT * FROM memory_nodes"),i=t.toLowerCase().split(/\s+/).filter(Boolean),s=r.rows.map(o=>Cd(o,i)).filter(o=>o!=null).sort((o,a)=>a.score-o.score).slice(0,Math.max(1,Math.min(100,n)));return{hits:s,context_md:s.map(o=>`- memory_nodes:${o.rid} ${o.label}: ${o.excerpt}`).join(`
29
+ `),diagnostics:{vector:{status:"unavailable",candidates:0,contributed:0,reason:"resident-basic-recall"}}}}async readRedDbIndex(){let t=await this.kvGet(kr());return Sr(t)?t:{version:1,records:[]}}async writeRedDbIndex(t){await this.kv().put(kr(),t)}async pruneRedDb(t,n=!1){let r=this.opts.now().getTime(),i=new Date(r).toISOString(),s=[];for(let c of t.records)Date.parse(c.expires_at)<=r?await this.expireRedDbEntry(c,c.expires_at):s.push(c);let o=s.reduce((c,u)=>c+u.bytes,0);for(s.sort((c,u)=>c.created_at.localeCompare(u.created_at));o>this.opts.byteBudget&&s.length>0;){let c=s.shift();o-=c.bytes,await this.expireRedDbEntry(c,i)}let a={version:1,records:s};return(n||s.length<t.records.length)&&await this.writeRedDbIndex(a),a}async expireRedDbEntry(t,n){await this.kv().delete(t.key),await this.kv().put(Ie(t.handle),{status:"expired",expired_at:n,command:t.command})}async assertRedDbMintPersisted(t,n){let r=await this.kvGet(ce(t));if(!Ze(r))throw new Error(`rsp resident failed to persist elision record ${t}`);let s=(await this.readRedDbIndex()).records.find(o=>o.handle===t);if(!s||s.bytes!==n)throw new Error(`rsp resident failed to persist elision index ${t}`)}}});var Oo={};D(Oo,{REPO_STORE_PATH:()=>Pr,mergeRspBlock:()=>vo,provisionRspRepoStore:()=>Zd});import{constants as Wd}from"node:fs";import{access as Hd,copyFile as Kd,mkdir as Ro,readFile as zd,writeFile as Eo}from"node:fs/promises";import{dirname as Yd,join as pn,resolve as Qd}from"node:path";async function Zd(e,t={}){let n=Qd(e),r=pn(n,".red"),i=pn(r,"config.yaml"),s=pn(n,Pr);await Ro(r,{recursive:!0}),await Ro(Yd(s),{recursive:!0});let o="";try{o=await zd(i,"utf8")}catch(m){if(m.code!=="ENOENT")throw m}let a=vo(o,{enabled:!0,ttlDays:t.ttlDays??se,byteBudget:t.byteBudget??oe,heavyGitByteThreshold:t.heavyGitByteThreshold??ie}),c=a!==o;c&&await Eo(i,a,"utf8");let u=!await So(s),l=!1;if(u){let m=pn(n,Xd);if(await So(m))await Kd(m,s),l=!0;else{let{RspElisionStore:b}=await Promise.resolve().then(()=>(mn(),xr)),_=process.env.REDDB_BIN;try{await(await b.open({uri:`file://${s}`,ttlDays:t.ttlDays??se,byteBudget:t.byteBudget??oe,allowResidentOpen:!0})).close()}finally{_===void 0?delete process.env.REDDB_BIN:process.env.REDDB_BIN=_}}}let d=ef(a,Pr);return d!==a&&await Eo(i,d,"utf8"),{configPath:i,storePath:s,configChanged:c||d!==a,storeCreated:u,memoryStoreMigrated:l}}function vo(e,t){let n=["rsp:",` enabled: ${t.enabled?"true":"false"}`,` ttlDays: ${Or(t.ttlDays,se)}`,` byteBudget: ${Or(t.byteBudget,oe)}`,` heavyGitByteThreshold: ${Or(t.heavyGitByteThreshold,ie)}`],r=e===""?[]:e.replace(/\n+$/,"").split(`
30
30
  `),i=To(r,"rsp");if(i===-1){let a=[...r];return a.length>0&&a[a.length-1].trim()!==""&&a.push(""),a.push(...n),`${a.join(`
31
31
  `)}
32
32
  `}let s=Dr(r,i,0);return`${[...r.slice(0,i),...n,...r.slice(s)].join(`
@@ -92,7 +92,7 @@ const timer = setInterval(() => {
92
92
  }, 500);
93
93
  `,String(process.pid)],{detached:!0,stdio:"ignore"});return t.unref(),t}function Tn(){for(let e of Wm())try{process.kill(e,"SIGTERM")}catch{}}function Wm(){if(process.platform==="win32")return[];let e="";try{e=vm("ps",["-eo","pid=,ppid=,args="],{encoding:"utf8"})}catch{return[]}let t=[];for(let n of e.split(/\n/)){let r=/^\s*(\d+)\s+(\d+)\s+([\s\S]*)$/.exec(n);if(!r)continue;let i=Number(r[1]),s=Number(r[2]),o=r[3]??"";s===process.pid&&/(^|\s)\S*red(?:\.exe)?\s+rpc\s+--stdio(\s|$)/.test(o)&&t.push(i)}return t}async function Hm(e){if(e.collection!==Re)return e;let t=await ka(e.raw_text,va(e.raw_bytes)),n=await ka(e.emitted_text,va(e.emitted_bytes)),{raw_text:r,emitted_text:i,...s}=e;return{...s,tokens_raw:t.tokens,tokens_emitted:n.tokens,estimated:t.estimated||n.estimated}}async function ka(e,t){if(typeof e=="string"){let n=Buffer.byteLength(e,"utf8");if(n<=Am)try{return await $a((async()=>({tokens:(await Km())("cl100k_base").encode(e).length,estimated:!1}))(),Nm,"telemetry tokenization timed out")}catch{return{tokens:Math.ceil(n/4),estimated:!0}}return{tokens:Math.ceil(n/4),estimated:!0}}return t!=null?{tokens:Math.ceil(t/4),estimated:!0}:{tokens:0,estimated:!1}}async function Km(){return Sa??=import($m(zm()).href).then(e=>{let t=e.getEncoding;if(!t)throw new Error("js-tiktoken getEncoding export not found");return t}),await Sa}function zm(){let e=ei(Dm(import.meta.url)),n=[At(e,"..","node_modules","js-tiktoken","dist","index.js"),At(e,"..","apps","rsp","node_modules","js-tiktoken","dist","index.js")].find(r=>xm(r));if(!n)throw new Error("js-tiktoken dependency not found");return n}function va(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function Qr(e){return typeof e=="string"&&e.trim()!==""?e:void 0}async function $a(e,t,n){let r;try{return await Promise.race([e,new Promise((i,s)=>{r=setTimeout(()=>s(new Error(n)),t),r.unref()})])}finally{r&&clearTimeout(r)}}function Ym(e){try{return JSON.parse(e)}catch{return e}}function Qm(e){return Ta(e)&&e.version===1&&Array.isArray(e.records)&&e.records.every(t=>Ta(t)&&(t.collection===Re||t.collection===Ee)&&typeof t.key=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string"&&typeof t.bytes=="number")}function Ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xm(e,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",r=>{n+=r;let i=n.indexOf(`
94
94
  `);if(i<0)return;let s=n.slice(0,i);e.pause(),(async()=>{let o;try{o=JSON.parse(s),await t(o)}catch(a){let u={id:o?.id??Xr(),ok:!1,error:a instanceof Error?a.message:String(a)};Ia(e,u)}finally{e.end()}})()})}function Ia(e,t){if(!(e.destroyed||!e.writable))try{e.write(`${JSON.stringify(t)}
95
- `)}catch{}}async function Zm(e,t,n,r){if(t.op==="handover")return{handover:!0,version:r,clientVersion:t.clientVersion};if(e.kind==="opening")throw new Error("rsp resident store is not ready");if(e.kind==="failed")throw new Error(`rsp resident store failed to open: ${e.error.message}`);let i=e.store;if(t.op==="ping")return{pong:!0,version:r};if(t.op==="stats")return await i.stats();if(t.op==="telemetry-stats"){let s=i.redDb();if(!s)throw new Error("rsp telemetry stats require the shared RedDB store");return await Sn(s,t.sinceDays)}if(t.op==="telemetry-gains"){let s=i.redDb();if(!s)throw new Error("rsp telemetry gains require the shared RedDB store");return await Kr(s,t.sinceDays)}if(t.op==="mint")return{handle:await i.mint(Buffer.from(t.original,"base64"),t.meta)};if(t.op==="get")return tp(await i.get(t.handle));if(t.op==="memory")return await i.memory(t.action,t.payload);if(t.op==="brain")return await ep(i,n,t.action,t.payload);throw new Error(`unsupported resident op: ${t.op??"unknown"}`)}async function ep(e,t,n,r){let i=e.redDb();if(!i)throw new Error("resident brain operations require the shared RedDB store");return await sa(i,t).request(n,r)}function tp(e){return e?"status"in e?e:{...e,original:e.original.toString("base64"),original_encoding:"base64"}:null}var Am,Nm,Pa,Bm,Lm,Cm,Zr,Ea,Sa,Na=S(()=>{"use strict";Qt();mn();la();vn();K();Am=256*1024,Nm=500,Pa=2e3,Bm=Math.max(1,Number(process.env.RSP_TEST_IDLE_SHUTDOWN_WATCHDOG_MS??"10000")),Lm=At(".red","tmp","rsp-status-summary.json"),Cm=[Re,Ee,It],Zr=class{constructor(t,n){this.store=t;this.opts=n;this.pendingHeals=[...n.bootHeals??[]]}running;pending=!1;pendingHeals;async drainAndSweep(){if(this.running){this.pending=!0,await this.running;return}this.running=(async()=>{do this.pending=!1,await this.drainAndSweepOnce();while(this.pending)})().finally(()=>{this.running=void 0}),await this.running}async drainAndSweepOnce(){let t=this.store.redDb();if(!t)return;let n=await jm(t);n.unshift(...this.pendingHeals),this.pendingHeals=[];let i=[...(await this.readIndex(t)).records];for(let s of n)i.push(await this.writeDrainDegradation(t,{reason:"telemetry collection model mismatch",command:"rsp resident telemetry drain",source_collection:s.collection,error:`expected kv, got ${s.previousModel}`,bytes:0}));await Wr(this.opts.rootDir,async s=>{let o=Hr(s);if(!o){let a=await this.writeDrainDegradation(t,{reason:"telemetry parse failed",command:"unknown",bytes:Buffer.byteLength(s,"utf8")});return i.push(a),!0}try{let a=await this.writeEvent(t,o);return i.push(a),!0}catch(a){let c=await this.writeDrainDegradation(t,{reason:"telemetry event dropped",command:Qr(o.command)||"unknown",source_id:Qr(o.id),source_collection:Qr(o.collection),error:a instanceof Error?a.message:String(a),bytes:Buffer.byteLength(s,"utf8")});return i.push(c),!0}}),await this.prune(t,{version:1,records:i}),await Mm(t,this.opts.rootDir)}async writeEvent(t,n){let r=new Date,i=typeof n.created_at=="string"?n.created_at:r.toISOString(),s=new Date(Date.parse(i)+this.opts.ttlDays*24*60*60*1e3).toISOString(),o=typeof n.id=="string"&&n.id.trim()!==""?n.id:Xr(),a={...await Hm(n),id:o,created_at:i,expires_at:s};return await t.kv(n.collection).put(o,a),{collection:n.collection,key:o,created_at:i,expires_at:s,bytes:typeof n.bytes=="number"&&Number.isFinite(n.bytes)?Math.max(0,n.bytes):Buffer.byteLength(JSON.stringify(a),"utf8")}}async writeDrainDegradation(t,n){return await this.writeEvent(t,{collection:Ee,id:Xr(),created_at:new Date().toISOString(),reason:n.reason,command:n.command,bytes:n.bytes,source_id:n.source_id,source_collection:n.source_collection,error:n.error})}async readIndex(t){let n=await t.kv(It).get("index:v1"),r=typeof n=="string"?Ym(n):n;return Qm(r)?r:{version:1,records:[]}}async writeIndex(t,n){await t.kv(It).put("index:v1",n)}async prune(t,n){let r=Date.now(),i=[];for(let o of n.records)Date.parse(o.expires_at)<=r?await t.kv(o.collection).delete(o.key):i.push(o);let s=i.reduce((o,a)=>o+a.bytes,0);for(i.sort((o,a)=>o.created_at.localeCompare(a.created_at));s>this.opts.byteBudget&&i.length>0;){let o=i.shift();s-=o.bytes,await t.kv(o.collection).delete(o.key)}await this.writeIndex(t,{version:1,records:i})}};Ea=!1});function ke(e){let t=[],n;for(let r=0;r<e.length;r++){let i=e[r];if(i==="--query"){n=e[++r];continue}if(i.startsWith("--query=")){n=i.slice(8);continue}t.push(i)}return{argv:t,query:n?.trim()||void 0}}function Ba(e,t){if(!t)return!0;let n=ti(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(r=>n.includes(r))}function I(e,t){return t?e.filter(n=>Ba(n,t)):[...e]}function it(e,t){if(!t)return e;let r=e.split(`
95
+ `)}catch{}}async function Zm(e,t,n,r){if(t.op==="handover")return{handover:!0,version:r,clientVersion:t.clientVersion};if(e.kind==="opening")throw new Error("rsp resident store is not ready");if(e.kind==="failed")throw new Error(`rsp resident store failed to open: ${e.error.message}`);let i=e.store;if(t.op==="ping")return{pong:!0,version:r};if(t.op==="stats")return await i.stats();if(t.op==="telemetry-stats"){let s=i.redDb();if(!s)throw new Error("rsp telemetry stats require the shared RedDB store");return await Sn(s,t.sinceDays)}if(t.op==="telemetry-gains"){let s=i.redDb();if(!s)throw new Error("rsp telemetry gains require the shared RedDB store");return await Kr(s,t.sinceDays)}if(t.op==="mint")return{handle:await i.mint(Buffer.from(t.original,"base64"),t.meta)};if(t.op==="get")return tp(await i.get(t.handle));if(t.op==="memory")return await i.memory(t.action,t.payload);if(t.op==="brain")return await ep(i,n,t.action,t.payload);throw new Error(`unsupported resident op: ${t.op??"unknown"}`)}async function ep(e,t,n,r){let i=e.redDb();if(!i)throw new Error("resident brain operations require the shared RedDB store");return await sa(i,t).request(n,r)}function tp(e){return e?"status"in e?e:{...e,original:e.original.toString("base64"),original_encoding:"base64"}:null}var Am,Nm,Pa,Bm,Lm,Cm,Zr,Ea,Sa,Na=S(()=>{"use strict";Qt();mn();la();vn();K();Am=256*1024,Nm=500,Pa=2e3,Bm=Math.max(1,Number(process.env.RSP_TEST_IDLE_SHUTDOWN_WATCHDOG_MS??"10000")),Lm=At(".red","tmp","rsp-status-summary.json"),Cm=[Re,Ee,It],Zr=class{constructor(t,n){this.store=t;this.opts=n;this.pendingHeals=[...n.bootHeals??[]]}running;pending=!1;pendingHeals;async drainAndSweep(){if(this.running){this.pending=!0,await this.running;return}this.running=(async()=>{do this.pending=!1,await this.drainAndSweepOnce();while(this.pending)})().finally(()=>{this.running=void 0}),await this.running}async drainAndSweepOnce(){let t=this.store.redDb();if(!t)return;let n=await jm(t);n.unshift(...this.pendingHeals),this.pendingHeals=[];let r=await this.readIndex(t),i=r.records.length,s=[...r.records];for(let a of n)s.push(await this.writeDrainDegradation(t,{reason:"telemetry collection model mismatch",command:"rsp resident telemetry drain",source_collection:a.collection,error:`expected kv, got ${a.previousModel}`,bytes:0}));await Wr(this.opts.rootDir,async a=>{let c=Hr(a);if(!c){let u=await this.writeDrainDegradation(t,{reason:"telemetry parse failed",command:"unknown",bytes:Buffer.byteLength(a,"utf8")});return s.push(u),!0}try{let u=await this.writeEvent(t,c);return s.push(u),!0}catch(u){let l=await this.writeDrainDegradation(t,{reason:"telemetry event dropped",command:Qr(c.command)||"unknown",source_id:Qr(c.id),source_collection:Qr(c.collection),error:u instanceof Error?u.message:String(u),bytes:Buffer.byteLength(a,"utf8")});return s.push(l),!0}});let o=s.length>i;await this.prune(t,{version:1,records:s},o),await Mm(t,this.opts.rootDir)}async writeEvent(t,n){let r=new Date,i=typeof n.created_at=="string"?n.created_at:r.toISOString(),s=new Date(Date.parse(i)+this.opts.ttlDays*24*60*60*1e3).toISOString(),o=typeof n.id=="string"&&n.id.trim()!==""?n.id:Xr(),a={...await Hm(n),id:o,created_at:i,expires_at:s};return await t.kv(n.collection).put(o,a),{collection:n.collection,key:o,created_at:i,expires_at:s,bytes:typeof n.bytes=="number"&&Number.isFinite(n.bytes)?Math.max(0,n.bytes):Buffer.byteLength(JSON.stringify(a),"utf8")}}async writeDrainDegradation(t,n){return await this.writeEvent(t,{collection:Ee,id:Xr(),created_at:new Date().toISOString(),reason:n.reason,command:n.command,bytes:n.bytes,source_id:n.source_id,source_collection:n.source_collection,error:n.error})}async readIndex(t){let n=await t.kv(It).get("index:v1"),r=typeof n=="string"?Ym(n):n;return Qm(r)?r:{version:1,records:[]}}async writeIndex(t,n){await t.kv(It).put("index:v1",n)}async prune(t,n,r=!1){let i=Date.now(),s=[];for(let a of n.records)Date.parse(a.expires_at)<=i?await t.kv(a.collection).delete(a.key):s.push(a);let o=s.reduce((a,c)=>a+c.bytes,0);for(s.sort((a,c)=>a.created_at.localeCompare(c.created_at));o>this.opts.byteBudget&&s.length>0;){let a=s.shift();o-=a.bytes,await t.kv(a.collection).delete(a.key)}(r||s.length<n.records.length)&&await this.writeIndex(t,{version:1,records:s})}};Ea=!1});function ke(e){let t=[],n;for(let r=0;r<e.length;r++){let i=e[r];if(i==="--query"){n=e[++r];continue}if(i.startsWith("--query=")){n=i.slice(8);continue}t.push(i)}return{argv:t,query:n?.trim()||void 0}}function Ba(e,t){if(!t)return!0;let n=ti(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(r=>n.includes(r))}function I(e,t){return t?e.filter(n=>Ba(n,t)):[...e]}function it(e,t){if(!t)return e;let r=e.split(`
96
96
  `).filter(i=>i&&Ba(i,t));return r.length>0?`${r.join(`
97
97
  `)}
98
98
  `:""}function Se(e,t){let n=t.filter(Boolean);return n.length===0?e:{...e,help:n}}function ti(e){return Array.isArray(e)?e.map(ti).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(ti).join(" "):String(e??"")}var xn=S(()=>{"use strict"});var ni={};D(ni,{DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>ie,GIT_LOG_MACHINE_FIELDS:()=>La,recoveryInstruction:()=>q,renderGitContract:()=>Ca,runGitWrapper:()=>rp});import{spawn as np}from"node:child_process";async function rp(e,t){let n=Ma(e),r=ja(n.argv),i=await ap(r,n.argv.slice(1));return Ca(e,i,t)}async function Ca(e,t,n){let r=Ma(e);if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(it(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let i=ja(r.argv),s=cp(i,r.argv,t.stdout,r.query);if(s===`git empty
@@ -126,7 +126,7 @@ ${n[n.length-1]}`,i=Buffer.from(r);return i.length<=t?r:i.subarray(0,t).toString
126
126
  `:""}`,truncated:o.length<i.length}}function ug(e){let t=[];for(let n=0;n<e.length;n++){let i=e[n].trim(),s=/^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(class|interface|type)\s+([A-Za-z_$][\w$]*)/.exec(i);if(s){t.push({kind:s[1],name:s[2],line:n+1,signature:i});continue}let o=/^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::[^{]+)?/.exec(i);if(o){t.push({kind:"function",name:o[1],line:n+1,signature:i});continue}let a=/^(?:public\s+|private\s+|protected\s+|static\s+|async\s+)*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::[^{]+)?\s*\{/.exec(i);a&&!lg(a[1])&&t.push({kind:"method",name:a[1],line:n+1,signature:i})}return t}function Dn(e){let t=e.split(`
127
127
  `);return t.at(-1)===""?t.slice(0,-1):t}function oc(e){return e.includes(0)||!Xp(e)}function nc(e){return rg.has(eg(e).toLowerCase())}function lg(e){return["for","if","switch","while"].includes(e)}function rc(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function ic(e,t){let n=Number(e);return Number.isInteger(n)&&n>0?n:t}var tc,di,tg,ng,rg,pi=S(()=>{"use strict";fe();Be();tc=8*1024,di=10,tg=8,ng=2,rg=new Set([".c",".cc",".cpp",".cs",".go",".java",".js",".jsx",".mjs",".py",".rs",".ts",".tsx"])});var $n={};D($n,{parseExecCommandLine:()=>uc,renderExecContract:()=>cc,runExecWrapper:()=>yg});import{isUtf8 as dg}from"node:buffer";import{spawn as fg}from"node:child_process";async function yg(e,t){let n=uc(e),r=await hg(n);return await cc(n,r,t)}async function cc(e,t,n){let r=Buffer.from(t.stdout,"binary"),i=Buffer.from(t.stderr,"binary");if(r.length===0)return{stdout:r,stderr:i,status:t.status,signal:t.signal,rawOutput:r};let s=wg(r);if(s.kind==="text"){let d=await wt(s.text,{level:n.level,command:e,store:n.store?{mint:async(...m)=>await n.store.mint(...m)}:void 0});if(d.detected)return{stdout:Buffer.from(d.output),stderr:i,status:t.status,signal:t.signal,mintedHandle:d.handle,bytesElided:d.lossy?r.length:void 0,rawOutput:r}}let o=s.kind==="text"?Buffer.from(s.text):r,a=Rg(n.heavyByteThreshold,mg);if(o.length<=a&&n.level!=="terse")return{stdout:o,stderr:i,status:t.status,signal:t.signal,rawOutput:r};let c=r.length,u=n.level==="lossless"?"terse":n.level,l=await n.store?.mint(r,{command:e,loss:{level:u,bytes_elided:c}});if(!l)throw new Error("rsp exec output elision requires an elision store");return{stdout:Buffer.from(bg(o,r.length,l,n.level)),stderr:i,status:t.status,signal:t.signal,mintedHandle:l,bytesElided:c,rawOutput:r}}function uc(e){if(e[0]!=="exec")throw new Error("expected rsp exec -- <command line>");let t=e.indexOf("--"),n=t>=0?e.slice(t+1):e.slice(1),r=n.length===1?n[0]:n.join(" ");if(!r.trim())throw new Error("usage: rsp exec -- <command line>");return r}async function hg(e){let t=fg(e,{shell:!0,stdio:["inherit","pipe","pipe"]}),n=[],r=[];return t.stdout.on("data",i=>n.push(i)),t.stderr.on("data",i=>r.push(i)),await new Promise((i,s)=>{t.on("error",s),t.on("close",(o,a)=>{i({stdout:Buffer.concat(n).toString("binary"),stderr:Buffer.concat(r).toString("binary"),status:o,signal:a})})})}function wg(e){return dg(e)?{kind:"text",text:ze(e.toString("utf8"))}:{kind:"bytes"}}function bg(e,t,n,r){let s=Math.max(1,Math.floor((r==="terse"?gg:pg)/2)),o=ac(e.subarray(0,s)),a=ac(e.subarray(Math.max(0,e.length-s))),c=_g(e),u=["stdout summary",`bytes: ${t}`,`lines: ${c}`,"head:",o];return a&&a!==o&&u.push("tail:",a),u.push(`\u2026 elided stdout (+${t}) \u2014 ${q(n)}`),`${u.join(`
128
128
  `)}
129
- `}function ac(e){return e.toString("utf8").replace(/�$/g,"")}function _g(e){if(e.length===0)return 0;let t=0;for(let n of e)n===10&&t++;return e[e.length-1]===10?t:t+1}function Rg(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}var mg,pg,gg,In=S(()=>{"use strict";Be();bt();mg=8*1024,pg=2*1024,gg=1024});fe();import{spawn as Eg}from"node:child_process";import{createHash as kg}from"node:crypto";import{appendFileSync as lc,existsSync as hi,mkdirSync as Sg,readFileSync as vg,readdirSync as Tg,statSync as xg}from"node:fs";import{tmpdir as Og}from"node:os";import{dirname as dc,join as Z}from"node:path";function qi(e){let t={app:e,version:pu(We("__RED_BUILD_VERSION__",()=>"2.55.2")??"0.0.0-dev"),gitSha:We("__RED_BUILD_GIT_SHA__",()=>"c2bbfd6d644ae033e4d5d012f98a7e0a9407a76c")??"unknown",buildTime:We("__RED_BUILD_TIME__",()=>"2026-07-13T23:33:42-03:00")??"unknown",bundleAsset:We("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},n=We("__REDDB_SDK_VERSION__",()=>"1.23.1"),r=We("__REDDB_BINARY_TAG__",()=>"v1.23.1");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function pu(e){return e.startsWith("v")?e.slice(1):e}function We(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}Hn();async function Pg(e=process.argv.slice(2)){let t=qi("rsp"),n=qg(e);if(n.command==="hook"&&n.positional[1]==="claude-pre-exec"){let{runClaudePreExecHook:p}=await Promise.resolve().then(()=>(sn(),nr));return await p()}if(n.command==="hook"&&n.positional[1]==="codex-pre-exec"){let{runCodexPreExecHook:p}=await Promise.resolve().then(()=>(sn(),nr));return await p()}if(n.command==="hook"&&n.positional[1]==="claude-post-exec"){let{runClaudePostExecHook:p}=await Promise.resolve().then(()=>(bt(),ir));return await p()}if(n.command==="hook"&&n.positional[1]==="codex-post-exec"){let{runCodexPostExecHook:p}=await Promise.resolve().then(()=>(bt(),ir));return await p()}if(n.command==="setup"){let{provisionRspRepoStore:p}=await Promise.resolve().then(()=>(Po(),Oo)),f=await p(process.cwd());return process.stdout.write(ey(f)),0}if(n.command==="mcp"){let{runRspMcpServer:p}=await Promise.resolve().then(()=>(Lo(),Bo));return await p(),0}if(n.command==="wait"){let{runWait:p}=await Promise.resolve().then(()=>(Jo(),Fo));return await p(n.positional)}if(n.command==="shell-init"){let p=n.positional[1];if(p!=="fish"&&p!=="bash"&&p!=="zsh")return process.stdout.write(`error: usage rsp shell-init fish|bash|zsh
129
+ `}function ac(e){return e.toString("utf8").replace(/�$/g,"")}function _g(e){if(e.length===0)return 0;let t=0;for(let n of e)n===10&&t++;return e[e.length-1]===10?t:t+1}function Rg(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}var mg,pg,gg,In=S(()=>{"use strict";Be();bt();mg=8*1024,pg=2*1024,gg=1024});fe();import{spawn as Eg}from"node:child_process";import{createHash as kg}from"node:crypto";import{appendFileSync as lc,existsSync as hi,mkdirSync as Sg,readFileSync as vg,readdirSync as Tg,statSync as xg}from"node:fs";import{tmpdir as Og}from"node:os";import{dirname as dc,join as Z}from"node:path";function qi(e){let t={app:e,version:pu(We("__RED_BUILD_VERSION__",()=>"2.55.3")??"0.0.0-dev"),gitSha:We("__RED_BUILD_GIT_SHA__",()=>"15be4622f2ef4c460ff55365d4731f90d6f2d570")??"unknown",buildTime:We("__RED_BUILD_TIME__",()=>"2026-07-13T23:50:13-03:00")??"unknown",bundleAsset:We("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},n=We("__REDDB_SDK_VERSION__",()=>"1.23.1"),r=We("__REDDB_BINARY_TAG__",()=>"v1.23.1");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function pu(e){return e.startsWith("v")?e.slice(1):e}function We(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}Hn();async function Pg(e=process.argv.slice(2)){let t=qi("rsp"),n=qg(e);if(n.command==="hook"&&n.positional[1]==="claude-pre-exec"){let{runClaudePreExecHook:p}=await Promise.resolve().then(()=>(sn(),nr));return await p()}if(n.command==="hook"&&n.positional[1]==="codex-pre-exec"){let{runCodexPreExecHook:p}=await Promise.resolve().then(()=>(sn(),nr));return await p()}if(n.command==="hook"&&n.positional[1]==="claude-post-exec"){let{runClaudePostExecHook:p}=await Promise.resolve().then(()=>(bt(),ir));return await p()}if(n.command==="hook"&&n.positional[1]==="codex-post-exec"){let{runCodexPostExecHook:p}=await Promise.resolve().then(()=>(bt(),ir));return await p()}if(n.command==="setup"){let{provisionRspRepoStore:p}=await Promise.resolve().then(()=>(Po(),Oo)),f=await p(process.cwd());return process.stdout.write(ey(f)),0}if(n.command==="mcp"){let{runRspMcpServer:p}=await Promise.resolve().then(()=>(Lo(),Bo));return await p(),0}if(n.command==="wait"){let{runWait:p}=await Promise.resolve().then(()=>(Jo(),Fo));return await p(n.positional)}if(n.command==="shell-init"){let p=n.positional[1];if(p!=="fish"&&p!=="bash"&&p!=="zsh")return process.stdout.write(`error: usage rsp shell-init fish|bash|zsh
130
130
  `),2;let{renderShellInit:f}=await Promise.resolve().then(()=>(Wo(),Vo));return process.stdout.write(f(p)),0}let{resolveRspConfig:r}=await Promise.resolve().then(()=>(K(),hs)),i=r(process.cwd(),process.env,n.storeUri),s=Fg(n.command);if(!i.enabled)return s?await Gg(n.positional):(process.stdout.write(`${Ei()}
131
131
  `),0);if(n.command==="git"&&wi(n.positional)){let p=process.hrtime.bigint();return await C(n,await bi(),p,void 0,await Dg(process.cwd()))}let{resolveResidentPaths:o,ResidentRspElisionStore:a,ensureResidentServer:c}=await Promise.resolve().then(()=>($e(),gt));if(n.command==="server"){let{runResidentServer:p}=await Promise.resolve().then(()=>(Na(),Aa)),f=o(process.cwd()),w=X(n.positional,"--socket")??f.socketPath,g=r(process.cwd(),process.env,n.storeUri??X(n.positional,"--store-uri"));return g.enabled?(await p({socketPath:w,pidPath:X(n.positional,"--pid-file")??o(process.cwd()).pidPath,rootDir:f.rootDir,storeUri:g.storeUri,ttlDays:N(n.positional,"--ttl-days")??g.ttlDays,byteBudget:N(n.positional,"--byte-budget")??g.byteBudget,telemetryTtlDays:N(n.positional,"--telemetry-ttl-days")??g.telemetryTtlDays,telemetryByteBudget:N(n.positional,"--telemetry-byte-budget")??g.telemetryByteBudget,telemetryDrainIntervalMs:N(n.positional,"--telemetry-drain-interval-ms")??g.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:N(n.positional,"--telemetry-drain-timeout-ms")??g.telemetryDrainTimeoutMs,idleMs:N(n.positional,"--idle-ms")??g.idleMs,residentVersion:X(n.positional,"--resident-version")??t.version,registryPath:X(n.positional,"--registry")??f.registryPath}),0):(process.stdout.write(`${Ei()}
132
132
  `),0)}if(n.command==="warm-resident"){let p=o(process.cwd()),f=X(n.positional,"--socket")??p.socketPath,w=X(n.positional,"--wake-lock")??p.wakeLockPath,g=r(process.cwd(),process.env,n.storeUri??X(n.positional,"--store-uri"));if(!g.enabled)return 0;let{warmResidentServer:E}=await Promise.resolve().then(()=>($e(),gt));return await E({...p,socketPath:f,wakeLockPath:w},{storeUri:g.storeUri,ttlDays:N(n.positional,"--ttl-days")??g.ttlDays,byteBudget:N(n.positional,"--byte-budget")??g.byteBudget,telemetryTtlDays:N(n.positional,"--telemetry-ttl-days")??g.telemetryTtlDays,telemetryByteBudget:N(n.positional,"--telemetry-byte-budget")??g.telemetryByteBudget,telemetryDrainIntervalMs:N(n.positional,"--telemetry-drain-interval-ms")??g.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:N(n.positional,"--telemetry-drain-timeout-ms")??g.telemetryDrainTimeoutMs,idleMs:N(n.positional,"--idle-ms")??g.idleMs,clientVersion:t.version}),0}let{existsSync:u}=await import("node:fs"),{fileURLToPath:l}=await import("node:url"),d=o(process.cwd());if(n.command==="status"||n.command==="sweep"){let{residentRegistryStatus:p,sweepResidentRegistry:f}=await Promise.resolve().then(()=>($e(),gt)),w=n.command==="sweep"?await f(d):await p(d);return process.stdout.write(`${P(w)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/red-skills",
3
- "version": "2.55.2",
3
+ "version": "2.55.3",
4
4
  "description": "RedSkills plugin runtime bundles (dev, code-nav, memory, brain) distributed over npm — the v2 client transport (ADR 0091). Carries the platform-independent JS bundles inside the tarball plus thin bin shims; no postinstall download.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",