@reddb-io/red-skills 2.34.0 → 2.34.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -74,7 +74,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
74
74
|
`:`[${n[c]}\r
|
|
75
75
|
]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function uc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=cc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ac(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function C_(t,e){if(e.mapStrategy==="record")return uc(t,e);let r=Q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Be(e),n=Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function O_(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function N_(t){return t.target==="openAi"?void 0:{not:Be({...t,currentPath:[...t.currentPath,"not"]})}}function j_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var is={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function M_(t,e){if(e.target==="openApi3")return D_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in is&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=is[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return D_(t,e)}var D_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Q(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function A_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:is[t.innerType._def.typeName],nullable:!0}:{type:[is[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function q_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",gf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?he(r,"minimum",n.value,n.message,e):he(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),he(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?he(r,"maximum",n.value,n.message,e):he(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),he(r,"maximum",n.value,n.message,e));break;case"multipleOf":he(r,"multipleOf",n.value,n.message,e);break}return r}function Z_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let l=Mz(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let f=Q(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});f!==void 0&&(n.properties[a]=f,l||o.push(a))}o.length&&(n.required=o);let s=Dz(t,e);return s!==void 0&&(n.additionalProperties=s),n}function Dz(t,e){if(t.catchall._def.typeName!=="ZodNever")return Q(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mz(t){try{return t.isOptional()}catch{return!0}}var L_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Q(t.innerType._def,e);let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Be(e)},r]}:Be(e)};var F_=(t,e)=>{if(e.pipeStrategy==="input")return Q(t.in._def,e);if(e.pipeStrategy==="output")return Q(t.out._def,e);let r=Q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function U_(t,e){return Q(t.type._def,e)}function V_(t,e){let n={type:"array",uniqueItems:!0,items:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&he(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&he(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function H_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function B_(t){return{not:Be(t)}}function W_(t){return Be(t)}var J_=(t,e)=>Q(t.innerType._def,e);var K_=(t,e,r)=>{switch(e){case D.ZodString:return cc(t,r);case D.ZodNumber:return q_(t,r);case D.ZodObject:return Z_(t,r);case D.ZodBigInt:return $_(t,r);case D.ZodBoolean:return k_();case D.ZodDate:return yf(t,r);case D.ZodUndefined:return B_(r);case D.ZodNull:return j_(r);case D.ZodArray:return x_(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return M_(t,r);case D.ZodIntersection:return z_(t,r);case D.ZodTuple:return H_(t,r);case D.ZodRecord:return uc(t,r);case D.ZodLiteral:return E_(t,r);case D.ZodEnum:return R_(t);case D.ZodNativeEnum:return O_(t);case D.ZodNullable:return A_(t,r);case D.ZodOptional:return L_(t,r);case D.ZodMap:return C_(t,r);case D.ZodSet:return V_(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return U_(t,r);case D.ZodNaN:case D.ZodNever:return N_(r);case D.ZodEffects:return P_(t,r);case D.ZodAny:return Be(r);case D.ZodUnknown:return W_(r);case D.ZodDefault:return T_(t,r);case D.ZodBranded:return ac(t,r);case D.ZodReadonly:return J_(t,r);case D.ZodCatch:return S_(t,r);case D.ZodPipeline:return F_(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}};function Q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==v_)return a}if(n&&!r){let a=Az(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=K_(t,t.typeName,e),s=typeof i=="function"?Q(i(),e):i;if(s&&qz(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var Az=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Be(e)):e.$refStrategy==="seen"?Be(e):void 0}},qz=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var bf=(t,e)=>{let r=w_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,f])=>({...c,[l]:Q(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Be(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Be(r),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Zz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function wf(t,e){return Kt(t)?Fd(t,{target:Zz(e?.target),io:e?.pipeStrategy??"input"}):bf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function xf(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $f(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var Lz=6e4,lc=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ua,r=>{this._oncancel(r)}),this.setNotificationHandler(Ha,r=>{this._onprogress(r)}),this.setRequestHandler(Va,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ba,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ja,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,f=this._requestResolvers.get(l);if(f)if(this._requestResolvers.delete(l),a.type==="response")f(c);else{let p=c,w=new B(p.error.code,p.error.message,p.error.data);f(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new B(G.InvalidParams,`Task not found: ${i}`);if(!cn(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(cn(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[an]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Ka,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new B(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Xa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(cn(o.status))throw new B(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new B(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof B?o:new B(G.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Gi(i)||a_(i)?this._onresponse(i):tf(i)?this._onrequest(i,s):s_(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=B.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[an]?.taskId;if(n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(f).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=n_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};i&&(p.relatedTask={taskId:i}),await this.notification(f,p)},sendRequest:async(f,p,w)=>{if(s.signal.aborted)throw new B(G.ConnectionClosed,"Request was cancelled");let b={...w,relatedRequestId:e.id};i&&!b.relatedTask&&(b.relatedTask={taskId:i});let g=b.relatedTask?.taskId??i;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(f,p,b)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async f=>{if(s.signal.aborted)return;let p={result:f,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async f=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:G.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Gi(e))n(e);else{let s=new B(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Gi(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Gi(e))o(e);else{let s=B.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}return}let i;try{let s=await this.request(e,jo,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new B(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},cn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new B(G.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(G.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,f)=>{let p=O=>{f(O)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(O){p(O);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(b.params={...b.params,task:a}),c&&(b.params={...b.params,_meta:{...b.params?._meta||{},[an]:c}});let g=O=>{this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(O)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`)));let z=O instanceof B?O:new B(G.RequestTimeout,String(O));f(z)};this._responseHandlers.set(w,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return f(O);try{let z=on(r,O.result);z.success?l(z.data):f(z.error)}catch(z){f(z)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let x=n?.timeout??Lz,S=()=>g(B.fromError(G.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(w,x,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let N=c?.taskId;if(N){let O=z=>{let Z=this._responseHandlers.get(w);Z?Z(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,O),this._enqueueTaskMessage(N,{type:"request",message:b,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),f(z)})}else this._transport.send(b,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(O=>{this._cleanupTimeout(w),f(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Wa,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ga,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},l_,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[an]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[an]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[an]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=xf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=$f(e,o);return Promise.resolve(r(s,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=xf(e);this._notificationHandlers.set(n,o=>{let i=$f(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&tf(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new B(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new B(G.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new B(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=ts.parse({method:"notifications/tasks/status",params:a});await this.notification(c),cn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new B(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(cn(a.status))throw new B(G.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=ts.parse({method:"notifications/tasks/status",params:c});await this.notification(l),cn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function G_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X_(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let s=r[o];G_(s)&&G_(i)?r[o]={...s,...i}:r[o]=i}return r}var Fw=la(um(),1),Uw=la(Lw(),1);function Vj(){let t=new Fw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Uw.default)(t),t}var Hc=class{constructor(e){this._ajv=e??Vj()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Bc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(f=>f.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(f=>f.type==="tool_use");if(s){if(i.some(f=>f.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let f=new Set(c.filter(w=>w.type==="tool_use").map(w=>w.id)),p=new Set(i.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(f.size!==p.size||![...f].every(w=>p.has(w)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},os,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},Ao,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Vw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Hw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Wc=class extends lc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ns.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Hc,this.setRequestHandler(of,n=>this._oninitialize(n)),this.setNotificationHandler(sf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(pf,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=ns.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Bc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=X_(this._capabilities,e)}setRequestHandler(e,r){let o=sn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Kt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,l)=>{let f=on(Mo,c);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new B(G.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:p}=f.data,w=await Promise.resolve(r(c,l));if(p.task){let g=on(jo,w);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new B(G.InvalidParams,`Invalid task creation result: ${x}`)}return g.data}let b=on(oc,w);if(!b.success){let g=b.error instanceof Error?b.error.message:String(b.error);throw new B(G.InvalidParams,`Invalid tools/call result: ${g}`)}return b.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Hw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Vw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:e_.includes(r)?r:Qd,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Fa)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(l=>l.type==="tool_use");if(i){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==f.size||![...l].every(p=>f.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},mf,r):this.request({method:"sampling/createMessage",params:e},os,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Ao,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Ao,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new B(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof B?s:new B(G.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},hf,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Ww=Symbol.for("mcp.completable");function ym(t){return!!t&&typeof t=="object"&&Ww in t}function Jw(t){return t[Ww]?.complete}var Bw;(function(t){t.Completable="McpCompletable"})(Bw||(Bw={}));var Hj=/^[A-Za-z0-9._-]{1,128}$/;function Bj(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Hj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Wj(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function _m(t){let e=Bj(t);return Wj(t,e.warnings),e.isValid}var Jc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Kc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Wc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Jc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(nc)),this.server.assertCanSetRequestHandler(yn(Mo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(nc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Oo(r.inputSchema);return o?wf(o,{strictUnions:!0,pipeStrategy:"input"}):Jj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Oo(r.outputSchema);o&&(n.outputSchema=wf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Mo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new B(G.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new B(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof B&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let i=Oo(e.inputSchema)??e.inputSchema,s=await Na(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=ja(a);throw new B(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Oo(e.outputSchema),i=await Na(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ja(s);throw new B(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(e.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,f=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(w=>setTimeout(w,f));let p=await n.taskStore.getTask(c);if(!p)throw new B(G.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(yn(ic)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ic,async e=>{switch(e.params.ref.type){case"ref/prompt":return g_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return y_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return js;let i=sn(n.argsSchema)?.[e.params.argument.name];if(!ym(i))return js;let s=Jw(i);if(!s)return js;let a=await s(e.params.argument.value,e.params.context);return Gw(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return js;throw new B(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return js;let i=await o(e.params.argument.value,e.params.context);return Gw(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(Ya)),this.server.assertCanSetRequestHandler(yn(Qa)),this.server.assertCanSetRequestHandler(yn(ec)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ya,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Qa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ec,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(G.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new B(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(tc)),this.server.assertCanSetRequestHandler(yn(rc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(tc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Kj(r.argsSchema):void 0}))})),this.server.setRequestHandler(rc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Oo(n.argsSchema),i=await Na(o,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=ja(c);throw new B(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,n,o,i){let s={name:e,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(e,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Qn(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Qn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,o&&Object.values(o).some(c=>{let l=c instanceof zt?c._def?.innerType:c;return ym(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,r,n,o,i,s,a,c,l){_m(e);let f={title:r,description:n,inputSchema:Kw(o),outputSchema:Kw(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>f.update({enabled:!1}),enable:()=>f.update({enabled:!0}),remove:()=>f.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&_m(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=f)),typeof p.title<"u"&&(f.title=p.title),typeof p.description<"u"&&(f.description=p.description),typeof p.paramsSchema<"u"&&(f.inputSchema=Qn(p.paramsSchema)),typeof p.outputSchema<"u"&&(f.outputSchema=Qn(p.outputSchema)),typeof p.callback<"u"&&(f.handler=p.callback),typeof p.annotations<"u"&&(f.annotations=p.annotations),typeof p._meta<"u"&&(f._meta=p._meta),typeof p.enabled<"u"&&(f.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=f,this.setToolRequestHandlers(),this.sendToolListChanged(),f}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(vm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!vm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,i,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(e,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(e,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Jj={type:"object",properties:{}};function Xw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Yw(t){return"_def"in t||"_zod"in t||Xw(t)}function vm(t){return typeof t!="object"||t===null||Yw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Xw)}function Kw(t){if(t){if(vm(t))return Qn(t);if(!Yw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Kj(t){let e=sn(t);return e?Object.entries(e).map(([r,n])=>{let o=Ey(n),i=Iy(n);return{name:r,description:o,required:!i}}):[]}function yn(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Gw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var js={completion:{values:[],hasMore:!1}};import ex from"node:process";var Gc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
76
76
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Gj(r)}clear(){this._buffer=void 0}};function Gj(t){return c_.parse(JSON.parse(t))}function Qw(t){return JSON.stringify(t)+`
|
|
77
|
-
`}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.34.
|
|
77
|
+
`}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.34.1")??"0.0.0-dev"),gitSha:ni("__RED_BUILD_GIT_SHA__",()=>"3da9554e72932153d1511cb549758c33b524906a")??"unknown",buildTime:ni("__RED_BUILD_TIME__",()=>"2026-07-12T18:04:50-03:00")??"unknown",bundleAsset:ni("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=ni("__REDDB_SDK_VERSION__",()=>""),n=ni("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function Xj(t){return t.startsWith("v")?t.slice(1):t}function rx(t){return`${t.app} ${t.version} ${t.gitSha}`}function ni(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var bm={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function nx(){let t=process.env.CODE_NAV_SERVERS;if(!t)return bm;try{let e=JSON.parse(t),r={...bm};for(let[n,o]of Object.entries(e))r[n]={...r[n]??{},...o};return r}catch(e){return process.stderr.write(`code-nav: failed to parse CODE_NAV_SERVERS, using defaults: ${String(e)}
|
|
78
78
|
`),bm}}function ox(t){let e=new Map;for(let[r,n]of Object.entries(t))for(let o of n.extensions)e.set(o,r);return e}var $i=la(jk(),1),xt=la(Jh(),1);import{spawn as t1}from"node:child_process";import{readFile as r1}from"node:fs/promises";import{pathToFileURL as Dk,fileURLToPath as n1}from"node:url";import{resolve as o1}from"node:path";var Hs=class{constructor(e,r){this.spec=e;this.rootPath=r}spec;rootPath;proc;conn;ready;openDocs=new Set;async ensureStarted(){return this.ready?this.ready:(this.ready=this.start(),this.ready)}async start(){let e=t1(this.spec.command,this.spec.args,{cwd:this.rootPath,stdio:["pipe","pipe","pipe"]});this.proc=e,await new Promise((i,s)=>{e.once("spawn",()=>i()),e.once("error",a=>s(new Error(`failed to spawn '${this.spec.command}': ${a.message}`)))}),e.stderr.on("data",i=>{process.stderr.write(`[${this.spec.command}] ${i.toString()}`)}),e.once("exit",()=>{try{this.conn?.dispose()}catch{}});let r=(0,$i.createProtocolConnection)(new $i.StreamMessageReader(e.stdout),new $i.StreamMessageWriter(e.stdin));this.conn=r,r.listen();let n=Dk(this.rootPath).toString(),o={processId:process.pid,rootUri:n,workspaceFolders:[{uri:n,name:"workspace"}],capabilities:{textDocument:{definition:{linkSupport:!0},references:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},hover:{contentFormat:["markdown","plaintext"]}},workspace:{symbol:{}}}};await r.sendRequest(xt.InitializeRequest.type,o),await r.sendNotification(xt.InitializedNotification.type,{})}async ensureOpen(e){let r=o1(this.rootPath,e),n=Dk(r).toString();if(this.openDocs.has(n))return n;let o=await r1(r,"utf8");return await this.conn.sendNotification(xt.DidOpenTextDocumentNotification.type,{textDocument:{uri:n,languageId:this.spec.languageId,version:1,text:o}}),this.openDocs.add(n),n}async definition(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e),i=await this.conn.sendRequest(xt.DefinitionRequest.type,{textDocument:{uri:o},position:{line:r,character:n}});return i1(i)}async references(e,r,n,o){await this.ensureStarted();let i=await this.ensureOpen(e);return await this.conn.sendRequest(xt.ReferencesRequest.type,{textDocument:{uri:i},position:{line:r,character:n},context:{includeDeclaration:o}})??[]}async documentSymbols(e){await this.ensureStarted();let r=await this.ensureOpen(e);return await this.conn.sendRequest(xt.DocumentSymbolRequest.type,{textDocument:{uri:r}})??[]}async hover(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e);return this.conn.sendRequest(xt.HoverRequest.type,{textDocument:{uri:o},position:{line:r,character:n}})}async workspaceSymbols(e){return await this.ensureStarted(),await this.conn.sendRequest(xt.WorkspaceSymbolRequest.type,{query:e})??[]}dispose(){try{this.conn?.dispose()}catch{}this.proc?.kill()}};function i1(t){return t?(Array.isArray(t)?t:[t]).map(r=>"targetUri"in r?{uri:r.targetUri,range:r.targetSelectionRange}:r):[]}function Kh(t,e){try{let r=n1(t);return(r.startsWith(e)?r.slice(e.length).replace(/^[/\\]/,""):r)||r}catch{return t}}var Ws=process.env.CODE_NAV_ROOT??process.cwd(),Bs=nx(),Mk=ox(Bs),ki=new Map;function Au(t){let e=s1(t),r=Mk.get(e);if(!r)throw new Error(`no language server configured for '${e}'. Configured extensions: ${[...Mk.keys()].join(", ")||"(none)"}.`);let n=ki.get(r);return n||(n=new Hs(Bs[r],Ws),ki.set(r,n)),n}function a1(){for(let t of Object.keys(Bs))ki.has(t)||ki.set(t,new Hs(Bs[t],Ws));return[...ki.values()]}function Xh(t,e){return`${Kh(t,Ws)}:${e.start.line+1}:${e.start.character+1}`}var Gh=tx("code-nav"),Si=new Kc({name:"code-nav",version:Gh.version}),qu={file:tn.string().describe("Workspace-relative path to the source file."),line:tn.number().int().describe("Zero-based line number."),character:tn.number().int().describe("Zero-based character offset on the line.")};Si.registerTool("goto_definition",{title:"Go to definition",description:"Resolve the symbol at a file position to its definition(s). Returns file:line:column locations. Use this instead of grepping for a name.",inputSchema:qu},async({file:t,line:e,character:r})=>{let n=await Au(t).definition(t,e,r);return n.length===0?Cr("No definition found."):Cr(n.map(o=>Xh(o.uri,o.range)).join(`
|
|
79
79
|
`))});Si.registerTool("find_references",{title:"Find references",description:"Find every reference to the symbol at a file position across the workspace. Semantic \u2014 matches the actual symbol, not text.",inputSchema:{...qu,includeDeclaration:tn.boolean().optional().describe("Include the declaration itself (default true).")}},async({file:t,line:e,character:r,includeDeclaration:n})=>{let o=await Au(t).references(t,e,r,n??!0);return o.length===0?Cr("No references found."):Cr(`${o.length} reference(s):
|
|
80
80
|
`+o.map(i=>Xh(i.uri,i.range)).join(`
|
package/dist/dev.bundle.min.mjs
CHANGED
|
@@ -825,7 +825,7 @@ requeued to ready-for-agent${e.activeBlocker?` (cleared active blocker: ${e.acti
|
|
|
825
825
|
`)},I)}catch(k){return process.stderr.write(`[afk] respond failed: ${k instanceof Error?k.message:String(k)}
|
|
826
826
|
`),1}return r.write(`Respond #${o}: ${v.action}${v.verb?` (/dev ${v.verb})`:""}.
|
|
827
827
|
`),0}OC();function cxr(e){let t=e.indexOf("--runner");return(t>=0?e[t+1]:void 0)==="claude"?"claude":"codex"}function uxr(e){let t=GP(void 0,{runner:e});return JSON.stringify(e==="codex"?{systemMessage:t}:{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:t}})}async function Yft(e){let t=cxr(e),r=GP(void 0,{runner:t});return process.stdout.write(e.includes("--hook")?uxr(t):r),e.includes("--hook")&&process.stdout.write(`
|
|
828
|
-
`),0}import{existsSync as Gxr,statSync as qxr}from"node:fs";import{join as fpt,basename as zxr}from"node:path";function MY(e){let t={app:e,version:lxr(OR("__RED_BUILD_VERSION__",()=>"2.34.
|
|
828
|
+
`),0}import{existsSync as Gxr,statSync as qxr}from"node:fs";import{join as fpt,basename as zxr}from"node:path";function MY(e){let t={app:e,version:lxr(OR("__RED_BUILD_VERSION__",()=>"2.34.1")??"0.0.0-dev"),gitSha:OR("__RED_BUILD_GIT_SHA__",()=>"3da9554e72932153d1511cb549758c33b524906a")??"unknown",buildTime:OR("__RED_BUILD_TIME__",()=>"2026-07-12T18:04:50-03:00")??"unknown",bundleAsset:OR("__RED_BUNDLE_ASSET__",()=>"dev.bundle.min.mjs")??"unknown"},r=OR("__REDDB_SDK_VERSION__",()=>""),n=OR("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function lxr(e){return e.startsWith("v")?e.slice(1):e}function Jft(e){return`${e.app} ${e.version} ${e.gitSha}`}function OR(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function LY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.floor(e/1e3)}k`:String(e)}function Xft(e){let t=(r,n)=>{let o=(Math.round(r*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${n}`};return e>=1e9?t(e/1e9,"B"):e>=1e6?t(e/1e6,"M"):e>=1e3?t(e/1e3,"k"):String(e>0?e:0)}function ept(e){let t=e.toLowerCase();for(let r of["opus","sonnet","haiku","fable"])if(t.includes(r))return r;return e}function dxr(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60);if(r<60)return`${r}m${t%60}s`;let n=Math.floor(r/60);return n<24?`${n}h${r%60}m`:`${Math.floor(n/24)}d${n%24}h`}function NR(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let r=Math.floor(t/60),n=t%60;return n>0?`${r}h${n}m`:`${r}h`}function Kft(e){let t=e.basename;if(e.branch){let r=e.branch;return r.length>28&&(r=`${r.slice(0,27)}\u2026`),`${t} (${r})`}return e.detachedSha?`${t} (detached ${e.detachedSha})`:t}function fxr(e){return!e||!e.model?null:e.effort?`${e.model}\xB7${e.effort}`:e.model}function Zft(e){if(!e)return null;let t=e.contextTokens;if(t===void 0||t===0)return null;let r=LY(t);return e.contextPercent===void 0?r:`${r} ${Math.round(e.contextPercent)}%`}function pxr(e){if(!e||e.workers<=0)return[];let t=[],r=(i,s)=>{t.push({label:i,value:s,suffix:""})};if(e.workers>0&&r("wrk=",String(e.workers)),e.sourceCounts&&e.sourceCounts.length>0)for(let{origin:i,count:s}of e.sourceCounts)r(`${i}=`,String(s));let n=e.cacheAgeS!==void 0?` (${NR(e.cacheAgeS)})`:"";if(e.queue>0&&t.push({label:"rdy=",value:String(e.queue),suffix:n}),e.human>0){let i=n&&e.queue===0?n:"";t.push({label:"hmn=",value:String(e.human),suffix:i})}e.blocked>0&&r("blk=",String(e.blocked));let o=[];return e.added>0&&o.push(`+${e.added}`),e.removed>0&&o.push(`-${e.removed}`),o.length&&r("loc=",e.locIsPeak?`~${o.join(" ")}`:o.join(" ")),e.waiting!==void 0&&e.waiting>0&&r("wai=",String(e.waiting)),e.tokens!==void 0&&e.tokens>0&&r("tok=",LY(e.tokens)),e.costUsd!==void 0&&e.costUsd>0&&r("usd=",e.costUsd.toFixed(2)),e.issues.forEach((i,s)=>{let a=e.phases?.[s],c=e.aliveMs?.[s],u=a?`\xB7${a}`:"";c!==void 0&&c>0&&(u+=`\xB7${dxr(c)}`),t.push({label:"#",value:String(i),suffix:u})}),t}function mxr(e){if(!e)return null;let t=[];return e.usage5h!==void 0&&t.push(`5h=${Math.round(e.usage5h)}%`),e.usage7d!==void 0&&t.push(`7d=${Math.round(e.usage7d)}%`),t.length?t.join(" "):null}function hxr(e){if(!e)return null;let t=[],r=e.cacheAgeS!==void 0?` (${NR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(`prs=${e.openPrs}${r}`),e.todayPrs&&e.todayPrs>0){let o=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(`cpr=${e.todayPrs}${o}`)}if(e.openIssues&&e.openIssues>0){let o=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(`iss=${e.openIssues}${o}`)}let n=[];return e.localAdded&&e.localAdded>0&&n.push(`+${e.localAdded}`),e.localRemoved&&e.localRemoved>0&&n.push(`-${e.localRemoved}`),n.length&&t.push(`loc=${n.join(" ")}`),t.length?t.join(" "):null}function gxr(e){if(!e||!e.openIssues||e.openIssues<=0)return null;let t=e.cacheAgeS!==void 0?` (${NR(e.cacheAgeS)})`:"";return`iss=${e.openIssues}${t}`}function Cye(e){if(!e)return null;let t=e.runner||"?",r=Math.max(0,Math.floor(e.busy)),n=Math.max(0,Math.floor(e.total)),o=Math.max(0,Math.floor(e.queue)),i=[`flt=${t} ${r}/${n} busy`,`q=${o}`];return e.parked!==void 0&&e.parked>0&&i.push(`park=${Math.floor(e.parked)}`),i.join(" \xB7 ")}function FY(e){return e?e==="on"?"rsp\u25CF":"rsp\u25CB":null}function Axr(e){let t=pxr(e);return t.length===0?null:t.map(r=>`${r.label}${r.value}${r.suffix}`).join(" ")}function tpt(e,t="full"){if(t==="short"){let l=[Kft(e.project)],d=Zft(e.claude);d!==null&&l.push(`ctx=${d}`);let f=gxr(e.repo);f!==null&&l.push(f);let p=FY(e.rsp);return p!==null&&l.push(p),l.join(" \xB7 ")}let r=[Kft(e.project)],n=fxr(e.claude);n!==null&&r.push(n);let o=Zft(e.claude);o!==null&&r.push(o);let i=mxr(e.claude);i!==null&&r.push(i);let s=hxr(e.repo);s!==null&&r.push(s);let a=Cye(e.fleet);a!==null&&r.push(a);let c=FY(e.rsp);c!==null&&r.push(c);let u=Axr(e.afk);return u!==null&&r.push(u),r.join(" \xB7 ")}var yxr="\x1B[48;2;114;47;55m",xxr="\x1B[48;2;88;36;42m",opt="\x1B[49m",LC="\x1B[38;2;255;255;255m",ipt="\x1B[38;2;255;214;214m",spt="\x1B[39m",PR="\x1B[38;2;224;138;148m",uM="\x1B[38;2;201;150;158m",Exr="\x1B[38;2;96;214;128m",bxr="\x1B[38;2;240;200;120m",apt="\x1B[1m",cpt="\x1B[22m",upt="\x1B[0m",Sxr=28,Cxr=" ",UY=["workerId","run","org","iss","phase","elapsed","loc","tks","tls","rsn","txt"],wxr=["workerId","iss","phase","elapsed"],Ixr=new Set(["requeue"]),kxr=new Set(["gate","push-pr","merge","cascade"]),vxr=e=>e.replace(/\x1b\[[0-9;]*m/g,"");function lpt(e){return vxr(e).length}function Rxr(e,t){return e+" ".repeat(Math.max(0,t-lpt(e)))}var Lx=(e,t)=>`${ipt}${e}=${spt}${t}${PR}`;function Bxr(e,t){let r=[];return e&&e>0&&r.push(`+${e}`),t&&t>0&&r.push(`-${t}`),r.length?r.join(" "):null}function _xr(e){return e.runner==="claude"&&e.tokens===0?"\u2014":Xft(e.tokens)}function Txr(e,t=!0){let r="";if(e.branch){let o=e.branch.length>Sxr?`${e.branch.slice(0,27)}\u2026`:e.branch;r=` ${uM}(${o})${LC}`}else e.detachedSha&&(r=` ${uM}(detached ${e.detachedSha})${LC}`);let n=t&&e.version?` ${uM}v${e.version}${LC}`:"";return`${bxr}\xBB${LC} ${apt}${e.basename}${cpt}${r}${n}`}function Dxr(e){return!e||!e.model?null:e.effort?`${e.model}${uM}\xB7${LC}${e.effort}`:e.model}function rpt(e){if(!e||!e.contextTokens)return null;let t=LY(e.contextTokens),r=e.contextPercent===void 0?t:`${t} ${Math.round(e.contextPercent)}%`;return Lx("ctx",r)}function Qxr(e){if(!e)return[];let t=[];return e.usage5h!==void 0&&t.push(Lx("5h",`${Math.round(e.usage5h)}%`)),e.usage7d!==void 0&&t.push(Lx("7d",`${Math.round(e.usage7d)}%`)),t}function Oxr(e){if(!e)return[];let t=[],r=e.cacheAgeS!==void 0?` (${NR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(Lx("prs",String(e.openPrs))+r),e.todayPrs&&e.todayPrs>0){let n=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(Lx("cpr",String(e.todayPrs))+n)}if(e.openIssues&&e.openIssues>0){let n=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(Lx("iss",String(e.openIssues))+n)}return t}function Nxr(e){if(!e)return[];let t=Bxr(e.localAdded,e.localRemoved);return t?[Lx("loc",t)]:[]}function Pxr(e){let t=Cye(e);return t?[t]:[]}function npt(e){let t=FY(e);return t?e==="on"?[`${Exr}${t}${PR}`]:[`${uM}${t}${PR}`]:[]}function Mxr(e,t,r,n,o="full",i){let s=`${xxr}${LC} ${Txr(e,o==="full")} `,a=Dxr(t);o==="full"&&a!==null&&(s+=`${yxr}${LC} ${a} `),s+=`${opt}${PR}`;let c=o==="short"?[rpt(t),r&&r.openIssues&&r.openIssues>0?Lx("iss",String(r.openIssues))+(r.cacheAgeS!==void 0?` (${NR(r.cacheAgeS)})`:""):null,...npt(i)].filter(u=>u!==null):[rpt(t),...Qxr(t),...Oxr(r),...Nxr(r),...Pxr(n),...npt(i)].filter(u=>u!==null);return c.length&&(s+=` ${c.join(" ")}`),`${s}${upt}`}function Fxr(e,t){return[e,t].filter(Boolean).join("\xB7")}function Lxr(e,t){let r=Kdt(e,t),n=[r.runner,r.model?ept(r.model):void 0,r.effort].filter(s=>!!s).join(" "),o=kxr.has(r.phase),i=o||r.origin!==void 0&&Ixr.has(r.origin);return{workerId:r.workerId,run:`run=${n}`,org:`org=${o?"landing":r.origin||"afk"}`,iss:r.issue===null?"":`iss=${String(r.issue)}`,phase:r.issue===null?"":Fxr(r.phase,r.activity),elapsed:r.elapsed,loc:i?"":`loc=${sM(r.added,r.removed)}`,tks:i?"":`tks=${_xr(r)}`,tls:i?"":`tls=${String(r.tools)}`,rsn:i?"":`rsn=${String(r.reasoning)}`,txt:i?"":`txt=${String(r.text)}`}}function Uxr(e,t=UY){let r=Object.fromEntries(UY.map(n=>[n,0]));for(let n of e)for(let o of t)r[o]=Math.max(r[o],lpt(n[o]));return r}function $xr(e,t){if(e==="workerId")return`${apt}${t}${cpt}`;let r=t.indexOf("=");return r>0?`${ipt}${t.slice(0,r+1)}${spt}${t.slice(r+1)}${PR}`:t}function Hxr(e,t,r=UY){let n=r.map(o=>$xr(o,Rxr(e[o],t[o])));return`${opt}${PR}${n.join(Cxr)}${upt}`}function Wxr(e,t,r="full"){let n=e.map(s=>Lxr(s,t)),o=r==="short"?wxr:UY,i=Uxr(n,o);return n.map(s=>Hxr(s,i,o))}function jxr(e,t={}){let r=t.preset??"full",n=[Mxr(e.project,e.claude,e.repo,e.fleet,r,e.rsp)],o=t.now??0;return n.push(...Wxr(t.workers??[],o,r)),n.join(`
|
|
829
829
|
`)}function dpt(e,t,r={}){let n=r.preset??"full";return t?jxr(e,r):tpt(e,n)}Mo();OP();function Vxr(e){return new Promise(t=>{if(e.isTTY){t("");return}let r="",n=!1,o=()=>{n||(n=!0,t(r))};e.setEncoding("utf8"),e.on("data",i=>{r+=i}),e.on("end",o),e.on("error",o),e.on("close",o)})}function Yxr(e){if(!e.trim())return{};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function Jxr(e){try{return qxr(e).isDirectory()}catch{return!1}}function Kxr(e,t,r){if(e&&Jxr(e))return e;let n=t.workspace?.project_dir||t.workspace?.current_dir||t.cwd;return n||r}function Zxr(e){let t=fpt(e,".red","config.yaml");if(!Gxr(t))return!0;let r=Cr(t,{warn:()=>{}});return!(Pe(r,"statusline")==="false"||Pe(r,"afk.statusline")==="false")}function $Y(e){return e==="full"||e==="short"?e:void 0}function Xxr(e){return $Y(Pe(e,"plugins.dev.statusline.preset"))??$Y(Pe(e,"dev.statusline.preset"))??$Y(Pe(e,"afk.statusline.preset"))??$Y(Pe(e,"statusline.preset"))??"full"}async function eEr(e,t=process.env){if(!wAe(e,t).enabled)return;let n=IAe(e);return await kAe(n.socketPath,50)?"on":"warming"}async function tEr(e){let t={cwd:e},r=MY("dev").version,n={basename:zxr(e),version:r},o=await gP(t);if(o)return{...n,branch:o};let i=await hg(t);return i?{...n,detachedSha:i}:n}function rEr(e){let t=e.model?.display_name,r=e.effort?.level,n=e.context_window?.total_input_tokens,o=e.context_window?.used_percentage,i=e.rate_limits?.five_hour?.used_percentage,s=e.rate_limits?.seven_day?.used_percentage;if(!(t===void 0&&n===void 0&&i===void 0&&s===void 0))return{model:t||void 0,effort:r||void 0,contextTokens:n,contextPercent:o,usage5h:i,usage7d:s}}async function ppt(e,t=process.cwd(),r=process.stdout,n=process.stdin){if(e.includes("--legend"))return r.write(`${_Y()}
|
|
830
830
|
`),0;let o=e[0],i=await Vxr(n),s=Yxr(i),a=Kxr(o,s,t);if(!Zxr(a))return 0;let c=await tEr(a),u=rEr(s),l={root:a,repo:hR(a),remote:"origin"},d=Cr(fpt(a,".red","config.yaml"),{warn:()=>{}}),f=Xxr(d),p=P4(process.env,_=>Pe(d,_)),g=`origin/${await lf({issueBody:""},{readLockedBranch:()=>bg(Bx(a)),configLockedBranch:Pe(d,"dev.lock.branch"),configTrunk:Pe(d,"dev.trunk"),fetchIssueBody:async()=>{}})}`,[A,E,y,b,w]=await Promise.all([Gat(l,p,g),Hat(l,p).then(_=>_??void 0),Wat(l),jat(l),eEr(a)]),I=!process.env.NO_COLOR,v=Number.parseInt(process.env.COLUMNS??"",10),k=Math.floor(Date.now()/1e3),R=dpt({project:c,claude:u,repo:A,fleet:y,afk:E,rsp:w},I,{columns:Number.isFinite(v)&&v>0?v:void 0,workers:b,now:k,preset:f});return r.write(`${R}
|
|
831
831
|
`),0}async function mpt(e,t=process.cwd()){let r=e[0]??t,n="",o="";for(let i=1;i<e.length;i+=1){let s=e[i];s==="--repo"?n=e[++i]??"":s==="--lock"&&(o=e[++i]??"")}return await $at(r,n||hR(r),o||void 0),0}ew();import{spawn as Bpt}from"node:child_process";import{existsSync as Iye,openSync as Tpt,closeSync as dEr,writeFileSync as Dpt,writeSync as fEr,rmSync as kye,renameSync as pEr}from"node:fs";import{join as UC}from"node:path";import{existsSync as nEr,readdirSync as lM,readFileSync as HY,statSync as ypt}from"node:fs";import{join as ls}from"node:path";ru();Vd();function oEr(e,t){return ls(e,`afk-supervisor-slot-${t}.log`)}function iEr(e){let t;try{t=HY(e,"utf8")}catch{return[]}let r=[],n=new Set;for(let o of t.split(`
|
|
@@ -6561,7 +6561,7 @@ Usage:
|
|
|
6561
6561
|
${n} archive --candidate <json> [--root <dir>] [--archive-dir <rel>]
|
|
6562
6562
|
${n} restore <name> [--root <dir>] [--archive-dir <rel>]`}function Fx(n){return AWn(typeof n.root=="string"?n.root:process.cwd())}function not(n){return typeof n["archive-dir"]=="string"?n["archive-dir"]:void 0}async function Yj(n){let a=await Co(n);return a?a.mode!=="graph"?{ok:!1,message:`curate: skill telemetry needs graph mode (this project is "${a.mode}") \u2014 run \`${iwe}\``}:sZ(a)?{ok:!0}:{ok:!1,message:`curate: skill telemetry is not enabled here \u2014 run \`${iwe}\``}:{ok:!1,message:`curate: memory is not initialized here \u2014 run \`${iwe}\``}}function xWn(){let n=kWn(LWn(import.meta.url));return n.includes("dist/curate-skill")||n.endsWith("dist/curate-skill")?eot(n,"..","cli.js"):eot(n,"..","cli.ts")}async function zWn(n,a){let i=["curate","skills","--json"];a!==void 0&&i.push("--stale-days",String(a));let d=xWn(),h=d.endsWith(".ts")?$st(process.execPath,["--import","tsx",d,...i,"--root",n],{encoding:"utf8"}):$st(process.execPath,[d,...i,"--root",n],{encoding:"utf8"}),y=h.status??1;if(y!==0)throw new Error(`memory curate skills exited ${y}`);return Kst(h.stdout??"")}function OWn(n){return typeof n.flags["stale-days"]=="string"?Number(n.flags["stale-days"]):void 0}async function Iot(n,a){return(a.loadCuratorReport??zWn)(Fx(n.flags),OWn(n))}async function UWn(n){let a=Fx(n.flags),i=await Yj(a);return i.ok?(console.log("curate: skill telemetry is enabled \u2014 ready to curate"),0):(console.error(i.message),2)}async function MWn(n,a){let i=Fx(n.flags),d=await Yj(i);if(!d.ok)return console.error(d.message),2;let b;try{b=await Iot(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{candidates:h,byCategory:y,filtered:w}=cwe(b);return console.log(JSON.stringify({candidates:h,byCategory:y,filtered:w,totals:{totalSkills:b.totalSkills,curatableSkills:b.curatableSkills,readOnlySkills:b.readOnlySkills}},null,2)),0}async function BWn(n,a){let i=Fx(n.flags),d=await Yj(i);if(!d.ok)return console.error(d.message),2;let b;try{b=await Iot(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{byCategory:h}=cwe(b);if(rwe(h)===0)return console.error("curate: no candidates \u2014 no issue filed"),0;let y=typeof n.flags.label=="string"?n.flags.label:void 0,w=await qst({byCategory:h,totals:{totalSkills:b.totalSkills,curatableSkills:b.curatableSkills,readOnlySkills:b.readOnlySkills},generatedAt:b.generatedAt},{cwd:i,label:y});return console.log(`curate: filed background issue \u2014 ${w.output||w.title}`),0}async function SWn(n){let a=Fx(n.flags),i=await Yj(a);if(!i.ok)return console.error(i.message),2;let d=n.flags.candidate;if(typeof d!="string")return console.error("curate archive: --candidate <json> is required"),2;let b;try{b=JSON.parse(d)}catch(y){return console.error(`curate archive: invalid --candidate JSON: ${y.message}`),2}let h=await jst(b,{rootDir:a,archiveDir:not(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 TWn(n){let a=Fx(n.flags),i=await Yj(a);if(!i.ok)return console.error(i.message),2;let d=n.positional[0];if(!d)return console.error("curate restore: skill name is required"),2;let b=await Dst(d,{rootDir:a,archiveDir:not(n.flags)});return console.log(`curate: restored "${b.name}" \u2192 ${b.restoredRoot} (${b.files.length} file(s) hash-verified)`),0}async function lot(n,a={}){switch(n.command){case"check":return UWn(n);case"list":return MWn(n,a);case"background":return BWn(n,a);case"archive":return SWn(n);case"restore":return TWn(n);case void 0:case"--help":case"-h":return console.log(tot(a.usageCommand)),0;default:return console.error(`unknown curate subcommand: ${n.command}
|
|
6563
6563
|
|
|
6564
|
-
${tot(a.usageCommand)}`),2}}function aot(n){let a={app:n,version:jWn(Xx("__RED_BUILD_VERSION__",()=>"2.34.
|
|
6564
|
+
${tot(a.usageCommand)}`),2}}function aot(n){let a={app:n,version:jWn(Xx("__RED_BUILD_VERSION__",()=>"2.34.1")??"0.0.0-dev"),gitSha:Xx("__RED_BUILD_GIT_SHA__",()=>"3da9554e72932153d1511cb549758c33b524906a")??"unknown",buildTime:Xx("__RED_BUILD_TIME__",()=>"2026-07-12T18:04:50-03:00")??"unknown",bundleAsset:Xx("__RED_BUNDLE_ASSET__",()=>"memory.bundle.min.mjs")??"unknown"},i=Xx("__REDDB_SDK_VERSION__",()=>"1.23.1"),d=Xx("__REDDB_BINARY_TAG__",()=>"v1.23.1");return i&&(a.reddbSdkVersion=i),d&&(a.reddbBinaryTag=d),a}function jWn(n){return n.startsWith("v")?n.slice(1):n}function cot(n){return`${n.app} ${n.version} ${n.gitSha}`}function Xx(n,a){try{let i=a();return typeof i=="string"&&i.length>0?i:void 0}catch{return process.env[n.replace(/^__|__$/g,"")]}}var rot=`memory \u2014 governed operational memory for code agents
|
|
6565
6565
|
|
|
6566
6566
|
Common workflows:
|
|
6567
6567
|
remember one fact memory store "Decision: ..."
|
package/dist/rsp.bundle.min.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`)){let i=r.replace(/\r$/,""),s=i.trim();if(!s||s.startsWith("#"))continue;let o=i.indexOf(":");if(o<0)continue;let a=i.length-i.trimStart().length,c=i.slice(0,o).trim();if(!c)continue;let l=i.slice(o+1).trim();for(;n.length&&n[n.length-1].indent>=a;)n.pop();if(n.push({indent:a,key:c}),l&&n.map(d=>d.key).join(".")===t)return
|
|
3
|
+
var _i=Object.defineProperty;var g=(e,t)=>()=>(e&&(t=e(e=0)),t);var P=(e,t)=>{for(var n in t)_i(e,n,{get:t[n],enumerable:!0})};import{existsSync as Ii,readFileSync as el}from"node:fs";import{dirname as vi,join as Ni}from"node:path";function on(e,t){let n=e;for(let r=0;r<16;r++){let i=Ni(n,t);if(Ii(i))return i;let s=vi(n);if(s===n)break;n=s}return null}function Li(e){let t=e.indexOf(" #");return(t>=0?e.slice(0,t):e).trim()}function ot(e,t){let n=[];for(let r of e.split(`
|
|
4
|
+
`)){let i=r.replace(/\r$/,""),s=i.trim();if(!s||s.startsWith("#"))continue;let o=i.indexOf(":");if(o<0)continue;let a=i.length-i.trimStart().length,c=i.slice(0,o).trim();if(!c)continue;let l=i.slice(o+1).trim();for(;n.length&&n[n.length-1].indent>=a;)n.pop();if(n.push({indent:a,key:c}),l&&n.map(d=>d.key).join(".")===t)return Li(l)}}var an=g(()=>{});var dn={};P(dn,{DEFAULT_RSP_BYTE_BUDGET:()=>U,DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>j,DEFAULT_RSP_STORE_PATH:()=>Be,DEFAULT_RSP_TTL_DAYS:()=>B,resolveRspConfig:()=>M});import{readFileSync as Di}from"node:fs";import{dirname as cn,join as ln,resolve as un}from"node:path";function M(e,t,n){let r=on(un(e),ln(".red","config.yaml")),i=r?cn(cn(r)):e,s=r?Di(r,"utf8"):"",o=ot(s,"rsp.enabled")==="true",a=ct(at(s,"rsp.ttlDays"),B),c=ct(at(s,"rsp.byteBudget"),U),l=ct(ji(t.RSP_HEAVY_GIT_BYTE_THRESHOLD)??at(s,"rsp.heavyGitByteThreshold"),j),u=n??t.RSP_STORE_URI??`file://${ln(un(i),Be)}`;return{enabled:o,storeUri:u,ttlDays:a,byteBudget:c,heavyGitByteThreshold:l}}function at(e,t){let n=ot(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function ct(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function ji(e){if(e==null||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)?t:void 0}var j,Be,B,U,C=g(()=>{"use strict";an();j=8*1024,Be=".red/tmp/red-skills.rdb",B=7,U=64*1024*1024});import{createConnection as Bi}from"node:net";async function lt(e,t){let n=e.timeoutMs??1e3;return await new Promise((r,i)=>{let s=Bi(e.socketPath),o=!1,a="",c=setTimeout(()=>{l(()=>i(new Error("resident rsp server timed out"))),s.destroy()},n);function l(u){o||(o=!0,clearTimeout(c),u())}s.on("connect",()=>{s.write(`${JSON.stringify(t)}
|
|
5
5
|
`)}),s.on("data",u=>{a+=u.toString("utf8");let d=a.indexOf(`
|
|
6
|
-
`);if(d<0)return;let y=a.slice(0,d);l(()=>{try{r(JSON.parse(y))}catch(E){i(E)}}),s.end()}),s.on("error",u=>l(()=>i(u))),s.on("close",()=>{o||l(()=>i(new Error("resident rsp server closed without response")))})})}var
|
|
7
|
-
`,status:0}:{stdout:"",status:1}}async function Yi(e){let t=e?Rn(e,"utf8"):Rn(0,"utf8"),n=await Sn(t,{cwd:process.cwd()}),r=xn(n);return r.stdout&&process.stdout.write(r.stdout),r.status}function Zi(e){return M(e,process.env).enabled}async function Xi(e){let t=se(e);return await X(t.socketPath,50)}async function es(e){let t=M(e,process.env);if(!t.enabled||!ns(t))return;let n=se(e);await
|
|
8
|
-
`,n+=2;continue}if(r==="t"){t+=" ",n+=2;continue}if(r==="r"){t+="\r",n+=2;continue}if(r==="\\"){t+="\\",n+=2;continue}if(r==='"'){t+='"',n+=2;continue}if(r==="u"){if(n+6>e.length)throw new SyntaxError(`Invalid escape sequence: truncated \\u escape at "${e.slice(n,n+6)}"`);let i=e.slice(n+2,n+6);if(!/^[0-9a-f]{4}$/i.test(i))throw new SyntaxError(`Invalid escape sequence: \\u must be followed by 4 hex digits, got "${i}"`);let s=Number.parseInt(i,16);if(s>=55296&&s<=57343)throw new SyntaxError(`Invalid escape sequence: \\u${i} is a lone surrogate; supplementary code points MUST appear as literal UTF-8`);t+=String.fromCodePoint(s),n+=6;continue}throw new SyntaxError(`Invalid escape sequence: \\${r}`)}t+=e[n],n++}return t}function He(e,t){let n=t+1;for(;n<e.length;){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==='"')return n;n++}return-1}function gt(e,t,n=0){let r=!1,i=n;for(;i<e.length;){if(e[i]==="\\"&&i+1<e.length&&r){i+=2;continue}if(e[i]==='"'){r=!r,i++;continue}if(e[i]===t&&!r)return i;i++}return-1}function T(e,t){try{return t()}catch(n){throw n instanceof A?n:n instanceof Error?new A(n.message,{line:e.lineNumber,source:e.raw,cause:n}):n}}function jn(e){return e==="true"||e==="false"||e==="null"}function cs(e){if(!e||!as.test(e))return!1;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)}function Me(e,t,n=!1){let r=e.trimStart(),i=-1;if(r.startsWith('"')){let p=He(r,0);if(p===-1||!r.slice(p+1).startsWith("["))return;let b=e.length-r.length+p+1;i=e.indexOf("[",b)}else i=e.indexOf("[");if(i===-1)return;let s=e.indexOf("]",i);if(s===-1)return;let o=s+1,a=o,c=e.indexOf("{",s);if(c!==-1&&c<e.indexOf(":",s)){let p=e.slice(s+1,c);if(p!==""){if(n){let D=p.trim();throw new SyntaxError(D===""?"Unexpected whitespace between bracket and fields segment":`Unexpected content "${D}" between bracket and fields segment`)}return}let b=e.indexOf("}",c);b!==-1&&(a=b+1)}if(o=e.indexOf(":",Math.max(s,a)),o===-1)return;let l=Math.max(s+1,a),u=e.slice(l,o);if(u!==""){if(n){let p=u.trim();throw new SyntaxError(p===""?"Unexpected whitespace between bracket segment and colon":`Unexpected content "${p}" between bracket segment and colon`)}return}let d;if(i>0){let p=e.slice(0,i).trim();d=p.startsWith('"')?yt(p):p}let y=e.slice(o+1).trim(),E=e.slice(i+1,s),R;try{R=us(E,t)}catch(p){if(n)throw p;return}let{length:k,delimiter:m}=R,h;if(c!==-1&&c<o){let p=e.indexOf("}",c);if(p!==-1&&p<o){let b=e.slice(c+1,p),D=fs(b,m);if(D!==void 0){if(n)throw new SyntaxError(`Header delimiter mismatch: bracket declares "${Pn(m)}" but fields segment contains unquoted "${Pn(D)}"`);return}h=wt(b,m).map(_i=>yt(_i.trim()))}}return{header:{key:d,length:k,delimiter:m,fields:h},inlineValues:y||void 0}}function us(e,t){let n=e,r=t;if(n.endsWith(" ")?(r=Je.tab,n=n.slice(0,-1)):n.endsWith("|")&&(r=Je.pipe,n=n.slice(0,-1)),!ls.test(n))throw new SyntaxError(`Invalid array length: "${e}" (expected non-negative integer with no leading zeros)`);return{length:Number.parseInt(n,10),delimiter:r}}function fs(e,t){for(let n of ds)if(n!==t&>(e,n)!==-1)return n}function Pn(e){return e===" "?"\\t":e}function wt(e,t){let n=[],r="",i=!1,s=0;for(;s<e.length;){let o=e[s];if(o==="\\"&&s+1<e.length&&i){r+=o+e[s+1],s+=2;continue}if(o==='"'){i=!i,r+=o,s++;continue}if(o===t&&!i){n.push(r.trim()),r="",s++;continue}r+=o,s++}return(r||n.length>0)&&n.push(r.trim()),n}function Bn(e){return e.map(t=>Ke(t))}function Ke(e){let t=e.trim();if(!t)return"";if(t.startsWith('"'))return yt(t);if(jn(t)){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null}if(cs(t)){let n=Number.parseFloat(t);return Object.is(n,-0)?0:n}return t}function yt(e){let t=e.trim();if(t.startsWith('"')){let n=He(t,0);if(n===-1)throw new SyntaxError("Unterminated string: missing closing quote");if(n!==t.length-1)throw new SyntaxError("Unexpected characters after closing quote");return Dn(t.slice(1,n))}return t}function ps(e,t){let n=t;for(;n<e.length&&e[n]!==":";)n++;if(n>=e.length||e[n]!==":")throw new SyntaxError("Missing colon after key");let r=e.slice(t,n).trim();return n++,{key:r,end:n}}function ms(e,t){let n=He(e,t);if(n===-1)throw new SyntaxError("Unterminated quoted key");let r=Dn(e.slice(t+1,n)),i=n+1;if(i>=e.length||e[i]!==":")throw new SyntaxError("Missing colon after key");return i++,{key:r,end:i}}function ys(e,t){let n=e[t]==='"';return{...n?ms(e,t):ps(e,t),isQuoted:n}}function Un(e){return e.trim().startsWith("[")&>(e,":")!==-1}function hs(e){return gt(e,":")!==-1}function gs(){return{lineNumber:0,blankLines:[]}}function ws(e,t,n,r){t.lineNumber++;let i=t.lineNumber,s=0;for(;s<e.length&&e[s]===" ";)s++;let o=e.slice(s);if(!o.trim()){let c=_n(s,n);t.blankLines.push({lineNumber:i,indent:s,depth:c});return}let a=_n(s,n);if(r){let c=0;for(;c<e.length&&(e[c]===" "||e[c]===" ");)c++;if(e.slice(0,c).includes(" "))throw new A("Tabs are not allowed in indentation in strict mode",{line:i,source:e});if(s>0&&s%n!==0)throw new A(`Indentation must be exact multiple of ${n}, but found ${s} spaces`,{line:i,source:e})}return{raw:e,indent:s,content:o,depth:a,lineNumber:i}}function*bs(e,t,n,r){for(let i of e){let s=ws(i,r,t,n);s!==void 0&&(yield s)}}function _n(e,t){return Math.floor(e/t)}function ke(e,t,n,r,i){if(r.strict&&e!==t)throw new A(`Expected ${t} ${n}, but got ${e}`,{line:i.lineNumber,source:i.raw})}function Rs(e,t,n){if(e?.depth===t&&e.content.startsWith("- "))throw new A(`Expected ${n} list array items, but found more`,{line:e.lineNumber,source:e.raw})}function Es(e,t,n){if(e?.depth===t&&!e.content.startsWith("- ")&&ks(e.content,n.delimiter))throw new A(`Expected ${n.length} tabular rows, but found more`,{line:e.lineNumber,source:e.raw})}function Cn(e,t,n,r,i){if(!r)return;let s=n.find(o=>o.lineNumber>e&&o.lineNumber<t);if(s)throw new A(`Blank lines inside ${i} are not allowed in strict mode`,{line:s.lineNumber})}function ks(e,t){let n=e.indexOf(":"),r=e.indexOf(t);return n===-1||r!==-1&&r<n}function*xs(e,t){if(t?.expandPaths!==void 0)throw new Error("expandPaths is not supported in streaming decode");let n={indent:t?.indent??2,strict:t?.strict??!0},r=gs(),i=new Ss(bs(e,n.indent,n.strict,r),r),s=i.peekSync();if(!s){yield{type:"startObject"},yield{type:"endObject"};return}if(s.content.trim()==="[]"){i.advanceSync(),yield{type:"startArray",length:0},yield{type:"endArray"};return}if(Un(s.content)){let a=T(s,()=>Me(s.content,v,n.strict));if(a){i.advanceSync(),yield*Fe(a.header,a.inlineValues,i,0,n,s);return}}if(i.advanceSync(),i.atEndSync()&&!vn(s)){yield{type:"primitive",value:T(s,()=>Ke(s.content.trim()))};return}if(!vn(s)&&i.peekSync()?.depth===0)throw new A("Top-level document must start with a key-value or array-header line",{line:s.lineNumber,source:s.raw});let o=n.strict?new Set:void 0;for(yield{type:"startObject"},yield*ae(s,i,0,n,o);!i.atEndSync();){let a=i.peekSync();if(!a||a.depth!==0)break;i.advanceSync(),yield*ae(a,i,0,n,o)}yield{type:"endObject"}}function In(e,t,n){if(n){if(n.has(e))throw new A(`Duplicate sibling key "${e}"`,{line:t.lineNumber,source:t.raw});n.add(e)}}function*ae(e,t,n,r,i){let s=e.content,o=T(e,()=>Me(s,v,r.strict));if(o&&o.header.key!==void 0){In(o.header.key,e,i),yield{type:"key",key:o.header.key},yield*Fe(o.header,o.inlineValues,t,n,r,e);return}let{key:a,isQuoted:c}=T(e,()=>ys(s,0)),l=s.indexOf(":",a.length),u=l>=0?s.slice(l+1).trim():"";if(In(a,e,i),yield c?{type:"key",key:a,wasQuoted:!0}:{type:"key",key:a},!u){let d=t.peekSync();if(d&&d.depth>n){yield{type:"startObject"},yield*Os(t,n+1,r),yield{type:"endObject"};return}yield{type:"startObject"},yield{type:"endObject"};return}if(u==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}yield{type:"primitive",value:T(e,()=>Ke(u))}}function*Os(e,t,n){let r,i=n.strict?new Set:void 0;for(;!e.atEndSync();){let s=e.peekSync();if(!s||s.depth<t)break;if(r===void 0&&s.depth>=t&&(r=s.depth),s.depth===r)e.advanceSync(),yield*ae(s,e,r,n,i);else break}}function*Fe(e,t,n,r,i,s){if(yield{type:"startArray",length:e.length},t){yield*Ts(e,t,i,s),yield{type:"endArray"};return}if(e.fields&&e.fields.length>0){yield*As(e,n,r,i,s),yield{type:"endArray"};return}yield*$s(e,n,r,i,s),yield{type:"endArray"}}function*Ts(e,t,n,r){if(!t.trim()){ke(0,e.length,"inline array items",n,r);return}let i=T(r,()=>wt(t,e.delimiter)),s=T(r,()=>Bn(i));ke(s.length,e.length,"inline array items",n,r);for(let o of s)yield{type:"primitive",value:o}}function*As(e,t,n,r,i){let s=n+1,o=0,a,c,l=i;for(;!t.atEndSync()&&o<e.length;){let u=t.peekSync();if(!u||u.depth<s)break;if(u.depth===s){a===void 0&&(a=u.lineNumber),c=u.lineNumber,l=u,t.advanceSync();let d=T(u,()=>wt(u.content,e.delimiter));ke(d.length,e.fields.length,"tabular row values",r,u);let y=T(u,()=>Bn(d));yield*_s(e.fields,y),o++}else break}ke(o,e.length,"tabular rows",r,l),r.strict&&a!==void 0&&c!==void 0&&Cn(a,c,t.getBlankLines(),r.strict,"tabular array"),r.strict&&Es(t.peekSync(),s,e)}function*$s(e,t,n,r,i){let s=n+1,o=0,a,c,l=i;for(;!t.atEndSync()&&o<e.length;){let u=t.peekSync();if(!u||u.depth<s)break;let d=u.content.startsWith("- ")||u.content==="-";if(u.depth===s&&d){a===void 0&&(a=u.lineNumber),c=u.lineNumber,l=u,yield*Ps(t,s,r);let y=t.current();y&&(c=y.lineNumber,l=y),o++}else break}ke(o,e.length,"list array items",r,l),r.strict&&a!==void 0&&c!==void 0&&Cn(a,c,t.getBlankLines(),r.strict,"list array"),r.strict&&Rs(t.peekSync(),s,e.length)}function*Ps(e,t,n){let r=e.nextSync();if(!r)throw new ReferenceError("Expected list item");let i;if(r.content==="-"){yield{type:"startObject"},yield{type:"endObject"};return}else if(r.content.startsWith("- "))i=r.content.slice(2);else throw new A('Expected list item to start with "- "',{line:r.lineNumber,source:r.raw});if(!i.trim()){yield{type:"startObject"},yield{type:"endObject"};return}if(i.trim()==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}let s={...r,content:i};if(Un(i)){let a=T(s,()=>Me(i,v,n.strict));if(a){yield*Fe(a.header,a.inlineValues,e,t,n,s);return}}let o=T(s,()=>Me(i,v,n.strict));if(o&&o.header.key!==void 0&&o.header.fields!==void 0){let a=o.header,c=n.strict?new Set([a.key]):void 0;yield{type:"startObject"},yield{type:"key",key:a.key},yield*Fe(a,o.inlineValues,e,t+1,n,s);let l=t+1;for(;!e.atEndSync();){let u=e.peekSync();if(!u||u.depth<l)break;if(u.depth===l&&!u.content.startsWith("- "))e.advanceSync(),yield*ae(u,e,l,n,c);else break}yield{type:"endObject"};return}if(hs(i)){let a=n.strict?new Set:void 0;yield{type:"startObject"},yield*ae(s,e,t+1,n,a);let c=t+1;for(;!e.atEndSync();){let l=e.peekSync();if(!l||l.depth<c)break;if(l.depth===c&&!l.content.startsWith("- "))e.advanceSync(),yield*ae(l,e,c,n,a);else break}yield{type:"endObject"};return}yield{type:"primitive",value:T(s,()=>Ke(i))}}function vn(e){let t=e.content;if(t.startsWith('"')){let n=He(t,0);return n===-1?!1:t.slice(n+1).includes(":")}else return t.includes(":")}function*_s(e,t){yield{type:"startObject"};for(let n=0;n<e.length;n++)yield{type:"key",key:e[n]},yield{type:"primitive",value:t[n]};yield{type:"endObject"}}function q(e){if(e===null)return null;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return q(t)}if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e=="bigint")return e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(q);if(e instanceof Set)return Array.from(e).map(q);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,n])=>[String(t),q(n)]));if(Is(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=q(e[n]));return t}return null}function ee(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function V(e){return Array.isArray(e)}function S(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Se(e){return Object.keys(e).length===0}function Is(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function xe(e){return e.length===0||e.every(t=>ee(t))}function vs(e){return e.length===0||e.every(t=>V(t))}function qn(e){return e.length===0||e.every(t=>S(t))}function Ds(e){return/^[A-Z_][\w.]*$/i.test(e)}function Gn(e){return/^[A-Z_]\w*$/i.test(e)}function js(e,t=v){return!(!e||e!==e.trim()||jn(e)||Bs(e)||e.includes(":")||e.includes('"')||e.includes("\\")||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith("-"))}function Bs(e){return Ns.test(e)||Ls.test(e)}function Ge(e,t){if(Array.isArray(e))return e.map(n=>Ge(n,t));if(S(e)){let n={},r=e[Jn];for(let[i,s]of Object.entries(e)){let o=r?.has(i);if(i.includes(".")&&!o){let c=i.split(".");if(c.every(l=>Gn(l))){Us(n,c,Ge(s,t),t);continue}}let a=Ge(s,t);if(i in n){let c=n[i];if(Rt(c,a))bt(c,a,t);else{if(t)throw new TypeError(`Path expansion conflict at key "${i}": cannot merge ${typeof c} with ${typeof a}`);n[i]=a}}else n[i]=a}return n}return e}function Us(e,t,n,r){let i=e;for(let a=0;a<t.length-1;a++){let c=t[a],l=i[c];if(l===void 0){let u={};i[c]=u,i=u}else if(S(l))i=l;else{if(r)throw new TypeError(`Path expansion conflict at segment "${c}": expected object but found ${typeof l}`);let u={};i[c]=u,i=u}}let s=t[t.length-1],o=i[s];if(o===void 0)i[s]=n;else if(Rt(o,n))bt(o,n,r);else{if(r)throw new TypeError(`Path expansion conflict at key "${s}": cannot merge ${typeof o} with ${typeof n}`);i[s]=n}}function bt(e,t,n){for(let[r,i]of Object.entries(t)){let s=e[r];if(s===void 0)e[r]=i;else if(Rt(s,i))bt(s,i,n);else{if(n)throw new TypeError(`Path expansion conflict at key "${r}": cannot merge ${typeof s} with ${typeof i}`);e[r]=i}}}function Rt(e,t){return S(e)&&S(t)}function Cs(e){let t={stack:[],root:void 0};for(let n of e)qs(t,n);return Gs(t)}function qs(e,t){let{stack:n}=e;switch(t.type){case"startObject":{let r={},i=new Set;if(n.length===0)n.push({type:"object",obj:r,quotedKeys:i});else{let s=n[n.length-1];if(s.type==="object"){if(s.currentKey===void 0)throw new Error("Object startObject event without preceding key");s.obj[s.currentKey]=r,s.currentKey=void 0}else s.type==="array"&&s.arr.push(r);n.push({type:"object",obj:r,quotedKeys:i})}break}case"endObject":{if(n.length===0)throw new Error("Unexpected endObject event");let r=n.pop();if(r.type!=="object")throw new Error("Mismatched endObject event");r.quotedKeys.size>0&&Object.defineProperty(r.obj,Jn,{value:r.quotedKeys,enumerable:!1,writable:!1,configurable:!1}),n.length===0&&(e.root=r.obj);break}case"startArray":{let r=[];if(n.length===0)n.push({type:"array",arr:r});else{let i=n[n.length-1];if(i.type==="object"){if(i.currentKey===void 0)throw new Error("Array startArray event without preceding key");i.obj[i.currentKey]=r,i.currentKey=void 0}else i.type==="array"&&i.arr.push(r);n.push({type:"array",arr:r})}break}case"endArray":{if(n.length===0)throw new Error("Unexpected endArray event");let r=n.pop();if(r.type!=="array")throw new Error("Mismatched endArray event");n.length===0&&(e.root=r.arr);break}case"key":{if(n.length===0)throw new Error("Key event outside of object context");let r=n[n.length-1];if(r.type!=="object")throw new Error("Key event in non-object context");r.currentKey=t.key,t.wasQuoted&&r.quotedKeys.add(t.key);break}case"primitive":if(n.length===0)e.root=t.value;else{let r=n[n.length-1];if(r.type==="object"){if(r.currentKey===void 0)throw new Error("Primitive event without preceding key in object");r.obj[r.currentKey]=t.value,r.currentKey=void 0}else r.type==="array"&&r.arr.push(t.value)}break}}function Gs(e){if(e.stack.length!==0)throw new Error("Incomplete event stream: stack not empty at end");if(e.root===void 0)throw new Error("No root value built from events");return e.root}function Js(e,t,n,r,i,s,o){if(r.keyFolding!=="safe"||!S(t))return;let{segments:a,tail:c,leafValue:l}=Ms(e,t,o??r.flattenDepth);if(a.length<2||!a.every(y=>Gn(y)))return;let u=Fs(a),d=s?`${s}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:a.length}}function Ms(e,t,n){let r=[e],i=t;for(;r.length<n&&S(i);){let s=Object.keys(i);if(s.length!==1)break;let o=s[0],a=i[o];r.push(o),i=a}return!S(i)||Se(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function Fs(e){return e.join(".")}function le(e,t){return e===null?os:typeof e=="boolean"||typeof e=="number"?String(e):Vs(e,t)}function Vs(e,t=v){return js(e,t)?e:`"${Ln(e)}"`}function ue(e){return Ds(e)?e:`"${Ln(e)}"`}function Mn(e,t=v){return e.map(n=>le(n,t)).join(t)}function te(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??",",s="";if(n!=null&&(s+=ue(n)),s+=`[${e}${i!==v?i:""}]`,r){let o=r.map(a=>ue(a));s+=`{${o.join(i)}}`}return s+=":",s}function*Hs(e,t,n){if(ee(e)){let r=le(e,t.delimiter);r!==""&&(yield r);return}V(e)?yield*ht(void 0,e,n,t):S(e)&&(yield*ce(e,n,t))}function*ce(e,t,n,r,i,s){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(c=>c.includes("."))));let a=s??n.flattenDepth;for(let[c,l]of Object.entries(e))yield*Ks(c,l,t,n,o,r,i,a)}function*Ks(e,t,n,r,i,s,o,a){let c=o?`${o}.${e}`:e,l=a??r.flattenDepth;if(r.keyFolding==="safe"&&i){let d=Js(e,t,i,r,s,o,l);if(d){let{foldedKey:y,remainder:E,leafValue:R,segmentCount:k}=d,m=ue(y);if(E===void 0){if(ee(R)){yield x(n,`${m}: ${le(R,r.delimiter)}`,r.indent);return}else if(V(R)){yield*ht(y,R,n,r);return}else if(S(R)&&Se(R)){yield x(n,`${m}:`,r.indent);return}}if(S(E)){yield x(n,`${m}:`,r.indent);let h=l-k,p=o?`${o}.${y}`:y;yield*ce(E,n+1,r,s,p,h);return}}}let u=ue(e);ee(t)?yield x(n,`${u}: ${le(t,r.delimiter)}`,r.indent):V(t)?yield*ht(e,t,n,r):S(t)&&(yield x(n,`${u}:`,r.indent),Se(t)||(yield*ce(t,n+1,r,s,c,l)))}function*ht(e,t,n,r){if(t.length===0){yield x(n,e!=null?`${ue(e)}: []`:"[]",r.indent);return}if(xe(t)){yield x(n,We(t,r.delimiter,e),r.indent);return}if(vs(t)&&t.every(i=>xe(i))){yield*Ws(e,t,n,r);return}if(qn(t)){let i=Fn(t);i?yield*zs(e,t,i,n,r):yield*Nn(e,t,n,r);return}yield*Nn(e,t,n,r)}function*Ws(e,t,n,r){yield x(n,te(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)if(xe(i)){let s=We(i,r.delimiter);yield I(n+1,s,r.indent)}}function We(e,t,n){let r=te(e.length,{key:n,delimiter:t}),i=Mn(e,t);return e.length===0?r:`${r} ${i}`}function*zs(e,t,n,r,i){yield x(r,te(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Vn(t,n,r+1,i)}function Fn(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Qs(e,n))return n}function Qs(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let r of t)if(!(r in n)||!ee(n[r]))return!1}return!0}function*Vn(e,t,n,r){for(let i of e)yield x(n,Mn(t.map(s=>i[s]),r.delimiter),r.indent)}function*Nn(e,t,n,r){yield x(n,te(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)yield*Et(i,n+1,r)}function*Ys(e,t,n){if(Se(e)){yield x(t,"-",n.indent);return}let r=Object.entries(e),[i,s]=r[0],o=r.slice(1);if(V(s)&&qn(s)){let c=Fn(s);if(c){yield I(t,te(s.length,{key:i,fields:c,delimiter:n.delimiter}),n.indent),yield*Vn(s,c,t+2,n),o.length>0&&(yield*ce(Object.fromEntries(o),t+1,n));return}}let a=ue(i);if(ee(s))yield I(t,`${a}: ${le(s,n.delimiter)}`,n.indent);else if(V(s))if(s.length===0)yield I(t,`${a}: []`,n.indent);else if(xe(s))yield I(t,`${a}${We(s,n.delimiter)}`,n.indent);else{yield I(t,`${a}${te(s.length,{delimiter:n.delimiter})}`,n.indent);for(let c of s)yield*Et(c,t+2,n)}else S(s)&&(yield I(t,`${a}:`,n.indent),Se(s)||(yield*ce(s,t+2,n)));o.length>0&&(yield*ce(Object.fromEntries(o),t+1,n))}function*Et(e,t,n){if(ee(e))yield I(t,le(e,n.delimiter),n.indent);else if(V(e))if(xe(e))yield I(t,We(e,n.delimiter),n.indent);else{yield I(t,te(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Et(r,t+1,n)}else S(e)&&(yield*Ys(e,t,n))}function x(e,t,n){return" ".repeat(n*e)+t}function I(e,t,n){return x(e,"- "+t,n)}function Zs(e,t){let n=t("",e,[]);return n===void 0?Ve(e,t,[]):Ve(q(n),t,[])}function Ve(e,t,n){return S(e)?Xs(e,t,n):V(e)?eo(e,t,n):e}function Xs(e,t,n){let r={};for(let[i,s]of Object.entries(e)){let o=[...n,i],a=t(i,s,o);a!==void 0&&(r[i]=Ve(q(a),t,o))}return r}function eo(e,t,n){let r=[];for(let i=0;i<e.length;i++){let s=e[i],o=[...n,i],a=t(String(i),s,o);if(a===void 0)continue;let c=q(a);r.push(Ve(c,t,o))}return r}function O(e,t){return Array.from(Hn(e,t)).join(`
|
|
9
|
-
`)}function
|
|
10
|
-
`),t)}function Hn(e,t){let n=q(e),r=to(t);return Hs(r.replacer?Zs(n,r.replacer):n,r,0)}function Kn(e,t){let n=no(t),r=Cs(xs(e,{indent:n.indent,strict:n.strict}));return n.expandPaths==="safe"?Ge(r,n.strict):r}function to(e){return{indent:e?.indent??2,delimiter:e?.delimiter??v,keyFolding:e?.keyFolding??"off",flattenDepth:e?.flattenDepth??Number.POSITIVE_INFINITY,replacer:e?.replacer}}function no(e){return{indent:e?.indent??2,strict:e?.strict??!0,expandPaths:e?.expandPaths??"off"}}var os,Je,v,A,as,ls,ds,Ss,Ns,Ls,Jn,Wn=g(()=>{os="null",Je={comma:",",tab:" ",pipe:"|"},v=Je.comma;A=class extends SyntaxError{constructor(e,t){let n=t?.line!==void 0?`Line ${t.line}: `:"";super(n+e,t?.cause!==void 0?{cause:t.cause}:void 0),this.name="ToonDecodeError",this.line=t?.line,this.source=t?.source}};as=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i;ls=/^(?:0|[1-9]\d*)$/;ds=[","," ","|"];Ss=class{constructor(e,t){this.buffer=[],this.done=!1,this.generator=e,this.scanState=t}getBlankLines(){return this.scanState.blankLines}async peek(){if(this.buffer.length>0)return this.buffer[0];if(this.done)return;let e=await this.generator.next();if(e.done){this.done=!0;return}return this.buffer.push(e.value),e.value}async next(){let e=await this.peek();return e!==void 0&&(this.buffer.shift(),this.lastLine=e),e}async advance(){await this.next()}current(){return this.lastLine}async atEnd(){return await this.peek()===void 0}peekSync(){if(this.buffer.length>0)return this.buffer[0];if(this.done)return;let e=this.generator.next();if(e.done){this.done=!0;return}return this.buffer.push(e.value),e.value}nextSync(){let e=this.peekSync();return e!==void 0&&(this.buffer.shift(),this.lastLine=e),e}advanceSync(){this.nextSync()}atEndSync(){return this.peekSync()===void 0}};Ns=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Ls=/^0\d+$/;Jn=Symbol("quotedKey")});var Oe=g(()=>{"use strict";Wn()});var ar={};P(ar,{NORMALIZATION_ALLOWLIST:()=>rr,NORMALIZE_ANSI:()=>Yn,NORMALIZE_BLANK_LINES:()=>er,NORMALIZE_CR_PROGRESS:()=>Zn,NORMALIZE_JSON_TOON:()=>nr,NORMALIZE_TRAILING_WHITESPACE:()=>Xn,formatNormalizeDecision:()=>or,hookDecisionFromClaudePostExecJson:()=>sr,normalizeOutput:()=>ir,runClaudePostExecHook:()=>ro,transcodeJsonToToon:()=>tr});import{readFileSync as zn}from"node:fs";function tr(e,t){let n=t?.encode??O,r=t?.decode??
|
|
6
|
+
`);if(d<0)return;let y=a.slice(0,d);l(()=>{try{r(JSON.parse(y))}catch(E){i(E)}}),s.end()}),s.on("error",u=>l(()=>i(u))),s.on("close",()=>{o||l(()=>i(new Error("resident rsp server closed without response")))})})}var fn=g(()=>{"use strict"});var qe={};P(qe,{ResidentRspElisionStore:()=>Re,ensureResidentServer:()=>pt,kickResidentServer:()=>mt,pingResident:()=>X,resolveResidentPaths:()=>se,warmResidentServer:()=>Mi});import{createHash as Ui,randomUUID as hn}from"node:crypto";import{spawn as gn}from"node:child_process";import{constants as ut}from"node:fs";import{readFileSync as Ci}from"node:fs";import{mkdir as dt,open as qi,rm as ft}from"node:fs/promises";import{tmpdir as Gi}from"node:os";import{dirname as Ue,join as F,resolve as Ce}from"node:path";import{fileURLToPath as wn}from"node:url";function se(e){let t=Ki(e)??Ce(e),n=Hi(t);return{rootDir:t,socketPath:F(n,"rsp.sock"),lockPath:F(n,"rsp.lock"),wakeLockPath:F(n,"rsp.wake.lock")}}async function pt(e,t){if(await dt(Ue(e.socketPath),{recursive:!0,mode:448}),await X(e.socketPath))return;let n=await bn(e.lockPath);if(n)try{if(await X(e.socketPath))return;await Fi(e.socketPath);let r=Vi(e,t);await pn(e.socketPath,r);return}finally{await n.close(),await ft(e.lockPath,{force:!0})}await pn(e.socketPath)}async function X(e,t=200){try{return(await lt({socketPath:e,timeoutMs:t},{id:hn(),op:"ping"})).ok}catch{return!1}}async function mt(e,t){if(await dt(Ue(e.socketPath),{recursive:!0,mode:448}),await X(e.socketPath,50))return!1;let n=await bn(e.wakeLockPath);if(!n)return!1;await n.close();let r=process.argv[1]?Ce(process.argv[1]):wn(import.meta.url);return gn(process.execPath,[...process.execArgv,r,"warm-resident","--socket",e.socketPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--byte-budget",String(t.byteBudget),"--wake-lock",e.wakeLockPath],{cwd:e.rootDir,detached:!0,stdio:"ignore",env:{...process.env,RSP_RESIDENT_WARMER:"1"}}).unref(),!0}async function Mi(e,t){try{await pt(e,t)}finally{await ft(e.wakeLockPath,{force:!0})}}async function pn(e,t){let n=Date.now()+5e3,r;for(;Date.now()<n;){if(await X(e))return;if(t&&t.exitCode!=null)throw new Error(`resident rsp server exited before ready (${t.exitCode})`);await new Promise(i=>setTimeout(i,50))}throw r instanceof Error?r:new Error("resident rsp server did not start")}async function Fi(e){await ft(e,{force:!0})}async function bn(e){await dt(Ue(e),{recursive:!0,mode:448});try{return await qi(e,ut.O_CREAT|ut.O_EXCL|ut.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function Vi(e,t){let n=process.argv[1]?Ce(process.argv[1]):wn(import.meta.url),r=gn(process.execPath,[...process.execArgv,n,"server","--socket",e.socketPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--byte-budget",String(t.byteBudget)],{cwd:e.rootDir,detached:!0,stdio:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return r.unref(),r}function Hi(e){let t=Ui("sha256").update(e).digest("hex").slice(0,20),n=process.env.XDG_RUNTIME_DIR;if(n){let i=F(n,"red-skills",t);if(F(i,"rsp.sock").length<Ji)return i}let r=typeof process.getuid=="function"?process.getuid():"nouid";return F(Gi(),`red-skills-${r}`,t)}function Ki(e){let t=Ce(e);for(let n=0;n<32;n++){try{if(mn(F(t,".red","config.yaml"))!=null||mn(F(t,".git","HEAD"))!=null)return t}catch{}let r=Ue(t);if(r===t)return null;t=r}return null}function mn(e){try{return Ci(e,"utf8")}catch{return null}}function yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ji,Re,oe=g(()=>{"use strict";fn();Ji=108;Re=class{constructor(t,n){this.paths=t;this.config=n}async mint(t,n){let i=(await this.request({op:"mint",original:Buffer.from(t).toString("base64"),meta:n})).handle;if(!i?.startsWith("el:"))throw new Error("resident rsp returned invalid handle");return i}async get(t){let n=await this.request({op:"get",handle:t});return n?yn(n)&&n.status==="expired"?n:!yn(n)||typeof n.original!="string"?null:{...n,original:Buffer.from(n.original,"base64")}:null}async stats(){return await this.request({op:"stats"})}async memory(t,n){return await this.request({op:"memory",action:t,payload:n})}async close(){}async request(t){await pt(this.paths,this.config);let n=await lt(this.paths,{...t,id:hn()});if(!n.ok)throw new Error(n.error);return n.value}}});var An={};P(An,{RSP_WRAPPER_CAPABILITIES:()=>yt,formatHookDecision:()=>xn,hookDecisionFromClaudePreExecJson:()=>Sn,rewriteCommand:()=>kn,rewriteTableFromCapabilities:()=>En,runClaudePreExecHook:()=>Yi});import{readFileSync as Rn}from"node:fs";import{existsSync as Wi}from"node:fs";import{fileURLToPath as zi}from"node:url";function En(e){let t=new Map;for(let n of e)t.set(Ee(n.command),["rsp",...n.wrapper]);return t}function kn(e){let t=is(e);if(!t)return{kind:"passthrough"};if(t.length>0&&On(t[0]))return{kind:"passthrough"};let n=Qi.get(Ee(t));if(!n)return{kind:"passthrough"};let r=yt.find(i=>Ee(i.command)===Ee(t));return{kind:"rewrite",command:n.join(" "),capabilityId:r?.id??Ee(t)}}async function Sn(e,t){let n=ss(e),r=_(n,["cwd"])||_(n,["tool_input","cwd"])||t.cwd;if(!await(t.isEnabled??Zi)(r))return{kind:"passthrough",reason:"disabled"};let s=rs(n);if(!s)return{kind:"passthrough",reason:"missing-command"};let o=(t.rewrite??kn)(s);return o.kind!=="rewrite"||await(t.isResidentHealthy??Xi)(r)?o:(await(t.wakeResident??es)(r),{kind:"passthrough",reason:"resident-unhealthy"})}function xn(e){return e.kind==="rewrite"?{stdout:`${e.command}
|
|
7
|
+
`,status:0}:{stdout:"",status:1}}async function Yi(e){let t=e?Rn(e,"utf8"):Rn(0,"utf8"),n=await Sn(t,{cwd:process.cwd()}),r=xn(n);return r.stdout&&process.stdout.write(r.stdout),r.status}function Zi(e){return M(e,process.env).enabled}async function Xi(e){let t=se(e);return await X(t.socketPath,50)}async function es(e){let t=M(e,process.env);if(!t.enabled||!ns(t))return;let n=se(e);await mt(n,ts(t))}function ts(e){return{storeUri:e.storeUri,ttlDays:e.ttlDays,byteBudget:e.byteBudget}}function ns(e){if(!e.storeUri.startsWith("file://"))return!0;try{return Wi(zi(e.storeUri))}catch{return!1}}function rs(e){return _(e,["tool_input","command"])||_(e,["tool_input","cmd"])||_(e,["tool_input","args","command"])||_(e,["input","command"])||_(e,["input","cmd"])||_(e,["arguments","command"])||_(e,["arguments","cmd"])||_(e,["command"])||_(e,["cmd"])}function is(e){let t=e.trim();if(!t||/[\n\r|&;()$<>`'"]/.test(t))return null;let n=t.split(/[ \t]+/).filter(Boolean);return n.length===0||n.some(r=>r.includes("=")&&On(r))?null:n}function On(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function Ee(e){return e.join("\0")}function ss(e){try{let t=JSON.parse(e);return Tn(t)?t:{}}catch{return{}}}function _(e,t){let n=e;for(let r of t){if(!Tn(n))return"";n=n[r]}return typeof n=="string"?n:""}function Tn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var yt,Qi,$n=g(()=>{"use strict";C();oe();yt=[{id:"git:status",command:["git","status"],wrapper:["git","status"]},{id:"git:log",command:["git","log"],wrapper:["git","log"]},{id:"git:diff",command:["git","diff"],wrapper:["git","diff"]},{id:"git:commit",command:["git","commit"],wrapper:["git","commit"]},{id:"git:push",command:["git","push"],wrapper:["git","push"]},{id:"gh:pr:list",command:["gh","pr","list"],wrapper:["gh","pr","list"]},{id:"gh:pr:view",command:["gh","pr","view"],wrapper:["gh","pr","view"]},{id:"gh:issue:list",command:["gh","issue","list"],wrapper:["gh","issue","list"]},{id:"gh:issue:view",command:["gh","issue","view"],wrapper:["gh","issue","view"]},{id:"gh:run:list",command:["gh","run","list"],wrapper:["gh","run","list"]},{id:"gh:run:view",command:["gh","run","view"],wrapper:["gh","run","view"]},{id:"vitest",command:["vitest"],wrapper:["vitest"]},{id:"vitest:run",command:["vitest","run"],wrapper:["vitest","run"]},{id:"cargo:test",command:["cargo","test"],wrapper:["cargo","test"]}],Qi=En(yt)});function Ln(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001F]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Dn(e){let t="",n=0;for(;n<e.length;){if(e[n]==="\\"){if(n+1>=e.length)throw new SyntaxError("Invalid escape sequence: backslash at end of string");let r=e[n+1];if(r==="n"){t+=`
|
|
8
|
+
`,n+=2;continue}if(r==="t"){t+=" ",n+=2;continue}if(r==="r"){t+="\r",n+=2;continue}if(r==="\\"){t+="\\",n+=2;continue}if(r==='"'){t+='"',n+=2;continue}if(r==="u"){if(n+6>e.length)throw new SyntaxError(`Invalid escape sequence: truncated \\u escape at "${e.slice(n,n+6)}"`);let i=e.slice(n+2,n+6);if(!/^[0-9a-f]{4}$/i.test(i))throw new SyntaxError(`Invalid escape sequence: \\u must be followed by 4 hex digits, got "${i}"`);let s=Number.parseInt(i,16);if(s>=55296&&s<=57343)throw new SyntaxError(`Invalid escape sequence: \\u${i} is a lone surrogate; supplementary code points MUST appear as literal UTF-8`);t+=String.fromCodePoint(s),n+=6;continue}throw new SyntaxError(`Invalid escape sequence: \\${r}`)}t+=e[n],n++}return t}function He(e,t){let n=t+1;for(;n<e.length;){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==='"')return n;n++}return-1}function wt(e,t,n=0){let r=!1,i=n;for(;i<e.length;){if(e[i]==="\\"&&i+1<e.length&&r){i+=2;continue}if(e[i]==='"'){r=!r,i++;continue}if(e[i]===t&&!r)return i;i++}return-1}function T(e,t){try{return t()}catch(n){throw n instanceof A?n:n instanceof Error?new A(n.message,{line:e.lineNumber,source:e.raw,cause:n}):n}}function jn(e){return e==="true"||e==="false"||e==="null"}function cs(e){if(!e||!as.test(e))return!1;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)}function Me(e,t,n=!1){let r=e.trimStart(),i=-1;if(r.startsWith('"')){let p=He(r,0);if(p===-1||!r.slice(p+1).startsWith("["))return;let b=e.length-r.length+p+1;i=e.indexOf("[",b)}else i=e.indexOf("[");if(i===-1)return;let s=e.indexOf("]",i);if(s===-1)return;let o=s+1,a=o,c=e.indexOf("{",s);if(c!==-1&&c<e.indexOf(":",s)){let p=e.slice(s+1,c);if(p!==""){if(n){let D=p.trim();throw new SyntaxError(D===""?"Unexpected whitespace between bracket and fields segment":`Unexpected content "${D}" between bracket and fields segment`)}return}let b=e.indexOf("}",c);b!==-1&&(a=b+1)}if(o=e.indexOf(":",Math.max(s,a)),o===-1)return;let l=Math.max(s+1,a),u=e.slice(l,o);if(u!==""){if(n){let p=u.trim();throw new SyntaxError(p===""?"Unexpected whitespace between bracket segment and colon":`Unexpected content "${p}" between bracket segment and colon`)}return}let d;if(i>0){let p=e.slice(0,i).trim();d=p.startsWith('"')?ht(p):p}let y=e.slice(o+1).trim(),E=e.slice(i+1,s),R;try{R=us(E,t)}catch(p){if(n)throw p;return}let{length:k,delimiter:m}=R,h;if(c!==-1&&c<o){let p=e.indexOf("}",c);if(p!==-1&&p<o){let b=e.slice(c+1,p),D=fs(b,m);if(D!==void 0){if(n)throw new SyntaxError(`Header delimiter mismatch: bracket declares "${Pn(m)}" but fields segment contains unquoted "${Pn(D)}"`);return}h=bt(b,m).map(Pi=>ht(Pi.trim()))}}return{header:{key:d,length:k,delimiter:m,fields:h},inlineValues:y||void 0}}function us(e,t){let n=e,r=t;if(n.endsWith(" ")?(r=Je.tab,n=n.slice(0,-1)):n.endsWith("|")&&(r=Je.pipe,n=n.slice(0,-1)),!ls.test(n))throw new SyntaxError(`Invalid array length: "${e}" (expected non-negative integer with no leading zeros)`);return{length:Number.parseInt(n,10),delimiter:r}}function fs(e,t){for(let n of ds)if(n!==t&&wt(e,n)!==-1)return n}function Pn(e){return e===" "?"\\t":e}function bt(e,t){let n=[],r="",i=!1,s=0;for(;s<e.length;){let o=e[s];if(o==="\\"&&s+1<e.length&&i){r+=o+e[s+1],s+=2;continue}if(o==='"'){i=!i,r+=o,s++;continue}if(o===t&&!i){n.push(r.trim()),r="",s++;continue}r+=o,s++}return(r||n.length>0)&&n.push(r.trim()),n}function Bn(e){return e.map(t=>Ke(t))}function Ke(e){let t=e.trim();if(!t)return"";if(t.startsWith('"'))return ht(t);if(jn(t)){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null}if(cs(t)){let n=Number.parseFloat(t);return Object.is(n,-0)?0:n}return t}function ht(e){let t=e.trim();if(t.startsWith('"')){let n=He(t,0);if(n===-1)throw new SyntaxError("Unterminated string: missing closing quote");if(n!==t.length-1)throw new SyntaxError("Unexpected characters after closing quote");return Dn(t.slice(1,n))}return t}function ps(e,t){let n=t;for(;n<e.length&&e[n]!==":";)n++;if(n>=e.length||e[n]!==":")throw new SyntaxError("Missing colon after key");let r=e.slice(t,n).trim();return n++,{key:r,end:n}}function ms(e,t){let n=He(e,t);if(n===-1)throw new SyntaxError("Unterminated quoted key");let r=Dn(e.slice(t+1,n)),i=n+1;if(i>=e.length||e[i]!==":")throw new SyntaxError("Missing colon after key");return i++,{key:r,end:i}}function ys(e,t){let n=e[t]==='"';return{...n?ms(e,t):ps(e,t),isQuoted:n}}function Un(e){return e.trim().startsWith("[")&&wt(e,":")!==-1}function hs(e){return wt(e,":")!==-1}function gs(){return{lineNumber:0,blankLines:[]}}function ws(e,t,n,r){t.lineNumber++;let i=t.lineNumber,s=0;for(;s<e.length&&e[s]===" ";)s++;let o=e.slice(s);if(!o.trim()){let c=_n(s,n);t.blankLines.push({lineNumber:i,indent:s,depth:c});return}let a=_n(s,n);if(r){let c=0;for(;c<e.length&&(e[c]===" "||e[c]===" ");)c++;if(e.slice(0,c).includes(" "))throw new A("Tabs are not allowed in indentation in strict mode",{line:i,source:e});if(s>0&&s%n!==0)throw new A(`Indentation must be exact multiple of ${n}, but found ${s} spaces`,{line:i,source:e})}return{raw:e,indent:s,content:o,depth:a,lineNumber:i}}function*bs(e,t,n,r){for(let i of e){let s=ws(i,r,t,n);s!==void 0&&(yield s)}}function _n(e,t){return Math.floor(e/t)}function ke(e,t,n,r,i){if(r.strict&&e!==t)throw new A(`Expected ${t} ${n}, but got ${e}`,{line:i.lineNumber,source:i.raw})}function Rs(e,t,n){if(e?.depth===t&&e.content.startsWith("- "))throw new A(`Expected ${n} list array items, but found more`,{line:e.lineNumber,source:e.raw})}function Es(e,t,n){if(e?.depth===t&&!e.content.startsWith("- ")&&ks(e.content,n.delimiter))throw new A(`Expected ${n.length} tabular rows, but found more`,{line:e.lineNumber,source:e.raw})}function Cn(e,t,n,r,i){if(!r)return;let s=n.find(o=>o.lineNumber>e&&o.lineNumber<t);if(s)throw new A(`Blank lines inside ${i} are not allowed in strict mode`,{line:s.lineNumber})}function ks(e,t){let n=e.indexOf(":"),r=e.indexOf(t);return n===-1||r!==-1&&r<n}function*xs(e,t){if(t?.expandPaths!==void 0)throw new Error("expandPaths is not supported in streaming decode");let n={indent:t?.indent??2,strict:t?.strict??!0},r=gs(),i=new Ss(bs(e,n.indent,n.strict,r),r),s=i.peekSync();if(!s){yield{type:"startObject"},yield{type:"endObject"};return}if(s.content.trim()==="[]"){i.advanceSync(),yield{type:"startArray",length:0},yield{type:"endArray"};return}if(Un(s.content)){let a=T(s,()=>Me(s.content,v,n.strict));if(a){i.advanceSync(),yield*Fe(a.header,a.inlineValues,i,0,n,s);return}}if(i.advanceSync(),i.atEndSync()&&!vn(s)){yield{type:"primitive",value:T(s,()=>Ke(s.content.trim()))};return}if(!vn(s)&&i.peekSync()?.depth===0)throw new A("Top-level document must start with a key-value or array-header line",{line:s.lineNumber,source:s.raw});let o=n.strict?new Set:void 0;for(yield{type:"startObject"},yield*ae(s,i,0,n,o);!i.atEndSync();){let a=i.peekSync();if(!a||a.depth!==0)break;i.advanceSync(),yield*ae(a,i,0,n,o)}yield{type:"endObject"}}function In(e,t,n){if(n){if(n.has(e))throw new A(`Duplicate sibling key "${e}"`,{line:t.lineNumber,source:t.raw});n.add(e)}}function*ae(e,t,n,r,i){let s=e.content,o=T(e,()=>Me(s,v,r.strict));if(o&&o.header.key!==void 0){In(o.header.key,e,i),yield{type:"key",key:o.header.key},yield*Fe(o.header,o.inlineValues,t,n,r,e);return}let{key:a,isQuoted:c}=T(e,()=>ys(s,0)),l=s.indexOf(":",a.length),u=l>=0?s.slice(l+1).trim():"";if(In(a,e,i),yield c?{type:"key",key:a,wasQuoted:!0}:{type:"key",key:a},!u){let d=t.peekSync();if(d&&d.depth>n){yield{type:"startObject"},yield*Os(t,n+1,r),yield{type:"endObject"};return}yield{type:"startObject"},yield{type:"endObject"};return}if(u==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}yield{type:"primitive",value:T(e,()=>Ke(u))}}function*Os(e,t,n){let r,i=n.strict?new Set:void 0;for(;!e.atEndSync();){let s=e.peekSync();if(!s||s.depth<t)break;if(r===void 0&&s.depth>=t&&(r=s.depth),s.depth===r)e.advanceSync(),yield*ae(s,e,r,n,i);else break}}function*Fe(e,t,n,r,i,s){if(yield{type:"startArray",length:e.length},t){yield*Ts(e,t,i,s),yield{type:"endArray"};return}if(e.fields&&e.fields.length>0){yield*As(e,n,r,i,s),yield{type:"endArray"};return}yield*$s(e,n,r,i,s),yield{type:"endArray"}}function*Ts(e,t,n,r){if(!t.trim()){ke(0,e.length,"inline array items",n,r);return}let i=T(r,()=>bt(t,e.delimiter)),s=T(r,()=>Bn(i));ke(s.length,e.length,"inline array items",n,r);for(let o of s)yield{type:"primitive",value:o}}function*As(e,t,n,r,i){let s=n+1,o=0,a,c,l=i;for(;!t.atEndSync()&&o<e.length;){let u=t.peekSync();if(!u||u.depth<s)break;if(u.depth===s){a===void 0&&(a=u.lineNumber),c=u.lineNumber,l=u,t.advanceSync();let d=T(u,()=>bt(u.content,e.delimiter));ke(d.length,e.fields.length,"tabular row values",r,u);let y=T(u,()=>Bn(d));yield*_s(e.fields,y),o++}else break}ke(o,e.length,"tabular rows",r,l),r.strict&&a!==void 0&&c!==void 0&&Cn(a,c,t.getBlankLines(),r.strict,"tabular array"),r.strict&&Es(t.peekSync(),s,e)}function*$s(e,t,n,r,i){let s=n+1,o=0,a,c,l=i;for(;!t.atEndSync()&&o<e.length;){let u=t.peekSync();if(!u||u.depth<s)break;let d=u.content.startsWith("- ")||u.content==="-";if(u.depth===s&&d){a===void 0&&(a=u.lineNumber),c=u.lineNumber,l=u,yield*Ps(t,s,r);let y=t.current();y&&(c=y.lineNumber,l=y),o++}else break}ke(o,e.length,"list array items",r,l),r.strict&&a!==void 0&&c!==void 0&&Cn(a,c,t.getBlankLines(),r.strict,"list array"),r.strict&&Rs(t.peekSync(),s,e.length)}function*Ps(e,t,n){let r=e.nextSync();if(!r)throw new ReferenceError("Expected list item");let i;if(r.content==="-"){yield{type:"startObject"},yield{type:"endObject"};return}else if(r.content.startsWith("- "))i=r.content.slice(2);else throw new A('Expected list item to start with "- "',{line:r.lineNumber,source:r.raw});if(!i.trim()){yield{type:"startObject"},yield{type:"endObject"};return}if(i.trim()==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}let s={...r,content:i};if(Un(i)){let a=T(s,()=>Me(i,v,n.strict));if(a){yield*Fe(a.header,a.inlineValues,e,t,n,s);return}}let o=T(s,()=>Me(i,v,n.strict));if(o&&o.header.key!==void 0&&o.header.fields!==void 0){let a=o.header,c=n.strict?new Set([a.key]):void 0;yield{type:"startObject"},yield{type:"key",key:a.key},yield*Fe(a,o.inlineValues,e,t+1,n,s);let l=t+1;for(;!e.atEndSync();){let u=e.peekSync();if(!u||u.depth<l)break;if(u.depth===l&&!u.content.startsWith("- "))e.advanceSync(),yield*ae(u,e,l,n,c);else break}yield{type:"endObject"};return}if(hs(i)){let a=n.strict?new Set:void 0;yield{type:"startObject"},yield*ae(s,e,t+1,n,a);let c=t+1;for(;!e.atEndSync();){let l=e.peekSync();if(!l||l.depth<c)break;if(l.depth===c&&!l.content.startsWith("- "))e.advanceSync(),yield*ae(l,e,c,n,a);else break}yield{type:"endObject"};return}yield{type:"primitive",value:T(s,()=>Ke(i))}}function vn(e){let t=e.content;if(t.startsWith('"')){let n=He(t,0);return n===-1?!1:t.slice(n+1).includes(":")}else return t.includes(":")}function*_s(e,t){yield{type:"startObject"};for(let n=0;n<e.length;n++)yield{type:"key",key:e[n]},yield{type:"primitive",value:t[n]};yield{type:"endObject"}}function q(e){if(e===null)return null;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return q(t)}if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e=="bigint")return e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(q);if(e instanceof Set)return Array.from(e).map(q);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,n])=>[String(t),q(n)]));if(Is(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=q(e[n]));return t}return null}function ee(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function V(e){return Array.isArray(e)}function S(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Se(e){return Object.keys(e).length===0}function Is(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function xe(e){return e.length===0||e.every(t=>ee(t))}function vs(e){return e.length===0||e.every(t=>V(t))}function qn(e){return e.length===0||e.every(t=>S(t))}function Ds(e){return/^[A-Z_][\w.]*$/i.test(e)}function Gn(e){return/^[A-Z_]\w*$/i.test(e)}function js(e,t=v){return!(!e||e!==e.trim()||jn(e)||Bs(e)||e.includes(":")||e.includes('"')||e.includes("\\")||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith("-"))}function Bs(e){return Ns.test(e)||Ls.test(e)}function Ge(e,t){if(Array.isArray(e))return e.map(n=>Ge(n,t));if(S(e)){let n={},r=e[Jn];for(let[i,s]of Object.entries(e)){let o=r?.has(i);if(i.includes(".")&&!o){let c=i.split(".");if(c.every(l=>Gn(l))){Us(n,c,Ge(s,t),t);continue}}let a=Ge(s,t);if(i in n){let c=n[i];if(Et(c,a))Rt(c,a,t);else{if(t)throw new TypeError(`Path expansion conflict at key "${i}": cannot merge ${typeof c} with ${typeof a}`);n[i]=a}}else n[i]=a}return n}return e}function Us(e,t,n,r){let i=e;for(let a=0;a<t.length-1;a++){let c=t[a],l=i[c];if(l===void 0){let u={};i[c]=u,i=u}else if(S(l))i=l;else{if(r)throw new TypeError(`Path expansion conflict at segment "${c}": expected object but found ${typeof l}`);let u={};i[c]=u,i=u}}let s=t[t.length-1],o=i[s];if(o===void 0)i[s]=n;else if(Et(o,n))Rt(o,n,r);else{if(r)throw new TypeError(`Path expansion conflict at key "${s}": cannot merge ${typeof o} with ${typeof n}`);i[s]=n}}function Rt(e,t,n){for(let[r,i]of Object.entries(t)){let s=e[r];if(s===void 0)e[r]=i;else if(Et(s,i))Rt(s,i,n);else{if(n)throw new TypeError(`Path expansion conflict at key "${r}": cannot merge ${typeof s} with ${typeof i}`);e[r]=i}}}function Et(e,t){return S(e)&&S(t)}function Cs(e){let t={stack:[],root:void 0};for(let n of e)qs(t,n);return Gs(t)}function qs(e,t){let{stack:n}=e;switch(t.type){case"startObject":{let r={},i=new Set;if(n.length===0)n.push({type:"object",obj:r,quotedKeys:i});else{let s=n[n.length-1];if(s.type==="object"){if(s.currentKey===void 0)throw new Error("Object startObject event without preceding key");s.obj[s.currentKey]=r,s.currentKey=void 0}else s.type==="array"&&s.arr.push(r);n.push({type:"object",obj:r,quotedKeys:i})}break}case"endObject":{if(n.length===0)throw new Error("Unexpected endObject event");let r=n.pop();if(r.type!=="object")throw new Error("Mismatched endObject event");r.quotedKeys.size>0&&Object.defineProperty(r.obj,Jn,{value:r.quotedKeys,enumerable:!1,writable:!1,configurable:!1}),n.length===0&&(e.root=r.obj);break}case"startArray":{let r=[];if(n.length===0)n.push({type:"array",arr:r});else{let i=n[n.length-1];if(i.type==="object"){if(i.currentKey===void 0)throw new Error("Array startArray event without preceding key");i.obj[i.currentKey]=r,i.currentKey=void 0}else i.type==="array"&&i.arr.push(r);n.push({type:"array",arr:r})}break}case"endArray":{if(n.length===0)throw new Error("Unexpected endArray event");let r=n.pop();if(r.type!=="array")throw new Error("Mismatched endArray event");n.length===0&&(e.root=r.arr);break}case"key":{if(n.length===0)throw new Error("Key event outside of object context");let r=n[n.length-1];if(r.type!=="object")throw new Error("Key event in non-object context");r.currentKey=t.key,t.wasQuoted&&r.quotedKeys.add(t.key);break}case"primitive":if(n.length===0)e.root=t.value;else{let r=n[n.length-1];if(r.type==="object"){if(r.currentKey===void 0)throw new Error("Primitive event without preceding key in object");r.obj[r.currentKey]=t.value,r.currentKey=void 0}else r.type==="array"&&r.arr.push(t.value)}break}}function Gs(e){if(e.stack.length!==0)throw new Error("Incomplete event stream: stack not empty at end");if(e.root===void 0)throw new Error("No root value built from events");return e.root}function Js(e,t,n,r,i,s,o){if(r.keyFolding!=="safe"||!S(t))return;let{segments:a,tail:c,leafValue:l}=Ms(e,t,o??r.flattenDepth);if(a.length<2||!a.every(y=>Gn(y)))return;let u=Fs(a),d=s?`${s}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:a.length}}function Ms(e,t,n){let r=[e],i=t;for(;r.length<n&&S(i);){let s=Object.keys(i);if(s.length!==1)break;let o=s[0],a=i[o];r.push(o),i=a}return!S(i)||Se(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function Fs(e){return e.join(".")}function le(e,t){return e===null?os:typeof e=="boolean"||typeof e=="number"?String(e):Vs(e,t)}function Vs(e,t=v){return js(e,t)?e:`"${Ln(e)}"`}function ue(e){return Ds(e)?e:`"${Ln(e)}"`}function Mn(e,t=v){return e.map(n=>le(n,t)).join(t)}function te(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??",",s="";if(n!=null&&(s+=ue(n)),s+=`[${e}${i!==v?i:""}]`,r){let o=r.map(a=>ue(a));s+=`{${o.join(i)}}`}return s+=":",s}function*Hs(e,t,n){if(ee(e)){let r=le(e,t.delimiter);r!==""&&(yield r);return}V(e)?yield*gt(void 0,e,n,t):S(e)&&(yield*ce(e,n,t))}function*ce(e,t,n,r,i,s){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(c=>c.includes("."))));let a=s??n.flattenDepth;for(let[c,l]of Object.entries(e))yield*Ks(c,l,t,n,o,r,i,a)}function*Ks(e,t,n,r,i,s,o,a){let c=o?`${o}.${e}`:e,l=a??r.flattenDepth;if(r.keyFolding==="safe"&&i){let d=Js(e,t,i,r,s,o,l);if(d){let{foldedKey:y,remainder:E,leafValue:R,segmentCount:k}=d,m=ue(y);if(E===void 0){if(ee(R)){yield x(n,`${m}: ${le(R,r.delimiter)}`,r.indent);return}else if(V(R)){yield*gt(y,R,n,r);return}else if(S(R)&&Se(R)){yield x(n,`${m}:`,r.indent);return}}if(S(E)){yield x(n,`${m}:`,r.indent);let h=l-k,p=o?`${o}.${y}`:y;yield*ce(E,n+1,r,s,p,h);return}}}let u=ue(e);ee(t)?yield x(n,`${u}: ${le(t,r.delimiter)}`,r.indent):V(t)?yield*gt(e,t,n,r):S(t)&&(yield x(n,`${u}:`,r.indent),Se(t)||(yield*ce(t,n+1,r,s,c,l)))}function*gt(e,t,n,r){if(t.length===0){yield x(n,e!=null?`${ue(e)}: []`:"[]",r.indent);return}if(xe(t)){yield x(n,We(t,r.delimiter,e),r.indent);return}if(vs(t)&&t.every(i=>xe(i))){yield*Ws(e,t,n,r);return}if(qn(t)){let i=Fn(t);i?yield*zs(e,t,i,n,r):yield*Nn(e,t,n,r);return}yield*Nn(e,t,n,r)}function*Ws(e,t,n,r){yield x(n,te(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)if(xe(i)){let s=We(i,r.delimiter);yield I(n+1,s,r.indent)}}function We(e,t,n){let r=te(e.length,{key:n,delimiter:t}),i=Mn(e,t);return e.length===0?r:`${r} ${i}`}function*zs(e,t,n,r,i){yield x(r,te(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Vn(t,n,r+1,i)}function Fn(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Qs(e,n))return n}function Qs(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let r of t)if(!(r in n)||!ee(n[r]))return!1}return!0}function*Vn(e,t,n,r){for(let i of e)yield x(n,Mn(t.map(s=>i[s]),r.delimiter),r.indent)}function*Nn(e,t,n,r){yield x(n,te(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)yield*kt(i,n+1,r)}function*Ys(e,t,n){if(Se(e)){yield x(t,"-",n.indent);return}let r=Object.entries(e),[i,s]=r[0],o=r.slice(1);if(V(s)&&qn(s)){let c=Fn(s);if(c){yield I(t,te(s.length,{key:i,fields:c,delimiter:n.delimiter}),n.indent),yield*Vn(s,c,t+2,n),o.length>0&&(yield*ce(Object.fromEntries(o),t+1,n));return}}let a=ue(i);if(ee(s))yield I(t,`${a}: ${le(s,n.delimiter)}`,n.indent);else if(V(s))if(s.length===0)yield I(t,`${a}: []`,n.indent);else if(xe(s))yield I(t,`${a}${We(s,n.delimiter)}`,n.indent);else{yield I(t,`${a}${te(s.length,{delimiter:n.delimiter})}`,n.indent);for(let c of s)yield*kt(c,t+2,n)}else S(s)&&(yield I(t,`${a}:`,n.indent),Se(s)||(yield*ce(s,t+2,n)));o.length>0&&(yield*ce(Object.fromEntries(o),t+1,n))}function*kt(e,t,n){if(ee(e))yield I(t,le(e,n.delimiter),n.indent);else if(V(e))if(xe(e))yield I(t,We(e,n.delimiter),n.indent);else{yield I(t,te(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*kt(r,t+1,n)}else S(e)&&(yield*Ys(e,t,n))}function x(e,t,n){return" ".repeat(n*e)+t}function I(e,t,n){return x(e,"- "+t,n)}function Zs(e,t){let n=t("",e,[]);return n===void 0?Ve(e,t,[]):Ve(q(n),t,[])}function Ve(e,t,n){return S(e)?Xs(e,t,n):V(e)?eo(e,t,n):e}function Xs(e,t,n){let r={};for(let[i,s]of Object.entries(e)){let o=[...n,i],a=t(i,s,o);a!==void 0&&(r[i]=Ve(q(a),t,o))}return r}function eo(e,t,n){let r=[];for(let i=0;i<e.length;i++){let s=e[i],o=[...n,i],a=t(String(i),s,o);if(a===void 0)continue;let c=q(a);r.push(Ve(c,t,o))}return r}function O(e,t){return Array.from(Hn(e,t)).join(`
|
|
9
|
+
`)}function St(e,t){return Kn(e.split(`
|
|
10
|
+
`),t)}function Hn(e,t){let n=q(e),r=to(t);return Hs(r.replacer?Zs(n,r.replacer):n,r,0)}function Kn(e,t){let n=no(t),r=Cs(xs(e,{indent:n.indent,strict:n.strict}));return n.expandPaths==="safe"?Ge(r,n.strict):r}function to(e){return{indent:e?.indent??2,delimiter:e?.delimiter??v,keyFolding:e?.keyFolding??"off",flattenDepth:e?.flattenDepth??Number.POSITIVE_INFINITY,replacer:e?.replacer}}function no(e){return{indent:e?.indent??2,strict:e?.strict??!0,expandPaths:e?.expandPaths??"off"}}var os,Je,v,A,as,ls,ds,Ss,Ns,Ls,Jn,Wn=g(()=>{os="null",Je={comma:",",tab:" ",pipe:"|"},v=Je.comma;A=class extends SyntaxError{constructor(e,t){let n=t?.line!==void 0?`Line ${t.line}: `:"";super(n+e,t?.cause!==void 0?{cause:t.cause}:void 0),this.name="ToonDecodeError",this.line=t?.line,this.source=t?.source}};as=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i;ls=/^(?:0|[1-9]\d*)$/;ds=[","," ","|"];Ss=class{constructor(e,t){this.buffer=[],this.done=!1,this.generator=e,this.scanState=t}getBlankLines(){return this.scanState.blankLines}async peek(){if(this.buffer.length>0)return this.buffer[0];if(this.done)return;let e=await this.generator.next();if(e.done){this.done=!0;return}return this.buffer.push(e.value),e.value}async next(){let e=await this.peek();return e!==void 0&&(this.buffer.shift(),this.lastLine=e),e}async advance(){await this.next()}current(){return this.lastLine}async atEnd(){return await this.peek()===void 0}peekSync(){if(this.buffer.length>0)return this.buffer[0];if(this.done)return;let e=this.generator.next();if(e.done){this.done=!0;return}return this.buffer.push(e.value),e.value}nextSync(){let e=this.peekSync();return e!==void 0&&(this.buffer.shift(),this.lastLine=e),e}advanceSync(){this.nextSync()}atEndSync(){return this.peekSync()===void 0}};Ns=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Ls=/^0\d+$/;Jn=Symbol("quotedKey")});var Oe=g(()=>{"use strict";Wn()});var ar={};P(ar,{NORMALIZATION_ALLOWLIST:()=>rr,NORMALIZE_ANSI:()=>Yn,NORMALIZE_BLANK_LINES:()=>er,NORMALIZE_CR_PROGRESS:()=>Zn,NORMALIZE_JSON_TOON:()=>nr,NORMALIZE_TRAILING_WHITESPACE:()=>Xn,formatNormalizeDecision:()=>or,hookDecisionFromClaudePostExecJson:()=>sr,normalizeOutput:()=>ir,runClaudePostExecHook:()=>ro,transcodeJsonToToon:()=>tr});import{readFileSync as zn}from"node:fs";function tr(e,t){let n=t?.encode??O,r=t?.decode??St,i=e.trimEnd();if(!i)return e;let s;try{s=JSON.parse(i)}catch{return e}let o;try{o=n(s)}catch{return e}let a;try{a=r(o)}catch{return e}return xt(s,a)?o:e}function ir(e){let t=e;for(let n of rr)t=n.apply(t);return t}async function sr(e,t){let n=oo(e),r=ao(n,["cwd"])||t.cwd;if(!await(t.isEnabled??so)(r))return{kind:"passthrough",reason:"disabled"};let s=co(n,"tool_response");if(!s)return{kind:"passthrough",reason:"missing-output"};if(typeof s.output!="string")return{kind:"passthrough",reason:"missing-output"};let o=s.output,c=(t.normalize??ir)(o);return c===o?{kind:"passthrough",reason:"no-change"}:{kind:"normalized",output:c}}function or(e){return e.kind==="normalized"?{stdout:JSON.stringify({tool_response:{output:e.output}}),status:0}:{stdout:"",status:0}}async function ro(e){let t=e?zn(e,"utf8"):zn(0,"utf8"),n=await sr(t,{cwd:process.cwd()}),r=or(n);return r.stdout&&process.stdout.write(r.stdout),r.status}function io(e){let t="",n=0;for(;n<e.length;){let r=e.charCodeAt(n);if(r===27){let i=e.charCodeAt(n+1);if(i===93){for(n+=2;n<e.length;){let s=e.charCodeAt(n);if(s===7){n++;break}if(s===27&&e.charCodeAt(n+1)===92){n+=2;break}n++}continue}if(i===91){for(n+=2;n<e.length&&Qn(e.charCodeAt(n));)n++;n<e.length&&n++;continue}n+=i>=32?2:1;continue}if(r===155){for(n++;n<e.length&&Qn(e.charCodeAt(n));)n++;n<e.length&&n++;continue}t+=e[n++]}return t}function Qn(e){return e>=32&&e<=63}function so(e){return M(e,process.env).enabled}function oo(e){try{let t=JSON.parse(e);return Ot(t)?t:{}}catch{return{}}}function ao(e,t){let n=e;for(let r of t){if(!Ot(n))return"";n=n[r]}return typeof n=="string"?n:""}function co(e,t){let n=e[t];return Ot(n)?n:null}function Ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!=typeof t||typeof e!="object"||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){let o=t;return e.length!==o.length?!1:e.every((a,c)=>xt(a,o[c]))}let n=e,r=t,i=Object.keys(n),s=Object.keys(r);return i.length!==s.length?!1:i.every(o=>Object.prototype.hasOwnProperty.call(r,o)&&xt(n[o],r[o]))}var Yn,Zn,Xn,er,nr,rr,cr=g(()=>{"use strict";Oe();C();Yn={id:"ansi",apply:io},Zn={id:"cr-progress",apply:e=>e.split(`
|
|
11
11
|
`).map(t=>{let n=t.endsWith("\r")?t.slice(0,-1):t,r=n.lastIndexOf("\r");return r>=0?n.slice(r+1):n}).join(`
|
|
12
12
|
`)},Xn={id:"trailing-whitespace",apply:e=>e.split(`
|
|
13
13
|
`).map(t=>t.replace(/[ \t]+$/,"")).join(`
|
|
@@ -17,58 +17,58 @@ var Ii=Object.defineProperty;var g=(e,t)=>()=>(e&&(t=e(e=0)),t);var P=(e,t)=>{fo
|
|
|
17
17
|
expected at: ${s}
|
|
18
18
|
override: set ${r}=/path/to/${t}
|
|
19
19
|
fix: re-run \`pnpm install\` (the postinstall script downloads it),
|
|
20
|
-
or check the postinstall log for a download error.`)}var fr=g(()=>{});import{fileURLToPath as bo}from"node:url";import{dirname as Ro,resolve as Eo,join as
|
|
21
|
-
`)).catch(a=>{this.pending.delete(r),o(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let n of this.child.stdout){let r=new Uint8Array(t.length+n.length);r.set(t,0),r.set(n,t.length),t=r;let i=0;for(let s=0;s<t.length;s++)if(t[s]===10){let o=t.subarray(i,s);this.#n(To.decode(o)),i=s+1}i>0&&(t=t.subarray(i))}}catch(n){this.#e(`stdout reader error: ${n.message}`);return}this.#e("server stdout closed")}#n(t){if(!t.trim())return;let n;try{n=JSON.parse(t)}catch(s){this.#e(`malformed server response: ${s.message}`);return}let r=n.id;if(r==null)return;let i=this.pending.get(r);i&&(this.pending.delete(r),n.error?i.reject(new f(n.error.code??"UNKNOWN",n.error.message??"unknown error",n.error.data)):i.resolve(n.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let n=new f("CLIENT_CLOSED",t);for(let{reject:r}of this.pending.values())r(n);this.pending.clear()}}});function
|
|
20
|
+
or check the postinstall log for a download error.`)}var fr=g(()=>{});import{fileURLToPath as bo}from"node:url";import{dirname as Ro,resolve as Eo,join as Ul}from"node:path";function xo(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function pr(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:dr({name:xo(),packageRoot:So,envVar:"REDDB_BIN"})}var ko,So,mr=g(()=>{fr();ko=Ro(bo(import.meta.url)),So=Eo(ko,"..")});var Oo,To,f,ze,H=g(()=>{Oo=new TextEncoder,To=new TextDecoder("utf-8"),f=class extends Error{constructor(t,n,r){super(n),this.name="RedDBError",this.code=t,this.data=r??null}},ze=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,n={}){if(this.closed)return Promise.reject(new f("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let r=this.nextId++,i=JSON.stringify({jsonrpc:"2.0",id:r,method:t,params:n});return new Promise((s,o)=>{this.pending.set(r,{resolve:s,reject:o}),this.child.stdin.write(Oo.encode(i+`
|
|
21
|
+
`)).catch(a=>{this.pending.delete(r),o(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let n of this.child.stdout){let r=new Uint8Array(t.length+n.length);r.set(t,0),r.set(n,t.length),t=r;let i=0;for(let s=0;s<t.length;s++)if(t[s]===10){let o=t.subarray(i,s);this.#n(To.decode(o)),i=s+1}i>0&&(t=t.subarray(i))}}catch(n){this.#e(`stdout reader error: ${n.message}`);return}this.#e("server stdout closed")}#n(t){if(!t.trim())return;let n;try{n=JSON.parse(t)}catch(s){this.#e(`malformed server response: ${s.message}`);return}let r=n.id;if(r==null)return;let i=this.pending.get(r);i&&(this.pending.delete(r),n.error?i.reject(new f(n.error.code??"UNKNOWN",n.error.message??"unknown error",n.error.data)):i.resolve(n.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let n=new f("CLIENT_CLOSED",t);for(let{reject:r}of this.pending.values())r(n);this.pending.clear()}}});function At(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?Ao(e):$o(e)}function Ao(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let n;try{n=new URL(t)}catch(u){throw new f("UNPARSEABLE_URI",`failed to parse '${e}': ${u.message}`)}let r=n.searchParams,i=(r.get("proto")||"").toLowerCase(),s=n.pathname&&n.pathname!=="/"?n.pathname:"";if(n.hostname==="embedded.local")return s?{kind:"embedded",path:s,params:r,originalUri:e}:{kind:"embedded",params:r,originalUri:e};let o=Po(i),a=n.port?Number(n.port):Tt(o),c=n.username?decodeURIComponent(n.username):void 0,l=n.password?decodeURIComponent(n.password):void 0;return{kind:o,host:n.hostname,port:a,path:s||void 0,username:c,password:l,token:r.get("token")??void 0,apiKey:r.get("apiKey")??r.get("api_key")??void 0,loginUrl:r.get("loginUrl")??r.get("login_url")??void 0,params:r,originalUri:e}}function $o(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],n;try{n=new URL("https://"+e.slice(`${t}://`.length))}catch(s){throw new f("UNPARSEABLE_URI",`failed to parse '${e}': ${s.message}`)}if(!n.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let r=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",i=n.searchParams;return{kind:r,host:n.hostname,port:n.port?Number(n.port):Tt(r),username:n.username?decodeURIComponent(n.username):void 0,password:n.password?decodeURIComponent(n.password):void 0,token:i.get("token")??void 0,apiKey:i.get("apiKey")??i.get("api_key")??void 0,loginUrl:i.get("loginUrl")??i.get("login_url")??void 0,params:i,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(n){throw new f("UNPARSEABLE_URI",`failed to parse '${e}': ${n.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):Tt(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new f("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function Po(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new f("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function Tt(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var $t=g(()=>{H()});function Io(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return yr(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return yr(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function yr(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function vo(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}var _o,Te,Pt=g(()=>{H();_o=new Set(["embedded"]),Te=class{constructor(t,n){this._client=t,this._transport=n??null}_guard(t){if(this._transport&&_o.has(this._transport))throw new f("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,n){this._guard("get");let r=await this._client.call("cache.get",{namespace:t,key:n});return r==null||r.value==null?null:vo(r.value)}async put(t,n,r,i={}){this._guard("put");let s=Io(r);await this._client.call("cache.put",{namespace:t,key:n,value:s,...i})}async exists(t,n){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:n}))?.status??"maybe"}async invalidate(t,n){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:n})}async invalidatePrefix(t,n){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:n}))?.removed??0}async invalidateTags(t,n){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:n}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}}});function _t(e,t){return`${It(e)}.${No(t)}`}function It(e){let t=String(e),n=t.match(/[^A-Za-z0-9_]/);if(n)throw new f("INVALID_KV_KEY",`invalid KV key "${t}": character "${n[0]}" is not supported`);return t}function No(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function Lo(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function hr(e){return`'${String(e).replace(/'/g,"''")}'`}var de,vt=g(()=>{H();de=class{constructor(t,n="kv_default"){this.client=t,this.collection=n}put(t,n,r={}){let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(hr).join(", ")}]`:"",o=r.expireMs!=null?` EXPIRE ${Number(r.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${_t(i,t)} = ${Lo(n)}${o}${s}`})}set(t,n,r={}){return this.put(t,n,r)}async get(t,n={}){let r=n.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${_t(r,t)}`}))?.rows?.[0]?.value??null}async getMany(t,n={}){let r=[];for(let i of t)r.push(await this.get(i,n));return r}async exists(t,n={}){return{exists:await this.get(t,n)!==null}}async delete(t,n={}){let r=n.collection??this.collection,i=await this.client.call("query",{sql:`KV DELETE ${_t(r,t)}`}),s=i.affected??i.affected_rows??0;return{affected:s,deleted:s>0}}async list(t={}){let n=t.collection??this.collection,r=t.limit==null?100:Number(t.limit);if(!Number.isInteger(r)||r<=0)throw new f("INVALID_ARGUMENT","kv.list limit must be a positive integer");let i=t.prefix==null?"":String(t.prefix),o=(await this.client.call("query",{sql:`SELECT key, value FROM ${It(n)} ORDER BY key ASC LIMIT ${r}`})).rows??[];return{items:i.length>0?o.filter(c=>String(c.key).startsWith(i)):o}}async invalidateTags(t,n={}){let r=n.collection??this.collection,i=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(hr).join(", ")}] FROM ${It(r)}`});return i.affected??i.affected_rows??i.rows?.[0]?.invalidated??0}async*watch(t,n={}){if(!this.client.baseUrl)throw new f("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let r=n.collection??this.collection,i=new URLSearchParams;n.sinceLsn!=null&&i.set("since_lsn",String(n.sinceLsn)),n.limit!=null&&i.set("limit",String(n.limit));let s=i.toString()?`?${i}`:"",o=`${this.client.baseUrl}/collections/${encodeURIComponent(r)}/kv/${encodeURIComponent(String(t))}/watch${s}`,a=await fetch(o,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new f("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let l of c.split(`
|
|
22
22
|
|
|
23
23
|
`)){let u=l.split(`
|
|
24
|
-
`).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,n={}){return this.watch(`${t}.*`,n)}}});function Do(e,t,n){let{waitMs:r,group:i=null,count:s=null}=n??{};if(!Number.isInteger(r)||r<0)throw new f("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let o=G(e),a=G(t),c=i!=null?` GROUP ${G(i)}`:"",l=s!=null?Nt(s):"";return`QUEUE READ ${o}${c} CONSUMER ${a}${l} WAIT ${r}ms`}function G(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new f("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Nt(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new f("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function jo(e){if(!Number.isInteger(e))throw new f("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function Bo(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new f("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${jo(e.priority)}`),e.key!=null&&(t+=` KEY ${Lt(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Lt(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function Uo(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Lt(e):JSON.stringify(e)}function Lt(e){return`'${String(e).replace(/'/g,"''")}'`}function vt(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Ae,Dt=g(()=>{H();Ae=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${G(t)}`})}push(t,n,r={}){let i=Bo(r);return this.client.call("query",{sql:`QUEUE PUSH ${G(t)} ${Uo(n)}${i}`})}async pop(t,n){let r=await this.client.call("query",{sql:`QUEUE POP ${G(t)}${Nt(n)}`});return vt(r)}async peek(t,n){let r=await this.client.call("query",{sql:`QUEUE PEEK ${G(t)}${Nt(n)}`});return vt(r)}async len(t){let n=await this.client.call("query",{sql:`QUEUE LEN ${G(t)}`});return Number(n?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${G(t)}`})}async readWait(t,n,r={}){let i=Do(t,n,r),s=await this.client.call("query",{sql:i});return vt(s)}}});function gr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new f("INVALID_ARGUMENT",`${t} must be an object`)}function Co(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new f("INVALID_ARGUMENT","limit must be a positive integer");return e}function Qe(e){return String(e).split(".").map(wr).join(".")}function wr(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new f("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function qo(e){return br(JSON.stringify(e))}function Go(e){return JSON.stringify(e)}function Jo(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?qo(e):br(e)}function br(e){return`'${String(e).replace(/'/g,"''")}'`}var $e,jt=g(()=>{H();$e=class{constructor(t){this.db=t}async insert(t,n){gr(n,"documents.insert document"),await this.ensureCollection(t);let r=await this.db.query(`INSERT INTO ${Qe(t)} DOCUMENT VALUES (${Go(n)}) RETURNING *`),i=r.rows?.[0];if(!i||i.rid==null)throw new f("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:r.affected??1,rid:i.rid,item:i}}async get(t,n){let r=await this.db.get(t,n);if(!r.entity)throw new f("NOT_FOUND",`document ${String(n)} was not found`);return r.entity}async list(t,n={}){let r=Co(n.limit),i=n.orderBy??n.order_by??"rid ASC",s=n.filter?` WHERE ${String(n.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${Qe(t)}${s} ORDER BY ${i} LIMIT ${r}`)).rows??[]}}async patch(t,n,r){gr(r,"documents.patch patch");let i=Object.entries(r);if(i.length===0)throw new f("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of i)if(c.includes("/"))throw new f("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let s=i.map(([c,l])=>`${wr(c)} = ${Jo(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Qe(t)} SET ${s} WHERE rid = $1 RETURNING *`,n)).rows?.[0];if(!a)throw new f("NOT_FOUND",`document ${String(n)} was not found`);return a}async delete(t,n){let i=(await this.db.delete(t,n)).affected??0;return{affected:i,deleted:i>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${Qe(t)}`)}catch(n){if(!String(n?.message??"").includes("already exists"))throw n}}}});function Mo(e,t){if(t.secretRef){let{collection:n,key:r}=t.secretRef;return`SECRET_REF(vault, ${K(n)}.${K(r)})`}return Vo(e)}function Fo(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function K(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Vo(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Rr(e)}function Rr(e){return`'${String(e).replace(/'/g,"''")}'`}var Pe,Bt=g(()=>{Pe=class{constructor(t,n="red.config"){this.client=t,this.collection=n}put(t,n,r={}){Fo(r,"config");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Rr).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${K(i)} ${K(t)} = ${Mo(n,r)}${s}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${K(r)} ${K(t)}`})}resolve(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${K(r)} ${K(t)}`})}}});function Ho(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function fe(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Ko(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Er(e)}function Er(e){return`'${String(e).replace(/'/g,"''")}'`}var _e,Ut=g(()=>{_e=class{constructor(t,n="red.vault"){this.client=t,this.collection=n}put(t,n,r={}){Ho(r,"vault");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Er).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${fe(i)}.${fe(t)} = ${Ko(n)}${s}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${fe(r)}.${fe(t)}`})}unseal(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${fe(r)}.${fe(t)}`})}}});async function Sr(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(Wo)}async function xr(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${Qo(t)}`)).rows??[]).some(r=>r.name===String(t))}function Wo(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function kr(e){return String(e).split(".").map(zo).join(".")}function zo(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new f("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function Qo(e){return`'${String(e).replace(/'/g,"''")}'`}var Ie,Ct=g(()=>{H();Ie=class e{constructor(t,n,r=null,i=[],s=[]){this.db=t,this.collection=n,this.columns=r,this.whereClauses=i,this.params=s}select(...t){let n=t.length===1&&Array.isArray(t[0])?t[0]:t,r=n.length===1&&n[0]==="*"?null:n;return new e(this.db,this.collection,r!=null&&r.length>0?r:null,this.whereClauses,this.params)}where(t,...n){if(typeof t!="string"||t.trim().length===0)throw new f("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...r])}async run(){let t=this.columns==null?"*":this.columns.map(kr).join(", "),n=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(o=>`(${o})`).join(" AND ")}`:"",r=`SELECT ${t} FROM ${kr(this.collection)}${n}`,s=(this.params.length>0?await this.db.query(r,this.params):await this.db.query(r)).rows??[];return this.columns==null?s:s.map(o=>{let a={};for(let c of this.columns)a[c]=o[c];return a})}}});async function $r(e,t={}){let n=Tt(e);if(oa(n),n.kind==="embedded"){let r=sa(n,t.auth);if(r.token||r.username)throw new f("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let i=ia(n),s=t.binary??pr(),o=await lr(s,i),a=new ze(o);return await a.call("version",{}),new Gt(a,{transport:"embedded"})}}function Tr(e){return Xo(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:ta(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&ra(e)?{$uuid:e}:e}function Xo(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new f("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new f("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new f("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function ea(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Tr):e.map(Tr)}function ta(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function na(e){if(typeof Buffer<"u"){let r=Buffer.from(e,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function ra(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Ye(e){if(Array.isArray(e))return e.map(Ye);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return na(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let r=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(r/1000000n))}}let n={};for(let[r,i]of Object.entries(e))n[r]=Ye(i);return n}return e}function ia(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function sa(e,t){let n={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return n;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");n.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");n.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");n.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");n.password=t.password}return t.loginUrl!=null&&(n.loginUrl=t.loginUrl),n}function oa(e){if(e.kind!=="embedded")throw new f("EMBEDDED_ONLY",Yo)}function Jt(){return new f(Or,`${Or}: nested transactions are not supported on one connection`)}function Pr(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function aa(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new f("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Ar} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function ca(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new f("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Ar} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new f("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}var Yo,Zo,Ar,Or,Ze,qt,Gt,_r=g(()=>{ur();mr();H();At();$t();It();Dt();jt();Bt();Ut();Ct();$t();It();Dt();jt();Bt();Ut();Ct();At();Yo="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",Zo="1.0",Ar="1.0.9",Or="NESTED_TX_NOT_SUPPORTED";Ze=class{constructor(t){this.db=t}query(t,...n){return this.db.query(t,...n)}execute(t,...n){return this.db.execute(t,...n)}insert(t,n){return this.db.insert(t,n)}bulkInsert(t,n){return this.db.bulkInsert(t,n)}async transaction(){throw Jt()}},qt=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Jt();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new f("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new f("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new f("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let n=await t(new Ze(this.db));return await this.commit(),n}catch(n){if(this.active)try{await this.rollback()}catch(r){Pr(n,r)}throw n}}},Gt=class{constructor(t,n={}){this.client=t,this.transport=n.transport??null,this.helperSpecVersion=Zo,this.cache=new Te(t,this.transport),this.queue=new Ae(t),this.queues=this.queue,this.documents=new $e(this);let r=new de(t);this.kv=Object.assign((i="kv_default")=>new de(t,i),{put:r.put.bind(r),invalidateTags:r.invalidateTags.bind(r),watch:r.watch.bind(r),watchPrefix:r.watchPrefix.bind(r)}),this.config=(i="red.config")=>new Pe(t,i),this.vault=(i="red.vault")=>new _e(t,i),this.inTransaction=!1}query(t,...n){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new f("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let r=ea(n);return r==null?this.client.call("query",{sql:t}).then(Ye):this.client.call("query",{sql:t,params:r}).then(Ye)}execute(t,...n){return this.query(t,...n)}async insert(t,n){let r=await this.client.call("insert",{collection:t,payload:n});return aa(r,"insert")}async bulkInsert(t,n){if(Array.isArray(n)&&n.length===0)return{affected:0,rids:[],ids:[]};let r=await this.client.call("bulk_insert",{collection:t,payloads:n});return ca(r,n.length)}tx(){return new qt(this)}async transaction(t){if(this.inTransaction)throw Jt();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let n=!1;try{await this.query("BEGIN"),n=!0;let r=await t(new Ze(this));return await this.query("COMMIT"),r}catch(r){if(n)try{await this.query("ROLLBACK")}catch(i){Pr(r,i)}throw r}finally{this.inTransaction=!1}}exists(t){return xr(this,t)}list(){return Sr(this)}from(t){return new Ie(this,t)}get(t,n){return this.client.call("get",{collection:t,id:String(n)})}delete(t,n){return this.client.call("delete",{collection:t,id:String(n)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,n){return this.client.call("auth.login",{username:t,password:n})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,n){return this.client.call("auth.change_password",{current_password:t,new_password:n})}createApiKey({username:t,role:n}={}){return this.client.call("auth.create_api_key",{username:t,role:n})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}}});var Vt={};P(Vt,{DEFAULT_RSP_BYTE_BUDGET:()=>U,DEFAULT_RSP_TTL_DAYS:()=>B,RSP_ELISION_COLLECTION:()=>re,RspElisionStore:()=>ve});import{createHash as la}from"node:crypto";import{existsSync as ua}from"node:fs";import{mkdir as da,readFile as Dr,readdir as fa,rename as pa,writeFile as ma}from"node:fs/promises";import{basename as jr,dirname as Br,join as Mt}from"node:path";import{fileURLToPath as ya}from"node:url";function Ir(e,t){return`el:${la("sha256").update("rsp-elision-v1\0").update(e).update("\0").update(JSON.stringify({command:t.command,loss:t.loss})).digest("hex").slice(0,12)}`}function ne(e){return`record:${e.slice(3)}`}function pe(e){return`expired:${e.slice(3)}`}function vr(){return"index:v1"}function et(e){return/^el:[a-f0-9]{12}$/.test(e)}function Nr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Xe(e){return W(e)?e.collection===re&&typeof e.handle=="string"&&et(e.handle)&&typeof e.original=="string"&&e.original_encoding==="base64"&&typeof e.original_bytes=="number"&&typeof e.command=="string"&&typeof e.created_at=="string"&&typeof e.expires_at=="string"&&ha(e.loss):!1}function Ur(e){return!W(e)||e.version!==1||!Array.isArray(e.records)?!1:e.records.every(t=>W(t)&&typeof t.handle=="string"&&et(t.handle)&&typeof t.key=="string"&&typeof t.bytes=="number"&&typeof t.command=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string")}function Ft(e){return W(e)&&e.status==="expired"&&typeof e.expired_at=="string"&&typeof e.command=="string"}function ha(e){return W(e)&&typeof e.level=="string"&&typeof e.bytes_elided=="number"}function W(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function ga(e){try{let t=await Dr(e,"utf8");if(t.trim()==="")return Lr();let n=JSON.parse(t);if(Sa(n))return n}catch(t){if(t.code==="ENOENT"){let n=Lr();return await Cr(e,n),n}throw t}throw new Error("rsp elision store is unreadable")}async function wa(e){try{let t=await Dr(e);return ba(t)?Ra(e):e}catch(t){if(t.code==="ENOENT")return e;throw t}}function ba(e){return e.subarray(0,8).toString("ascii")==="RDBSBLK1"}function Ra(e){return jr(e)==="red.rdb"?Mt(Br(e),"tmp","rsp-elisions.json"):`${e}.json`}function Ea(e){return jr(e)==="red-skills.rdb"}async function ka(){if(process.env.REDDB_BIN||!process.env.RED_SKILLS_CACHE_DIR)return;let e=Mt(process.env.RED_SKILLS_CACHE_DIR,"reddb"),t;try{t=await fa(e)}catch{return}t.sort().reverse();for(let n of t){let r=Mt(e,n,process.platform==="win32"?"red.exe":"red");if(ua(r)){process.env.REDDB_BIN=r;return}}}async function Cr(e,t){await da(Br(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await ma(n,`${JSON.stringify(t)}
|
|
25
|
-
`,"utf8"),await pa(n,e)}function Lr(){return{version:1,records:{},tombstones:{},index:{version:1,records:[]}}}function Sa(e){return W(e)&&e.version===1&&W(e.records)&&Object.values(e.records).every(Xe)&&W(e.tombstones)&&Object.values(e.tombstones).every(
|
|
24
|
+
`).find(d=>d.startsWith("data: "));u&&(yield JSON.parse(u.slice(6)))}}watchPrefix(t,n={}){return this.watch(`${t}.*`,n)}}});function Do(e,t,n){let{waitMs:r,group:i=null,count:s=null}=n??{};if(!Number.isInteger(r)||r<0)throw new f("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let o=G(e),a=G(t),c=i!=null?` GROUP ${G(i)}`:"",l=s!=null?Lt(s):"";return`QUEUE READ ${o}${c} CONSUMER ${a}${l} WAIT ${r}ms`}function G(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new f("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Lt(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new f("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function jo(e){if(!Number.isInteger(e))throw new f("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function Bo(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new f("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${jo(e.priority)}`),e.key!=null&&(t+=` KEY ${Dt(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Dt(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function Uo(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Dt(e):JSON.stringify(e)}function Dt(e){return`'${String(e).replace(/'/g,"''")}'`}function Nt(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Ae,jt=g(()=>{H();Ae=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${G(t)}`})}push(t,n,r={}){let i=Bo(r);return this.client.call("query",{sql:`QUEUE PUSH ${G(t)} ${Uo(n)}${i}`})}async pop(t,n){let r=await this.client.call("query",{sql:`QUEUE POP ${G(t)}${Lt(n)}`});return Nt(r)}async peek(t,n){let r=await this.client.call("query",{sql:`QUEUE PEEK ${G(t)}${Lt(n)}`});return Nt(r)}async len(t){let n=await this.client.call("query",{sql:`QUEUE LEN ${G(t)}`});return Number(n?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${G(t)}`})}async readWait(t,n,r={}){let i=Do(t,n,r),s=await this.client.call("query",{sql:i});return Nt(s)}}});function gr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new f("INVALID_ARGUMENT",`${t} must be an object`)}function Co(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new f("INVALID_ARGUMENT","limit must be a positive integer");return e}function Qe(e){return String(e).split(".").map(wr).join(".")}function wr(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new f("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function qo(e){return br(JSON.stringify(e))}function Go(e){return JSON.stringify(e)}function Jo(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?qo(e):br(e)}function br(e){return`'${String(e).replace(/'/g,"''")}'`}var $e,Bt=g(()=>{H();$e=class{constructor(t){this.db=t}async insert(t,n){gr(n,"documents.insert document"),await this.ensureCollection(t);let r=await this.db.query(`INSERT INTO ${Qe(t)} DOCUMENT VALUES (${Go(n)}) RETURNING *`),i=r.rows?.[0];if(!i||i.rid==null)throw new f("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:r.affected??1,rid:i.rid,item:i}}async get(t,n){let r=await this.db.get(t,n);if(!r.entity)throw new f("NOT_FOUND",`document ${String(n)} was not found`);return r.entity}async list(t,n={}){let r=Co(n.limit),i=n.orderBy??n.order_by??"rid ASC",s=n.filter?` WHERE ${String(n.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${Qe(t)}${s} ORDER BY ${i} LIMIT ${r}`)).rows??[]}}async patch(t,n,r){gr(r,"documents.patch patch");let i=Object.entries(r);if(i.length===0)throw new f("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of i)if(c.includes("/"))throw new f("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let s=i.map(([c,l])=>`${wr(c)} = ${Jo(l)}`).join(", "),a=(await this.db.query(`UPDATE ${Qe(t)} SET ${s} WHERE rid = $1 RETURNING *`,n)).rows?.[0];if(!a)throw new f("NOT_FOUND",`document ${String(n)} was not found`);return a}async delete(t,n){let i=(await this.db.delete(t,n)).affected??0;return{affected:i,deleted:i>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${Qe(t)}`)}catch(n){if(!String(n?.message??"").includes("already exists"))throw n}}}});function Mo(e,t){if(t.secretRef){let{collection:n,key:r}=t.secretRef;return`SECRET_REF(vault, ${K(n)}.${K(r)})`}return Vo(e)}function Fo(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function K(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Vo(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Rr(e)}function Rr(e){return`'${String(e).replace(/'/g,"''")}'`}var Pe,Ut=g(()=>{Pe=class{constructor(t,n="red.config"){this.client=t,this.collection=n}put(t,n,r={}){Fo(r,"config");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Rr).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${K(i)} ${K(t)} = ${Mo(n,r)}${s}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${K(r)} ${K(t)}`})}resolve(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${K(r)} ${K(t)}`})}}});function Ho(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function fe(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Ko(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Er(e)}function Er(e){return`'${String(e).replace(/'/g,"''")}'`}var _e,Ct=g(()=>{_e=class{constructor(t,n="red.vault"){this.client=t,this.collection=n}put(t,n,r={}){Ho(r,"vault");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Er).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${fe(i)}.${fe(t)} = ${Ko(n)}${s}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${fe(r)}.${fe(t)}`})}unseal(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${fe(r)}.${fe(t)}`})}}});async function Sr(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(Wo)}async function xr(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${Qo(t)}`)).rows??[]).some(r=>r.name===String(t))}function Wo(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function kr(e){return String(e).split(".").map(zo).join(".")}function zo(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new f("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function Qo(e){return`'${String(e).replace(/'/g,"''")}'`}var Ie,qt=g(()=>{H();Ie=class e{constructor(t,n,r=null,i=[],s=[]){this.db=t,this.collection=n,this.columns=r,this.whereClauses=i,this.params=s}select(...t){let n=t.length===1&&Array.isArray(t[0])?t[0]:t,r=n.length===1&&n[0]==="*"?null:n;return new e(this.db,this.collection,r!=null&&r.length>0?r:null,this.whereClauses,this.params)}where(t,...n){if(typeof t!="string"||t.trim().length===0)throw new f("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...r])}async run(){let t=this.columns==null?"*":this.columns.map(kr).join(", "),n=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(o=>`(${o})`).join(" AND ")}`:"",r=`SELECT ${t} FROM ${kr(this.collection)}${n}`,s=(this.params.length>0?await this.db.query(r,this.params):await this.db.query(r)).rows??[];return this.columns==null?s:s.map(o=>{let a={};for(let c of this.columns)a[c]=o[c];return a})}}});async function $r(e,t={}){let n=At(e);if(oa(n),n.kind==="embedded"){let r=sa(n,t.auth);if(r.token||r.username)throw new f("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let i=ia(n),s=t.binary??pr(),o=await lr(s,i),a=new ze(o);return await a.call("version",{}),new Jt(a,{transport:"embedded"})}}function Tr(e){return Xo(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:ta(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&ra(e)?{$uuid:e}:e}function Xo(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new f("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new f("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new f("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function ea(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Tr):e.map(Tr)}function ta(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function na(e){if(typeof Buffer<"u"){let r=Buffer.from(e,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function ra(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function Ye(e){if(Array.isArray(e))return e.map(Ye);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return na(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let r=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(r/1000000n))}}let n={};for(let[r,i]of Object.entries(e))n[r]=Ye(i);return n}return e}function ia(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function sa(e,t){let n={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return n;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");n.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");n.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");n.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");n.password=t.password}return t.loginUrl!=null&&(n.loginUrl=t.loginUrl),n}function oa(e){if(e.kind!=="embedded")throw new f("EMBEDDED_ONLY",Yo)}function Mt(){return new f(Or,`${Or}: nested transactions are not supported on one connection`)}function Pr(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function aa(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new f("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Ar} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function ca(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new f("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Ar} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new f("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}var Yo,Zo,Ar,Or,Ze,Gt,Jt,_r=g(()=>{ur();mr();H();$t();Pt();vt();jt();Bt();Ut();Ct();qt();Pt();vt();jt();Bt();Ut();Ct();qt();$t();Yo="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",Zo="1.0",Ar="1.0.9",Or="NESTED_TX_NOT_SUPPORTED";Ze=class{constructor(t){this.db=t}query(t,...n){return this.db.query(t,...n)}execute(t,...n){return this.db.execute(t,...n)}insert(t,n){return this.db.insert(t,n)}bulkInsert(t,n){return this.db.bulkInsert(t,n)}async transaction(){throw Mt()}},Gt=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Mt();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new f("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new f("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new f("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let n=await t(new Ze(this.db));return await this.commit(),n}catch(n){if(this.active)try{await this.rollback()}catch(r){Pr(n,r)}throw n}}},Jt=class{constructor(t,n={}){this.client=t,this.transport=n.transport??null,this.helperSpecVersion=Zo,this.cache=new Te(t,this.transport),this.queue=new Ae(t),this.queues=this.queue,this.documents=new $e(this);let r=new de(t);this.kv=Object.assign((i="kv_default")=>new de(t,i),{put:r.put.bind(r),invalidateTags:r.invalidateTags.bind(r),watch:r.watch.bind(r),watchPrefix:r.watchPrefix.bind(r)}),this.config=(i="red.config")=>new Pe(t,i),this.vault=(i="red.vault")=>new _e(t,i),this.inTransaction=!1}query(t,...n){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new f("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let r=ea(n);return r==null?this.client.call("query",{sql:t}).then(Ye):this.client.call("query",{sql:t,params:r}).then(Ye)}execute(t,...n){return this.query(t,...n)}async insert(t,n){let r=await this.client.call("insert",{collection:t,payload:n});return aa(r,"insert")}async bulkInsert(t,n){if(Array.isArray(n)&&n.length===0)return{affected:0,rids:[],ids:[]};let r=await this.client.call("bulk_insert",{collection:t,payloads:n});return ca(r,n.length)}tx(){return new Gt(this)}async transaction(t){if(this.inTransaction)throw Mt();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let n=!1;try{await this.query("BEGIN"),n=!0;let r=await t(new Ze(this));return await this.query("COMMIT"),r}catch(r){if(n)try{await this.query("ROLLBACK")}catch(i){Pr(r,i)}throw r}finally{this.inTransaction=!1}}exists(t){return xr(this,t)}list(){return Sr(this)}from(t){return new Ie(this,t)}get(t,n){return this.client.call("get",{collection:t,id:String(n)})}delete(t,n){return this.client.call("delete",{collection:t,id:String(n)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,n){return this.client.call("auth.login",{username:t,password:n})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,n){return this.client.call("auth.change_password",{current_password:t,new_password:n})}createApiKey({username:t,role:n}={}){return this.client.call("auth.create_api_key",{username:t,role:n})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}}});var Ht={};P(Ht,{DEFAULT_RSP_BYTE_BUDGET:()=>U,DEFAULT_RSP_TTL_DAYS:()=>B,RSP_ELISION_COLLECTION:()=>re,RspElisionStore:()=>ve});import{createHash as la}from"node:crypto";import{existsSync as ua}from"node:fs";import{mkdir as da,readFile as Dr,readdir as fa,rename as pa,writeFile as ma}from"node:fs/promises";import{basename as jr,dirname as Br,join as Ft}from"node:path";import{fileURLToPath as ya}from"node:url";function Ir(e,t){return`el:${la("sha256").update("rsp-elision-v1\0").update(e).update("\0").update(JSON.stringify({command:t.command,loss:t.loss})).digest("hex").slice(0,12)}`}function ne(e){return`record:${e.slice(3)}`}function pe(e){return`expired:${e.slice(3)}`}function vr(){return"index:v1"}function et(e){return/^el:[a-f0-9]{12}$/.test(e)}function Nr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Xe(e){return W(e)?e.collection===re&&typeof e.handle=="string"&&et(e.handle)&&typeof e.original=="string"&&e.original_encoding==="base64"&&typeof e.original_bytes=="number"&&typeof e.command=="string"&&typeof e.created_at=="string"&&typeof e.expires_at=="string"&&ha(e.loss):!1}function Ur(e){return!W(e)||e.version!==1||!Array.isArray(e.records)?!1:e.records.every(t=>W(t)&&typeof t.handle=="string"&&et(t.handle)&&typeof t.key=="string"&&typeof t.bytes=="number"&&typeof t.command=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string")}function Vt(e){return W(e)&&e.status==="expired"&&typeof e.expired_at=="string"&&typeof e.command=="string"}function ha(e){return W(e)&&typeof e.level=="string"&&typeof e.bytes_elided=="number"}function W(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function ga(e){try{let t=await Dr(e,"utf8");if(t.trim()==="")return Lr();let n=JSON.parse(t);if(Sa(n))return n}catch(t){if(t.code==="ENOENT"){let n=Lr();return await Cr(e,n),n}throw t}throw new Error("rsp elision store is unreadable")}async function wa(e){try{let t=await Dr(e);return ba(t)?Ra(e):e}catch(t){if(t.code==="ENOENT")return e;throw t}}function ba(e){return e.subarray(0,8).toString("ascii")==="RDBSBLK1"}function Ra(e){return jr(e)==="red.rdb"?Ft(Br(e),"tmp","rsp-elisions.json"):`${e}.json`}function Ea(e){return jr(e)==="red-skills.rdb"}async function ka(){if(process.env.REDDB_BIN||!process.env.RED_SKILLS_CACHE_DIR)return;let e=Ft(process.env.RED_SKILLS_CACHE_DIR,"reddb"),t;try{t=await fa(e)}catch{return}t.sort().reverse();for(let n of t){let r=Ft(e,n,process.platform==="win32"?"red.exe":"red");if(ua(r)){process.env.REDDB_BIN=r;return}}}async function Cr(e,t){await da(Br(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await ma(n,`${JSON.stringify(t)}
|
|
25
|
+
`,"utf8"),await pa(n,e)}function Lr(){return{version:1,records:{},tombstones:{},index:{version:1,records:[]}}}function Sa(e){return W(e)&&e.version===1&&W(e.records)&&Object.values(e.records).every(Xe)&&W(e.tombstones)&&Object.values(e.tombstones).every(Vt)&&Ur(e.index)}function xa(e){if(!e.startsWith("file://"))throw new Error("rsp elision store requires a file:// URI");return ya(e)}var re,ve,tt=g(()=>{"use strict";_r();C();re="rsp_elisions_v1",ve=class e{constructor(t,n){this.opts=n;this.path=t}document;db;path;static async open(t){if(process.env.RSP_FAIL_IF_STORE_OPEN==="1"&&!t.allowResidentOpen)throw new Error("RSP_FAIL_IF_STORE_OPEN blocked store open");let n=xa(t.uri),r=await wa(n),i=new e(r,{uri:t.uri,ttlDays:Nr(t.ttlDays,B),byteBudget:Nr(t.byteBudget,U),now:t.now??(()=>new Date)});return Ea(r)?(await ka(),i.db=await $r(`file://${r}`),await i.ensureRedDbStore()):i.document=await ga(i.path),i}async close(){await this.db?.close()}async mint(t,n){if(this.db)return await this.mintRedDb(t,n);let r=Buffer.from(t),i=this.opts.now(),s=i.toISOString(),o=new Date(i.getTime()+this.opts.ttlDays*24*60*60*1e3).toISOString(),a=Ir(r,n),c=ne(a),l={collection:re,handle:a,original:r.toString("base64"),original_encoding:"base64",original_bytes:r.length,command:n.command,created_at:s,expires_at:o,loss:n.loss};return delete this.document.tombstones[pe(a)],this.document.records[c]=l,this.upsertIndex({handle:a,key:c,bytes:r.length,command:n.command,created_at:s,expires_at:o}),this.prune(),await this.flush(),a}async get(t){if(this.db)return await this.getRedDb(t);if(!et(t))return null;let n=this.tombstone(t);if(n)return n;let r=this.document.records[ne(t)];if(!Xe(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return this.expireEntry({handle:r.handle,key:ne(r.handle),bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at},r.expires_at),await this.flush(),s}let i=this.readOriginal(r);return i?{collection:re,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss}:null}async stats(){if(this.db)return await this.statsRedDb();this.prune(),await this.flush();let n=this.readIndex().records;return{records:n.length,bytes:n.reduce((r,i)=>r+i.bytes,0),oldest:n.reduce((r,i)=>r==null||i.created_at<r?i.created_at:r,null),budget:this.opts.byteBudget}}readIndex(){return this.document.index}writeIndex(t){this.document.index=t}upsertIndex(t){let r=this.readIndex().records.filter(i=>i.handle!==t.handle);r.push(t),this.writeIndex({version:1,records:r})}prune(){let t=this.opts.now().getTime(),n=new Date(t).toISOString(),r=this.readIndex(),i=[];for(let o of r.records)Date.parse(o.expires_at)<=t?this.expireEntry(o,o.expires_at):i.push(o);let s=i.reduce((o,a)=>o+a.bytes,0);for(i.sort((o,a)=>o.created_at.localeCompare(a.created_at));s>this.opts.byteBudget&&i.length>0;){let o=i.shift();s-=o.bytes,this.expireEntry(o,n)}this.writeIndex({version:1,records:i})}expireEntry(t,n){delete this.document.records[t.key],this.document.tombstones[pe(t.handle)]={status:"expired",expired_at:n,command:t.command}}tombstone(t){let n=this.document.tombstones[pe(t)];return Vt(n)?n:null}readOriginal(t){return t.original?Buffer.from(t.original,"base64"):null}async flush(){await Cr(this.path,this.document)}kv(){if(!this.db)throw new Error("rsp RedDB store is not open");return this.db.kv(re)}async ensureRedDbStore(){let t=await this.readRedDbIndex();await this.writeRedDbIndex(t)}async mintRedDb(t,n){let r=Buffer.from(t),i=this.opts.now(),s=i.toISOString(),o=new Date(i.getTime()+this.opts.ttlDays*24*60*60*1e3).toISOString(),a=Ir(r,n),c=ne(a),l={collection:re,handle:a,original:r.toString("base64"),original_encoding:"base64",original_bytes:r.length,command:n.command,created_at:s,expires_at:o,loss:n.loss};await this.kv().delete(pe(a)),await this.kv().put(c,l);let d=(await this.readRedDbIndex()).records.filter(y=>y.handle!==a);return d.push({handle:a,key:c,bytes:r.length,command:n.command,created_at:s,expires_at:o}),await this.pruneRedDb({version:1,records:d}),await this.assertRedDbMintPersisted(a,r.length),a}async getRedDb(t){if(!et(t))return null;let n=await this.kv().get(pe(t));if(Vt(n))return n;let r=await this.kv().get(ne(t));if(!Xe(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return await this.expireRedDbEntry({handle:r.handle,key:ne(r.handle),bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at},r.expires_at),s}let i=this.readOriginal(r);return i?{collection:re,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss}:null}async statsRedDb(){let t=await this.pruneRedDb(await this.readRedDbIndex());return{records:t.records.length,bytes:t.records.reduce((n,r)=>n+r.bytes,0),oldest:t.records.reduce((n,r)=>n==null||r.created_at<n?r.created_at:n,null),budget:this.opts.byteBudget}}async memory(t,n){if(t==="recall")return{status:"resident",action:t,payload:n};if(t==="ingest")return{status:"resident",action:t,payload:n};throw new Error(`unsupported memory action: ${t}`)}async readRedDbIndex(){let t=await this.kv().get(vr());return Ur(t)?t:{version:1,records:[]}}async writeRedDbIndex(t){await this.kv().put(vr(),t)}async pruneRedDb(t){let n=this.opts.now().getTime(),r=new Date(n).toISOString(),i=[];for(let a of t.records)Date.parse(a.expires_at)<=n?await this.expireRedDbEntry(a,a.expires_at):i.push(a);let s=i.reduce((a,c)=>a+c.bytes,0);for(i.sort((a,c)=>a.created_at.localeCompare(c.created_at));s>this.opts.byteBudget&&i.length>0;){let a=i.shift();s-=a.bytes,await this.expireRedDbEntry(a,r)}let o={version:1,records:i};return await this.writeRedDbIndex(o),o}async expireRedDbEntry(t,n){await this.kv().delete(t.key),await this.kv().put(pe(t.handle),{status:"expired",expired_at:n,command:t.command})}async assertRedDbMintPersisted(t,n){let r=await this.kv().get(ne(t));if(!Xe(r))throw new Error(`rsp resident failed to persist elision record ${t}`);let s=(await this.readRedDbIndex()).records.find(o=>o.handle===t);if(!s||s.bytes!==n)throw new Error(`rsp resident failed to persist elision index ${t}`)}}});var Kr={};P(Kr,{REPO_STORE_PATH:()=>Wt,mergeRspBlock:()=>Fr,provisionRspRepoStore:()=>va});import{constants as Oa}from"node:fs";import{access as Ta,copyFile as Aa,mkdir as qr,readFile as $a,writeFile as Gr}from"node:fs/promises";import{dirname as Pa,join as nt,resolve as _a}from"node:path";async function va(e,t={}){let n=_a(e),r=nt(n,".red"),i=nt(r,"config.yaml"),s=nt(n,Wt);await qr(r,{recursive:!0}),await qr(Pa(s),{recursive:!0});let o="";try{o=await $a(i,"utf8")}catch(y){if(y.code!=="ENOENT")throw y}let a=Fr(o,{enabled:!0,ttlDays:t.ttlDays??B,byteBudget:t.byteBudget??U,heavyGitByteThreshold:t.heavyGitByteThreshold??j}),c=a!==o;c&&await Gr(i,a,"utf8");let l=!await Mr(s),u=!1;if(l){let y=nt(n,Ia);if(await Mr(y))await Aa(y,s),u=!0;else{let{RspElisionStore:E}=await Promise.resolve().then(()=>(tt(),Ht));await(await E.open({uri:`file://${s}`,ttlDays:t.ttlDays??B,byteBudget:t.byteBudget??U,allowResidentOpen:!0})).close()}}let d=Na(a,Wt);return d!==a&&await Gr(i,d,"utf8"),{configPath:i,storePath:s,configChanged:c||d!==a,storeCreated:l,memoryStoreMigrated:u}}function Fr(e,t){let n=["rsp:",` enabled: ${t.enabled?"true":"false"}`,` ttlDays: ${Kt(t.ttlDays,B)}`,` byteBudget: ${Kt(t.byteBudget,U)}`,` heavyGitByteThreshold: ${Kt(t.heavyGitByteThreshold,j)}`],r=e===""?[]:e.replace(/\n+$/,"").split(`
|
|
26
26
|
`),i=Vr(r,"rsp");if(i===-1){let a=[...r];return a.length>0&&a[a.length-1].trim()!==""&&a.push(""),a.push(...n),`${a.join(`
|
|
27
27
|
`)}
|
|
28
|
-
`}let s=
|
|
28
|
+
`}let s=zt(r,i,0);return`${[...r.slice(0,i),...n,...r.slice(s)].join(`
|
|
29
29
|
`)}
|
|
30
|
-
`}function Vr(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(
|
|
31
|
-
`),r=Vr(n,"plugins");if(r===-1)return e;let i=
|
|
30
|
+
`}function Vr(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(Yt(r)&&Qt(r)===0&&Hr(r)===t)return n}return-1}function zt(e,t,n){let r=e.length;for(let i=t+1;i<e.length;i++)if(Yt(e[i])&&Qt(e[i])<=n){r=i;break}for(;r-1>t&&e[r-1].trim()==="";)r--;return r}function Qt(e){return(e.match(/^ */)?.[0]??"").length}function Yt(e){let t=e.trim();return t!==""&&!t.startsWith("#")}function Hr(e){return e.replace(/^ */,"").replace(/:.*$/,"").trim()}function Kt(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Na(e,t){let n=e===""?[]:e.replace(/\n+$/,"").split(`
|
|
31
|
+
`),r=Vr(n,"plugins");if(r===-1)return e;let i=zt(n,r,0),s=Jr(n,"memory",r+1,i,2);if(s===-1)return e;let o=zt(n,s,2),a=[...n],c=Jr(a,"storePath",s+1,o,4);return c!==-1?a[c]=` storePath: ${t}`:a.splice(o,0,` storePath: ${t}`),`${a.join(`
|
|
32
32
|
`)}
|
|
33
|
-
`}function Jr(e,t,n,r,i){for(let s=n;s<r;s++){let o=e[s];if(
|
|
34
|
-
`)}function Yr(e){try{return JSON.parse(e)}catch{return null}}var Xr=g(()=>{"use strict";C();oe()});var
|
|
35
|
-
`)})});function c(){o&&clearTimeout(o),o=setTimeout(()=>a.close(),s),o.unref()}await new Promise((l,u)=>{a.once("error",u),a.listen(e.socketPath,()=>{a.off("error",u),l()})}),c(),await new Promise(l=>a.once("close",l)),i=0,o&&clearTimeout(o),await n.close(),await
|
|
33
|
+
`}function Jr(e,t,n,r,i){for(let s=n;s<r;s++){let o=e[s];if(Yt(o)&&Qt(o)===i&&Hr(o)===t)return s}return-1}async function Mr(e){try{return await Ta(e,Oa.F_OK),!0}catch{return!1}}var Wt,Ia,Wr=g(()=>{"use strict";C();Wt=Be,Ia=".red/memory/graph.rdb"});var Zr={};P(Zr,{runRspMcpServer:()=>Da});import{createInterface as La}from"node:readline";async function Da(){let e=M(process.cwd(),process.env),t=La({input:process.stdin,crlfDelay:1/0});for await(let n of t){if(!n.trim())continue;let r;try{r=JSON.parse(n);let i=await ja(r,e);Qr({jsonrpc:"2.0",id:r.id??null,result:i})}catch(i){Qr({jsonrpc:"2.0",id:typeof Yr(n)?.id>"u"?null:Yr(n)?.id,error:{code:-32e3,message:i instanceof Error?i.message:String(i)}})}}}async function ja(e,t){if(e.method==="initialize")return{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"rsp",version:"0.1.0"}};if(e.method==="tools/list")return t.enabled?{tools:[{name:"rsp_status",description:"Explain whether rsp is enabled in this directory.",inputSchema:{type:"object",properties:{}}},{name:"rsp_stats",description:"Read resident rsp elision store stats.",inputSchema:{type:"object",properties:{}}},{name:"rsp_show",description:"Read an rsp elision handle through the resident server.",inputSchema:{type:"object",properties:{handle:{type:"string"}},required:["handle"]}}]}:{tools:[{name:"rsp_status",description:"Explain whether rsp is enabled in this directory.",inputSchema:{type:"object",properties:{}}}]};if(e.method==="tools/call"){let n=e.params;if(n?.name==="rsp_status")return{content:[{type:"text",text:zr(t)}]};if(!t.enabled)return{content:[{type:"text",text:zr(t)}],isError:!0};let r=Ba(t);if(n?.name==="rsp_stats")return{content:[{type:"text",text:JSON.stringify(await r.stats())}]};if(n?.name==="rsp_show"){let i=String(n.arguments?.handle??""),s=await r.get(i);return s?"status"in s?{content:[{type:"text",text:JSON.stringify(s)}],isError:!0}:{content:[{type:"text",text:s.original.toString("utf8")}]}:{content:[{type:"text",text:"not found"}],isError:!0}}}return{}}function Ba(e){return new Re(se(process.cwd()),{storeUri:e.storeUri,ttlDays:e.ttlDays,byteBudget:e.byteBudget})}function zr(e){return e.enabled?"rsp is enabled in this directory":"rsp is not enabled in this directory; run /red-setup"}function Qr(e){process.stdout.write(`${JSON.stringify(e)}
|
|
34
|
+
`)}function Yr(e){try{return JSON.parse(e)}catch{return null}}var Xr=g(()=>{"use strict";C();oe()});var ei={};P(ei,{runResidentServer:()=>Ma});import{randomUUID as Ua}from"node:crypto";import{mkdir as Ca,rm as qa}from"node:fs/promises";import{createServer as Ga}from"node:net";import{dirname as Ja}from"node:path";async function Ma(e){await Ca(Ja(e.socketPath),{recursive:!0});let t=process.hrtime.bigint(),n=await ve.open({uri:e.storeUri,ttlDays:e.ttlDays,byteBudget:e.byteBudget,allowResidentOpen:!0}),r=Number(process.hrtime.bigint()-t)/1e6,i=1,s=e.idleMs??3e4,o,a=Ga(l=>{c(),Fa(l,async u=>{c();let d=await Va(n,u),y={id:u.id,ok:!0,value:d,storeOpenCount:i,storeElapsedMs:r};l.write(`${JSON.stringify(y)}
|
|
35
|
+
`)})});function c(){o&&clearTimeout(o),o=setTimeout(()=>a.close(),s),o.unref()}await new Promise((l,u)=>{a.once("error",u),a.listen(e.socketPath,()=>{a.off("error",u),l()})}),c(),await new Promise(l=>a.once("close",l)),i=0,o&&clearTimeout(o),await n.close(),await qa(e.socketPath,{force:!0})}function Fa(e,t){let n="";e.setEncoding("utf8"),e.on("data",r=>{n+=r;let i=n.indexOf(`
|
|
36
36
|
`);if(i<0)return;let s=n.slice(0,i);e.pause(),(async()=>{let o;try{o=JSON.parse(s),await t(o)}catch(a){let l={id:o?.id??Ua(),ok:!1,error:a instanceof Error?a.message:String(a)};e.write(`${JSON.stringify(l)}
|
|
37
|
-
`)}finally{e.end()}})()})}async function
|
|
38
|
-
`).filter(i=>i&&
|
|
37
|
+
`)}finally{e.end()}})()})}async function Va(e,t){if(t.op==="ping")return{pong:!0};if(t.op==="stats")return await e.stats();if(t.op==="mint")return{handle:await e.mint(Buffer.from(t.original,"base64"),t.meta)};if(t.op==="get")return Ha(await e.get(t.handle));if(t.op==="memory")return await e.memory(t.action,t.payload);throw new Error(`unsupported resident op: ${t.op??"unknown"}`)}function Ha(e){return e?"status"in e?e:{...e,original:e.original.toString("base64"),original_encoding:"base64"}:null}var ti=g(()=>{"use strict";tt()});function z(e){let t=[],n;for(let r=0;r<e.length;r++){let i=e[r];if(i==="--query"){n=e[++r];continue}if(i.startsWith("--query=")){n=i.slice(8);continue}t.push(i)}return{argv:t,query:n?.trim()||void 0}}function ni(e,t){if(!t)return!0;let n=Zt(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(r=>n.includes(r))}function $(e,t){return t?e.filter(n=>ni(n,t)):[...e]}function me(e,t){if(!t)return e;let r=e.split(`
|
|
38
|
+
`).filter(i=>i&&ni(i,t));return r.length>0?`${r.join(`
|
|
39
39
|
`)}
|
|
40
|
-
`:""}function Q(e,t){let n=t.filter(Boolean);return n.length===0?e:{...e,help:n}}function
|
|
41
|
-
`)return{stdout:Buffer.from(s),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let o=
|
|
42
|
-
`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:s,oneLine:!0};let a=O(s);if(
|
|
40
|
+
`:""}function Q(e,t){let n=t.filter(Boolean);return n.length===0?e:{...e,help:n}}function Zt(e){return Array.isArray(e)?e.map(Zt).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(Zt).join(" "):String(e??"")}var rt=g(()=>{"use strict"});var ai={};P(ai,{DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>j,GIT_LOG_MACHINE_FIELDS:()=>ri,renderGitContract:()=>ii,runGitWrapper:()=>Wa});import{spawn as Ka}from"node:child_process";async function Wa(e,t){let n=si(e),r=oi(n.argv),i=await Za(r,n.argv.slice(1));return ii(e,i,t)}async function ii(e,t,n){let r=si(e);if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(me(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let i=oi(r.argv),s=Xa(i,r.argv,t.stdout,r.query);if(s===`git empty
|
|
41
|
+
`)return{stdout:Buffer.from(s),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let o=sc(i,s);if(o)return{stdout:Buffer.from(`${o}
|
|
42
|
+
`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:s,oneLine:!0};let a=O(s);if(za(i,a,r.full,n))return{stdout:Buffer.from(a),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:s};let c=uc(s);if(!c)return{stdout:Buffer.from(a),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:s};let l=Buffer.byteLength(a),u=await n.store?.mint(Buffer.from(a),{command:e.join(" "),loss:{level:"terse",bytes_elided:l}});if(!u)throw new Error("terse git output requires an elision store");let d=`\u2026 elided ${c.rowsElided} rows (+${l}) \u2014 rsp show ${u}
|
|
43
43
|
`;return{stdout:Buffer.from(`${O(c.payload)}
|
|
44
|
-
${d}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:c.payload,mintedHandle:u,bytesElided:l,rowsElided:c.rowsElided}}function
|
|
45
|
-
`;let s=$(i,n),o=
|
|
46
|
-
`)[0]??"",r=/^\[([^ ]+) ([0-9a-f]+)\] (.+)$/.exec(n),i=/(\d+) files? changed/.exec(t),s=/(\d+) insertions?\(\+\)/.exec(t),o=/(\d+) deletions?\(-\)/.exec(t),a=r?.[1]??"",c=r?.[2]??"",l=Number(i?.[1]??0),u=Number(s?.[1]??0),d=Number(o?.[1]??0);return{command:e.join(" "),branch:a,commit:c,subject:r?.[3]??"",files_changed:l,insertions:u,deletions:d,summary:`commit ${c} on ${a}: ${l} files, +${u} -${d}`}}function
|
|
47
|
-
`).filter(Boolean),r=n.find(c=>c.startsWith("To "))?.slice(3)??"",i=n.filter(c=>c.includes(" ")).map(c=>{let[l,u,d=""]=c.split(" "),[y,E]=(u??"").split(":");return{flag:l??"",from:y??"",to:E??"",summary:d}}),s=i.find(c=>c.flag!=="=")??i[0],o=s?.to.startsWith("refs/heads/")?s.to.slice(11):s?.to??"",a=s?.summary.includes("..")?1:0;return{command:e.join(" "),remote:r,refs:i,summary:`pushed ${o} -> ${r} +${a} commits`}}function Ne(e,t,n){return t?Q(e,n):e}function
|
|
44
|
+
${d}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:c.payload,mintedHandle:u,bytesElided:l,rowsElided:c.rowsElided}}function si(e){let t=z(e),n=[],r=!1;for(let i of t.argv){if(i==="--full"){r=!0;continue}n.push(i)}return{argv:n,query:t.query,full:r}}function za(e,t,n,r){if(r.level==="terse")return!1;if(n||r.level==="full"||!Qa(e)||r.level!=="lossless")return!0;let i=lc(r.heavyGitByteThreshold,j);return Buffer.byteLength(t)<=i}function Qa(e){return e==="diff"||e==="log"}function oi(e){if(e[0]!=="git")throw new Error("expected rsp git <subcommand>");let t=e[1];if(t==="status"||t==="log"||t==="diff"||t==="commit"||t==="push")return t;throw new Error(`unsupported git subcommand: ${t??""}`)}function Ya(e,t){let n=t.slice(1);switch(e){case"status":return["status","--porcelain=v2","-z","-b",...n];case"log":return["log",`--format=%x1e${ri.join("%x1f")}`,"-z",...n];case"diff":return["diff","--numstat","-z",...n];case"commit":return["commit",...n];case"push":return["push","--porcelain",...n]}}async function Za(e,t){let n=Ka("git",Ya(e,t),{stdio:["ignore","pipe","pipe"]}),r=[],i=[];return n.stdout.on("data",s=>r.push(s)),n.stderr.on("data",s=>i.push(s)),await new Promise((s,o)=>{n.on("error",o),n.on("close",(a,c)=>{s({stdout:Buffer.concat(r).toString("utf8"),stderr:Buffer.concat(i).toString("utf8"),status:a,signal:c})})})}function Xa(e,t,n,r){switch(e){case"status":return ec(t,n,r);case"log":return tc(t,n,r);case"diff":return nc(t,n,r);case"commit":return Ne(rc(t,n),r,["rsp git status --query <path-or-state>"]);case"push":return Ne(ic(t,n),r,["rsp gh pr list --query <branch>"])}}function ec(e,t,n){let r="",i=[];for(let a of t.split("\0")){if(!a)continue;if(a.startsWith("# branch.head ")){r=a.slice(14);continue}if(!a.startsWith("1 "))continue;let c=a.split(" "),l=c[1]??"..",u=c.slice(8).join(" ");i.push({path:u,index:l[0]??".",worktree:l[1]??".",state:ac(l)})}if(i.length===0)return`git empty
|
|
45
|
+
`;let s=$(i,n),o=cc(s,"state");return Ne({command:e.join(" "),branch:r,rows:s,summary:`${n?`${s.length}/${i.length}`:s.length} changes: ${o.added??0} added, ${o.modified??0} modified, ${o.deleted??0} deleted`},n,["rsp git diff --query <path>","rsp git log --query <subject>"])}function tc(e,t,n){let r=t.split("\0").filter(Boolean).map(s=>{let o=s.replace(/^\x1e/,"").split("");return{short:o[0]??"",author:o[1]??"",date:o[2]??"",subject:o[3]??""}}),i=$(r,n);return Ne({command:e.join(" "),commits:i,summary:`${n?`${i.length}/${r.length}`:i.length} commits`},n,["rsp git diff --query <path>","rsp gh pr list --query <branch>"])}function nc(e,t,n){let i=t.split("\0").filter(Boolean).map(a=>{let[c,l,u]=a.split(" ");return{path:u??"",added:c==="-"?null:Number(c??0),deleted:l==="-"?null:Number(l??0)}}),s=$(i,n),o=s.reduce((a,c)=>(a.added+=typeof c.added=="number"?c.added:0,a.deleted+=typeof c.deleted=="number"?c.deleted:0,a),{added:0,deleted:0});return Ne({command:e.join(" "),files:s,summary:`${n?`${s.length}/${i.length}`:s.length} files, +${o.added} -${o.deleted}`},n,["rsp git status --query <path>","rsp git log --query <subject>"])}function rc(e,t){let n=t.split(`
|
|
46
|
+
`)[0]??"",r=/^\[([^ ]+) ([0-9a-f]+)\] (.+)$/.exec(n),i=/(\d+) files? changed/.exec(t),s=/(\d+) insertions?\(\+\)/.exec(t),o=/(\d+) deletions?\(-\)/.exec(t),a=r?.[1]??"",c=r?.[2]??"",l=Number(i?.[1]??0),u=Number(s?.[1]??0),d=Number(o?.[1]??0);return{command:e.join(" "),branch:a,commit:c,subject:r?.[3]??"",files_changed:l,insertions:u,deletions:d,summary:`commit ${c} on ${a}: ${l} files, +${u} -${d}`}}function ic(e,t){let n=t.split(`
|
|
47
|
+
`).filter(Boolean),r=n.find(c=>c.startsWith("To "))?.slice(3)??"",i=n.filter(c=>c.includes(" ")).map(c=>{let[l,u,d=""]=c.split(" "),[y,E]=(u??"").split(":");return{flag:l??"",from:y??"",to:E??"",summary:d}}),s=i.find(c=>c.flag!=="=")??i[0],o=s?.to.startsWith("refs/heads/")?s.to.slice(11):s?.to??"",a=s?.summary.includes("..")?1:0;return{command:e.join(" "),remote:r,refs:i,summary:`pushed ${o} -> ${r} +${a} commits`}}function Ne(e,t,n){return t?Q(e,n):e}function sc(e,t){if(e==="commit"&&typeof t.commit=="string"&&t.commit.length>0)return String(t.summary??"");if(e==="push"){let n=t.refs;return(Array.isArray(n)?n:[]).filter(s=>oc(s)&&s.flag!=="=").length===1?String(t.summary??""):null}return null}function oc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ac(e){return e.includes("A")?"added":e.includes("D")?"deleted":e.includes("R")?"renamed":e.includes("M")?"modified":"changed"}function cc(e,t){let n={};for(let r of e){let i=String(r[t]??"");n[i]=(n[i]??0)+1}return n}function lc(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function uc(e){for(let t of["rows","commits","files","refs"]){let n=e[t];if(Array.isArray(n)&&n.length>1)return{payload:{...e,[t]:n.slice(0,1)},rowsElided:n.length-1}}return null}var ri,ci=g(()=>{"use strict";Oe();C();rt();C();ri=["%h","%an","%as","%s"]});var Ri={};P(Ri,{renderGhContract:()=>di,runGhWrapper:()=>mc});import{spawn as ui}from"node:child_process";async function mc(e,t){let n=fi(e),r=await hc(n);return di(e,r,t)}async function di(e,t,n){let r=z(e);if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(me(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let i=fi(e),s=it(t.stdout),o=wc(i,e,s);if(typeof o=="string")return{stdout:Buffer.from(o),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let a=Oc(o);if(a){if(!n.store)throw new Error("truncated gh output requires an elision store");let R=await n.store.mint(Buffer.from(a.original),{command:e.join(" "),loss:{level:i.full?"brief":n.level,bytes_elided:a.bytes}});a.target.truncated.handle=R}let c=a?.target.truncated.handle||void 0,l=O(o);if(n.level!=="terse")return{stdout:Buffer.from(l),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:o,mintedHandle:c,bytesElided:a?.bytes};let u=Tc(o);if(!u)return{stdout:Buffer.from(l),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:o,mintedHandle:c,bytesElided:a?.bytes};let d=Buffer.byteLength(l),y=await n.store?.mint(Buffer.from(l),{command:e.join(" "),loss:{level:"terse",bytes_elided:d}});if(!y)throw new Error("terse gh output requires an elision store");let E=`\u2026 elided ${u.rowsElided} rows (+${d}) \u2014 rsp show ${y}
|
|
48
48
|
`;return{stdout:Buffer.from(`${O(u.payload)}
|
|
49
|
-
${E}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:u.payload,mintedHandle:y,bytesElided:d,rowsElided:u.rowsElided}}function
|
|
49
|
+
${E}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:u.payload,mintedHandle:y,bytesElided:d,rowsElided:u.rowsElided}}function fi(e){let t=z(e);if(t.argv[0]!=="gh")throw new Error("expected rsp gh <surface> <subcommand>");let n=t.argv[1],r=t.argv[2];if(!(n==="pr"||n==="issue"||n==="run"))throw new Error(`unsupported gh surface: ${n??""}`);let i=n==="pr"&&r&&r!=="list"&&r!=="view";if(!(r==="list"||r==="view"||i))throw new Error(`unsupported gh subcommand: ${r??""}`);let s=[],o=!1,a=!1;for(let l of t.argv.slice(3))l==="--full"?o=!0:l==="--wide"?a=!0:s.push(l);return{kind:n,action:i?"combined":r==="list"?"list":"view",target:i?r:void 0,full:o,wide:a,passthrough:s,query:t.query}}function yc(e){if(e.action==="combined")throw new Error("combined gh command uses multiple machine calls");let t=`${e.kind}:${e.action}`,n=e.wide?fc[t]:dc[t];return[e.kind,e.action,...e.passthrough,"--json",n.join(",")]}async function hc(e){if(e.action==="combined")return await gc(e);let t=ui("gh",yc(e),{stdio:["ignore","pipe","pipe"]}),n=[],r=[];return t.stdout.on("data",i=>n.push(i)),t.stderr.on("data",i=>r.push(i)),await new Promise((i,s)=>{t.on("error",s),t.on("close",(o,a)=>{i({stdout:Buffer.concat(n).toString("utf8"),stderr:Buffer.concat(r).toString("utf8"),status:o,signal:a})})})}async function gc(e){let t=e.target??"",n=["number","title","state","body","author","labels","url","baseRefName","headRefName"],r=["comments"],[i,s,o]=await Promise.all([Xt(["pr","view",t,"--json",n.join(",")]),Xt(["pr","checks",t,"--json","name,state,bucket,conclusion,link,startedAt,completedAt,workflow"]),Xt(["pr","view",t,"--comments","--json",r.join(",")])]),a=[i,s,o].find(c=>(c.status??0)!==0||c.signal);return a||{stdout:JSON.stringify({view:it(i.stdout),checks:it(s.stdout),comments:it(o.stdout)}),stderr:[i.stderr,s.stderr,o.stderr].filter(Boolean).join(""),status:0,signal:null}}async function Xt(e){let t=ui("gh",e,{stdio:["ignore","pipe","pipe"]}),n=[],r=[];return t.stdout.on("data",i=>n.push(i)),t.stderr.on("data",i=>r.push(i)),await new Promise((i,s)=>{t.on("error",s),t.on("close",(o,a)=>{i({stdout:Buffer.concat(n).toString("utf8"),stderr:Buffer.concat(r).toString("utf8"),status:o,signal:a})})})}function wc(e,t,n){if(e.action==="list"&&Array.isArray(n)&&n.length===0)return kc(e.kind);let r={command:t.join(" ")};switch(`${e.kind}:${e.action}`){case"pr:list":{let i=he(n).map(o=>pi(o,e.wide)),s=$(i,e.query);return ye({...r,prs:s,summary:`${en(s.length,i.length,e.query)} ${li(s,"open")} PRs`},e,["rsp gh pr <number>","rsp gh pr list --query <title-or-label>"])}case"pr:view":return ye({...r,pr:mi(N(n),e),summary:`PR #${ie(N(n),"number")}`},e,["rsp gh pr <number>","rsp gh pr view <number> --full"]);case"pr:combined":return bc(e,t,N(n));case"issue:list":{let i=he(n).map(o=>yi(o,e.wide)),s=$(i,e.query);return ye({...r,issues:s,summary:`${en(s.length,i.length,e.query)} ${li(s,"open")} issues`},e,["rsp gh issue view <number>","rsp gh issue list --query <label-or-title>"])}case"issue:view":return ye({...r,issue:Sc(N(n),e),summary:`issue #${ie(N(n),"number")}`},e,["rsp gh issue view <number> --full"]);case"run:list":{let i=he(n).map(o=>hi(o,e.wide)),s=$(i,e.query);return ye({...r,runs:s,summary:`${en(s.length,i.length,e.query)} runs`},e,["rsp gh run view <id>","rsp gh run list --query <workflow-or-status>"])}case"run:view":return ye({...r,run:xc(N(n),e),summary:`run ${ie(N(n),"databaseId")}`},e,["rsp gh run view <id> --full"])}throw new Error(`unsupported gh command: ${e.kind} ${e.action}`)}function bc(e,t,n){let r=mi(N(n.view),{...e,action:"view",wide:!0}),i=$(he(n.checks).map(Rc),e.query),s=N(n.comments).comments,o=$(he(s).map(Ec).slice(-3),e.query);return Q({command:t.join(" "),pr:r,checks:i,comments:o,summary:`PR #${ie(N(n.view),"number")}: ${i.length} checks, ${o.length} comments`},["rsp gh pr view <number> --full","rsp gh pr <number> --query <check-or-comment>","rsp gh run view <id>"])}function Rc(e){return{name:w(e,"name"),state:Le(e),bucket:w(e,"bucket"),conclusion:w(e,"conclusion"),workflow:w(e,"workflow"),link:w(e,"link")}}function Ec(e){return{author:bi(e.author),body:st(e,"body",tn,!1),created:w(e,"createdAt")}}function kc(e){return e==="pr"?`0 open PRs \u2014 try: rsp gh issue list
|
|
50
50
|
`:e==="issue"?`0 open issues \u2014 try: rsp gh issue list --state all
|
|
51
51
|
`:`0 runs \u2014 try: rsp gh run list --limit 20
|
|
52
|
-
`}function
|
|
53
|
-
${p}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:l,mintedHandle:m,bytesElided:k,rowsElided:d}}function
|
|
52
|
+
`}function pi(e,t){let n={number:ie(e,"number"),title:w(e,"title"),state:Le(e),draft:!!e.isDraft};return t&&Object.assign(n,gi(e)),n}function mi(e,t){let n=pi(e,t.wide);return n.body=st(e,"body",tn,t.full),t.wide&&(n.base=w(e,"baseRefName"),n.head=w(e,"headRefName")),n}function yi(e,t){let n={number:ie(e,"number"),title:w(e,"title"),state:Le(e),labels:wi(e.labels)};return t&&Object.assign(n,gi(e)),n}function Sc(e,t){let n=yi(e,t.wide);return n.body=st(e,"body",tn,t.full),n}function hi(e,t){let n={id:ie(e,"databaseId"),name:w(e,"name"),status:Le(e),conclusion:w(e,"conclusion")};return t&&(n.event=w(e,"event"),n.branch=w(e,"headBranch"),n.workflow=w(e,"workflowName"),n.created=w(e,"createdAt")),n}function xc(e,t){let n=hi(e,t.wide),r=he(e.jobs).map(i=>({name:w(i,"name"),status:Le(i),conclusion:w(i,"conclusion"),log:st(i,"log",pc,t.full)}));return n.jobs=r,n}function st(e,t,n,r){let i=w(e,t);if(r||Buffer.byteLength(i)<=n)return i;let s=i.slice(0,n),o={preview:s,truncated:{bytes:Buffer.byteLength(i),shown_bytes:Buffer.byteLength(s),hint:"--full",handle:""}};return Object.defineProperty(o,"__rsp_original",{value:i,enumerable:!1}),o}function Oc(e){let t=[e];for(;t.length>0;){let n=t.pop();if(Array.isArray(n))t.push(...n);else if(ge(n)){if(ge(n.truncated)&&n.truncated.handle===""&&typeof n.preview=="string"){let r=typeof n.__rsp_original=="string"?n.__rsp_original:n.preview;return{target:n,original:r,bytes:Number(n.truncated.bytes??0)}}t.push(...Object.values(n))}}return null}function Tc(e){for(let t of["prs","issues","runs","jobs"]){let n=e[t];if(Array.isArray(n)&&n.length>1)return{payload:{...e,[t]:n.slice(0,1)},rowsElided:n.length-1}}return null}function li(e,t){return e.every(n=>n.state===t)?t:"returned"}function en(e,t,n){return n?`${e}/${t}`:String(e)}function ye(e,t,n){return t.query?Q(e,n):e}function Le(e){return(w(e,"state")||w(e,"status")).toLowerCase()}function gi(e){return{author:bi(e.author),labels:wi(e.labels),url:w(e,"url"),updated:w(e,"updatedAt")}}function wi(e){return Array.isArray(e)?e.map(t=>ge(t)?w(t,"name"):String(t)).filter(Boolean):[]}function bi(e){return ge(e)?w(e,"login"):""}function it(e){return e.trim()?JSON.parse(e):null}function he(e){return Array.isArray(e)?e.filter(ge):[]}function N(e){return ge(e)?e:{}}function w(e,t){let n=e[t];return typeof n=="string"?n:""}function ie(e,t){let n=e[t];return typeof n=="number"?n:0}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var dc,fc,tn,pc,Ei=g(()=>{"use strict";Oe();rt();dc={"pr:list":["number","title","state","isDraft"],"pr:view":["number","title","state","body"],"issue:list":["number","title","state","labels"],"issue:view":["number","title","state","body"],"run:list":["databaseId","name","status","conclusion"],"run:view":["databaseId","name","status","conclusion","jobs"]},fc={"pr:list":["number","title","state","isDraft","author","labels","url","updatedAt"],"pr:view":["number","title","state","body","author","labels","url","baseRefName","headRefName"],"issue:list":["number","title","state","labels","author","url","updatedAt"],"issue:view":["number","title","state","body","author","labels","url","updatedAt"],"run:list":["databaseId","name","status","conclusion","event","headBranch","workflowName","createdAt"],"run:view":["databaseId","name","status","conclusion","event","headBranch","workflowName","createdAt","jobs","url"]},tn=160,pc=160});var Oi={};P(Oi,{renderTestContract:()=>ki,runTestWrapper:()=>Ic});import{spawn as Ac}from"node:child_process";async function Ic(e,t){let n=z(e),r=await jc(n.argv);return await ki(e,r,t)}async function ki(e,t,n){let r=z(e),s=Si(r.argv)==="vitest"?Bc(t.stdout):Uc(t.stdout),o=t.status;if(!s||(o??0)!==0&&s.failed===0)return{stdout:Buffer.from(me(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let a=`${s.failed}/${s.total} failed \xB7 ${s.suites} suites \xB7 ${Gc(s.durationSeconds)}`,c=$(s.failures,r.query);if(n.level==="terse")return await vc(r.argv,t,{...s,failures:c},o,a,n,r.query);let l=[],u,d=0;for(let R of c){let k=await Cc(R.excerpt,r.argv.join(" "),n.store);l.push({suite:R.suite,name:R.name,excerpt:k.text}),u??=k.handle,d+=k.bytesElided}let y={exit_code:o,summary:r.query?`${a} \xB7 ${c.length}/${s.failures.length} failures matched`:a};l.length>0&&(y.failures=l);let E=r.query?Q(y,["rsp show <handle>","rsp vitest --query <suite-or-test>"]):y;return{stdout:Buffer.from(O(E)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:E,mintedHandle:u,bytesElided:d>0?d:void 0,rowsElided:l.length>0?Math.max(0,s.total-l.length):void 0}}async function vc(e,t,n,r,i,s,o){let a=Nc(n.failures),c={exit_code:r,summary:o?`${i} \xB7 ${n.failures.length} failures matched`:i};a.length>0&&(c.failures=a);let l=o?Q(c,["rsp show <handle>","rsp vitest --query <suite-or-test>"]):c,u=O(l),d=Math.max(0,n.failures.length-a.length),y=a.some((b,D)=>b.excerpt!==n.failures[D].excerpt);if(d===0&&!y)return{stdout:Buffer.from(u),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:l};let E={exit_code:r,summary:i};n.failures.length>0&&(E.failures=n.failures.map(b=>({suite:b.suite,name:b.name,excerpt:b.excerpt})));let R=O(E),k=Buffer.byteLength(R),m=await s.store?.mint(Buffer.from(R),{command:e.join(" "),loss:{level:"terse",bytes_elided:k}});if(!m)throw new Error("terse test output requires an elision store");let p=`\u2026 elided ${d>0?`${d} failures`:"full detail"} (+${k}) \u2014 rsp show ${m}`;return{stdout:Buffer.from(`${u}
|
|
53
|
+
${p}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:l,mintedHandle:m,bytesElided:k,rowsElided:d}}function Nc(e){let t=[],n=Pc;for(let r of e.slice(0,_c)){let i=Lc(r.excerpt,Math.min($c,n));n=Math.max(0,n-Buffer.byteLength(i)),t.push({suite:r.suite,name:r.name,excerpt:i})}return t}function Lc(e,t){if(t<=0)return"";let n=e.split(`
|
|
54
54
|
`),r=n.length<=2?e:`${n[0]}
|
|
55
55
|
\u2026
|
|
56
|
-
${n[n.length-1]}`,i=Buffer.from(r);return i.length<=t?r:i.subarray(0,t).toString("utf8").replace(/�$/,"")}function
|
|
57
|
-
`).filter(Boolean).map(c=>
|
|
58
|
-
`)}),s||=1,r||=1,i||=1),i||=n.length,s||=1,r||=Math.max(i,n.length),{failed:i,total:r,suites:s,durationSeconds:o,failures:n}}async function
|
|
59
|
-
\u2026 elided ${o} bytes (+${r.length}) \u2014 rsp show ${i}`,handle:i,bytesElided:r.length}}function
|
|
60
|
-
`):""}function
|
|
61
|
-
`),0);if(t.command==="git"
|
|
56
|
+
${n[n.length-1]}`,i=Buffer.from(r);return i.length<=t?r:i.subarray(0,t).toString("utf8").replace(/�$/,"")}function Si(e){if(e[0]==="vitest")return"vitest";if(e[0]==="cargo"&&e[1]==="test")return"cargo";throw new Error(`unsupported test command: ${e.join(" ")}`)}function Dc(e){if(Si(e)==="vitest"){let i=e.slice(1);return{executable:"vitest",args:i.some(o=>o==="--reporter=json"||o==="--reporter"||o.startsWith("--reporter="))?i:["run","--reporter=json",...i]}}let n=e.slice(1);return{executable:"cargo",args:n.some(i=>i==="--message-format=json"||i.startsWith("--message-format="))?n:["test","--message-format=json",...n.slice(1)]}}async function jc(e){let t=Dc(e),n=Ac(t.executable,t.args,{stdio:["ignore","pipe","pipe"]}),r=[],i=[];return n.stdout.on("data",s=>r.push(s)),n.stderr.on("data",s=>i.push(s)),await new Promise((s,o)=>{n.on("error",o),n.on("close",(a,c)=>{s({stdout:Buffer.concat(r).toString("utf8"),stderr:Buffer.concat(i).toString("utf8"),status:a,signal:c})})})}function Bc(e){let t=xi(e);if(!Y(t))return null;let n=Array.isArray(t.testResults)?t.testResults:[],r=[],i=Z(t.numTotalTests),s=Z(t.numFailedTests),o=Jc(Z(t.startTime),Z(t.endTime));for(let a of n){if(!Y(a))continue;let c=L(a.name)||L(a.file)||"",l=Array.isArray(a.assertionResults)?a.assertionResults:[];for(let u of l)Y(u)&&u.status==="failed"&&r.push({suite:c,name:L(u.fullName)||L(u.title)||L(u.name),excerpt:qc(u.failureMessages)||L(u.failureMessage)})}return i||=n.reduce((a,c)=>!Y(c)||!Array.isArray(c.assertionResults)?a:a+c.assertionResults.length,0),s||=r.length,o||=n.reduce((a,c)=>Y(c)?a+Z(c.perfStats&&Y(c.perfStats)?c.perfStats.runtime:c.duration)/1e3:a,0),{failed:s,total:i,suites:n.length||1,durationSeconds:o,failures:r}}function Uc(e){let t=e.split(`
|
|
57
|
+
`).filter(Boolean).map(c=>xi(c)).filter(Y);if(t.length===0)return null;let n=[],r=0,i=0,s=0,o=0,a=[];for(let c of t){if(c.type==="suite"){c.event==="started"&&(s+=1,r+=Z(c.test_count)),(c.event==="failed"||c.event==="ok")&&(i+=Z(c.failed),o+=Z(c.exec_time));continue}if(c.type==="test"&&c.event==="failed"){n.push({suite:L(c.name).split("::").slice(0,-1).join("::"),name:L(c.name),excerpt:L(c.stdout)});continue}if(c.reason==="compiler-message"&&Y(c.message)){let l=L(c.message.rendered);l&&a.push(l)}}return n.length===0&&a.length>0&&(n.push({suite:"cargo check",name:"compile-error",excerpt:a.join(`
|
|
58
|
+
`)}),s||=1,r||=1,i||=1),i||=n.length,s||=1,r||=Math.max(i,n.length),{failed:i,total:r,suites:s,durationSeconds:o,failures:n}}async function Cc(e,t,n){let r=Buffer.from(e);if(r.length<=nn)return{text:e,bytesElided:0};if(!n)throw new Error("over-limit test failure excerpt requires an elision store");let i=await n.mint(r,{command:t,loss:{level:"brief",bytes_elided:r.length}}),s=r.subarray(0,nn).toString("utf8").replace(/\uFFFD$/,""),o=r.length-Buffer.byteLength(s);return{text:`${s}
|
|
59
|
+
\u2026 elided ${o} bytes (+${r.length}) \u2014 rsp show ${i}`,handle:i,bytesElided:r.length}}function xi(e){try{return JSON.parse(e)}catch{return null}}function qc(e){return Array.isArray(e)?e.map(t=>String(t)).filter(Boolean).join(`
|
|
60
|
+
`):""}function Gc(e){return`${Number(e.toFixed(1))}s`}function Jc(e,t){return e>0&&t>e?(t-e)/1e3:0}function Z(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function L(e){return typeof e=="string"?e:""}function Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var nn,$c,Pc,_c,Ti=g(()=>{"use strict";Oe();rt();nn=320,$c=160,Pc=nn,_c=3});import{existsSync as sn,readdirSync as Mc}from"node:fs";async function Fc(e=process.argv.slice(2)){let t=zc(e);if(t.command==="hook"&&t.positional[1]==="claude-pre-exec"){let{runClaudePreExecHook:m}=await Promise.resolve().then(()=>($n(),An));return await m()}if(t.command==="hook"&&t.positional[1]==="claude-post-exec"){let{runClaudePostExecHook:m}=await Promise.resolve().then(()=>(cr(),ar));return await m()}if(t.command==="setup"){let{provisionRspRepoStore:m}=await Promise.resolve().then(()=>(Wr(),Kr)),h=await m(process.cwd());return process.stdout.write(Yc(h)),0}if(t.command==="mcp"){let{runRspMcpServer:m}=await Promise.resolve().then(()=>(Xr(),Zr));return await m(),0}let{resolveRspConfig:n}=await Promise.resolve().then(()=>(C(),dn)),r=n(process.cwd(),process.env,t.storeUri),i=Kc(t.command);if(!r.enabled)return i?await we(rn(),t.positional):(process.stdout.write(`${rn()}
|
|
61
|
+
`),0);if(t.command==="git"&&Ai(t.positional)&&await Vc(process.cwd()))return await $i();let{resolveResidentPaths:s,ResidentRspElisionStore:o,ensureResidentServer:a}=await Promise.resolve().then(()=>(oe(),qe));if(t.command==="server"){let{runResidentServer:m}=await Promise.resolve().then(()=>(ti(),ei)),h=be(t.positional,"--socket")??s(process.cwd()).socketPath,p=n(process.cwd(),process.env,t.storeUri??be(t.positional,"--store-uri"));return p.enabled?(await m({socketPath:h,storeUri:p.storeUri,ttlDays:De(t.positional,"--ttl-days")??p.ttlDays,byteBudget:De(t.positional,"--byte-budget")??p.byteBudget,idleMs:De(t.positional,"--idle-ms")}),0):(process.stdout.write(`${rn()}
|
|
62
62
|
`),0)}if(t.command==="warm-resident"){let m=s(process.cwd()),h=be(t.positional,"--socket")??m.socketPath,p=be(t.positional,"--wake-lock")??m.wakeLockPath,b=n(process.cwd(),process.env,t.storeUri??be(t.positional,"--store-uri"));if(!b.enabled)return 0;let{warmResidentServer:D}=await Promise.resolve().then(()=>(oe(),qe));return await D({...m,socketPath:h,wakeLockPath:p},{storeUri:b.storeUri,ttlDays:De(t.positional,"--ttl-days")??b.ttlDays,byteBudget:De(t.positional,"--byte-budget")??b.byteBudget}),0}let{existsSync:c}=await import("node:fs"),{fileURLToPath:l}=await import("node:url"),u=s(process.cwd());if(!t.storeUri&&r.storeUri.startsWith("file://")&&!c(l(r.storeUri)))return i?await we("store not provisioned",t.positional):(process.stdout.write(`error: rsp repo store is not provisioned - run /red-setup
|
|
63
|
-
`),1);let d=()=>Promise.resolve(new o(u,{storeUri:r.storeUri,ttlDays:r.ttlDays,byteBudget:r.byteBudget})),y=()=>a(u,{storeUri:r.storeUri,ttlDays:r.ttlDays,byteBudget:r.byteBudget}),E=async()=>{let{RspElisionStore:m}=await Promise.resolve().then(()=>(tt(),
|
|
63
|
+
`),1);let d=()=>Promise.resolve(new o(u,{storeUri:r.storeUri,ttlDays:r.ttlDays,byteBudget:r.byteBudget})),y=()=>a(u,{storeUri:r.storeUri,ttlDays:r.ttlDays,byteBudget:r.byteBudget}),E=async()=>{let{RspElisionStore:m}=await Promise.resolve().then(()=>(tt(),Ht));return await m.open({uri:r.storeUri,ttlDays:r.ttlDays,byteBudget:r.byteBudget})},R=()=>r.storeUri.endsWith("/red-skills.rdb")?d():E(),k;try{if(!t.command){let m=await R();k=()=>m.close();let h=await m.stats();return process.stdout.write(Qc(h)),0}if(t.command==="git"){try{await J(y)}catch(b){return await we("resident unavailable",t.positional,b)}if(Ai(t.positional))return await $i();let{runGitWrapper:m}=await Promise.resolve().then(()=>(ci(),ai)),h=new je(()=>J(d));k=()=>h.close();let p=await J(()=>m(t.positional,{level:t.level,store:h,heavyGitByteThreshold:r.heavyGitByteThreshold}));return process.stdout.write(p.stdout),process.stderr.write(p.stderr),p.signal?(process.kill(process.pid,p.signal),128):p.status??0}if(t.command==="gh"){try{await J(y)}catch(b){return await we("resident unavailable",t.positional,b)}let{runGhWrapper:m}=await Promise.resolve().then(()=>(Ei(),Ri)),h=new je(()=>J(d));k=()=>h.close();let p=await J(()=>m(t.positional,{level:t.level,store:h}));return process.stdout.write(p.stdout),process.stderr.write(p.stderr),p.signal?(process.kill(process.pid,p.signal),128):p.status??0}if(t.command==="vitest"||t.command==="cargo"){try{await J(y)}catch(b){return await we("resident unavailable",t.positional,b)}let{runTestWrapper:m}=await Promise.resolve().then(()=>(Ti(),Oi)),h=new je(()=>J(d));k=()=>h.close();let p=await J(()=>m(t.positional,{level:t.level,store:h}));return process.stdout.write(p.stdout),process.stderr.write(p.stderr),p.signal?(process.kill(process.pid,p.signal),128):p.status??0}if(t.command==="show"&&t.handle){let m=await R();k=()=>m.close();let h=await m.get(t.handle);return h&&"original"in h&&h.original?(process.stdout.write(h.original),0):h?.status==="expired"?(process.stdout.write(`expired ${h.expired_at} \u2014 re-run: ${h.command}
|
|
64
64
|
`),1):(process.stdout.write(`expired unknown \u2014 re-run: ${t.handle}
|
|
65
65
|
`),1)}return process.stdout.write(`error: usage rsp show el:<id>
|
|
66
|
-
`),2}catch(m){if(i)return await we("wrapper failed",t.positional,m);throw m}finally{await k?.()}}function be(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:void 0}function De(e,t){let n=be(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)&&r>0?r:void 0}function
|
|
66
|
+
`),2}catch(m){if(i)return await we("wrapper failed",t.positional,m);throw m}finally{await k?.()}}function be(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:void 0}function De(e,t){let n=be(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)&&r>0?r:void 0}function Ai(e){return e.length===2&&e[0]==="git"&&e[1]==="status"}async function Vc(e){let{resolveResidentPaths:t}=await Promise.resolve().then(()=>(oe(),qe));return sn(t(e).socketPath)}async function $i(){if(Hc(process.cwd()))return process.stdout.write(`git empty
|
|
67
67
|
`),0;let{spawnSync:e}=await import("node:child_process");if(e("git",["diff-index","--quiet","HEAD","--"],{stdio:"ignore"}).status===0)return process.stdout.write(`git empty
|
|
68
68
|
`),0;let n=e("git",["status","--porcelain=v1"],{encoding:"buffer"});return(n.status??0)!==0?(process.stdout.write(n.stdout),process.stderr.write(n.stderr),n.status??1):(process.stdout.write(n.stdout.length===0?`git empty
|
|
69
|
-
`:n.stdout),0)}function
|
|
70
|
-
`),await
|
|
71
|
-
`),i(127)}),r.on("close",(s,o)=>{if(o){process.kill(process.pid,o),i(128);return}i(s??0)})})}function
|
|
72
|
-
`)}function
|
|
73
|
-
`)}import.meta.url===`file://${process.argv[1]}`&&
|
|
74
|
-
`),process.exit(1)});export{
|
|
69
|
+
`:n.stdout),0)}function Hc(e){try{return!sn(`${e}/.git`)||sn(`${e}/.git/index`)?!1:Mc(e).every(t=>t===".git")}catch{return!1}}var je=class{constructor(t){this.openStore=t}store;async mint(...t){return await(await this.open()).mint(...t)}async close(){if(!this.store)return;let t;try{t=await this.store}catch{return}await t.close()}open(){return this.store??=this.openStore(),this.store}};async function we(e,t,n){if(process.env.RSP_DEBUG==="1")throw n instanceof Error?n:new Error(e);return process.stderr.write(`rsp: ${e}, passing through
|
|
70
|
+
`),await Wc(t)}function rn(){return"rsp is not enabled in this directory; run /red-setup"}async function J(e){let t=process.stderr.write;process.stderr.write=()=>!0;try{return await e()}finally{process.stderr.write=t}}function Kc(e){return e==="git"||e==="gh"||e==="vitest"||e==="cargo"}async function Wc(e){let t=e[0];if(!t)return 2;let{spawn:n}=await import("node:child_process"),r=n(t,e.slice(1),{stdio:"inherit"});return await new Promise(i=>{r.on("error",s=>{process.stderr.write(`${s instanceof Error?s.message:String(s)}
|
|
71
|
+
`),i(127)}),r.on("close",(s,o)=>{if(o){process.kill(process.pid,o),i(128);return}i(s??0)})})}function zc(e){let t={level:"lossless",positional:[]},n=[];for(let r=0;r<e.length;r++){let i=e[r];i==="--store-uri"?t.storeUri=e[++r]:i==="--brief"?t.level="brief":i==="--terse"?t.level="terse":i==="--query"?t.query=e[++r]:i.startsWith("--query=")?t.query=i.slice(8):n.push(i)}return t.query&&n[0]!=="show"&&!n.some(r=>r==="--query"||r.startsWith("--query="))&&n.push("--query",t.query),t.command=n[0],t.handle=n[1],t.positional=n,t}function Qc(e){return[`records: ${e.records}`,`bytes: ${e.bytes}`,`oldest: ${e.oldest??"none"}`,`budget: ${e.budget}`,""].join(`
|
|
72
|
+
`)}function Yc(e){return[`config: ${e.configChanged?"updated":"unchanged"}`,`store: ${e.storeCreated?"created":"existing"}`,""].join(`
|
|
73
|
+
`)}import.meta.url===`file://${process.argv[1]}`&&Fc().then(e=>process.exit(e),e=>{process.stdout.write(`error: ${e instanceof Error?e.message:String(e)}
|
|
74
|
+
`),process.exit(1)});export{Fc as main,Yc as renderSetupResult,Qc as renderStats};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reddb-io/red-skills",
|
|
3
|
-
"version": "2.34.
|
|
3
|
+
"version": "2.34.1",
|
|
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",
|