@reddb-io/red-skills 2.74.4 → 2.74.5
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.
|
@@ -50,7 +50,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
50
50
|
`:`[${n[c]}\r
|
|
51
51
|
]`;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 ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Ka(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??Ce(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===E.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Ga(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===E.ZodBranded&&e.keyType._def.type._def.typeName===E.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Ja(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function Bv(e,t){if(t.mapStrategy==="record")return Ka(e,t);let r=W(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ce(t),n=W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ce(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Wv(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[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 Jv(e){return e.target==="openAi"?void 0:{not:Ce({...e,currentPath:[...e.currentPath,"not"]})}}function Gv(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ki={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Xv(e,t){if(t.target==="openApi3")return Kv(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Ki&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Ki[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 Kv(e,t)}var Kv=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>W(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Yv(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Ki[e.innerType._def.typeName],nullable:!0}:{type:[Ki[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Qv(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",of(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,t):ie(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,t):ie(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,t));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,t);break}return r}function eb(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=nO(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=W(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let s=rO(e,t);return s!==void 0&&(n.additionalProperties=s),n}function rO(e,t){if(e.catchall._def.typeName!=="ZodNever")return W(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function nO(e){try{return e.isOptional()}catch{return!0}}var tb=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return W(e.innerType._def,t);let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ce(t)},r]}:Ce(t)};var rb=(e,t)=>{if(t.pipeStrategy==="input")return W(e.in._def,t);if(t.pipeStrategy==="output")return W(e.out._def,t);let r=W(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=W(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function nb(e,t){return W(e.type._def,t)}function ob(e,t){let n={type:"array",uniqueItems:!0,items:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ie(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ie(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function ib(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:W(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function sb(e){return{not:Ce(e)}}function ab(e){return Ce(e)}var cb=(e,t)=>W(e.innerType._def,t);var ub=(e,t,r)=>{switch(t){case E.ZodString:return Ga(e,r);case E.ZodNumber:return Qv(e,r);case E.ZodObject:return eb(e,r);case E.ZodBigInt:return Nv(e,r);case E.ZodBoolean:return Av();case E.ZodDate:return sf(e,r);case E.ZodUndefined:return sb(r);case E.ZodNull:return Gv(r);case E.ZodArray:return Dv(e,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return Xv(e,r);case E.ZodIntersection:return Fv(e,r);case E.ZodTuple:return ib(e,r);case E.ZodRecord:return Ka(e,r);case E.ZodLiteral:return Vv(e,r);case E.ZodEnum:return Uv(e);case E.ZodNativeEnum:return Wv(e);case E.ZodNullable:return Yv(e,r);case E.ZodOptional:return tb(e,r);case E.ZodMap:return Bv(e,r);case E.ZodSet:return ob(e,r);case E.ZodLazy:return()=>e.getter()._def;case E.ZodPromise:return nb(e,r);case E.ZodNaN:case E.ZodNever:return Jv(r);case E.ZodEffects:return Lv(e,r);case E.ZodAny:return Ce(r);case E.ZodUnknown:return ab(r);case E.ZodDefault:return qv(e,r);case E.ZodBranded:return Ja(e,r);case E.ZodReadonly:return cb(e,r);case E.ZodCatch:return Zv(e,r);case E.ZodPipeline:return rb(e,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(t)}};function W(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==jv)return a}if(n&&!r){let a=oO(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=ub(e,e.typeName,t),s=typeof i=="function"?W(i(),t):i;if(s&&iO(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var oO=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Wa(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ce(t)):t.$refStrategy==="seen"?Ce(t):void 0}},iO=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var uf=(e,t)=>{let r=Iv(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ce(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=W(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ce(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.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 sO(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function lf(e,t){return Nt(e)?Od(e,{target:sO(t?.target),io:t?.pipeStrategy??"input"}):uf(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function df(e){let r=Wr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$a(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ff(e,t){let r=Br(e,t);if(!r.success)throw r.error;return r.data}var aO=6e4,Xa=class{constructor(t){this._options=t,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(Ea,r=>{this._oncancel(r)}),this.setNotificationHandler(Ca,r=>{this._onprogress(r)}),this.setRequestHandler(Oa,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ja,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(F.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ia,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,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,g=new q(d.error.code,d.error.message,d.error.data);l(g)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new q(F.InvalidParams,`Task not found: ${i}`);if(!Gr(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Gr(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Jr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Da,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 q(F.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Aa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(F.InvalidParams,`Task not found: ${r.params.taskId}`);if(Gr(o.status))throw new q(F.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 q(F.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof q?o:new q(F.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),q.fromError(F.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){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=t;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),Li(i)||wv(i)?this._onresponse(i):Vd(i)?this._onrequest(i,s):bv(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=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=q.fromError(F.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[Jr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:F.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=yv(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,g)=>{if(s.signal.aborted)throw new q(F.ConnectionClosed,"Request was cancelled");let m={...g,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});let p=m.relatedTask?.taskId??i;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:F.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.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(t)}`));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(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Li(t))n(t);else{let s=new q(t.error.code,t.error.message,t.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(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Li(t)&&t.result&&typeof t.result=="object"){let s=t.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),Li(t))o(t);else{let s=q.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof q?s:new q(F.InternalError,String(s))}}return}let i;try{let s=await this.request(t,So,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new q(F.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Gr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new q(F.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(F.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(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof q?s:new q(F.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=T=>{l(T)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(T){d(T);return}n?.signal?.throwIfAborted();let g=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:g};n?.onprogress&&(this._progressHandlers.set(g,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:g}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Jr]:c}});let p=T=>{this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(T)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(D=>this._onerror(new Error(`Failed to send cancellation: ${D}`)));let R=T instanceof q?T:new q(F.RequestTimeout,String(T));l(R)};this._responseHandlers.set(g,T=>{if(!n?.signal?.aborted){if(T instanceof Error)return l(T);try{let R=Br(r,T.result);R.success?u(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let y=n?.timeout??aO,v=()=>p(q.fromError(F.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(g,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let P=c?.taskId;if(P){let T=R=>{let D=this._responseHandlers.get(g);D?D(R):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,T),this._enqueueTaskMessage(P,{type:"request",message:m,timestamp:Date.now()}).catch(R=>{this._cleanupTimeout(g),l(R)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(T=>{this._cleanupTimeout(g),l(T)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ma,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Na,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Sv,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Jr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Jr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Jr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=df(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=ff(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=df(t);this._notificationHandlers.set(n,o=>{let i=ff(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,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(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&Vd(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new q(F.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new q(F.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new q(F.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new q(F.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=Bi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Gr(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 q(F.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Gr(a.status))throw new q(F.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 u=Bi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Gr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function lb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function db(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];lb(s)&&lb(i)?r[o]={...s,...i}:r[o]=i}return r}var r0=Xs(Yp(),1),n0=Xs(t0(),1);function lN(){let e=new r0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,n0.default)(e),e}var Cc=class{constructor(t){this._ajv=t??lN()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var jc=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(g=>g.type==="tool_use").map(g=>g.id)),d=new Set(i.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(l.size!==d.size||![...l].every(g=>d.has(g)))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:t},Gi,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.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"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},To,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function o0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function i0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Mc=class extends Xa{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ji.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 Cc,this.setRequestHandler(Wd,n=>this._oninitialize(n)),this.setNotificationHandler(Jd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(tf,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=Ji.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new jc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=db(this._capabilities,t)}setRequestHandler(t,r){let o=Wr(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Nt(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,u)=>{let l=Br(Po,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new q(F.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,g=await Promise.resolve(r(c,u));if(d.task){let p=Br(So,g);if(!p.success){let y=p.error instanceof Error?p.error.message:String(p.error);throw new q(F.InvalidParams,`Invalid task creation result: ${y}`)}return p.data}let m=Br(Ha,g);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new q(F.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);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 ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);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 ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){i0(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&o0(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:mv.includes(r)?r:Ud,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"},Ra)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},rf,r):this.request({method:"sampling/createMessage",params:t},Gi,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},To,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},To,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new q(F.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof q?s:new q(F.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,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:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},nf,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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 a0=Symbol.for("mcp.completable");function sm(e){return!!e&&typeof e=="object"&&a0 in e}function c0(e){return e[a0]?.complete}var s0;(function(e){e.Completable="McpCompletable"})(s0||(s0={}));var dN=/^[A-Za-z0-9._-]{1,128}$/;function fN(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!dN.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.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:t}}return{isValid:!0,warnings:t}}function pN(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)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 am(e){let t=fN(e);return pN(e,t.warnings),t.isValid}var Ic=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Dc=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Mc(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ic(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Va)),this.server.assertCanSetRequestHandler(on(Po)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Va,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=xo(r.inputSchema);return o?lf(o,{strictUnions:!0,pipeStrategy:"input"}):mN})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=xo(r.outputSchema);o&&(n.outputSchema=lf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Po,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new q(F.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new q(F.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new q(F.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new q(F.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof q&&n.code===F.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=xo(t.inputSchema)??t.inputSchema,s=await wa(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=xa(a);throw new q(F.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new q(F.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=xo(t.outputSchema),i=await wa(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=xa(s);throw new q(F.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.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,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(g=>setTimeout(g,l));let d=await n.taskStore.getTask(c);if(!d)throw new q(F.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(on(Ba)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ba,async t=>{switch(t.params.ref.type){case"ref/prompt":return Ev(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Ov(t),this.handleResourceCompletion(t,t.params.ref);default:throw new q(F.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new q(F.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new q(F.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ps;let i=Wr(n.argsSchema)?.[t.params.argument.name];if(!sm(i))return Ps;let s=c0(i);if(!s)return Ps;let a=await s(t.params.argument.value,t.params.context);return l0(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Ps;throw new q(F.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Ps;let i=await o(t.params.argument.value,t.params.context);return l0(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Za)),this.server.assertCanSetRequestHandler(on(qa)),this.server.assertCanSetRequestHandler(on(La)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Za,async(t,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(La,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new q(F.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 q(F.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(on(Ua)),this.server.assertCanSetRequestHandler(on(Fa)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ua,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?hN(r.argsSchema):void 0}))})),this.server.setRequestHandler(Fa,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new q(F.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new q(F.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=xo(n.argsSchema),i=await wa(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=xa(c);throw new q(F.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}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(t,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(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,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(t,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:u=>{typeof u.name<"u"&&u.name!==t&&(delete this._registeredResourceTemplates[t],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Un(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!==t&&(delete this._registeredPrompts[t],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=Un(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let u=c instanceof vt?c._def?.innerType:c;return sm(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,u){am(t);let l={title:r,description:n,inputSchema:u0(o),outputSchema:u0(i),annotations:s,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&am(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Un(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Un(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(cm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!cm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},u,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} 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(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var mN={type:"object",properties:{}};function d0(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function f0(e){return"_def"in e||"_zod"in e||d0(e)}function cm(e){return typeof e!="object"||e===null||f0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(d0)}function u0(e){if(e){if(cm(e))return Un(e);if(!f0(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function hN(e){let t=Wr(e);return t?Object.entries(t).map(([r,n])=>{let o=V_(n),i=H_(n);return{name:r,description:o,required:!i}}):[]}function on(e){let r=Wr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$a(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function l0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ps={completion:{values:[],hasMore:!1}};import m0 from"node:process";var Nc=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
52
52
|
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),gN(r)}clear(){this._buffer=void 0}};function gN(e){return xv.parse(JSON.parse(e))}function p0(e){return JSON.stringify(e)+`
|
|
53
|
-
`}var Ac=class{constructor(t=m0.stdin,r=m0.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Nc,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 t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}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(t){return new Promise(r=>{let n=p0(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function h0(e){let t={app:e,version:yN(Bo("__RED_BUILD_VERSION__",()=>"2.74.
|
|
53
|
+
`}var Ac=class{constructor(t=m0.stdin,r=m0.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Nc,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 t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}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(t){return new Promise(r=>{let n=p0(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function h0(e){let t={app:e,version:yN(Bo("__RED_BUILD_VERSION__",()=>"2.74.5")??"0.0.0-dev"),gitSha:Bo("__RED_BUILD_GIT_SHA__",()=>"4ce30c4b04883dcc4750241a651dfec458f7f047")??"unknown",buildTime:Bo("__RED_BUILD_TIME__",()=>"2026-07-18T23:22:31-03:00")??"unknown",bundleAsset:Bo("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Bo("__REDDB_SDK_VERSION__",()=>""),n=Bo("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function yN(e){return e.startsWith("v")?e.slice(1):e}function g0(e){return`${e.app} ${e.version} ${e.gitSha}`}function Bo(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var um={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 y0(){let e=process.env.CODE_NAV_SERVERS;if(!e)return um;try{let t=JSON.parse(e),r={...um};for(let[n,o]of Object.entries(t))r[n]={...r[n]??{},...o};return r}catch(t){return process.stderr.write(`code-nav: failed to parse CODE_NAV_SERVERS, using defaults: ${String(t)}
|
|
54
54
|
`),um}}function _0(e){let t=new Map;for(let[r,n]of Object.entries(e))for(let o of n.extensions)t.set(o,r);return t}var hi=Xs(Zk(),1),ft=Xs(ny(),1);import{spawn as rA}from"node:child_process";import{readFile as nA}from"node:fs/promises";import{pathToFileURL as qk,fileURLToPath as oA}from"node:url";import{resolve as iA}from"node:path";var Bs=class{constructor(t,r){this.spec=t;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 t=rA(this.spec.command,this.spec.args,{cwd:this.rootPath,stdio:["pipe","pipe","pipe"]});this.proc=t,await new Promise((i,s)=>{t.once("spawn",()=>i()),t.once("error",a=>s(new Error(`failed to spawn '${this.spec.command}': ${a.message}`)))}),t.stderr.on("data",i=>{process.stderr.write(`[${this.spec.command}] ${i.toString()}`)}),t.once("exit",()=>{try{this.conn?.dispose()}catch{}});let r=(0,hi.createProtocolConnection)(new hi.StreamMessageReader(t.stdout),new hi.StreamMessageWriter(t.stdin));this.conn=r,r.listen();let n=qk(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(ft.InitializeRequest.type,o),await r.sendNotification(ft.InitializedNotification.type,{})}async ensureOpen(t){let r=iA(this.rootPath,t),n=qk(r).toString();if(this.openDocs.has(n))return n;let o=await nA(r,"utf8");return await this.conn.sendNotification(ft.DidOpenTextDocumentNotification.type,{textDocument:{uri:n,languageId:this.spec.languageId,version:1,text:o}}),this.openDocs.add(n),n}async definition(t,r,n){await this.ensureStarted();let o=await this.ensureOpen(t),i=await this.conn.sendRequest(ft.DefinitionRequest.type,{textDocument:{uri:o},position:{line:r,character:n}});return sA(i)}async references(t,r,n,o){await this.ensureStarted();let i=await this.ensureOpen(t);return await this.conn.sendRequest(ft.ReferencesRequest.type,{textDocument:{uri:i},position:{line:r,character:n},context:{includeDeclaration:o}})??[]}async documentSymbols(t){await this.ensureStarted();let r=await this.ensureOpen(t);return await this.conn.sendRequest(ft.DocumentSymbolRequest.type,{textDocument:{uri:r}})??[]}async hover(t,r,n){await this.ensureStarted();let o=await this.ensureOpen(t);return this.conn.sendRequest(ft.HoverRequest.type,{textDocument:{uri:o},position:{line:r,character:n}})}async workspaceSymbols(t){return await this.ensureStarted(),await this.conn.sendRequest(ft.WorkspaceSymbolRequest.type,{query:t})??[]}dispose(){try{this.conn?.dispose()}catch{}this.proc?.kill()}};function sA(e){return e?(Array.isArray(e)?e:[e]).map(r=>"targetUri"in r?{uri:r.targetUri,range:r.targetSelectionRange}:r):[]}function oy(e,t){try{let r=oA(e);return(r.startsWith(t)?r.slice(t.length).replace(/^[/\\]/,""):r)||r}catch{return e}}var Js=process.env.CODE_NAV_ROOT??process.cwd(),Ws=y0(),Lk=_0(Ws),gi=new Map;function ku(e){let t=aA(e),r=Lk.get(t);if(!r)throw new Error(`no language server configured for '${t}'. Configured extensions: ${[...Lk.keys()].join(", ")||"(none)"}.`);let n=gi.get(r);return n||(n=new Bs(Ws[r],Js),gi.set(r,n)),n}function cA(){for(let e of Object.keys(Ws))gi.has(e)||gi.set(e,new Bs(Ws[e],Js));return[...gi.values()]}function sy(e,t){return`${oy(e,Js)}:${t.start.line+1}:${t.start.character+1}`}var iy=h0("code-nav"),yi=new Dc({name:"code-nav",version:iy.version}),Pu={file:Fr.string().describe("Workspace-relative path to the source file."),line:Fr.number().int().describe("Zero-based line number."),character:Fr.number().int().describe("Zero-based character offset on the line.")};yi.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:Pu},async({file:e,line:t,character:r})=>{let n=await ku(e).definition(e,t,r);return n.length===0?_r("No definition found."):_r(n.map(o=>sy(o.uri,o.range)).join(`
|
|
55
55
|
`))});yi.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:{...Pu,includeDeclaration:Fr.boolean().optional().describe("Include the declaration itself (default true).")}},async({file:e,line:t,character:r,includeDeclaration:n})=>{let o=await ku(e).references(e,t,r,n??!0);return o.length===0?_r("No references found."):_r(`${o.length} reference(s):
|
|
56
56
|
`+o.map(i=>sy(i.uri,i.range)).join(`
|
package/dist/dev.bundle.min.mjs
CHANGED
|
@@ -550,7 +550,7 @@ ${n}`,"</details>"].join(`
|
|
|
550
550
|
`),0}async function pCe(e,t=process.cwd(),r=process.stdout){let n=e[0];if(n!=="render"&&n!=="refresh"&&n!=="act")return process.stderr.write(`[afk] hitl-card requires a subcommand: render | refresh | act
|
|
551
551
|
`),2;let{values:o}=xd(e.slice(1),CRr),i=Number(o.issue);if(!Number.isInteger(i)||i<=0)return process.stderr.write(`[afk] hitl-card requires --issue <N>
|
|
552
552
|
`),2;let s=o.root?.trim()||t,a=kRr(s),c=await IRr(a,o.repo);try{if(n==="render")return await RRr(a,c,i,r);if(n==="refresh")return await _Rr(a,c,i,r);let u=o.body??"",l=o.author?.trim()||void 0;return await ORr(a,c,i,u,l,s,r)}catch(u){return process.stderr.write(`[afk] hitl-card ${n} failed: ${u instanceof Error?u.message:String(u)}
|
|
553
|
-
`),1}}var CRr,mCe=h(()=>{"use strict";sE();mn();zb();aE();qs();wo();Bk();_A();uCe();qr();_bt();A6();CRr={issue:{kind:"value",coerce:e=>Number(e)},body:{kind:"value",coerce:e=>e},author:{kind:"value",coerce:e=>e},repo:{kind:"value",aliases:["R"],coerce:e=>e},root:{kind:"value",coerce:e=>e}}});Cn();Li();import{mkdir as _we,readFile as Vkr,readdir as zkr,rename as Ykr,rm as zyt,stat as Jkr,writeFile as Jyt}from"node:fs/promises";import{dirname as MK,join as Twe}from"node:path";import{spawn as XCr}from"node:child_process";import{copyFileSync as ekr,readFileSync as _k,writeFileSync as wK,renameSync as Syt,existsSync as kK,mkdirSync as IK,rmSync as tkr,unlinkSync as rkr}from"node:fs";import{dirname as UA,join as Br}from"node:path";function ey(e){let t={app:e,version:svt(lI("__RED_BUILD_VERSION__",()=>"2.74.
|
|
553
|
+
`),1}}var CRr,mCe=h(()=>{"use strict";sE();mn();zb();aE();qs();wo();Bk();_A();uCe();qr();_bt();A6();CRr={issue:{kind:"value",coerce:e=>Number(e)},body:{kind:"value",coerce:e=>e},author:{kind:"value",coerce:e=>e},repo:{kind:"value",aliases:["R"],coerce:e=>e},root:{kind:"value",coerce:e=>e}}});Cn();Li();import{mkdir as _we,readFile as Vkr,readdir as zkr,rename as Ykr,rm as zyt,stat as Jkr,writeFile as Jyt}from"node:fs/promises";import{dirname as MK,join as Twe}from"node:path";import{spawn as XCr}from"node:child_process";import{copyFileSync as ekr,readFileSync as _k,writeFileSync as wK,renameSync as Syt,existsSync as kK,mkdirSync as IK,rmSync as tkr,unlinkSync as rkr}from"node:fs";import{dirname as UA,join as Br}from"node:path";function ey(e){let t={app:e,version:svt(lI("__RED_BUILD_VERSION__",()=>"2.74.5")??"0.0.0-dev"),gitSha:lI("__RED_BUILD_GIT_SHA__",()=>"4ce30c4b04883dcc4750241a651dfec458f7f047")??"unknown",buildTime:lI("__RED_BUILD_TIME__",()=>"2026-07-18T23:22:31-03:00")??"unknown",bundleAsset:lI("__RED_BUNDLE_ASSET__",()=>"dev.bundle.min.mjs")??"unknown"},r=lI("__REDDB_SDK_VERSION__",()=>""),n=lI("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function svt(e){return e.startsWith("v")?e.slice(1):e}function P0e(e){return`${e.app} ${e.version} ${e.gitSha}`}function lI(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}DB();zs();Cn();wo();EI();var ZRt=/^[ \t]*(?:[-*][ \t]+)?branch:[ \t]+(\S+)/,XRt=/Spec[ \t]*#[ \t]*(\d+)/,HB="main";function f8(e,t,r){let n=e;return n.startsWith(t)&&(n=n.slice(t.length)),n.endsWith(r)&&(n=n.slice(0,n.length-r.length)),n}function Cve(e){for(let t of e.split(`
|
|
554
554
|
`)){let r=ZRt.exec(t);if(!r)continue;let n=r[1];if(n=f8(n,"`","`"),n=f8(n,'"','"'),n=f8(n,"'","'"),n.length!==0)return n}}function e_t(e){let t=XRt.exec(e);return t?Number(t[1]):void 0}async function kve(e,t){let r=Cve(e.issueBody);if(r)return{branch:r,source:"pin"};let n=e_t(e.issueBody);if(n!==void 0){let i=await t.fetchIssueBody(n);if(i!==void 0){let s=Cve(i);if(s)return{branch:s,source:"pin"}}}let o=t.defaultBranch?.trim();return{branch:o!==void 0&&o.length>0?o:HB,source:"trunk"}}function Y1(e){return e!==void 0&&e.trim().length>0}async function p8(e,t){let r=await t.readLockedBranch();if(Y1(r))return{branch:r.trim(),source:"lock"};if(Y1(t.configLockedBranch))return{branch:t.configLockedBranch.trim(),source:"pin"};let n=await kve(e,{fetchIssueBody:t.fetchIssueBody,defaultBranch:t.configTrunk});return Y1(n.branch)?n:{branch:Y1(t.configTrunk)?t.configTrunk.trim():HB,source:"trunk"}}async function ay(e,t){return(await p8(e,t)).branch}h8();Dd();OA();hSe();import{execFileSync as jSr}from"node:child_process";var Lgt=[{command:"unknown",cpu:100}];function qSr(e){return Number.isInteger(e)&&e>1}function GSr(e){let t=new Map,r=new Map;for(let n of e.split(`
|
|
555
555
|
`)){let o=n.trim();if(o.length===0)continue;let i=o.split(/\s+/);if(i.length<4)continue;let s=Number(i[0]),a=Number(i[1]),c=Number(i[2]);if(!Number.isInteger(s)||!Number.isInteger(a))continue;let u=i.slice(3).join(" "),l=VSr(u);r.set(s,{command:l,cpu:Number.isFinite(c)?c:0});let d=t.get(a);d?d.push(s):t.set(a,[s])}return{children:t,info:r}}function VSr(e){let t=e.split(/\s+/)[0]??e,r=t.lastIndexOf("/");return r>=0?t.slice(r+1):t}function zSr(e,t,r){let n=[],o=new Set,i=[e];for(;i.length>0;){let s=i.pop();if(o.has(s))continue;o.add(s);let a=r.get(s);a&&n.push(a);let c=t.get(s);if(c)for(let u of c)i.push(u)}return n}function YSr(e,t){if(!qSr(e))return[];let r;try{r=t()}catch{return Lgt}try{let{children:n,info:o}=GSr(r);return zSr(e,n,o)}catch{return Lgt}}function z6(e){return YSr(e,()=>jSr("ps",["-e","-o","pid=,ppid=,%cpu=,comm="],{encoding:"utf8",maxBuffer:16*1024*1024,timeout:5e3}))}jc();Li();wT();Li();qs();mn();var FT="red-trunk",USe=`refs/heads/${FT}`;function yAt(e){return{cwd:e.cwd}}function $t(e,t){return(e.exec??ht)("git",t,yAt(e))}async function xAt(e){let t=await $t(e,["rev-parse","--is-inside-work-tree"]);return t.code===0&&t.stdout.trim()==="true"}async function bAt(e){let t=await $t(e,["remote","-v"]);if(t.code!==0)return[];let r=new Set,n=[];for(let o of t.stdout.split(`
|
|
556
556
|
`)){let i=o.trim().split(/\s+/),s=i[0],a=i[1];if(!s||!a)continue;let c=`${s}\0${a}`;r.has(c)||(r.add(c),n.push({name:s,url:a}))}return n}async function EAt(e,t,r){if((await $t(e,["remote","set-url",t,r])).code!==0)throw new Error(`git remote set-url failed for ${t}`)}async function SAt(e){return(await $t(e,["rev-parse","--verify","--quiet","refs/heads/main"])).code===0}async function AL(e){let t=await $t(e,["branch","--show-current"]);return t.code===0?t.stdout.trim():""}async function oh(e){let t=await $t(e,["rev-parse","--short","HEAD"]);return t.code===0?t.stdout.trim():""}async function wAt(e){let t=await $t(e,["rev-parse","--verify","--quiet","HEAD"]),r=t.stdout.trim();return t.code===0&&r!==""?r:void 0}async function ih(e,t){t&&await $t(e,["branch","-D",t])}async function HSe(e,t){t&&await $t(e,["push","origin","--delete",t])}async function hd(e,t){return t?(await $t(e,["rev-parse","--verify","--quiet",`refs/heads/${t}`])).code===0:!1}async function sh(e,t){if(!t)return;let r=await $t(e,["rev-parse","--verify","--quiet",`refs/heads/${t}`]),n=r.stdout.trim();return r.code===0&&n!==""?n:void 0}async function CAt(e,t){let r=t.remote.trim()||"origin",n=t.branch.trim();if(!n)return{remoteReachable:!1};let o=await $t(e,["fetch","--quiet",r,n]),i=await aK(e,`refs/heads/${n}`),s=await aK(e,`${r}/${n}`),a=i&&s?await Ewr(e,`refs/heads/${n}`,`${r}/${n}`):void 0;return{localSha:i,remoteSha:s,ahead:a?.ahead,behind:a?.behind,remoteReachable:o.code===0}}async function QT(e,t){t&&await $t(e,["fetch","origin",t])}async function aK(e,t){let r=await $t(e,["rev-parse","--verify","--quiet",t]),n=r.stdout.trim();return r.code===0&&n!==""?n:void 0}async function Ewr(e,t,r){let n=await $t(e,["rev-list","--left-right","--count",`${t}...${r}`]);if(n.code!==0)return;let[o,i]=n.stdout.trim().split(/\s+/),s=Number(o),a=Number(i);if(!(!Number.isFinite(s)||!Number.isFinite(a)))return{ahead:s,behind:a}}async function cK(e,t){let r=t.base.trim(),n=t.remote?.trim()||"origin",o=`${n}/${r}`,i=r?await $t(e,["fetch",n,r]):Swr("empty base"),s=r?await aK(e,o):void 0;if(i.code===0&&s){let a=await aK(e,USe);return a&&a!==s&&await $t(e,["merge-base","--is-ancestor",USe,o]),(await $t(e,["update-ref",USe,s])).code!==0?{ok:!1,base:r,baseRef:o,sha:s,source:"mirror",remoteReachable:!0,reason:"base-stale",message:`could not update fleet trunk mirror ${FT} from ${o}`}:{ok:!0,base:r,baseRef:FT,sha:s,source:"mirror",remoteReachable:!0}}return{ok:!1,base:r,baseRef:o,sha:s??"",source:"mirror",remoteReachable:!1,reason:"base-stale",message:`could not refresh fleet trunk mirror ${FT} from ${o}`}}function Swr(e){return{code:1,stdout:"",stderr:e}}async function kAt(e,t){let r=t.branch.trim(),n=t.baseRef.trim(),o=t.remote?.trim()||"origin";if(!r||!n)return!1;let i=await $t(e,["rev-parse","--verify","--quiet",n]),s=i.code===0?i.stdout.trim():"";if(!s)return!1;let a=await yL(e,r),c=await hd(e,r),u=`refs/remotes/${o}/${r}`,l=await $t(e,["rev-parse","--verify","--quiet",u]),d=l.code===0&&l.stdout.trim()!=="",f=c?r:d?`${o}/${r}`:void 0,p=!1;if(f){let A=await $t(e,["merge-base",f,n]);p=A.code!==0||A.stdout.trim()!==s}let m=!!(a||c||d);return(t.force?m:p)?(a&&await Xo(e,a),c&&await ih(e,r),d&&await $t(e,["update-ref","-d",u]),await $t(e,["push",o,"--delete",r]),!0):!1}async function IAt(e,t,r){if(!t||!r)return!1;let n=await sh(e,t);if(!n){let i=await $t(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${t}`]);n=i.code===0&&i.stdout.trim()!==""?i.stdout.trim():void 0}return n?(await $t(e,["merge-base","--is-ancestor",n,`origin/${r}`])).code===0:!1}async function MT(e,t,r){let n=await $t(e,["diff","--name-only",`${r}...${t}`]);return n.code!==0?[]:n.stdout.split(`
|
|
@@ -6578,7 +6578,7 @@ Usage:
|
|
|
6578
6578
|
${n} archive --candidate <json> [--root <dir>] [--archive-dir <rel>]
|
|
6579
6579
|
${n} restore <name> [--root <dir>] [--archive-dir <rel>]`}function Sx(n){return bVn(typeof n.root=="string"?n.root:process.cwd())}function lut(n){return typeof n["archive-dir"]=="string"?n["archive-dir"]:void 0}async function DD(n){let a=await xs(n);return a?a.mode!=="graph"?{ok:!1,message:`curate: skill telemetry needs graph mode (this project is "${a.mode}") \u2014 run \`${cEe}\``}:ju(a)?{ok:!0}:{ok:!1,message:`curate: skill telemetry is not enabled here \u2014 run \`${cEe}\``}:{ok:!1,message:`curate: memory is not initialized here \u2014 run \`${cEe}\``}}function ZVn(){let n=uVn(pVn(import.meta.url));return n.includes("dist/curate-skill")||n.endsWith("dist/curate-skill")?nut(n,"..","cli.js"):nut(n,"..","cli.ts")}async function hVn(n,a){let i=["curate","skills","--json"];a!==void 0&&i.push("--stale-days",String(a));let d=ZVn(),h=d.endsWith(".ts")?tut(process.execPath,["--import","tsx",d,...i,"--root",n],{encoding:"utf8"}):tut(process.execPath,[d,...i,"--root",n],{encoding:"utf8"}),g=h.status??1;if(g!==0)throw new Error(`memory curate skills exited ${g}`);return qmt(h.stdout??"")}function WVn(n){return typeof n.flags["stale-days"]=="string"?Number(n.flags["stale-days"]):void 0}async function aut(n,a){return(a.loadCuratorReport??hVn)(Sx(n.flags),WVn(n))}async function NVn(n){let a=Sx(n.flags),i=await DD(a);return i.ok?(console.log("curate: skill telemetry is enabled \u2014 ready to curate"),0):(console.error(i.message),2)}async function YVn(n,a){let i=Sx(n.flags),d=await DD(i);if(!d.ok)return console.error(d.message),2;let u;try{u=await aut(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{candidates:h,byCategory:g,filtered:f}=aEe(u);return console.log(JSON.stringify({candidates:h,byCategory:g,filtered:f,totals:{totalSkills:u.totalSkills,curatableSkills:u.curatableSkills,readOnlySkills:u.readOnlySkills}},null,2)),0}async function VVn(n,a){let i=Sx(n.flags),d=await DD(i);if(!d.ok)return console.error(d.message),2;let u;try{u=await aut(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{byCategory:h}=aEe(u);if(rEe(h)===0)return console.error("curate: no candidates \u2014 no issue filed"),0;let g=typeof n.flags.label=="string"?n.flags.label:void 0,f=await eut({byCategory:h,totals:{totalSkills:u.totalSkills,curatableSkills:u.curatableSkills,readOnlySkills:u.readOnlySkills},generatedAt:u.generatedAt},{cwd:i,label:g});return console.log(`curate: filed background issue \u2014 ${f.output||f.title}`),0}async function gVn(n){let a=Sx(n.flags),i=await DD(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 u;try{u=JSON.parse(d)}catch(g){return console.error(`curate archive: invalid --candidate JSON: ${g.message}`),2}let h=await Kmt(u,{rootDir:a,archiveDir:lut(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 yVn(n){let a=Sx(n.flags),i=await DD(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 u=await Pmt(d,{rootDir:a,archiveDir:lut(n.flags)});return console.log(`curate: restored "${u.name}" \u2192 ${u.restoredRoot} (${u.files.length} file(s) hash-verified)`),0}async function iEe(n,a={}){switch(n.command){case"check":return NVn(n);case"list":return YVn(n,a);case"background":return VVn(n,a);case"archive":return gVn(n);case"restore":return yVn(n);case void 0:case"--help":case"-h":return console.log(Iut(a.usageCommand)),0;default:return console.error(`unknown curate subcommand: ${n.command}
|
|
6580
6580
|
|
|
6581
|
-
${Iut(a.usageCommand)}`),2}}function sEe(n){let a={app:n,version:RVn(Ux("__RED_BUILD_VERSION__",()=>"2.74.
|
|
6581
|
+
${Iut(a.usageCommand)}`),2}}function sEe(n){let a={app:n,version:RVn(Ux("__RED_BUILD_VERSION__",()=>"2.74.5")??"0.0.0-dev"),gitSha:Ux("__RED_BUILD_GIT_SHA__",()=>"4ce30c4b04883dcc4750241a651dfec458f7f047")??"unknown",buildTime:Ux("__RED_BUILD_TIME__",()=>"2026-07-18T23:22:31-03:00")??"unknown",bundleAsset:Ux("__RED_BUNDLE_ASSET__",()=>"memory.bundle.min.mjs")??"unknown"},i=Ux("__REDDB_SDK_VERSION__",()=>"1.23.1"),d=Ux("__REDDB_BINARY_TAG__",()=>"v1.23.1");return i&&(a.reddbSdkVersion=i),d&&(a.reddbBinaryTag=d),a}function RVn(n){return n.startsWith("v")?n.slice(1):n}function oEe(n){return`${n.app} ${n.version} ${n.gitSha}`}function Ux(n,a){try{let i=a();return typeof i=="string"&&i.length>0?i:void 0}catch{return process.env[n.replace(/^__|__$/g,"")]}}async function dut(n){let a=n.positional[0];if(a==="context")return QVn(n);if(a!=="skills")throw new Error("status needs a kind \u2014 supported: memory status skills|context");let i=pa(n.flags),d=n.flags.json===!0,u=await xs(i);if(!u)return dEe(d,"uninitialized","memory is not initialized here",{hint:"run `memory init --mode graph --skill-telemetry`"});if(u.mode!=="graph")return dEe(d,"no-op",`skill telemetry needs graph mode, this project is "${u.mode}"`,{hint:"re-run `memory init --mode graph --skill-telemetry`"});if(!ju(u))return dEe(d,"unavailable","skill telemetry is not enabled here",{hint:"re-run `memory init --mode graph --skill-telemetry`"});let h=n.flags.all===!0,g=Pa(n.flags,"limit")??10,f=await Xi.open({uri:di(i,u)}),J,S;try{J=await DG(f),S=await wx(f,g)}finally{await f.close()}let ne=J.filter(Pe=>Ox(Pe.source_kind)).length,be=h?J:J.filter(Pe=>Ox(Pe.source_kind)),j=h?S:S.filter(Pe=>Ox(Pe.source_kind));if(d){console.log(JSON.stringify({state:"enabled",scope:h?"all":"curatable",totalSkills:J.length,curatableSkills:ne,readOnlySkills:J.length-ne,skills:be,recentEvents:j},null,2));return}if(console.log("memory: skill telemetry status \u2014 enabled (graph mode)"),console.log(` ${J.length} ${Dv(J.length,"skill")} observed (${ne} curatable, ${J.length-ne} read-only)`),J.length===0){console.log(" no skills observed yet \u2014 telemetry is enabled but nothing has been recorded"),console.log(`
|
|
6582
6582
|
Diagnostic command: normal-use ingestion stays silent; this surface only reads.`);return}if(console.log(h?" scope: all observed skills (including bundled plugin/hub skills)":" scope: curatable skills (use --all to include bundled plugin/hub skills)"),be.length===0)console.log(" no curatable skills observed \u2014 re-run with --all to see bundled skills");else{console.log(`
|
|
6583
6583
|
skill / kind / events (v\xB7u\xB7p\xB7c\xB7r) / outcomes / last-activity:`);for(let Pe of be){let ye=zVn(Pe.outcome_counts);console.log(` ${Pe.name} (${Pe.source_kind}) \u2014 ${Pe.event_count} event(s) (v${Pe.view_count}\xB7u${Pe.use_count}\xB7p${Pe.patch_count}\xB7c${Pe.change_count}\xB7r${Pe.result_count})${ye?` ${ye}`:""} \u2014 ${Pe.last_activity}`)}}if(j.length>0){console.log(`
|
|
6584
6584
|
recent events (newest first, up to ${g}):`);for(let Pe of j){let ye=Pe.status?` [${Pe.status}]`:"";console.log(` ${Pe.timestamp} ${Pe.event_type}${ye} ${Pe.name} (${Pe.source_kind}) <${Pe.runner}>`)}}console.log(`
|
package/dist/rsp.bundle.min.mjs
CHANGED
|
@@ -155,7 +155,7 @@ const timer = setInterval(() => {
|
|
|
155
155
|
}, 500);
|
|
156
156
|
`,String(process.pid)],{detached:!0,stdio:"ignore"});return t.unref(),t}function _s(){for(let e of ZR())try{process.kill(e,"SIGTERM")}catch{}}function ZR(){if(process.platform==="win32")return[];let e="";try{e=DR("ps",["-eo","pid=,ppid=,args="],{encoding:"utf8"})}catch{return[]}let t=[];for(let r of e.split(/\n/)){let n=/^\s*(\d+)\s+(\d+)\s+([\s\S]*)$/.exec(r);if(!n)continue;let s=Number(n[1]),i=Number(n[2]),o=n[3]??"";i===process.pid&&/(^|\s)\S*red(?:\.exe)?\s+rpc\s+--stdio(\s|$)/.test(o)&&t.push(s)}return t}async function XR(e){if(e.collection!==ce)return e;let t=await cf(e.raw_text,lf(e.raw_bytes)),r=await cf(e.emitted_text,lf(e.emitted_bytes)),{raw_text:n,emitted_text:s,...i}=e;return{...i,tokens_raw:t.tokens,tokens_emitted:r.tokens,estimated:t.estimated||r.estimated}}async function cf(e,t){if(typeof e=="string"){let r=Buffer.byteLength(e,"utf8");if(r<=jR)try{return await hf((async()=>({tokens:(await eS())("cl100k_base").encode(e).length,estimated:!1}))(),UR,"telemetry tokenization timed out")}catch{return{tokens:Math.ceil(r/4),estimated:!0}}return{tokens:Math.ceil(r/4),estimated:!0}}return t!=null?{tokens:Math.ceil(t/4),estimated:!0}:{tokens:0,estimated:!1}}async function eS(){return uf??=import(BR(tS()).href).then(e=>{let t=e.getEncoding;if(!t)throw new Error("js-tiktoken getEncoding export not found");return t}),await uf}function tS(){let e=sa(LR(import.meta.url)),r=[bs(e,"..","node_modules","js-tiktoken","dist","index.js"),bs(e,"..","apps","rsp","node_modules","js-tiktoken","dist","index.js")].find(n=>AR(n));if(!r)throw new Error("js-tiktoken dependency not found");return r}function lf(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function H(e){return typeof e=="string"&&e.trim()!==""?e:void 0}function ra(e){return e.trim().split(/\s+/).filter(Boolean)[0]??"unknown"}async function hf(e,t,r){let n;try{return await Promise.race([e,new Promise((s,i)=>{n=setTimeout(()=>i(new Error(r)),t),n.unref()})])}finally{n&&clearTimeout(n)}}function rS(e){try{return JSON.parse(e)}catch{return e}}function nS(e){return df(e)&&e.version===1&&Array.isArray(e.records)&&e.records.every(t=>df(t)&&(t.collection===te||t.collection===G||t.collection===ce||t.collection===Ce)&&typeof t.key=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string"&&typeof t.bytes=="number")}function df(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sS(e,t){let r="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",n=>{r+=n;let s=r.indexOf(`
|
|
157
157
|
`);if(s<0)return;let i=r.slice(0,s);e.pause(),(async()=>{let o;try{o=JSON.parse(i),await t(o)}catch(a){let u={id:o?.id??sr(),ok:!1,error:a instanceof Error?a.message:String(a)};yf(e,u)}finally{e.end()}})()})}function yf(e,t){if(!(e.destroyed||!e.writable))try{e.write(`${JSON.stringify(t)}
|
|
158
|
-
`)}catch{}}async function iS(e,t,r,n){if(t.op==="handover")return{handover:!0,version:n,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 s=e.store;if(t.op==="ping")return{pong:!0,version:n};if(t.op==="stats")return await s.stats();if(t.op==="accounting-stats"){let i=s.redDb();if(!i)throw new Error("rsp accounting stats require the shared RedDB store");return await Ji(i,t.byteBudget)}if(t.op==="telemetry-stats"){let i=s.redDb();if(!i)throw new Error("rsp telemetry stats require the shared RedDB store");return await Bn(i,t.sinceDays)}if(t.op==="telemetry-gains"){let i=s.redDb();if(!i)throw new Error("rsp telemetry gains require the shared RedDB store");return await Gi(i,t.sinceDays)}if(t.op==="mint")return{handle:await s.mint(Buffer.from(t.original,"base64"),t.meta)};if(t.op==="get")return aS(await s.get(t.handle));if(t.op==="memory")return await s.memory(t.action,t.payload);if(t.op==="brain")return await oS(s,r,t.action,t.payload);throw new Error(`unsupported resident op: ${t.op??"unknown"}`)}async function oS(e,t,r,n){let s=e.redDb();if(!s)throw new Error("resident brain operations require the shared RedDB store");return await Xd(s,t).request(r,n)}function aS(e){return e?"status"in e?e:{...e,original:e.original.toString("base64"),original_encoding:"base64"}:null}var jR,UR,mf,FR,JR,GR,na,af,uf,bf=_(()=>{"use strict";Be();wn();Me();et();sf();_e();Pe();jR=256*1024,UR=500,mf=2e3,FR=Math.max(1,Number(process.env.RSP_TEST_IDLE_SHUTDOWN_WATCHDOG_MS??"10000")),JR="rsp-status-summary.json",GR=[te,G,ce,Ce,Cr],na=class{constructor(t,r){this.store=t;this.opts=r;this.pendingHeals=[...r.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 r=await qR(t);r.unshift(...this.pendingHeals),this.pendingHeals=[];let n=await this.readIndex(t),s=n.records.length,i=[...n.records];for(let a of r)i.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 Fi(this.opts.rootDir,async a=>{let c=Kt(a);if(!c){let u=await this.writeDrainDegradation(t,{reason:"telemetry parse failed",command:"unknown",bytes:Buffer.byteLength(a,"utf8")});return i.push(u),!0}try{let u=await this.writeEvent(t,c);i.push(u);let l=await this.writeAccountingMirror(t,c);return l&&i.push(l),!0}catch(u){let l=await this.writeDrainDegradation(t,{reason:"telemetry event dropped",command:H(c.command)||"unknown",source_id:H(c.id),source_collection:H(c.collection),error:u instanceof Error?u.message:String(u),bytes:Buffer.byteLength(a,"utf8")});return i.push(l),!0}});let o=i.length>s;await this.prune(t,{version:1,records:i},o),await HR(t,this.opts.rootDir)}async writeEvent(t,r){let n=new Date,s=typeof r.created_at=="string"?r.created_at:n.toISOString(),i=new Date(Date.parse(s)+this.opts.ttlDays*24*60*60*1e3).toISOString(),o=typeof r.id=="string"&&r.id.trim()!==""?r.id:sr(),a={...await XR(r),id:o,created_at:s,expires_at:i};return await t.kv(r.collection).put(o,a),{collection:r.collection,key:o,created_at:s,expires_at:i,bytes:r.collection===te?0:typeof r.bytes=="number"&&Number.isFinite(r.bytes)?Math.max(0,r.bytes):Buffer.byteLength(JSON.stringify(a),"utf8")}}async writeAccountingMirror(t,r){return r.collection===te||r.accounting_recorded===!0?null:r.collection===ce?await this.writeEvent(t,{collection:te,id:`mirror:${H(r.id)||sr()}`,created_at:H(r.created_at)||H(r.ts)||new Date().toISOString(),event_type:"invocation",command:H(r.command)||"unknown",command_class:ra(H(r.command)||"unknown"),wrapper:r.wrapper,loss:r.loss,elided:r.elided,raw_bytes:r.raw_bytes,emitted_bytes:r.emitted_bytes,tokens_raw:r.tokens_raw,tokens_emitted:r.tokens_emitted,estimated:r.estimated,wrapper_ms:r.wrapper_ms,store_open_count:r.store_open_count,store_elapsed_ms:r.store_elapsed_ms}):r.collection===Ce?await this.writeEvent(t,{collection:te,id:`mirror:${H(r.id)||sr()}`,created_at:H(r.created_at)||H(r.ts)||new Date().toISOString(),event_type:"invocation",command:H(r.command)||"unknown",command_class:ra(H(r.command)||"unknown"),loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:H(r.reason)||"unknown",wrapper_family:H(r.wrapper_family),wrapper_exit_code:r.wrapper_exit_code,stderr_head:H(r.stderr_head)}):null}async writeDrainDegradation(t,r){let n=await this.writeEvent(t,{collection:Ce,id:sr(),created_at:new Date().toISOString(),reason:r.reason,command:r.command,bytes:r.bytes,source_id:r.source_id,source_collection:r.source_collection,error:r.error});return await this.writeEvent(t,{collection:te,id:`mirror:${sr()}`,created_at:n.created_at,event_type:"invocation",command:r.command,command_class:ra(r.command),loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:r.reason,source_id:r.source_id,source_collection:r.source_collection,error:r.error}),n}async readIndex(t){let r=await t.kv(Cr).get("index:v1"),n=typeof r=="string"?rS(r):r;return nS(n)?n:{version:1,records:[]}}async writeIndex(t,r){await t.kv(Cr).put("index:v1",r)}async prune(t,r,n=!1){let s=Date.now(),i=[];for(let a of r.records)Date.parse(a.expires_at)<=s?await t.kv(a.collection).delete(a.key):i.push(a);let o=i.reduce((a,c)=>a+c.bytes,0);for(i.sort((a,c)=>a.created_at.localeCompare(c.created_at));o>this.opts.byteBudget&&i.length>0;){let a=i.shift();o-=a.bytes,await t.kv(a.collection).delete(a.key)}(n||i.length<r.records.length)&&await this.writeIndex(t,{version:1,records:i})}};af=!1});ve();function ge(e,t){let r=e.indexOf(t);return r>=0?e[r+1]:void 0}function U(e,t){let r=ge(e,t);if(r==null)return;let n=Number(r);return Number.isFinite(n)&&n>0?n:void 0}function Pa(e){return e[0]==="--help"||e[0]==="-h"||e.includes("--help")||e.includes("-h")}function Ca(e){let t={level:"lossless",positional:[]},r=[];for(let n=0;n<e.length;n++){let s=e[n];if(s==="--store-uri")t.storeUri=e[++n];else if(s==="--brief")t.level="brief";else if(s==="--terse")t.level="terse";else if(s==="--query")t.query=e[++n];else if(s.startsWith("--query="))t.query=s.slice(8);else{if(r.length===0&&s.startsWith("--"))throw new js(s);r.push(s)}}return t.query&&r[0]!=="show"&&!r.some(n=>n==="--query"||n.startsWith("--query="))&&r.push("--query",t.query),t.command=r[0],t.handle=r[1],t.positional=r,t}var js=class extends Error{constructor(r){super(`unknown flag: ${r}`);this.flag=r}render(){return sn("rsp",this.flag,["--store-uri","--brief","--terse","--query"],"rsp --help")}};function $t(e){return typeof e=="object"&&e!==null&&"render"in e&&typeof e.render=="function"}function Da(e){let t=e[1];if(!t)return null;let r={};for(let n=2;n<e.length;n++){let s=e[n];if(s!=="-f"&&s!=="-F")continue;let i=e[++n]??"",o=i.indexOf("=");o<=0||(r[i.slice(0,o)]=i.slice(o+1))}return{path:t,params:r}}function on(e,t){let r=ge(e,"--since")??e.find(i=>i.startsWith("--since="))?.slice(8);if(!r)return t;let n=/^(\d+)(d)?$/.exec(r);if(!n)return t;let s=Number(n[1]);return Number.isFinite(s)&&s>0?s:t}function Ia(e){return e.includes("--full")}Me();import{existsSync as cS}from"node:fs";import{fileURLToPath as uS}from"node:url";function Ma(e){let t={app:e,version:up(Bt("__RED_BUILD_VERSION__",()=>"2.74.
|
|
158
|
+
`)}catch{}}async function iS(e,t,r,n){if(t.op==="handover")return{handover:!0,version:n,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 s=e.store;if(t.op==="ping")return{pong:!0,version:n};if(t.op==="stats")return await s.stats();if(t.op==="accounting-stats"){let i=s.redDb();if(!i)throw new Error("rsp accounting stats require the shared RedDB store");return await Ji(i,t.byteBudget)}if(t.op==="telemetry-stats"){let i=s.redDb();if(!i)throw new Error("rsp telemetry stats require the shared RedDB store");return await Bn(i,t.sinceDays)}if(t.op==="telemetry-gains"){let i=s.redDb();if(!i)throw new Error("rsp telemetry gains require the shared RedDB store");return await Gi(i,t.sinceDays)}if(t.op==="mint")return{handle:await s.mint(Buffer.from(t.original,"base64"),t.meta)};if(t.op==="get")return aS(await s.get(t.handle));if(t.op==="memory")return await s.memory(t.action,t.payload);if(t.op==="brain")return await oS(s,r,t.action,t.payload);throw new Error(`unsupported resident op: ${t.op??"unknown"}`)}async function oS(e,t,r,n){let s=e.redDb();if(!s)throw new Error("resident brain operations require the shared RedDB store");return await Xd(s,t).request(r,n)}function aS(e){return e?"status"in e?e:{...e,original:e.original.toString("base64"),original_encoding:"base64"}:null}var jR,UR,mf,FR,JR,GR,na,af,uf,bf=_(()=>{"use strict";Be();wn();Me();et();sf();_e();Pe();jR=256*1024,UR=500,mf=2e3,FR=Math.max(1,Number(process.env.RSP_TEST_IDLE_SHUTDOWN_WATCHDOG_MS??"10000")),JR="rsp-status-summary.json",GR=[te,G,ce,Ce,Cr],na=class{constructor(t,r){this.store=t;this.opts=r;this.pendingHeals=[...r.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 r=await qR(t);r.unshift(...this.pendingHeals),this.pendingHeals=[];let n=await this.readIndex(t),s=n.records.length,i=[...n.records];for(let a of r)i.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 Fi(this.opts.rootDir,async a=>{let c=Kt(a);if(!c){let u=await this.writeDrainDegradation(t,{reason:"telemetry parse failed",command:"unknown",bytes:Buffer.byteLength(a,"utf8")});return i.push(u),!0}try{let u=await this.writeEvent(t,c);i.push(u);let l=await this.writeAccountingMirror(t,c);return l&&i.push(l),!0}catch(u){let l=await this.writeDrainDegradation(t,{reason:"telemetry event dropped",command:H(c.command)||"unknown",source_id:H(c.id),source_collection:H(c.collection),error:u instanceof Error?u.message:String(u),bytes:Buffer.byteLength(a,"utf8")});return i.push(l),!0}});let o=i.length>s;await this.prune(t,{version:1,records:i},o),await HR(t,this.opts.rootDir)}async writeEvent(t,r){let n=new Date,s=typeof r.created_at=="string"?r.created_at:n.toISOString(),i=new Date(Date.parse(s)+this.opts.ttlDays*24*60*60*1e3).toISOString(),o=typeof r.id=="string"&&r.id.trim()!==""?r.id:sr(),a={...await XR(r),id:o,created_at:s,expires_at:i};return await t.kv(r.collection).put(o,a),{collection:r.collection,key:o,created_at:s,expires_at:i,bytes:r.collection===te?0:typeof r.bytes=="number"&&Number.isFinite(r.bytes)?Math.max(0,r.bytes):Buffer.byteLength(JSON.stringify(a),"utf8")}}async writeAccountingMirror(t,r){return r.collection===te||r.accounting_recorded===!0?null:r.collection===ce?await this.writeEvent(t,{collection:te,id:`mirror:${H(r.id)||sr()}`,created_at:H(r.created_at)||H(r.ts)||new Date().toISOString(),event_type:"invocation",command:H(r.command)||"unknown",command_class:ra(H(r.command)||"unknown"),wrapper:r.wrapper,loss:r.loss,elided:r.elided,raw_bytes:r.raw_bytes,emitted_bytes:r.emitted_bytes,tokens_raw:r.tokens_raw,tokens_emitted:r.tokens_emitted,estimated:r.estimated,wrapper_ms:r.wrapper_ms,store_open_count:r.store_open_count,store_elapsed_ms:r.store_elapsed_ms}):r.collection===Ce?await this.writeEvent(t,{collection:te,id:`mirror:${H(r.id)||sr()}`,created_at:H(r.created_at)||H(r.ts)||new Date().toISOString(),event_type:"invocation",command:H(r.command)||"unknown",command_class:ra(H(r.command)||"unknown"),loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:H(r.reason)||"unknown",wrapper_family:H(r.wrapper_family),wrapper_exit_code:r.wrapper_exit_code,stderr_head:H(r.stderr_head)}):null}async writeDrainDegradation(t,r){let n=await this.writeEvent(t,{collection:Ce,id:sr(),created_at:new Date().toISOString(),reason:r.reason,command:r.command,bytes:r.bytes,source_id:r.source_id,source_collection:r.source_collection,error:r.error});return await this.writeEvent(t,{collection:te,id:`mirror:${sr()}`,created_at:n.created_at,event_type:"invocation",command:r.command,command_class:ra(r.command),loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:r.reason,source_id:r.source_id,source_collection:r.source_collection,error:r.error}),n}async readIndex(t){let r=await t.kv(Cr).get("index:v1"),n=typeof r=="string"?rS(r):r;return nS(n)?n:{version:1,records:[]}}async writeIndex(t,r){await t.kv(Cr).put("index:v1",r)}async prune(t,r,n=!1){let s=Date.now(),i=[];for(let a of r.records)Date.parse(a.expires_at)<=s?await t.kv(a.collection).delete(a.key):i.push(a);let o=i.reduce((a,c)=>a+c.bytes,0);for(i.sort((a,c)=>a.created_at.localeCompare(c.created_at));o>this.opts.byteBudget&&i.length>0;){let a=i.shift();o-=a.bytes,await t.kv(a.collection).delete(a.key)}(n||i.length<r.records.length)&&await this.writeIndex(t,{version:1,records:i})}};af=!1});ve();function ge(e,t){let r=e.indexOf(t);return r>=0?e[r+1]:void 0}function U(e,t){let r=ge(e,t);if(r==null)return;let n=Number(r);return Number.isFinite(n)&&n>0?n:void 0}function Pa(e){return e[0]==="--help"||e[0]==="-h"||e.includes("--help")||e.includes("-h")}function Ca(e){let t={level:"lossless",positional:[]},r=[];for(let n=0;n<e.length;n++){let s=e[n];if(s==="--store-uri")t.storeUri=e[++n];else if(s==="--brief")t.level="brief";else if(s==="--terse")t.level="terse";else if(s==="--query")t.query=e[++n];else if(s.startsWith("--query="))t.query=s.slice(8);else{if(r.length===0&&s.startsWith("--"))throw new js(s);r.push(s)}}return t.query&&r[0]!=="show"&&!r.some(n=>n==="--query"||n.startsWith("--query="))&&r.push("--query",t.query),t.command=r[0],t.handle=r[1],t.positional=r,t}var js=class extends Error{constructor(r){super(`unknown flag: ${r}`);this.flag=r}render(){return sn("rsp",this.flag,["--store-uri","--brief","--terse","--query"],"rsp --help")}};function $t(e){return typeof e=="object"&&e!==null&&"render"in e&&typeof e.render=="function"}function Da(e){let t=e[1];if(!t)return null;let r={};for(let n=2;n<e.length;n++){let s=e[n];if(s!=="-f"&&s!=="-F")continue;let i=e[++n]??"",o=i.indexOf("=");o<=0||(r[i.slice(0,o)]=i.slice(o+1))}return{path:t,params:r}}function on(e,t){let r=ge(e,"--since")??e.find(i=>i.startsWith("--since="))?.slice(8);if(!r)return t;let n=/^(\d+)(d)?$/.exec(r);if(!n)return t;let s=Number(n[1]);return Number.isFinite(s)&&s>0?s:t}function Ia(e){return e.includes("--full")}Me();import{existsSync as cS}from"node:fs";import{fileURLToPath as uS}from"node:url";function Ma(e){let t={app:e,version:up(Bt("__RED_BUILD_VERSION__",()=>"2.74.5")??"0.0.0-dev"),gitSha:Bt("__RED_BUILD_GIT_SHA__",()=>"4ce30c4b04883dcc4750241a651dfec458f7f047")??"unknown",buildTime:Bt("__RED_BUILD_TIME__",()=>"2026-07-18T23:22:31-03:00")??"unknown",bundleAsset:Bt("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},r=Bt("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=Bt("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function up(e){return e.startsWith("v")?e.slice(1):e}function Bt(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}ve();Me();pr();import{existsSync as Xh}from"node:fs";import{fileURLToPath as ey}from"node:url";oi();Me();ui();import{existsSync as Xg}from"node:fs";import{fileURLToPath as eh}from"node:url";async function Xt(e,t){let r={stats:th(e.telemetryByteBudget),telemetry:Wi(t)};if(!e.storeUri.startsWith("file://"))return r;let n=eh(e.storeUri);if(!Xg(n))return r;if(!n.endsWith("red-skills.rdb")){let{RspElisionStore:c}=await Promise.resolve().then(()=>(et(),Wt)),u=await c.open({uri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget});try{return{stats:await u.stats(),telemetry:Wi(t)}}finally{await u.close()}}let{ensureReddbBinaryFromWarmCache:s}=await Promise.resolve().then(()=>(et(),Wt));await s();let{readAccountingLaneStats:i,readTelemetryStats:o}=await Promise.resolve().then(()=>(_e(),Ar)),a=await Ut(e.storeUri);try{return{stats:await i(a,e.telemetryByteBudget),telemetry:await o(a,t)}}finally{await a.close()}}function Vi(e,t=Wi(30),r=!1){return`${j(zi(e,t,r))}
|
|
159
159
|
`}function zi(e,t,r){let n=t.savings.top_commands.slice(0,r?10:3),s=r?t.savings.daily_tokens_saved:t.savings.daily_tokens_saved.slice(-7),i=e.storage_classes??Mn(),o=t.health.recent_failures.slice(0,r?20:5),a=t.decisions.top_pass_reasons.slice(0,r?10:3);return{records:e.records,bytes:e.bytes,oldest:e.oldest,budget:e.budget,storage_classes:i,savings:{window_days:t.window_days,empty:t.empty,...t.savings,tokens_saved_display:rh(t.savings),dollars_saved_estimate_usd_display:nh(t.savings),daily_tokens_saved:s,daily_tokens_saved_elided:r?0:Math.max(0,t.savings.daily_tokens_saved.length-s.length),top_commands:n,top_commands_elided:r?0:Math.max(0,t.savings.top_commands.length-n.length)},health:{...t.health,degradation_rate_display:qi(t.health.degradation_rate),show_hit_rate_display:qi(t.health.show_hit_rate),by_reason:t.health.by_reason,by_family:t.health.by_family,recent_failures:o,recent_failures_elided:r?0:Math.max(0,t.health.recent_failures.length-o.length),most_recent_degradation_at:t.health.most_recent?.timestamp??null,most_recent_degradation_reason:t.health.most_recent?.reason??null},decisions:{...t.decisions,contribution_rate_display:qi(t.decisions.contribution_rate),top_pass_reasons:a,top_pass_reasons_elided:r?0:Math.max(0,t.decisions.top_pass_reasons.length-a.length)},latency:{...t.latency,wrapper_ms_p50_display:Hi(t.latency.wrapper_ms_p50),wrapper_ms_p95_display:Hi(t.latency.wrapper_ms_p95),store_elapsed_ms_avg_display:Hi(t.latency.store_elapsed_ms_avg)}}}function gu(e){return`${j(e)}
|
|
160
160
|
`}function Wi(e){return{window_days:e,empty:!0,savings:{invocations:0,elided:0,raw_bytes:0,emitted_bytes:0,bytes_saved:0,tokens_saved:0,tokens_saved_estimated:!1,token_estimate_range_pct:null,tokens_saved_low:null,tokens_saved_high:null,dollars_saved_estimate_usd:0,dollars_saved_low_usd:null,dollars_saved_high_usd:null,pricing_model_family:"gpt-5",pricing_input_usd_per_million_tokens:1.25,pricing_note:"estimate derived from byte-based token estimate when token counts are estimated",daily_tokens_saved:[],top_commands:[]},health:{degradations:0,degradation_rate:0,show_total:0,show_hits:0,show_misses:0,show_hit_rate:0,by_reason:[],by_family:[],recent_failures:[],most_recent:null},latency:{wrapper_ms_p50:null,wrapper_ms_p95:null,store_open_count_sum:0,store_elapsed_ms_sum:0,store_elapsed_ms_avg:null},decisions:{seen:0,contributed:0,passed:0,failed_open:0,quota_free_saved_units:0,contribution_rate:0,top_pass_reasons:[]}}}function th(e){return{records:0,bytes:0,oldest:null,budget:e,storage_classes:Mn()}}function Mn(){return{derivable:{records:0,bytes:0,raw_bytes:0},"re-executable":{records:0,bytes:0,raw_bytes:0},ephemeral:{records:0,bytes:0,raw_bytes:0}}}function Ki(e){let t=e.legacyStoreMigrated?"migrated":e.storeCreated?"created":"existing";return[`config: ${e.configChanged?"updated":"unchanged"}`,`store: ${t}`,""].join(`
|
|
161
161
|
`)}function rh(e){return e.tokens_saved_estimated?`${e.tokens_saved_low}-${e.tokens_saved_high} (estimate_midpoint: ${e.tokens_saved}, range_pct: ${e.token_estimate_range_pct})`:String(e.tokens_saved)}function nh(e){return e.dollars_saved_low_usd==null||e.dollars_saved_high_usd==null?_r(e.dollars_saved_estimate_usd):`${_r(e.dollars_saved_low_usd)}-${_r(e.dollars_saved_high_usd)} (estimate_midpoint: ${_r(e.dollars_saved_estimate_usd)})`}function Hi(e){return e==null?"none":String(e)}function qi(e){return e.toFixed(4).replace(/0+$/,"").replace(/\.$/,".0")}async function Ou(e){let{stats:t,telemetry:r}=await Xt(e,30),[n,s]=await Promise.all([ty(e),Promise.resolve().then(()=>(ao(),oo)).then(i=>i.listWaits(process.cwd()),()=>[])]);return{stats:t,telemetry:r,recoveryHandles:n,waits:s}}function Pu(e){let t=zi(e.stats,e.telemetry,!1),r=Fs({executable:{name:"rsp",command:"rsp"},recovery:{pending:e.recoveryHandles.length,handles:e.recoveryHandles},waits:{active:e.waits.length,entries:e.waits},store:{records:e.stats.records,bytes:e.stats.bytes,oldest:e.stats.oldest,budget:e.stats.budget,storage_classes:e.stats.storage_classes??Mn()},savings:t.savings,health:t.health,decisions:t.decisions,latency:t.latency},ry(e));return`${j(r)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reddb-io/red-skills",
|
|
3
|
-
"version": "2.74.
|
|
3
|
+
"version": "2.74.5",
|
|
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",
|