@reddb-io/red-skills 4.0.8 → 4.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
50
50
  `:`[${n[c]}\r
51
51
  ]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Qa(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??je(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===E.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Ya(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===E.ZodBranded&&e.keyType._def.type._def.typeName===E.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Xa(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function Qv(e,t){if(t.mapStrategy==="record")return Qa(e,t);let r=W(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||je(t),n=W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||je(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function eb(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function tb(e){return e.target==="openAi"?void 0:{not:je({...e,currentPath:[...e.currentPath,"not"]})}}function rb(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Qi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ob(e,t){if(t.target==="openApi3")return nb(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Qi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Qi[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 nb(e,t)}var nb=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>W(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ib(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Qi[e.innerType._def.typeName],nullable:!0}:{type:[Qi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function sb(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",lf(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,t):ie(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,t):ie(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,t));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,t);break}return r}function ab(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=vO(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=W(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let s=_O(e,t);return s!==void 0&&(n.additionalProperties=s),n}function _O(e,t){if(e.catchall._def.typeName!=="ZodNever")return W(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function vO(e){try{return e.isOptional()}catch{return!0}}var cb=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return W(e.innerType._def,t);let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:je(t)},r]}:je(t)};var ub=(e,t)=>{if(t.pipeStrategy==="input")return W(e.in._def,t);if(t.pipeStrategy==="output")return W(e.out._def,t);let r=W(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=W(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function lb(e,t){return W(e.type._def,t)}function db(e,t){let n={type:"array",uniqueItems:!0,items:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ie(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ie(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function fb(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:W(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function pb(e){return{not:je(e)}}function mb(e){return je(e)}var hb=(e,t)=>W(e.innerType._def,t);var gb=(e,t,r)=>{switch(t){case E.ZodString:return Ya(e,r);case E.ZodNumber:return sb(e,r);case E.ZodObject:return ab(e,r);case E.ZodBigInt:return Vv(e,r);case E.ZodBoolean:return Hv();case E.ZodDate:return df(e,r);case E.ZodUndefined:return pb(r);case E.ZodNull:return rb(r);case E.ZodArray:return Uv(e,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return ob(e,r);case E.ZodIntersection:return Kv(e,r);case E.ZodTuple:return fb(e,r);case E.ZodRecord:return Qa(e,r);case E.ZodLiteral:return Xv(e,r);case E.ZodEnum:return Gv(e);case E.ZodNativeEnum:return eb(e);case E.ZodNullable:return ib(e,r);case E.ZodOptional:return cb(e,r);case E.ZodMap:return Qv(e,r);case E.ZodSet:return db(e,r);case E.ZodLazy:return()=>e.getter()._def;case E.ZodPromise:return lb(e,r);case E.ZodNaN:case E.ZodNever:return tb(r);case E.ZodEffects:return Jv(e,r);case E.ZodAny:return je(r);case E.ZodUnknown:return mb(r);case E.ZodDefault:return Wv(e,r);case E.ZodBranded:return Xa(e,r);case E.ZodReadonly:return hb(e,r);case E.ZodCatch:return Bv(e,r);case E.ZodPipeline:return ub(e,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(t)}};function W(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==Zv)return a}if(n&&!r){let a=bO(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=gb(e,e.typeName,t),s=typeof i=="function"?W(i(),t):i;if(s&&wO(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var bO=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ka(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),je(t)):t.$refStrategy==="seen"?je(t):void 0}},wO=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var mf=(e,t)=>{let r=Fv(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??je(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=W(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??je(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function xO(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function hf(e,t){return At(e)?Md(e,{target:xO(t?.target),io:t?.pipeStrategy??"input"}):mf(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function gf(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Pa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function yf(e,t){let r=Wr(e,t);if(!r.success)throw r.error;return r.data}var $O=6e4,ec=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ja,r=>{this._oncancel(r)}),this.setNotificationHandler(Ia,r=>{this._onprogress(r)}),this.setRequestHandler(Na,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ma,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(U.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Aa,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,h=new Z(d.error.code,d.error.message,d.error.data);l(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new Z(U.InvalidParams,`Task not found: ${i}`);if(!Kr(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Kr(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Gr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(qa,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 Z(U.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(La,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(Kr(o.status))throw new Z(U.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 Z(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof Z?o:new Z(U.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Z.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Vi(i)||Rv(i)?this._onresponse(i):Gd(i)?this._onrequest(i,s):Tv(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[Gr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Sv(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,h)=>{if(s.signal.aborted)throw new Z(U.ConnectionClosed,"Request was cancelled");let m={...h,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});let p=m.relatedTask?.taskId??i;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Vi(t))n(t);else{let s=new Z(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Vi(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Vi(t))o(t);else{let s=Z.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof Z?s:new Z(U.InternalError,String(s))}}return}let i;try{let s=await this.request(t,zo,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Z(U.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Kr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(U.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(U.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Z?s:new Z(U.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=T=>{l(T)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(T){d(T);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Gr]:c}});let p=T=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(T)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`)));let z=T instanceof Z?T:new Z(U.RequestTimeout,String(T));l(z)};this._responseHandlers.set(h,T=>{if(!n?.signal?.aborted){if(T instanceof Error)return l(T);try{let z=Wr(r,T.result);z.success?u(z.data):l(z.error)}catch(z){l(z)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let y=n?.timeout??$O,v=()=>p(Z.fromError(U.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(h,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let P=c?.taskId;if(P){let T=z=>{let M=this._responseHandlers.get(h);M?M(z):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,T),this._enqueueTaskMessage(P,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(h),l(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(T=>{this._cleanupTimeout(h),l(T)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Da,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Za,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Ov,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Gr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Gr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Gr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=gf(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=yf(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=gf(t);this._notificationHandlers.set(n,o=>{let i=yf(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&Gd(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new Z(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new Z(U.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new Z(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new Z(U.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=Gi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Kr(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 Z(U.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Kr(a.status))throw new Z(U.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let u=Gi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Kr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function yb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _b(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];yb(s)&&yb(i)?r[o]={...s,...i}:r[o]=i}return r}var u$=ea(nm(),1),l$=ea(c$(),1);function P1(){let e=new u$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,l$.default)(e),e}var Ic=class{constructor(t){this._ajv=t??P1()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Mc=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(i.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==d.size||![...l].every(h=>d.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Yi,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},Co,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function d$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function f$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Dc=class extends ec{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Xi.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 Ic,this.setRequestHandler(Yd,n=>this._oninitialize(n)),this.setNotificationHandler(Qd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(af,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=Xi.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Mc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=_b(this._capabilities,t)}setRequestHandler(t,r){let o=Jr(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(At(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=Wr(Oo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new Z(U.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,h=await Promise.resolve(r(c,u));if(d.task){let p=Wr(zo,h);if(!p.success){let y=p.error instanceof Error?p.error.message:String(p.error);throw new Z(U.InvalidParams,`Invalid task creation result: ${y}`)}return p.data}let m=Wr(Ja,h);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new Z(U.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){f$(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&d$(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:wv.includes(r)?r:Wd,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"},Ca)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},cf,r):this.request({method:"sampling/createMessage",params:t},Yi,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},Co,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Co,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Z(U.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Z?s:new Z(U.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},uf,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var m$=Symbol.for("mcp.completable");function dm(e){return!!e&&typeof e=="object"&&m$ in e}function h$(e){return e[m$]?.complete}var p$;(function(e){e.Completable="McpCompletable"})(p$||(p$={}));var T1=/^[A-Za-z0-9._-]{1,128}$/;function R1(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!T1.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function z1(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function fm(e){let t=R1(e);return z1(e,t.warnings),t.isValid}var Ac=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var qc=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Dc(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ac(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Wa)),this.server.assertCanSetRequestHandler(sn(Oo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Wa,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=To(r.inputSchema);return o?hf(o,{strictUnions:!0,pipeStrategy:"input"}):E1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=To(r.outputSchema);o&&(n.outputSchema=hf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Oo,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new Z(U.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new Z(U.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new Z(U.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof Z&&n.code===U.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=To(t.inputSchema)??t.inputSchema,s=await Sa(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=ka(a);throw new Z(U.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(U.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=To(t.outputSchema),i=await Sa(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ka(s);throw new Z(U.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(h=>setTimeout(h,l));let d=await n.taskStore.getTask(c);if(!d)throw new Z(U.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(sn(Ga)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ga,async t=>{switch(t.params.ref.type){case"ref/prompt":return Dv(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Av(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Z(U.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(U.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return zs;let i=Jr(n.argsSchema)?.[t.params.argument.name];if(!dm(i))return zs;let s=h$(i);if(!s)return zs;let a=await s(t.params.argument.value,t.params.context);return y$(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return zs;throw new Z(U.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return zs;let i=await o(t.params.argument.value,t.params.context);return y$(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Fa)),this.server.assertCanSetRequestHandler(sn(Ua)),this.server.assertCanSetRequestHandler(sn(Va)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Fa,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Ua,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Va,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(U.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 Z(U.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Ha)),this.server.assertCanSetRequestHandler(sn(Ba)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ha,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?O1(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ba,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new Z(U.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=To(n.argsSchema),i=await Sa(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=ka(c);throw new Z(U.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==t&&(delete this._registeredResourceTemplates[t],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Hn(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Hn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let u=c instanceof bt?c._def?.innerType:c;return dm(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,u){fm(t);let l={title:r,description:n,inputSchema:g$(o),outputSchema:g$(i),annotations:s,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&fm(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Hn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(pm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!pm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},u,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var E1={type:"object",properties:{}};function _$(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function v$(e){return"_def"in e||"_zod"in e||_$(e)}function pm(e){return typeof e!="object"||e===null||v$(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(_$)}function g$(e){if(e){if(pm(e))return Hn(e);if(!v$(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function O1(e){let t=Jr(e);return t?Object.entries(t).map(([r,n])=>{let o=X_(n),i=Y_(n);return{name:r,description:o,required:!i}}):[]}function sn(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Pa(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function y$(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var zs={completion:{values:[],hasMore:!1}};import w$ from"node:process";var Zc=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
52
52
  `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),C1(r)}clear(){this._buffer=void 0}};function C1(e){return zv.parse(JSON.parse(e))}function b$(e){return JSON.stringify(e)+`
53
- `}var Lc=class{constructor(t=w$.stdin,r=w$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Zc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=b$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function mm(e){let t={app:e,version:j1(Xo("__RED_BUILD_VERSION__",()=>"4.0.8")??"0.0.0-dev"),gitSha:Xo("__RED_BUILD_GIT_SHA__",()=>"4767ffba5cfef04cb196ab6dfe383ff3f9817243")??"unknown",buildTime:Xo("__RED_BUILD_TIME__",()=>"2026-08-20T09:32:28-03:00")??"unknown",bundleAsset:Xo("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Xo("__REDDB_SDK_VERSION__",()=>""),n=Xo("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function j1(e){return e.startsWith("v")?e.slice(1):e}function x$(e){return`${e.app} ${e.version} ${e.gitSha}`}function Xo(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var $$={"=":"data",":=":{to:"data",typed:!0},":":"meta"},N1=/^[a-z][a-z0-9+.-]*:\/\//i;function I1(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function M1(e=$$){return Object.entries(e).map(([t,r])=>I1(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function D1(e){return/^-\d+(\.\d+)?$/.test(e)}function Es(e){return!(!e||e.startsWith("-")&&!D1(e))}function Fc(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function S$(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>S$(r.trim())):e}function no(e,t){switch(t){case"boolean":return A1(e);case"number":return q1(e);case"array":return e.split(",").map(r=>Fc(r.trim()));default:return e}}function A1(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function q1(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function an(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Z1(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function $e(e,t){return{type:e,value:t}}function L1(e){let t=[],r=U1(e);if(t.push($e("section-header","Usage:"),$e("text"," "),$e("usage-text",r),$e("newline",`
53
+ `}var Lc=class{constructor(t=w$.stdin,r=w$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Zc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=b$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function mm(e){let t={app:e,version:j1(Xo("__RED_BUILD_VERSION__",()=>"4.0.9")??"0.0.0-dev"),gitSha:Xo("__RED_BUILD_GIT_SHA__",()=>"8091e7743f0244689a216447fe6773333c6640af")??"unknown",buildTime:Xo("__RED_BUILD_TIME__",()=>"2026-08-20T09:52:47-03:00")??"unknown",bundleAsset:Xo("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Xo("__REDDB_SDK_VERSION__",()=>""),n=Xo("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function j1(e){return e.startsWith("v")?e.slice(1):e}function x$(e){return`${e.app} ${e.version} ${e.gitSha}`}function Xo(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var $$={"=":"data",":=":{to:"data",typed:!0},":":"meta"},N1=/^[a-z][a-z0-9+.-]*:\/\//i;function I1(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function M1(e=$$){return Object.entries(e).map(([t,r])=>I1(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function D1(e){return/^-\d+(\.\d+)?$/.test(e)}function Es(e){return!(!e||e.startsWith("-")&&!D1(e))}function Fc(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function S$(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>S$(r.trim())):e}function no(e,t){switch(t){case"boolean":return A1(e);case"number":return q1(e);case"array":return e.split(",").map(r=>Fc(r.trim()));default:return e}}function A1(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function q1(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function an(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Z1(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function $e(e,t){return{type:e,value:t}}function L1(e){let t=[],r=U1(e);if(t.push($e("section-header","Usage:"),$e("text"," "),$e("usage-text",r),$e("newline",`
54
54
  `),$e("newline",`
55
55
  `)),e.positional&&e.positional.length>0){t.push($e("section-header","Arguments:"),$e("newline",`
56
56
  `));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;t.push($e("indent"," "),$e("positional-name",`<${o}>`)),n.required||t.push($e("positional-optional"," (optional)")),t.push($e("newline",`
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
2
- import{mkdirSync as Pe,readFileSync as nn,writeFileSync as on}from"node:fs";import{dirname as sn,resolve as V}from"node:path";function W(e){let t={app:e,version:Ce(b("__RED_BUILD_VERSION__",()=>"4.0.8")??"0.0.0-dev"),gitSha:b("__RED_BUILD_GIT_SHA__",()=>"4767ffba5cfef04cb196ab6dfe383ff3f9817243")??"unknown",buildTime:b("__RED_BUILD_TIME__",()=>"2026-08-20T09:32:28-03:00")??"unknown",bundleAsset:b("__RED_BUNDLE_ASSET__",()=>"opencode-host.bundle.min.mjs")??"unknown"},n=b("__REDDB_SDK_VERSION__",()=>""),s=b("__REDDB_BINARY_TAG__",()=>"");return n&&(t.reddbSdkVersion=n),s&&(t.reddbBinaryTag=s),t}function Ce(e){return e.startsWith("v")?e.slice(1):e}function G(e){return`${e.app} ${e.version} ${e.gitSha}`}function b(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ne={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Te=/^[a-z][a-z0-9+.-]*:\/\//i;function Ie(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function je(e=ne){return Object.entries(e).map(([t,n])=>Ie(t,n)).sort((t,n)=>n.separator.length-t.separator.length)}function Fe(e){return/^-\d+(\.\d+)?$/.test(e)}function $(e){return!(!e||e.startsWith("-")&&!Fe(e))}function A(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function oe(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(n=>oe(n.trim())):e}function k(e,t){switch(t){case"boolean":return Ne(e);case"number":return De(e);case"array":return e.split(",").map(n=>A(n.trim()));case"string":default:return e}}function Ne(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function De(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function _(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Me(e,t={}){return e.map(n=>{let s=t[n.type];return s?s(n.value):n.value}).join("")}function g(e,t){return{type:e,value:t}}function Le(e){let t=[],n=Ve(e);if(t.push(g("section-header","Usage:"),g("text"," "),g("usage-text",n),g("newline",`
2
+ import{mkdirSync as Pe,readFileSync as nn,writeFileSync as on}from"node:fs";import{dirname as sn,resolve as V}from"node:path";function W(e){let t={app:e,version:Ce(b("__RED_BUILD_VERSION__",()=>"4.0.9")??"0.0.0-dev"),gitSha:b("__RED_BUILD_GIT_SHA__",()=>"8091e7743f0244689a216447fe6773333c6640af")??"unknown",buildTime:b("__RED_BUILD_TIME__",()=>"2026-08-20T09:52:47-03:00")??"unknown",bundleAsset:b("__RED_BUNDLE_ASSET__",()=>"opencode-host.bundle.min.mjs")??"unknown"},n=b("__REDDB_SDK_VERSION__",()=>""),s=b("__REDDB_BINARY_TAG__",()=>"");return n&&(t.reddbSdkVersion=n),s&&(t.reddbBinaryTag=s),t}function Ce(e){return e.startsWith("v")?e.slice(1):e}function G(e){return`${e.app} ${e.version} ${e.gitSha}`}function b(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ne={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Te=/^[a-z][a-z0-9+.-]*:\/\//i;function Ie(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function je(e=ne){return Object.entries(e).map(([t,n])=>Ie(t,n)).sort((t,n)=>n.separator.length-t.separator.length)}function Fe(e){return/^-\d+(\.\d+)?$/.test(e)}function $(e){return!(!e||e.startsWith("-")&&!Fe(e))}function A(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function oe(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(n=>oe(n.trim())):e}function k(e,t){switch(t){case"boolean":return Ne(e);case"number":return De(e);case"array":return e.split(",").map(n=>A(n.trim()));case"string":default:return e}}function Ne(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function De(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function _(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Me(e,t={}){return e.map(n=>{let s=t[n.type];return s?s(n.value):n.value}).join("")}function g(e,t){return{type:e,value:t}}function Le(e){let t=[],n=Ve(e);if(t.push(g("section-header","Usage:"),g("text"," "),g("usage-text",n),g("newline",`
3
3
  `),g("newline",`
4
4
  `)),e.positional&&e.positional.length>0){t.push(g("section-header","Arguments:"),g("newline",`
5
5
  `));for(let s of e.positional)if(s.description){let o=s.variadic?`${s.name}...`:s.name;t.push(g("indent"," "),g("positional-name",`<${o}>`)),s.required||t.push(g("positional-optional"," (optional)")),t.push(g("newline",`
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Idt=Object.create;var VW=Object.defineProperty;var Adt=Object.getOwnPropertyDescriptor;var Odt=Object.getOwnPropertyNames;var $dt=Object.getPrototypeOf,Mdt=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vn=(e,t)=>{for(var r in t)VW(e,r,{get:t[r],enumerable:!0})},Ddt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Odt(t))!Mdt.call(e,o)&&o!==r&&VW(e,o,{get:()=>t[o],enumerable:!(n=Adt(t,o))||n.enumerable});return e};var Cp=(e,t,r)=>(r=e!=null?Idt($dt(e)):{},Ddt(t||!e||!e.__esModule?VW(r,"default",{value:e,enumerable:!0}):r,e));function KW(e){let t={app:e,version:Ndt(fk("__RED_BUILD_VERSION__",()=>"4.0.8")??"0.0.0-dev"),gitSha:fk("__RED_BUILD_GIT_SHA__",()=>"4767ffba5cfef04cb196ab6dfe383ff3f9817243")??"unknown",buildTime:fk("__RED_BUILD_TIME__",()=>"2026-08-20T09:32:28-03:00")??"unknown",bundleAsset:fk("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=fk("__REDDB_SDK_VERSION__",()=>""),n=fk("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Ndt(e){return e.startsWith("v")?e.slice(1):e}function rSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function fk(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ZW=p(()=>{});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function yo(e){return e&&Object.assign(jy,e),jy}var nSe,QW,YW,Hl,qm,jy,Uy=p(()=>{QW=Object.freeze({status:"aborted"});YW=Symbol("zod_brand"),Hl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},qm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(nSe=globalThis).__zod_globalConfig??(nSe.__zod_globalConfig={});jy=globalThis.__zod_globalConfig});var Re={};Vn(Re,{BIGINT_FORMAT_RANGES:()=>c4,Class:()=>e4,NUMBER_FORMAT_RANGES:()=>a4,aborted:()=>Vm,allowsEval:()=>n4,assert:()=>Hdt,assertEqual:()=>Ldt,assertIs:()=>jdt,assertNever:()=>Udt,assertNotEqual:()=>Fdt,assignProp:()=>Bm,base64ToUint8Array:()=>iSe,base64urlToUint8Array:()=>ipt,cached:()=>hk,captureStackTrace:()=>T$,cleanEnum:()=>opt,cleanRegex:()=>C0,clone:()=>Cs,cloneDef:()=>Gdt,createTransparentProxy:()=>Jdt,defineLazy:()=>Jt,esc:()=>R$,escapeRegex:()=>$c,explicitlyAborted:()=>l4,extend:()=>Xdt,finalizeIssue:()=>Ps,floatSafeRemainder:()=>t4,getElementAtPath:()=>Bdt,getEnumValues:()=>T0,getLengthableOrigin:()=>A0,getParsedType:()=>Zdt,getSizableOrigin:()=>I0,hexToUint8Array:()=>apt,isObject:()=>Hy,isPlainObject:()=>Wm,issue:()=>gk,joinValues:()=>ne,jsonStringifyReplacer:()=>mk,merge:()=>tpt,mergeDefs:()=>Pp,normalizeParams:()=>Ie,nullish:()=>Gm,numKeys:()=>Kdt,objectClone:()=>qdt,omit:()=>Ydt,optionalKeys:()=>s4,parsedType:()=>Ee,partial:()=>rpt,pick:()=>Qdt,prefixIssues:()=>ca,primitiveTypes:()=>i4,promiseAllObject:()=>Wdt,propertyKeyTypes:()=>P0,randomString:()=>Vdt,required:()=>npt,safeExtend:()=>ept,shallowClone:()=>o4,slugify:()=>r4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>sSe,uint8ArrayToBase64url:()=>spt,uint8ArrayToHex:()=>cpt,unwrapMessage:()=>R0});function Ldt(e){return e}function Fdt(e){return e}function jdt(e){}function Udt(e){throw new Error("Unexpected value in exhaustive check")}function Hdt(e){}function T0(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function mk(e,t){return typeof t=="bigint"?t.toString():t}function hk(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gm(e){return e==null}function C0(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function t4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Jt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==oSe)return n===void 0&&(n=oSe,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function qdt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Bm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Pp(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Gdt(e){return Pp(e._zod.def)}function Bdt(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Wdt(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function Vdt(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function R$(e){return JSON.stringify(e)}function r4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Hy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wm(e){if(Hy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Hy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function o4(e){return Wm(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Kdt(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function $c(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cs(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Jdt(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function s4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function Qdt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function Ydt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function Xdt(e,t){if(!Wm(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Pp(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Bm(this,"shape",i),i}});return Cs(e,o)}function ept(e,t){if(!Wm(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Bm(this,"shape",n),n}});return Cs(e,r)}function tpt(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Bm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Cs(e,r)}function rpt(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Pp(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Bm(this,"shape",c),c},checks:[]});return Cs(t,s)}function npt(e,t,r){let n=Pp(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Bm(this,"shape",i),i}});return Cs(t,n)}function Vm(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function l4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ca(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function R0(e){return typeof e=="string"?e:e?.message}function Ps(e,t,r){let n=e.message?e.message:R0(e.inst?._zod.def?.error?.(e))??R0(t?.error?.(e))??R0(r.customError?.(e))??R0(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function I0(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function A0(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function gk(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function opt(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function iSe(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function sSe(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function ipt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return iSe(t+r)}function spt(e){return sSe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function apt(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function cpt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var oSe,T$,n4,Zdt,P0,i4,a4,c4,e4,ot=p(()=>{Uy();oSe=Symbol("evaluating");T$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};n4=hk(()=>{if(jy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});Zdt=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},P0=new Set(["string","number","symbol"]),i4=new Set(["string","number","bigint","boolean","symbol","undefined"]);a4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},c4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};e4=class{constructor(...t){}}});function $0(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function M0(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function u4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function cSe(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function d4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${cSe(n.path)}`);return t.join(`
3
+ var Idt=Object.create;var VW=Object.defineProperty;var Adt=Object.getOwnPropertyDescriptor;var Odt=Object.getOwnPropertyNames;var $dt=Object.getPrototypeOf,Mdt=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vn=(e,t)=>{for(var r in t)VW(e,r,{get:t[r],enumerable:!0})},Ddt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Odt(t))!Mdt.call(e,o)&&o!==r&&VW(e,o,{get:()=>t[o],enumerable:!(n=Adt(t,o))||n.enumerable});return e};var Cp=(e,t,r)=>(r=e!=null?Idt($dt(e)):{},Ddt(t||!e||!e.__esModule?VW(r,"default",{value:e,enumerable:!0}):r,e));function KW(e){let t={app:e,version:Ndt(fk("__RED_BUILD_VERSION__",()=>"4.0.9")??"0.0.0-dev"),gitSha:fk("__RED_BUILD_GIT_SHA__",()=>"8091e7743f0244689a216447fe6773333c6640af")??"unknown",buildTime:fk("__RED_BUILD_TIME__",()=>"2026-08-20T09:52:47-03:00")??"unknown",bundleAsset:fk("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=fk("__REDDB_SDK_VERSION__",()=>""),n=fk("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Ndt(e){return e.startsWith("v")?e.slice(1):e}function rSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function fk(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ZW=p(()=>{});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function yo(e){return e&&Object.assign(jy,e),jy}var nSe,QW,YW,Hl,qm,jy,Uy=p(()=>{QW=Object.freeze({status:"aborted"});YW=Symbol("zod_brand"),Hl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},qm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(nSe=globalThis).__zod_globalConfig??(nSe.__zod_globalConfig={});jy=globalThis.__zod_globalConfig});var Re={};Vn(Re,{BIGINT_FORMAT_RANGES:()=>c4,Class:()=>e4,NUMBER_FORMAT_RANGES:()=>a4,aborted:()=>Vm,allowsEval:()=>n4,assert:()=>Hdt,assertEqual:()=>Ldt,assertIs:()=>jdt,assertNever:()=>Udt,assertNotEqual:()=>Fdt,assignProp:()=>Bm,base64ToUint8Array:()=>iSe,base64urlToUint8Array:()=>ipt,cached:()=>hk,captureStackTrace:()=>T$,cleanEnum:()=>opt,cleanRegex:()=>C0,clone:()=>Cs,cloneDef:()=>Gdt,createTransparentProxy:()=>Jdt,defineLazy:()=>Jt,esc:()=>R$,escapeRegex:()=>$c,explicitlyAborted:()=>l4,extend:()=>Xdt,finalizeIssue:()=>Ps,floatSafeRemainder:()=>t4,getElementAtPath:()=>Bdt,getEnumValues:()=>T0,getLengthableOrigin:()=>A0,getParsedType:()=>Zdt,getSizableOrigin:()=>I0,hexToUint8Array:()=>apt,isObject:()=>Hy,isPlainObject:()=>Wm,issue:()=>gk,joinValues:()=>ne,jsonStringifyReplacer:()=>mk,merge:()=>tpt,mergeDefs:()=>Pp,normalizeParams:()=>Ie,nullish:()=>Gm,numKeys:()=>Kdt,objectClone:()=>qdt,omit:()=>Ydt,optionalKeys:()=>s4,parsedType:()=>Ee,partial:()=>rpt,pick:()=>Qdt,prefixIssues:()=>ca,primitiveTypes:()=>i4,promiseAllObject:()=>Wdt,propertyKeyTypes:()=>P0,randomString:()=>Vdt,required:()=>npt,safeExtend:()=>ept,shallowClone:()=>o4,slugify:()=>r4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>sSe,uint8ArrayToBase64url:()=>spt,uint8ArrayToHex:()=>cpt,unwrapMessage:()=>R0});function Ldt(e){return e}function Fdt(e){return e}function jdt(e){}function Udt(e){throw new Error("Unexpected value in exhaustive check")}function Hdt(e){}function T0(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function mk(e,t){return typeof t=="bigint"?t.toString():t}function hk(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gm(e){return e==null}function C0(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function t4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Jt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==oSe)return n===void 0&&(n=oSe,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function qdt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Bm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Pp(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Gdt(e){return Pp(e._zod.def)}function Bdt(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Wdt(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function Vdt(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function R$(e){return JSON.stringify(e)}function r4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Hy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wm(e){if(Hy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Hy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function o4(e){return Wm(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Kdt(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function $c(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cs(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Jdt(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function s4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function Qdt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function Ydt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function Xdt(e,t){if(!Wm(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Pp(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Bm(this,"shape",i),i}});return Cs(e,o)}function ept(e,t){if(!Wm(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Bm(this,"shape",n),n}});return Cs(e,r)}function tpt(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Bm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Cs(e,r)}function rpt(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Pp(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Bm(this,"shape",c),c},checks:[]});return Cs(t,s)}function npt(e,t,r){let n=Pp(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Bm(this,"shape",i),i}});return Cs(t,n)}function Vm(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function l4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ca(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function R0(e){return typeof e=="string"?e:e?.message}function Ps(e,t,r){let n=e.message?e.message:R0(e.inst?._zod.def?.error?.(e))??R0(t?.error?.(e))??R0(r.customError?.(e))??R0(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function I0(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function A0(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function gk(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function opt(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function iSe(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function sSe(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function ipt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return iSe(t+r)}function spt(e){return sSe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function apt(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function cpt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var oSe,T$,n4,Zdt,P0,i4,a4,c4,e4,ot=p(()=>{Uy();oSe=Symbol("evaluating");T$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};n4=hk(()=>{if(jy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});Zdt=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},P0=new Set(["string","number","symbol"]),i4=new Set(["string","number","bigint","boolean","symbol","undefined"]);a4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},c4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};e4=class{constructor(...t){}}});function $0(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function M0(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function u4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function cSe(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function d4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${cSe(n.path)}`);return t.join(`
4
4
  `)}var aSe,O0,la,p4=p(()=>{Uy();ot();aSe=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,mk,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},O0=K("$ZodError",aSe),la=K("$ZodError",aSe,{Parent:Error})});var yk,C$,bk,P$,xk,f4,Sk,m4,I$,upt,A$,dpt,O$,ppt,$$,fpt,M$,mpt,D$,hpt,N$,gpt,z$,ypt,h4=p(()=>{Uy();p4();ot();yk=e=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Hl;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ps(c,i,yo())));throw T$(a,o?.callee),a}return s.value},C$=yk(la),bk=e=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ps(c,i,yo())));throw T$(a,o?.callee),a}return s.value},P$=bk(la),xk=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Hl;return i.issues.length?{success:!1,error:new(e??O0)(i.issues.map(s=>Ps(s,o,yo())))}:{success:!0,data:i.value}},f4=xk(la),Sk=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Ps(s,o,yo())))}:{success:!0,data:i.value}},m4=Sk(la),I$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return yk(e)(t,r,o)},upt=I$(la),A$=e=>(t,r,n)=>yk(e)(t,r,n),dpt=A$(la),O$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return bk(e)(t,r,o)},ppt=O$(la),$$=e=>async(t,r,n)=>bk(e)(t,r,n),fpt=$$(la),M$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return xk(e)(t,r,o)},mpt=M$(la),D$=e=>(t,r,n)=>xk(e)(t,r,n),hpt=D$(la),N$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Sk(e)(t,r,o)},gpt=N$(la),z$=e=>async(t,r,n)=>Sk(e)(t,r,n),ypt=z$(la)});var Va={};Vn(Va,{base64:()=>A4,base64url:()=>L$,bigint:()=>L4,boolean:()=>j4,browserEmail:()=>Ept,cidrv4:()=>P4,cidrv6:()=>I4,cuid:()=>g4,cuid2:()=>y4,date:()=>M4,datetime:()=>N4,domain:()=>Cpt,duration:()=>_4,e164:()=>$4,email:()=>v4,emoji:()=>E4,extendedDuration:()=>bpt,guid:()=>w4,hex:()=>Ppt,hostname:()=>Tpt,html5Email:()=>_pt,httpProtocol:()=>O4,idnEmail:()=>vpt,integer:()=>F4,ipv4:()=>R4,ipv6:()=>T4,ksuid:()=>S4,lowercase:()=>q4,mac:()=>C4,md5_base64:()=>Apt,md5_base64url:()=>Opt,md5_hex:()=>Ipt,nanoid:()=>k4,null:()=>U4,number:()=>F$,rfc5322Email:()=>wpt,sha1_base64:()=>Mpt,sha1_base64url:()=>Dpt,sha1_hex:()=>$pt,sha256_base64:()=>zpt,sha256_base64url:()=>Lpt,sha256_hex:()=>Npt,sha384_base64:()=>jpt,sha384_base64url:()=>Upt,sha384_hex:()=>Fpt,sha512_base64:()=>qpt,sha512_base64url:()=>Gpt,sha512_hex:()=>Hpt,string:()=>z4,time:()=>D4,ulid:()=>b4,undefined:()=>H4,unicodeEmail:()=>lSe,uppercase:()=>G4,uuid:()=>qy,uuid4:()=>xpt,uuid6:()=>Spt,uuid7:()=>kpt,xid:()=>x4});function E4(){return new RegExp(Rpt,"u")}function dSe(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function D4(e){return new RegExp(`^${dSe(e)}$`)}function N4(e){let t=dSe({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${uSe}T(?:${n})$`)}function D0(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function N0(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var g4,y4,b4,x4,S4,k4,_4,bpt,w4,qy,xpt,Spt,kpt,v4,_pt,wpt,lSe,vpt,Ept,Rpt,R4,T4,C4,P4,I4,A4,L$,Tpt,Cpt,O4,$4,uSe,M4,z4,L4,F4,F$,j4,U4,H4,q4,G4,Ppt,Ipt,Apt,Opt,$pt,Mpt,Dpt,Npt,zpt,Lpt,Fpt,jpt,Upt,Hpt,qpt,Gpt,j$=p(()=>{ot();g4=/^[cC][0-9a-z]{6,}$/,y4=/^[0-9a-z]+$/,b4=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,x4=/^[0-9a-vA-V]{20}$/,S4=/^[A-Za-z0-9]{27}$/,k4=/^[a-zA-Z0-9_-]{21}$/,_4=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bpt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,w4=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qy=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,xpt=qy(4),Spt=qy(6),kpt=qy(7),v4=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,_pt=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,wpt=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,lSe=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,vpt=lSe,Ept=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Rpt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";R4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,T4=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,C4=e=>{let t=$c(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},P4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,I4=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,A4=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,L$=/^[A-Za-z0-9_-]*$/,Tpt=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Cpt=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,O4=/^https?$/,$4=/^\+[1-9]\d{6,14}$/,uSe="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",M4=new RegExp(`^${uSe}$`);z4=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},L4=/^-?\d+n?$/,F4=/^-?\d+$/,F$=/^-?\d+(?:\.\d+)?$/,j4=/^(?:true|false)$/i,U4=/^null$/i,H4=/^undefined$/i,q4=/^[^A-Z]*$/,G4=/^[^a-z]*$/,Ppt=/^[0-9a-fA-F]*$/;Ipt=/^[0-9a-fA-F]{32}$/,Apt=D0(22,"=="),Opt=N0(22),$pt=/^[0-9a-fA-F]{40}$/,Mpt=D0(27,"="),Dpt=N0(27),Npt=/^[0-9a-fA-F]{64}$/,zpt=D0(43,"="),Lpt=N0(43),Fpt=/^[0-9a-fA-F]{96}$/,jpt=D0(64,""),Upt=N0(64),Hpt=/^[0-9a-fA-F]{128}$/,qpt=D0(86,"=="),Gpt=N0(86)});function pSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues))}var un,fSe,U$,H$,B4,W4,V4,K4,Z4,J4,Q4,Y4,X4,kk,eV,tV,rV,nV,oV,iV,sV,aV,cV,q$=p(()=>{Uy();j$();ot();un=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),fSe={number:"number",bigint:"bigint",object:"date"},U$=K("$ZodCheckLessThan",(e,t)=>{un.init(e,t);let r=fSe[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),H$=K("$ZodCheckGreaterThan",(e,t)=>{un.init(e,t);let r=fSe[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),B4=K("$ZodCheckMultipleOf",(e,t)=>{un.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):t4(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),W4=K("$ZodCheckNumberFormat",(e,t)=>{un.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=a4[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=F4)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),V4=K("$ZodCheckBigIntFormat",(e,t)=>{un.init(e,t);let[r,n]=c4[t.format];e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{let i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),K4=K("$ZodCheckMaxSize",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;o.size<=t.maximum||n.issues.push({origin:I0(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Z4=K("$ZodCheckMinSize",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:I0(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),J4=K("$ZodCheckSizeEquals",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,i=o.size;if(i===t.size)return;let s=i>t.size;n.issues.push({origin:I0(o),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Q4=K("$ZodCheckMaxLength",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=A0(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Y4=K("$ZodCheckMinLength",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=A0(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),X4=K("$ZodCheckLengthEquals",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=A0(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),kk=K("$ZodCheckStringFormat",(e,t)=>{var r,n;un.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),eV=K("$ZodCheckRegex",(e,t)=>{kk.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tV=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=q4),kk.init(e,t)}),rV=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=G4),kk.init(e,t)}),nV=K("$ZodCheckIncludes",(e,t)=>{un.init(e,t);let r=$c(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),oV=K("$ZodCheckStartsWith",(e,t)=>{un.init(e,t);let r=new RegExp(`^${$c(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),iV=K("$ZodCheckEndsWith",(e,t)=>{un.init(e,t);let r=new RegExp(`.*${$c(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});sV=K("$ZodCheckProperty",(e,t)=>{un.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>pSe(o,r,t.property));pSe(n,r,t.property)}}),aV=K("$ZodCheckMimeType",(e,t)=>{un.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),cV=K("$ZodCheckOverwrite",(e,t)=>{un.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var z0,lV=p(()=>{z0=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
5
5
  `).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
6
6
  `))}}});var uV,dV=p(()=>{uV={major:4,minor:4,patch:3}});function $V(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function PSe(e){if(!L$.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return $V(r)}function ISe(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}function hSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues)),t.value[r]=e.value}function V$(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...ca(r,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function ASe(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=s4(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function OSe(e,t,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,l=c.def.type,u=c.optin==="optional",d=c.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(l==="never"){s.push(f);continue}let m=c.run({value:t[f],issues:[]},n);m instanceof Promise?e.push(m.then(b=>V$(b,r,f,t,u,d))):V$(m,r,f,t,u,d)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function gSe(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!Vm(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Ps(s,n,yo())))}),t)}function ySe(e,t,r,n){let o=e.filter(i=>i.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Ps(s,n,yo())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function pV(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Wm(e)&&Wm(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=pV(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=pV(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function bSe(e,t,r){let n=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),Vm(e))return e;let s=pV(t.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}function xSe(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function SSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues)),t.value[r]=e.value}function kSe(e,t,r,n,o){for(let i=0;i<r.length;i++){let s=e[i],a=i<n.length;if(s.issues.length){if(!a&&i>=o){t.value.length=i;break}t.issues.push(...ca(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=n.length&&(r[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}function _Se(e,t,r,n,o,i,s){e.issues.length&&(P0.has(typeof n)?r.issues.push(...ca(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map(a=>Ps(a,s,yo()))})),t.issues.length&&(P0.has(typeof n)?r.issues.push(...ca(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:t.issues.map(a=>Ps(a,s,yo()))})),r.value.set(e.value,t.value)}function wSe(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function vSe(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}function ESe(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function RSe(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function G$(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function B$(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(i=>W$(e,i,t.out,r)):W$(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(i=>W$(e,i,t.in,r)):W$(e,o,t.in,r)}}function W$(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}function TSe(e){return e.value=Object.freeze(e.value),e}function CSe(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(gk(o))}}var At,Gy,Qr,fV,mV,hV,gV,yV,bV,xV,SV,kV,_V,wV,vV,EV,RV,TV,CV,PV,IV,AV,OV,MV,DV,NV,zV,LV,K$,FV,L0,Z$,jV,UV,HV,qV,GV,BV,WV,VV,KV,ZV,$Se,JV,F0,QV,YV,XV,J$,e6,t6,r6,n6,o6,i6,s6,Q$,a6,c6,l6,u6,d6,p6,f6,m6,Y$,j0,h6,g6,y6,b6,x6,S6,k6,_6=p(()=>{q$();Uy();lV();h4();j$();ot();dV();ot();At=K("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=uV;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,a,c)=>{let l=Vm(s),u;for(let d of a){if(d._zod.def.when){if(l4(s)||!d._zod.def.when(s))continue}else if(l)continue;let f=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&c?.async===!1)throw new Hl;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==f&&(l||(l=Vm(s,f)))});else{if(s.issues.length===f)continue;l||(l=Vm(s,f))}}return u?u.then(()=>s):s},i=(s,a,c)=>{if(Vm(s))return s.aborted=!0,s;let l=o(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new Hl;return l.then(u=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>i(u,s,a)):i(l,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Hl;return c.then(l=>o(l,n,a))}return o(c,n,a)}}Jt(e,"~standard",()=>({validate:o=>{try{let i=f4(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return m4(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Gy=K("$ZodString",(e,t)=>{At.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??z4(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Qr=K("$ZodStringFormat",(e,t)=>{kk.init(e,t),Gy.init(e,t)}),fV=K("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=w4),Qr.init(e,t)}),mV=K("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=qy(n))}else t.pattern??(t.pattern=qy());Qr.init(e,t)}),hV=K("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=v4),Qr.init(e,t)}),gV=K("$ZodURL",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===O4.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),yV=K("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=E4()),Qr.init(e,t)}),bV=K("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=k4),Qr.init(e,t)}),xV=K("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=g4),Qr.init(e,t)}),SV=K("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=y4),Qr.init(e,t)}),kV=K("$ZodULID",(e,t)=>{t.pattern??(t.pattern=b4),Qr.init(e,t)}),_V=K("$ZodXID",(e,t)=>{t.pattern??(t.pattern=x4),Qr.init(e,t)}),wV=K("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=S4),Qr.init(e,t)}),vV=K("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=N4(t)),Qr.init(e,t)}),EV=K("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=M4),Qr.init(e,t)}),RV=K("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=D4(t)),Qr.init(e,t)}),TV=K("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_4),Qr.init(e,t)}),CV=K("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=R4),Qr.init(e,t),e._zod.bag.format="ipv4"}),PV=K("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=T4),Qr.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),IV=K("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=C4(t.delimiter)),Qr.init(e,t),e._zod.bag.format="mac"}),AV=K("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=P4),Qr.init(e,t)}),OV=K("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=I4),Qr.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});MV=K("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=A4),Qr.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{$V(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});DV=K("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=L$),Qr.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{PSe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),NV=K("$ZodE164",(e,t)=>{t.pattern??(t.pattern=$4),Qr.init(e,t)});zV=K("$ZodJWT",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{ISe(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),LV=K("$ZodCustomStringFormat",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),K$=K("$ZodNumber",(e,t)=>{At.init(e,t),e._zod.pattern=e._zod.bag.pattern??F$,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),FV=K("$ZodNumberFormat",(e,t)=>{W4.init(e,t),K$.init(e,t)}),L0=K("$ZodBoolean",(e,t)=>{At.init(e,t),e._zod.pattern=j4,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),Z$=K("$ZodBigInt",(e,t)=>{At.init(e,t),e._zod.pattern=L4,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),jV=K("$ZodBigIntFormat",(e,t)=>{V4.init(e,t),Z$.init(e,t)}),UV=K("$ZodSymbol",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),HV=K("$ZodUndefined",(e,t)=>{At.init(e,t),e._zod.pattern=H4,e._zod.values=new Set([void 0]),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),qV=K("$ZodNull",(e,t)=>{At.init(e,t),e._zod.pattern=U4,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),GV=K("$ZodAny",(e,t)=>{At.init(e,t),e._zod.parse=r=>r}),BV=K("$ZodUnknown",(e,t)=>{At.init(e,t),e._zod.parse=r=>r}),WV=K("$ZodNever",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),VV=K("$ZodVoid",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),KV=K("$ZodDate",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});ZV=K("$ZodArray",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>hSe(l,r,s))):hSe(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});$Se=K("$ZodObject",(e,t)=>{if(At.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=hk(()=>ASe(t));Jt(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let o=Hy,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!o(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let m=d[f],b=m._zod.optin==="optional",S=m._zod.optout==="optional",_=m._zod.run({value:l[f],issues:[]},c);_ instanceof Promise?u.push(_.then(E=>V$(E,a,f,l,b,S))):V$(_,a,f,l,b,S)}return i?OSe(u,l,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}}),JV=K("$ZodObjectJIT",(e,t)=>{$Se.init(e,t);let r=e._zod.parse,n=hk(()=>ASe(t)),o=f=>{let m=new z0(["shape","payload","ctx"]),b=n.value,S=A=>{let $=R$(A);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};m.write("const input = payload.value;");let _=Object.create(null),E=0;for(let A of b.keys)_[A]=`key_${E++}`;m.write("const newResult = {};");for(let A of b.keys){let $=_[A],M=R$(A),L=f[A],F=L?._zod?.optin==="optional",H=L?._zod?.optout==="optional";m.write(`const ${$} = ${S(A)};`),F&&H?m.write(`
@@ -164,7 +164,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
164
164
  `}function GS(e,t){return t.map(Qr).join(e)}function Vue(e){if(!Array.isArray(e)||e.length===0)throw Rt(0,"TOONL header requires fields");return e.map(t=>{let r;try{[r]=Ys(String(t),0)}catch(n){throw ed(n)}if(r==="")throw Rt(0,"TOONL header requires fields");return r})}function KU(e,t){return e!==null&&e.length===t.length&&e.every((r,n)=>r===t[n])}function JU(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw Rt(0,"TOONL continuation cadence must be positive")}function Kue(e,t,r){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&r>=e.continuationEveryBytes}function ZU(e){if(e===null||typeof e!="object"||Array.isArray(e))throw Rt(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw Rt(0,"TOONL output requires object rows");if(t.some(r=>!Xp(e[r])))throw Rt(0,"TOONL rows must be flat objects");return t}function Jue(e){return JSON.stringify([...e].sort())}function YU(e,t){let r=Jue(e),n=t.get(r);return n!==void 0?n:(t.set(r,e),e)}function Ht({delimiter:e=ss,trailer:t=!0,continuationEveryRows:r,continuationEveryBytes:n}={}){Hue(e),JU(r),JU(n);let o=null,i="",s=new Map,a=0,l=0,c=0,d=new Map,u=!1,p={continuationEveryRows:r,continuationEveryBytes:n},m=()=>o===null||!t?"":`[=${a}]
165
165
  `,h=()=>Kue(p,l,c)?(l=0,c=0,HU(e,i,!0)):"",g=k=>{t2(k,0);let _=d.get(k);if(_===void 0){if(d.size>=XU)throw Rt(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},d.set(k,_)}return _};return{push(k){if(u)throw Rt(0,"TOONL encoder is closed");let _=YU(ZU(k),s),S="";(o===null||o.length!==_.length||o.some((E,O)=>E!==_[O]))&&(S+=m(),o=_,i=GS(e,o),a=0,l=0,c=0,S+=HU(e,i));let P=o.map(E=>Yr(k[E],e));S+=h();let A=`${P.join(e)}
166
166
  `;return S+=A,a+=1,l+=1,c+=A.length,S},declareLane(k,_){if(u)throw Rt(0,"TOONL encoder is closed");let S=Vue(_),P=GS(ss,S),A=g(k);return KU(A.fields,S)?"":(A.fields=S,VU(k,P))},pushTagged(k,_){if(u)throw Rt(0,"TOONL encoder is closed");let S=g(k),P=YU(ZU(_),S.fieldsByShape),A=GS(ss,P),E=P.map(D=>Yr(_[D],ss)),O="";return KU(S.fields,P)||(S.fields=P,O+=VU(k,A)),`${O}${k}:${E.join(ss)}
167
- `},end(){return u?"":(u=!0,m())}}}var $t=jS;function ml(e){let t={app:e,version:Zue(id("__RED_BUILD_VERSION__",()=>"4.0.8")??"0.0.0-dev"),gitSha:id("__RED_BUILD_GIT_SHA__",()=>"4767ffba5cfef04cb196ab6dfe383ff3f9817243")??"unknown",buildTime:id("__RED_BUILD_TIME__",()=>"2026-08-20T09:32:28-03:00")??"unknown",bundleAsset:id("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},r=id("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=id("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Zue(e){return e.startsWith("v")?e.slice(1):e}function r2(e){return`${e.app} ${e.version} ${e.gitSha}`}function id(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var n2={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Yue=/^[a-z][a-z0-9+.-]*:\/\//i;function Que(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function Xue(e=n2){return Object.entries(e).map(([t,r])=>Que(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function epe(e){return/^-\d+(\.\d+)?$/.test(e)}function rf(e){return!(!e||e.startsWith("-")&&!epe(e))}function wy(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function o2(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>o2(r.trim())):e}function hl(e,t){switch(t){case"boolean":return tpe(e);case"number":return rpe(e);case"array":return e.split(",").map(r=>wy(r.trim()));case"string":default:return e}}function tpe(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function rpe(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function Qs(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function npe(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function qt(e,t){return{type:e,value:t}}function ope(e){let t=[],r=spe(e);if(t.push(qt("section-header","Usage:"),qt("text"," "),qt("usage-text",r),qt("newline",`
167
+ `},end(){return u?"":(u=!0,m())}}}var $t=jS;function ml(e){let t={app:e,version:Zue(id("__RED_BUILD_VERSION__",()=>"4.0.9")??"0.0.0-dev"),gitSha:id("__RED_BUILD_GIT_SHA__",()=>"8091e7743f0244689a216447fe6773333c6640af")??"unknown",buildTime:id("__RED_BUILD_TIME__",()=>"2026-08-20T09:52:47-03:00")??"unknown",bundleAsset:id("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},r=id("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=id("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Zue(e){return e.startsWith("v")?e.slice(1):e}function r2(e){return`${e.app} ${e.version} ${e.gitSha}`}function id(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var n2={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Yue=/^[a-z][a-z0-9+.-]*:\/\//i;function Que(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function Xue(e=n2){return Object.entries(e).map(([t,r])=>Que(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function epe(e){return/^-\d+(\.\d+)?$/.test(e)}function rf(e){return!(!e||e.startsWith("-")&&!epe(e))}function wy(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function o2(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>o2(r.trim())):e}function hl(e,t){switch(t){case"boolean":return tpe(e);case"number":return rpe(e);case"array":return e.split(",").map(r=>wy(r.trim()));case"string":default:return e}}function tpe(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function rpe(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function Qs(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function npe(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function qt(e,t){return{type:e,value:t}}function ope(e){let t=[],r=spe(e);if(t.push(qt("section-header","Usage:"),qt("text"," "),qt("usage-text",r),qt("newline",`
168
168
  `),qt("newline",`
169
169
  `)),e.positional&&e.positional.length>0){t.push(qt("section-header","Arguments:"),qt("newline",`
170
170
  `));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;t.push(qt("indent"," "),qt("positional-name",`<${o}>`)),n.required||t.push(qt("positional-optional"," (optional)")),t.push(qt("newline",`
@@ -335,7 +335,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
335
335
  `),aliases:n}}function PQ(e,t){let r=$h(t),n=$h(r.data),o=Array.isArray(r.errors)?r.errors.map($h):[],i=BNe(n.rateLimit,o);return{projects:e.aliases.map(({alias:a,project:l})=>{let c=qNe(n[a]);if(c!=null)return{project_label:l.project_label,outcome:"counted",depth:c,detail:`project ${JSON.stringify(l.project_label)} has ${c} item(s) matching its selector`};let d=o.find(u=>UNe(u.path,a));return i.exhausted||$Q(d)?{project_label:l.project_label,outcome:"rate-limited",depth:null,detail:`the host token's quota was spent before project ${JSON.stringify(l.project_label)} answered, so this queue has no depth rather than a depth of zero`+(i.reset_at==null?"":`; the quota resets at ${i.reset_at}`)}:{project_label:l.project_label,outcome:"unreachable",depth:null,detail:`project ${JSON.stringify(l.project_label)} could not be counted with the host token: ${bN(d?.message)||"the query returned no count for this selector"}`}}),rate_limit:i}}function NNe(e){return{version:1,fetched_at:e,request_count:0,project_count:0,batch_size:zh,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:[]}}function AQ(e,t,r){return{version:1,fetched_at:t,request_count:0,project_count:e.length,batch_size:zh,rate_limit:{remaining:null,reset_at:null,exhausted:!1},projects:e.map(n=>({project_label:n.project_label,outcome:"unconfigured",depth:null,detail:`project ${JSON.stringify(n.project_label)} was not counted because this host polls no tracker: ${r}`}))}}async function IQ(e){if(e.projects.length===0)return NNe(e.now);if(e.transport.conditionalList)return await FNe(e);let t=e.batchSize??zh,r=MNe(e.projects,t),n=[],o={remaining:null,reset_at:null,exhausted:!1};for(let i of r){let s=TQ(i,{batchSize:t});try{let a=await e.transport(s.query),l=PQ(s,a);n.push(...l.projects),o=Ih(o,l.rate_limit)}catch(a){let l=a instanceof Error?a.message:String(a),c=/rate limit|secondary rate|429/i.test(l);o=Ih(o,{remaining:null,reset_at:null,exhausted:c});for(let d of i)n.push({project_label:d.project_label,outcome:c?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(d.project_label)} answered: ${l}`})}}return{version:1,fetched_at:e.now,request_count:r.length,project_count:n.length,batch_size:t,rate_limit:o,projects:n}}var LNe={key:"redskilled queue poll",budget:"rest"};async function FNe(e){_N(e.projects);let t=e.transport.conditionalList,r=[],n={remaining:null,reset_at:null,exhausted:!1},o=0;for(let i of e.projects)try{if(i.poll==null){let c=TQ([i],{batchSize:1}),d=PQ(c,await e.transport(c.query));o+=1,r.push(...d.projects),n=Ih(n,d.rate_limit);continue}let s=await t({cacheKey:`queue:${i.project_label}:${JSON.stringify(i.poll)}`,route:"GET /repos/{owner}/{repo}/issues",parameters:{owner:i.poll.owner,repo:i.poll.repo,state:"open",labels:i.poll.labels.join(","),...i.poll.creator==null?{}:{creator:i.poll.creator}},operation:LNe});o+=s.requestCount;let a=s.data.filter(c=>!zQ(c.pull_request)),l=a.length;n=Ih(n,GNe(s.headers)),r.push({project_label:i.project_label,outcome:"counted",depth:l,detail:`project ${JSON.stringify(i.project_label)} has ${l} item(s) matching its selector`,items:jNe(a),tickets:EQ(a)})}catch(s){let a=Sl(s);n=Ih(n,{remaining:null,reset_at:a?vf(s):null,exhausted:a}),r.push({project_label:i.project_label,outcome:a?"rate-limited":"unreachable",depth:null,detail:`the queue fetch failed before project ${JSON.stringify(i.project_label)} answered: ${s instanceof Error?s.message:String(s)}`})}return{version:1,fetched_at:e.now,request_count:o,project_count:r.length,batch_size:1,rate_limit:n,projects:r}}function _N(e){if(e.length===0)throw new Error("redskilled queue discovery needs at least one registered project");let t=new Set;for(let r of e){if(typeof r.project_label!="string"||r.project_label==="")throw new Error("redskilled queue discovery needs a project label for every registered project");if(typeof r.selector!="string"||r.selector==="")throw new Error(`redskilled queue discovery needs a selector for project ${JSON.stringify(r.project_label)}: a project that names no work has no queue to discover`);if(t.has(r.project_label))throw new Error(`redskilled holds one selector per project, and ${JSON.stringify(r.project_label)} is registered twice`);t.add(r.project_label)}}function Ih(e,t){return{remaining:t.remaining==null?e.remaining:e.remaining==null?t.remaining:Math.min(e.remaining,t.remaining),reset_at:t.reset_at??e.reset_at,exhausted:e.exhausted||t.exhausted}}function GNe(e){let t=RQ(e,"x-ratelimit-remaining"),r=RQ(e,"x-ratelimit-reset");return{remaining:t,reset_at:r==null?null:new Date(r*1e3).toISOString(),exhausted:t===0}}function RQ(e,t){let r=e[t];if(typeof r!="string"&&typeof r!="number")return null;let n=Number(r);return Number.isSafeInteger(n)&&n>=0?n:null}function BNe(e,t){let r=$h(e),n=typeof r.remaining=="number"&&Number.isFinite(r.remaining)?r.remaining:null,o=typeof r.resetAt=="string"?r.resetAt:null;return{remaining:n,reset_at:o,exhausted:t.some($Q)||n===0}}function $Q(e){return e==null?!1:bN(e.type)==="RATE_LIMITED"||/rate limit/i.test(bN(e.message))}function UNe(e,t){return Array.isArray(e)&&e.includes(t)}function qNe(e){let t=$h(e);return Number.isInteger(t.issueCount)?t.issueCount:null}function $h(e){return zQ(e)?e:{}}function zQ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bN(e){return typeof e=="string"?e:""}function CQ(e,t,r){let n=e?.rate_limit;if(n==null)return t;if(n.exhausted){let i=n.reset_at==null?Number.NaN:Date.parse(n.reset_at),s=Number.isFinite(i)?i-r+1e3:t*4;return Math.min(WNe,Math.max(t,s))}let o=n.remaining;return o==null?t:o<=HNe?Math.max(t,3e4):o<=VNe?Math.max(t,2e4):t}var WNe=1e5,HNe=250,VNe=1e3;var Dv=[Ee.projectDrain,Ee.projectStop,Ee.projectStatus];function jv(e,t){let r=t.get(e.projectId)??{drainIntent:"inactive",revision:0,updates:[]};return{version:1,project_id:e.projectId,project_label:e.projectLabel,workspace_path:e.workspacePath,drain_intent:r.drainIntent,revision:r.revision,requested_target:r.target??null,requested_runner:r.runner??null,updates:[...r.updates]}}function e1e(e,t,r,n){let o=r.workers.filter(k=>k.project_label===e.projectLabel).sort((k,_)=>k.worker_id.localeCompare(_.worker_id)),i=r.registrations?.find(k=>k.project_label===e.projectLabel),s=r.demand?.projects.find(k=>k.project_label===e.projectLabel),a=i?.last_poll,l=i1e(n,a?.at),c=a==null||l==null?"unknown":l>SQ?"stale":"fresh",d=a?.outcome==="counted"?a.depth:null,u=s?.outcome??(d==null?"unknown":d===0?"queue-drained":"queued"),p=t.get(e.projectId)?.drainIntent??"inactive",m=i==null&&p==="draining",h=r.request_health,g={version:1,observed_at:n,queue:{posture:u,depth:d,target:s?.target??i?.target??null,live:o.length,wanted:s?.wanted??null,observed_at:a?.at??null,age_ms:l,freshness:c,detail:m?GQ:s?.detail??a?.detail??"the daemon has not observed this Project queue",registered:i!=null,items:[...a?.items??[]]},workers:{total:o.length,freshness:"fresh",observed_at:n,items:o.map(k=>({worker_id:k.worker_id,state:"running",started_at:k.started_at,isolated:k.isolated,warnings:[...k.warnings],base_commits_ahead:k.base_commits_ahead??null}))},adapter_health:h==null?{status:"unknown",checked_at:null,last_success_at:null,last_failure_at:null,detail:"the daemon has not published request-lane health"}:{status:h.status,checked_at:h.last_probe_at,last_success_at:h.last_success_at,last_failure_at:h.last_failure_at,detail:h.detail}};return{...jv(e,t),context:g}}async function jQ(e,t,r,n,o={}){let i=r.get(e.projectId);if(i==null&&t==="stop")return{...jv(e,r),status:"already-stopped"};let s=i??{drainIntent:"inactive",revision:0,updates:[]},a=t==="drain"?"draining":"stopped",l=o.target??s.target,c=o.runner??s.runner,d=l!==s.target||c!==s.runner;if(s.drainIntent===a&&!d){let m=t==="drain"?"already-draining":"already-stopped";return{...jv(e,r),status:m}}let u=s.revision+1,p=new Map(r);return p.set(e.projectId,{drainIntent:a,revision:u,updates:[...s.updates,{sequence:u,operation:t,drain_intent:a}],...l==null?{}:{target:l},...c==null?{}:{runner:c}}),await n(p),r.set(e.projectId,p.get(e.projectId)),{...jv(e,r),status:a}}function MQ(e){return XNe(DQ(e),"redskilled.project-control.toon")}function NQ(e){let t=Promise.resolve();return{async read(){await t;let r;try{r=await ZNe(e,"utf8")}catch(o){if(o.code==="ENOENT")return new Map;throw o}let n=s1e(r);return a1e(n)?new Map(n.projects.map(({project_id:o,state:i})=>[o,i])):new Map},replace(r){let n={version:1,projects:[...r].map(([o,i])=>({project_id:o,state:i}))};return t=t.then(async()=>{await JNe(DQ(e),{recursive:!0,mode:448});let o=`${e}.${process.pid}.${KNe()}.tmp`;await QNe(o,`${We(n)}
336
336
  `,{encoding:"utf8",mode:384}),await YNe(o,e)}),t}}}var t1e=new Map([["drain","drain"],["project_drain","drain"],["stop","stop"],["project_stop","stop"],["status","status"],["project_status","status"]]);function wN(e){let t=n1e(e).trim(),r=t.indexOf("{"),n=(r<0?t:t.slice(0,r)).trim().toLowerCase(),o=t1e.get(n.startsWith("/")?n.slice(1):n);if(o==null)return;if(r<0)return{operation:o};let i=sc(r1e(t.slice(r)));if(i==null)return{operation:o};let s=typeof i.target=="number"&&Number.isInteger(i.target)&&i.target>=0?i.target:void 0,a=typeof i.runner=="string"&&i.runner.length>0?i.runner:void 0;return{operation:o,...s==null?{}:{target:s},...a==null?{}:{runner:a}}}function r1e(e){try{return JSON.parse(e)}catch{return null}}function n1e(e){return Array.isArray(e)?e.map(t=>sc(t)).filter(t=>t?.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
337
337
  `):""}async function o1e(e,t,r,n){await e.notify(Te.client.session.update,{sessionId:t,update:{sessionUpdate:"plan",entries:[{content:r==="status"?"Observe the Project status":`${r==="drain"?"Continue":"Stop"} the Project drain`,priority:"high",status:"completed"}]}}),await e.notify(Te.client.session.update,{sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project drain intent is ${n.drain_intent} at revision ${n.revision}
338
- `}}})}async function LQ(e,t,r,n){let o=wN(e.prompt);if(o==null)return null;let i=o.operation,s=i==="status"?await n.read(r):await n.mutate(i,{target:o.target,runner:o.runner});return await o1e(t,e.sessionId,i,s),{stopReason:"end_turn",_meta:{redskills:{authority:"redskilled",projectControl:s}}}}async function FQ(e,t,r,n,o,i,s){let a=e.get(t.sessionId);if(a==null)return;let l=n.operation,c=l==="status"?await s(a.project):await jQ(a.project,l,o,i,{target:n.target,runner:n.runner});await r.notify(Er.client.session.update,{sessionId:t.sessionId,update:{sessionUpdate:"plan_update",plan:{type:"items",planId:"project-control",entries:[{content:l==="status"?"Observe the Project status":`${l==="drain"?"Continue":"Stop"} the Project drain`,priority:"high",status:"completed"}]}}}),await r.notify(Er.client.session.update,{sessionId:t.sessionId,update:{sessionUpdate:"state_update",state:"idle",stopReason:"end_turn"},_meta:{redskills:{authority:"redskilled",projectControl:c}}})}function i1e(e,t){if(t==null)return null;let r=Date.parse(e),n=Date.parse(t);return Number.isFinite(r)&&Number.isFinite(n)?Math.max(0,r-n):null}function s1e(e){let t=e.trim();if(!t)return null;try{return $t(t)}catch{try{return JSON.parse(t)}catch{return null}}}function a1e(e){let t=sc(e);return t?.version===1&&Array.isArray(t.projects)&&t.projects.every(r=>{let n=sc(r),o=sc(n?.state);return typeof n?.project_id=="string"&&(o?.drainIntent==="inactive"||o?.drainIntent==="draining"||o?.drainIntent==="stopped")&&typeof o.revision=="number"&&Array.isArray(o.updates)})}function sc(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function OQ(e){let t=sc(e);if(t==null)return{};let{target:r,runner:n}=t;if(r!==void 0&&!(typeof r=="number"&&Number.isInteger(r)&&r>=0))throw oe.invalidParams("target must be a non-negative integer");if(n!==void 0&&!(typeof n=="string"&&n.length>0))throw oe.invalidParams("runner must be a non-empty string");let o=t.registration;if(o!==void 0&&sc(o)==null)throw oe.invalidParams("registration must be an object");return{...r===void 0?{}:{target:r},...n===void 0?{}:{runner:n},...o===void 0?{}:{registration:o}}}var GQ="this Project holds no registration, so the daemon polls no queue and births no Worker for it; the drain intent is recorded and nothing acts on it";function l1e(e){return e instanceof Error&&e.name==="RedskilledProjectRegisteredError"}function c1e(e,t){return(e.registrations??[]).some(r=>r.project_label===t.projectLabel)}function BQ(e){return{mutateProjectControl:async(t,r={})=>{let n=e.scopedProject();if(t==="drain"&&r.registration!=null){if(e.registerProject==null)throw new Error("this endpoint cannot register a project: the daemon handed it no registration path");try{e.registerProject({...r.registration,project_label:n.projectLabel})}catch(i){if(!l1e(i))throw i}}let o=await jQ(n,t,e.projectControls,e.persistProjectControls,r);return t==="drain"&&!c1e(e.hostState(),n)?{...o,warning:GQ}:o},readProjectStatus:async t=>{let r=e1e(t,e.projectControls,e.hostState(),e.clock()),n=await e.readGithubCustody();return n==null?r:{...r,merge_custody:n}}}}function UQ(e){return{domain:"project",bindings:[jt(Dv[0],OQ,({params:t})=>e.mutate("drain",t)),jt(Dv[1],OQ,({params:t})=>e.mutate("stop",t)),jt(Dv[2],$v,()=>e.read())],capability:{projectControl:{version:1,methods:Dv}}}}function qQ(e){let t=r=>jY([hQ({scopedState:e.scopedState}),UQ({mutate:e.mutateProjectControl,read:e.readProjectStatus}),zv({gateway:e.githubGateway,scopedProject:e.scopedProject,onReader:e.onGithubReader}),VY({gateway:e.githubGateway,scopedProject:e.scopedProject,hostAdministration:e.hostAdministration}),fQ({tracker:mQ(e.githubGateway,e.scopedProject),admit:r}),vQ({registeredCheckout:()=>u1e(e),workerWorktrees:()=>p1e(e)}),yQ({hostAdministration:e.hostAdministration}),BY({store:e.brainStore}),gQ({store:e.memoryStore,scopedProject:e.scopedProject})]);return{v1:t(f1e(e)),v2:t(m1e(e))}}function u1e(e){let t=e.scopedProject(),r=e.hostState().registrations?.find(n=>n.project_label===t.projectLabel);if(r!=null)return{project_label:t.projectLabel,checkout_root:t.checkoutRoot,...r.trunk==null?{}:{trunk:r.trunk}}}function p1e(e){let t=e.scopedProject();return e.hostState().workers.filter(r=>r.project_label===t.projectLabel).map(r=>({worker_id:r.worker_id,path:r.workspace_path}))}function f1e(e){return async(t,r)=>{let n=r.client;return await WQ(e,{forward:()=>n.notify.bind(n),permission:o=>n.request(Te.client.session.requestPermission,o)})(t)}}function m1e(e){return async(t,r)=>{let n=r.client,o=d1e();return await WQ(e,{forward:i=>async(s,a)=>{let l=Ev(a.update,o);l!=null&&await n.notify(Er.client.session.update,{sessionId:i,update:l,_meta:a._meta})},permission:async i=>await n.request(Er.client.session.requestPermission,i)})(t)}}function WQ(e,t){return pQ({paths:e.paths,startWorker:e.startWorker,hostState:e.hostState,sessionJournal:e.sessionJournal,sessions:e.sessions,active:e.active,project:e.scopedProject,forward:t.forward,permission:(r,n)=>e.permission(r,n,t.permission)})}import{randomUUID as h1e}from"node:crypto";function vN(e){return Array.isArray(e)?e.map(r=>g1e(r)).filter(r=>r?.type==="text"&&typeof r.text=="string").map(r=>r.text).join(`
338
+ `}}})}async function LQ(e,t,r,n){let o=wN(e.prompt);if(o==null)return null;let i=o.operation,s=i==="status"?await n.read(r):await n.mutate(i,{target:o.target,runner:o.runner});return await o1e(t,e.sessionId,i,s),{stopReason:"end_turn",_meta:{redskills:{authority:"redskilled",projectControl:s}}}}async function FQ(e,t,r,n,o,i,s){let a=e.get(t.sessionId);if(a==null)return;let l=n.operation,c=l==="status"?await s(a.project):await jQ(a.project,l,o,i,{target:n.target,runner:n.runner});await r.notify(Er.client.session.update,{sessionId:t.sessionId,update:{sessionUpdate:"plan_update",plan:{type:"items",planId:"project-control",entries:[{content:l==="status"?"Observe the Project status":`${l==="drain"?"Continue":"Stop"} the Project drain`,priority:"high",status:"completed"}]}}}),await r.notify(Er.client.session.update,{sessionId:t.sessionId,update:{sessionUpdate:"state_update",state:"idle",stopReason:"end_turn"},_meta:{redskills:{authority:"redskilled",projectControl:c}}})}function i1e(e,t){if(t==null)return null;let r=Date.parse(e),n=Date.parse(t);return Number.isFinite(r)&&Number.isFinite(n)?Math.max(0,r-n):null}function s1e(e){let t=e.trim();if(!t)return null;try{return $t(t)}catch{try{return JSON.parse(t)}catch{return null}}}function a1e(e){let t=sc(e);return t?.version===1&&Array.isArray(t.projects)&&t.projects.every(r=>{let n=sc(r),o=sc(n?.state);return typeof n?.project_id=="string"&&(o?.drainIntent==="inactive"||o?.drainIntent==="draining"||o?.drainIntent==="stopped")&&typeof o.revision=="number"&&Array.isArray(o.updates)})}function sc(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function OQ(e){let t=sc(e);if(t==null)return{};let{target:r,runner:n}=t;if(r!==void 0&&!(typeof r=="number"&&Number.isInteger(r)&&r>=0))throw oe.invalidParams("target must be a non-negative integer");if(n!==void 0&&!(typeof n=="string"&&n.length>0))throw oe.invalidParams("runner must be a non-empty string");let o=t.registration;if(o!==void 0&&sc(o)==null)throw oe.invalidParams("registration must be an object");return{...r===void 0?{}:{target:r},...n===void 0?{}:{runner:n},...o===void 0?{}:{registration:o}}}var GQ="this Project holds no registration, so the daemon polls no queue and births no Worker for it; the drain intent is recorded and nothing acts on it";function l1e(e){return e instanceof Error&&e.name==="RedskilledProjectRegisteredError"}function c1e(e,t){return(e.registrations??[]).some(r=>r.project_label===t.projectLabel)}function BQ(e){return{mutateProjectControl:async(t,r={})=>{let n=e.scopedProject();if(t==="drain"&&r.registration!=null){if(e.registerProject==null)throw new Error("this endpoint cannot register a project: the daemon handed it no registration path");try{e.registerProject({...r.registration,project_label:n.projectId})}catch(i){if(!l1e(i))throw i}}let o=await jQ(n,t,e.projectControls,e.persistProjectControls,r);return t==="drain"&&!c1e(e.hostState(),n)?{...o,warning:GQ}:o},readProjectStatus:async t=>{let r=e1e(t,e.projectControls,e.hostState(),e.clock()),n=await e.readGithubCustody();return n==null?r:{...r,merge_custody:n}}}}function UQ(e){return{domain:"project",bindings:[jt(Dv[0],OQ,({params:t})=>e.mutate("drain",t)),jt(Dv[1],OQ,({params:t})=>e.mutate("stop",t)),jt(Dv[2],$v,()=>e.read())],capability:{projectControl:{version:1,methods:Dv}}}}function qQ(e){let t=r=>jY([hQ({scopedState:e.scopedState}),UQ({mutate:e.mutateProjectControl,read:e.readProjectStatus}),zv({gateway:e.githubGateway,scopedProject:e.scopedProject,onReader:e.onGithubReader}),VY({gateway:e.githubGateway,scopedProject:e.scopedProject,hostAdministration:e.hostAdministration}),fQ({tracker:mQ(e.githubGateway,e.scopedProject),admit:r}),vQ({registeredCheckout:()=>u1e(e),workerWorktrees:()=>p1e(e)}),yQ({hostAdministration:e.hostAdministration}),BY({store:e.brainStore}),gQ({store:e.memoryStore,scopedProject:e.scopedProject})]);return{v1:t(f1e(e)),v2:t(m1e(e))}}function u1e(e){let t=e.scopedProject(),r=e.hostState().registrations?.find(n=>n.project_label===t.projectLabel);if(r!=null)return{project_label:t.projectLabel,checkout_root:t.checkoutRoot,...r.trunk==null?{}:{trunk:r.trunk}}}function p1e(e){let t=e.scopedProject();return e.hostState().workers.filter(r=>r.project_label===t.projectLabel).map(r=>({worker_id:r.worker_id,path:r.workspace_path}))}function f1e(e){return async(t,r)=>{let n=r.client;return await WQ(e,{forward:()=>n.notify.bind(n),permission:o=>n.request(Te.client.session.requestPermission,o)})(t)}}function m1e(e){return async(t,r)=>{let n=r.client,o=d1e();return await WQ(e,{forward:i=>async(s,a)=>{let l=Ev(a.update,o);l!=null&&await n.notify(Er.client.session.update,{sessionId:i,update:l,_meta:a._meta})},permission:async i=>await n.request(Er.client.session.requestPermission,i)})(t)}}function WQ(e,t){return pQ({paths:e.paths,startWorker:e.startWorker,hostState:e.hostState,sessionJournal:e.sessionJournal,sessions:e.sessions,active:e.active,project:e.scopedProject,forward:t.forward,permission:(r,n)=>e.permission(r,n,t.permission)})}import{randomUUID as h1e}from"node:crypto";function vN(e){return Array.isArray(e)?e.map(r=>g1e(r)).filter(r=>r?.type==="text"&&typeof r.text=="string").map(r=>r.text).join(`
339
339
  `).trim().toLowerCase()==="/retake":!1}function HQ(e){let t=["Subordinate provider session evidence (the redskilled journal remains session truth):"];e.evidence.length===0&&t.push("- no provider artifact was reported");for(let r of e.evidence)t.push(r.reference==null?`- ${r.provider} reported no provider artifact`:`- ${r.reference} \u2014 ${r.provider}, ${r.availability}, retained as evidence`);return`${t.join(`
340
340
  `)}
341
341
  `}async function VQ(e,t,r){await e.notify(Te.client.session.update,{sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:HQ(r)}}})}async function KQ(e,t,r){await e.notify(Er.client.session.update,{sessionId:t,update:{sessionUpdate:"agent_message_chunk",messageId:h1e(),content:{type:"text",text:HQ(r)}}}),await e.notify(Er.client.session.update,{sessionId:t,update:{sessionUpdate:"state_update",state:"idle",stopReason:"end_turn"},_meta:{redskills:{authority:"redskilled"}}})}function g1e(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async function Mv(e,t,r,n,o){let i=y1e(r),s=[...e.recovery(t).entries].reverse().find(l=>l.kind==="permission"&&l.policy_key===i&&l.decision==="attached-approved"&&l.option_kind==="allow_always"),a=s==null?void 0:r.options.find(l=>l.optionId===s.option_id&&l.kind==="allow_always");if(a!=null)return await e.permission(t,r,i,"policy-pre-authorized",a.optionId),JQ(a.optionId,"policy-pre-authorized");if(n())try{let l=await Lu(o(r),b1e(),"attached ACP permission decision"),c=l.outcome,d=c.outcome==="selected"?r.options.find(u=>u.optionId===c.optionId):void 0;if(d!=null){let p=d.kind==="allow_once"||d.kind==="allow_always"?"attached-approved":"attached-denied";return await e.permission(t,r,i,p,d.optionId),JQ(d.optionId,p,l._meta)}}catch{}return await e.permission(t,r,i,"hitl-required"),{outcome:{outcome:"cancelled"},_meta:{redskills:{permissionResolution:"hitl-required",durableHitl:!0}}}}function JQ(e,t,r){return{outcome:{outcome:"selected",optionId:e},_meta:{...r??{},redskills:{...r?.redskills??{},permissionResolution:t}}}}function y1e(e){return`${e.toolCall.kind??"other"}:${e.toolCall.title??"untitled"}`}function b1e(){let e=Number.parseInt(process.env.REDSKILLED_ACP_PERMISSION_TIMEOUT_MS??"30000",10);return Number.isFinite(e)&&e>=0?e:3e4}function Bu(e,t,r){let n=Number.parseInt(process.env.REDSKILLED_ACP_WORKER_IDLE_MS??"30000",10),o=Number.isFinite(n)&&n>=0?n:3e4,i=setTimeout(()=>void Cs(e,t,r,"idle-policy"),o);i.unref(),t.idleTimer=i}async function Cs(e,t,r,n){await zs(t,"reaping",n).catch(()=>{}),Jo(e,t,r,n)}async function zs(e,t,r){await Ch(e.notify,e.publicSessionId,{event:t,workerId:e.workerId,...e.dispatch==null?{}:{dispatch:e.dispatch},...r==null?{}:{reason:r}})}async function Ch(e,t,r){await e(Te.client.session.update,{sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:""}},_meta:{redskills:{lifecycle:r}}})}function Uu(e){return e.stopReason==="cancelled"?"cancellation":e._meta?.redskills?.workflowOutcome}function Jo(e,t,r,n="cleanup"){if(t.cleaned)return;t.cleaned=!0,t.idleTimer!=null&&clearTimeout(t.idleTimer),r.get(e)===t&&r.delete(e),t.connection.close(),t.socket.destroy(),Is(t.endpoint);let o=[...r.values()].map(s=>s.workerId);(t.evidence==null?Promise.resolve():x9(k1e(t,t.evidence,n)).then(()=>{})).catch(()=>{}).then(async()=>{t.workspace!=null&&await Ah(t.workspace).catch(()=>{}),t.evidence!=null&&await E9({root:t.evidence.root,ttlMs:t.evidence.ttlMs,live:o}).catch(()=>{})}).catch(()=>{})}function k1e(e,t,r){return{root:t.root,...t.logPath==null?{}:{logPath:t.logPath},verdict:{workerId:e.workerId,outcome:r,diedAt:new Date().toISOString(),publicSessionId:e.publicSessionId,...e.workspace==null?{}:{workspacePath:e.workspace.workspacePath},...t.sessionArtifact==null?{}:{sessionArtifact:t.sessionArtifact}}}}function RN(e){return e.socket.destroyed||e.socket.readableEnded||e.socket.writableEnded||!e.socket.readable||!e.socket.writable}async function Nv(e,t,r,n){let o=t.get(e);o==null&&(o=await n(!1),t.set(e,o),await zs(o,"admission")),o.idleTimer!=null&&clearTimeout(o.idleTimer);let i=async a=>(a.cancelled&&await a.connection.agent.notify(Te.agent.session.cancel,{sessionId:a.downstreamSessionId}),a.connection.agent.request(Te.agent.session.prompt,{sessionId:a.downstreamSessionId,prompt:r.prompt,...r._meta==null?{}:{_meta:r._meta}}));try{let a=await i(o);return po().observeTurn("completed"),{worker:o,response:a}}catch(a){if(!RN(o))throw Bu(e,o,t),po().observeTurn("refused"),a;Jo(e,o,t)}let s=await n(!0);t.set(e,s),await zs(s,"replacement");try{let a=await i(s);return po().observeTurn("completed"),{worker:s,response:a}}catch(a){throw Jo(e,s,t),po().observeTurn("refused"),a}}function _1e(e){let t=e._meta?.redskills?.ticket,r=t==null||typeof t!="object"?void 0:t;if(r?.outcome!=null){let n=r.stage??r.failedStage;return`${String(r.outcome)}${n==null?"":` at ${String(n)}`}${r.detail==null?"":`: ${String(r.detail)}`}`}return`${Uu(e)??"no-workflow-outcome"} (${e.stopReason})`}function ZQ(e,t,r){if(r!=null)return e.find(n=>n.project_label===t)?.tickets?.find(n=>n.id===r)}function YQ(e,t,r,n){if(e?.prompt==null)return null;let o=Tx({argv:[e.prompt]},{worker_id:r,slot:t.index,workspace_path:t.workspace_path,...t.work_item==null?{}:{work_item:t.work_item}}).argv[0],i=Number(n?.id),s=e.trunk?.branch,a=n!=null&&Number.isInteger(i)&&i>0&&n.title!==""&&s!=null&&s!=="";return{workspacePath:t.workspace_path,prompt:o,...t.work_item==null?{}:{workItem:t.work_item},...a?{ticket:{number:i,title:n.title,labels:[...n.labels],base:s,handoff:o,worker_id:r}}:{}}}function QQ(e){return`redskilled: unattended turn ${e.event} for project ${JSON.stringify(e.project_label)}${e.work_item==null?"":` on item ${e.work_item}`}${e.worker_id==null?"":` (worker ${e.worker_id})`}${e.detail==null?"":`: ${e.detail}`}
@@ -138,7 +138,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
138
138
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
139
139
  `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Hn(s,r.start),s.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,s=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&r.sep&&!r.value){let o=[];for(let a=0;a<r.sep.length;++a){let c=r.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||r.value?(i.push(this.sourceToken),t.items.push({start:i}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):s||r.value?(i.push(this.sourceToken),t.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(qe(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(ap(r.key)&&!qe(r.sep,"newline")){let o=vt(r.start),a=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?r.sep=r.sep.concat(i,this.sourceToken):r.sep.push(this.sourceToken);else if(qe(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=vt(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||s?t.items.push({start:i,key:null,sep:[this.sourceToken]}):qe(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);s||r.value?(t.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!qe(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Hn(s,r.start),s.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||qe(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:s,sep:[]}):r.sep?this.stack.push(s):Object.assign(r,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let s=Vn(n),i=vt(s);op(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
140
140
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
141
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cp.Parser=Io});var fp=P(ur=>{"use strict";var lp=To(),xE=tr(),lr=sr(),IE=bi(),NE=L(),LE=xo(),up=No();function dp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new LE.LineCounter||null,prettyErrors:t}}function qE(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=Array.from(i.compose(s.parse(e)));if(n&&r)for(let a of o)a.errors.forEach(lr.prettifyError(e,r)),a.warnings.forEach(lr.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function pp(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=null;for(let a of i.compose(s.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new lr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(lr.prettifyError(e,r)),o.warnings.forEach(lr.prettifyError(e,r))),o}function DE(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let s=pp(e,r);if(!s)return null;if(s.warnings.forEach(i=>IE.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},r))}function FE(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let s=Math.round(r);r=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=r??t??{};if(!s)return}return NE.isDocument(e)&&!n?e.toString(r):new xE.Document(e,n,r).toString(r)}ur.parse=DE;ur.parseAllDocuments=qE;ur.parseDocument=pp;ur.stringify=FE});var qo=P(q=>{"use strict";var jE=To(),BE=tr(),UE=eo(),Lo=sr(),ME=Ft(),De=L(),VE=xe(),HE=U(),KE=Ne(),WE=Le(),zE=Un(),JE=Co(),YE=xo(),QE=No(),Kn=fp(),hp=Nt();q.Composer=jE.Composer;q.Document=BE.Document;q.Schema=UE.Schema;q.YAMLError=Lo.YAMLError;q.YAMLParseError=Lo.YAMLParseError;q.YAMLWarning=Lo.YAMLWarning;q.Alias=ME.Alias;q.isAlias=De.isAlias;q.isCollection=De.isCollection;q.isDocument=De.isDocument;q.isMap=De.isMap;q.isNode=De.isNode;q.isPair=De.isPair;q.isScalar=De.isScalar;q.isSeq=De.isSeq;q.Pair=VE.Pair;q.Scalar=HE.Scalar;q.YAMLMap=KE.YAMLMap;q.YAMLSeq=WE.YAMLSeq;q.CST=zE;q.Lexer=JE.Lexer;q.LineCounter=YE.LineCounter;q.Parser=QE.Parser;q.parse=Kn.parse;q.parseAllDocuments=Kn.parseAllDocuments;q.parseDocument=Kn.parseDocument;q.stringify=Kn.stringify;q.visit=hp.visit;q.visitAsync=hp.visitAsync});import{readFileSync as ef}from"node:fs";import{join as tf,resolve as ta}from"node:path";function Ta(e){let t={app:e,version:bf(it("__RED_BUILD_VERSION__",()=>"4.0.8")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"4767ffba5cfef04cb196ab6dfe383ff3f9817243")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-20T09:32:28-03:00")??"unknown",bundleAsset:it("__RED_BUNDLE_ASSET__",()=>"release.bundle.min.mjs")??"unknown"},r=it("__REDDB_SDK_VERSION__",()=>""),n=it("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function bf(e){return e.startsWith("v")?e.slice(1):e}function _a(e){return`${e.app} ${e.version} ${e.gitSha}`}function it(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function ka(e){return e==="single-object"?"rest":"graphql"}function va(e,t){return e==="stable-poll"?"rest":ka(t)}function Z(e){return{none:e}}function M(e,t,r,n,s,i,o){let a=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"read",cardinality:t,volatility:r,surface:o??va(r,t),budget:n,...a,...o?{only:o}:{},why:i}}function ee(e,t,r,n,s){let i=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"write",cardinality:"single-object",surface:t,budget:r,...i,why:n}}var Sa=[M("issue view","single-object","stable-poll","rest","graphql","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),M("pr view","single-object","stable-poll","rest","graphql","one pull request by number, polled per Worker per iteration"),M("repo view","single-object","stable-poll","rest","graphql","one repository's own metadata, repeatedly read while usually unchanged"),M("run view","single-object","stable-poll","rest",Z("Actions runs have no GraphQL resource"),"one Actions run repeatedly polled to terminal"),M("release view","single-object","stable-poll","rest",Z("release lookup has no GraphQL client method"),"one release by tag, repeatedly checked while usually absent or unchanged"),M("pr diff","single-object","one-shot","rest",Z("the complete diff is exposed as a REST media type"),"one pull request's diff, read once for review"),M("issue list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged issue collection; REST can make an unchanged poll free"),M("pr list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged pull-request collection; REST can make an unchanged poll free"),M("pr checks","multi-node","stable-poll","rest","graphql","check contexts are repeatedly polled while awaiting terminal state"),M("release list","multi-node","stable-poll","rest",Z("Releases has no GraphQL collection client method"),"release waits poll a usually-unchanged list"),M("run list","multi-node","stable-poll","rest",Z("Actions has no GraphQL collection client method"),"run waits poll a usually-unchanged list"),M("label list","multi-node","one-shot","graphql","rest","a label connection loaded once for the current operation"),M("issue list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"queue discovery polls usually-unchanged search results through the 30/min search connection"),M("pr list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"PR discovery polls usually-unchanged search results through the 30/min search connection"),M("search issues","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search prs","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search repos","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("api graphql","multi-node","one-shot","graphql",Z("the caller explicitly chose GraphQL"),"the caller supplies one explicit GraphQL query rather than a routed poll"),M("api rest","single-object","one-shot","rest",Z("the caller explicitly chose REST"),"the caller supplies one explicit REST path rather than a routed poll"),ee("issue create","rest","rest","the write plan POSTs to `repos/{o}/{r}/issues`; GraphQL exposes createIssue","graphql"),ee("issue edit","rest","rest","the write plan PATCHes labels and body; GraphQL exposes updateIssue","graphql"),ee("issue close","rest","rest","the write plan PATCHes issue state; GraphQL exposes closeIssue","graphql"),ee("issue reopen","graphql","graphql","gh uses reopenIssue; REST can PATCH the issue state to open","rest"),ee("issue comment","rest","rest","the write plan POSTs an issue comment; GraphQL exposes addComment","graphql"),ee("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation",Z("linked-branch creation has no REST mutation")),ee("pr create","rest","rest","the write plan POSTs a pull request; GraphQL exposes createPullRequest","graphql"),ee("pr comment","rest","rest","a pull request comment is an issue comment; GraphQL exposes addComment","graphql"),ee("pr merge","rest","rest","the default plan PUTs the merge; GraphQL exposes mergePullRequest","graphql"),ee("pr close","graphql","graphql","gh uses closePullRequest; REST can PATCH the pull request state","rest"),ee("pr edit","graphql","graphql","gh uses GraphQL mutations; REST can PATCH pull-request fields and issue labels","rest"),ee("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation",Z("GitHub exposes no REST ready-for-review mutation")),ee("pr update-branch","rest","rest","the write plan PUTs update-branch; GraphQL exposes updatePullRequestBranch","graphql"),ee("label create","rest","rest","the write plan POSTs a label; GraphQL exposes createLabel","graphql")],q_=new Map(Sa.map(e=>[e.key,e]));var ss="RED_GITHUB_REQUEST_TIMEOUT_MS",ot=class extends Error{subject;timeoutMs;constructor(t,r,n){super(`GitHub ${t} passed its ${r}ms deadline and was abandoned; raise ${ss} if this host is genuinely this slow`,n),this.name="GithubTimeoutError",this.subject=t,this.timeoutMs=r}};function Ra(e){return e instanceof ot}function _r(e=process.env){let t=e[ss];if(t===void 0||t.trim()==="")return 3e4;let r=Number(t);return!Number.isFinite(r)||r<0?3e4:Math.trunc(r)}async function kr(e,t,r){if(!Number.isFinite(t)||t<=0)return await r();let n,s=new Promise((o,a)=>{n=setTimeout(()=>a(new ot(e,t)),t),n.unref?.()}),i=Promise.resolve().then(r);i.catch(()=>{});try{return await Promise.race([i,s])}finally{n!==void 0&&clearTimeout(n)}}function is(e={}){let t=e.fetchImpl??fetch,r=e.timeoutMs??_r();return!Number.isFinite(r)||r<=0?t:async(n,s)=>{let i=AbortSignal.timeout(r),o=s?.signal??null,a=o==null?i:AbortSignal.any([o,i]),c=wf(n);try{return await kr(c,r,async()=>await t(n,{...s??{},signal:a}))}catch(l){throw Ra(l)?l:i.aborted&&o?.aborted!==!0?new ot(c,r,{cause:l}):l}}}function wf(e){let t=typeof e=="string"?e:e instanceof URL?e.href:typeof e.url=="string"?e.url:"request";try{return new URL(t).pathname}catch{return t}}var vr="off";var Aa="RED_GITHUB_BUDGET_GATE";function Ga(e){if(e===!0)return"on";if(typeof e!="string")return vr;let t=e.trim().toLowerCase();return t==="on"||t==="enabled"||t==="true"?"on":vr}function os(e){return(e??vr)==="on"}function as(e=process.env){return Ga(e[Aa])}import{execFile as Yf}from"node:child_process";import{promisify as Qf}from"node:util";var at=class extends SyntaxError{line;source;reason;constructor(t,r,n={}){super(t===0?r:`line ${t}: ${r}`,n.cause===void 0?void 0:{cause:n.cause}),this.name="ToonError",this.line=t,this.source=n.source,this.reason=r}};function ve(e,t,r={}){return new at(e,t,r)}var Ef=/(?:^\uFEFF?|\n) *#/,cs=class{value;constructor(t){if(Ef.test(t))throw new TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(t)}`);this.value=t}};function Me(e){return e instanceof cs}function Tf(e){return/^[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function _f(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw ve(0,"number is not representable in TOON");return String(e)}function Sr(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function te(e,t){if(Me(e))return e.value;if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return _f(e);if(typeof e=="string")return vf(e,t);throw ve(0,"not a primitive")}function kf(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function X(e){return kf(e)?e:Rr(e)}function vf(e,t){return ls(e,t)?Rr(e):e}function ls(e,t){return e===""||/^[ \t]|[ \t]$/.test(e)||e==="true"||e==="false"||e==="null"||Tf(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")||e.startsWith("#")}var Oa=/["\\\u0000-\u001f]/g;function Rr(e){return`"${Pa(e)}"`}function Pa(e){let t="",r=0;Oa.lastIndex=0;let n;for(;(n=Oa.exec(e))!==null;){let s=e.charCodeAt(n.index),i;s===34?i='\\"':s===92?i="\\\\":s===10?i="\\n":s===13?i="\\r":s===9?i="\\t":i=`\\u${s.toString(16).padStart(4,"0")}`,t+=e.slice(r,n.index)+i,r=n.index+1}return`${t}${e.slice(r)}`}var Ca={comma:",",tab:" ",pipe:"|"},Sf=Ca.comma;var Ar=1e3,$a=["type","kind","event"],Ve="|";var tk=Symbol("need line");var Of=/[\uD800-\uDFFF]/;function be(e){if(e===null)return null;if(Me(e))return e;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return be(t)}if(typeof e=="string")return Na(e,"string value"),e;if(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(be);if(e instanceof Set)return Array.from(e,be);if(e instanceof Map){let t={};for(let[r,n]of e)Gt(t,String(r),be(n));return t}if(J(e)){let t={};for(let r of Object.keys(e))Na(r,"object key"),Gt(t,r,be(e[r]));return t}return null}function Na(e,t){if(Of.test(e))for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n<55296||n>57343)continue;let s=e.charCodeAt(r+1);if(n<=56319&&s>=56320&&s<=57343){r+=1;continue}throw new TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${n.toString(16).toUpperCase()} at index ${r}`)}}function J(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ce(e){return e===null||Me(e)||["string","number","boolean"].includes(typeof e)}function Gt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function La(e){return encodeURIComponent(e)}function Da(e){if(!J(e))return;let t=Object.entries(e);if(t.length===0)return;let r=[];for(let[s,i]of t){let o=Cf(i);if(o===void 0)return;r.push([s,o])}let n=[];for(let[s,i]of r)Nf(n,s,i);return n.join("")}function Cf(e){if(!Array.isArray(e)||e.length===0||!e.every(J))return;let t=$f(e);if(t===void 0)return;let r=e.map(a=>a[t]),n=xf(r);if(n===void 0)return;let s=If(e,t),i=new Map;for(let a of e){let c=a[t];i.has(c)||i.set(c,[]);let l={};for(let[d,p]of Object.entries(a))if(d!==t&&!s.includes(d)&&!us(p,d,l))return;i.get(c).push(l)}let o=[];for(let a of n.cycle){let c=i.get(a),l=qf(c);if(l===void 0||l.length===0)return;o.push({fields:l,label:a,rows:c})}return{common:s,commonRows:e.map(a=>Object.fromEntries(s.map(c=>[c,a[c]]))),discriminator:t,groups:o,order:n,rows:e}}function $f(e){return $a.find(t=>e.every(r=>typeof r[t]=="string"))}function xf(e){if(!(e.length<12))for(let t=2;t<=Math.min(8,Math.floor(e.length/3));t+=1){if(e.length%t!==0)continue;let r=e.slice(0,t);if(new Set(r).size<2||!e.every((o,a)=>o===r[a%t]))continue;let n=e.length/t;if(n<3)continue;let s=e.map(La).join(","),i=`cycle(${r.map(La).join(",")})*${n}`;if(i.length<=s.length*.4)return{cycle:r,encoded:i,repeats:n}}}function If(e,t){let r=[],n=Object.keys(e[0]),s=n.indexOf(t)+1;for(let i of n.slice(s).filter(o=>o!==t)){if(!Lf(i)||!e.every(o=>Object.prototype.hasOwnProperty.call(o,i))||!e.every(o=>Sr(o[i])))break;r.push(i)}return r}function Nf(e,t,r){e.push(X(t),`:
141
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cp.Parser=Io});var fp=P(ur=>{"use strict";var lp=To(),xE=tr(),lr=sr(),IE=bi(),NE=L(),LE=xo(),up=No();function dp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new LE.LineCounter||null,prettyErrors:t}}function qE(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=Array.from(i.compose(s.parse(e)));if(n&&r)for(let a of o)a.errors.forEach(lr.prettifyError(e,r)),a.warnings.forEach(lr.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function pp(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=null;for(let a of i.compose(s.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new lr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(lr.prettifyError(e,r)),o.warnings.forEach(lr.prettifyError(e,r))),o}function DE(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let s=pp(e,r);if(!s)return null;if(s.warnings.forEach(i=>IE.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},r))}function FE(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let s=Math.round(r);r=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=r??t??{};if(!s)return}return NE.isDocument(e)&&!n?e.toString(r):new xE.Document(e,n,r).toString(r)}ur.parse=DE;ur.parseAllDocuments=qE;ur.parseDocument=pp;ur.stringify=FE});var qo=P(q=>{"use strict";var jE=To(),BE=tr(),UE=eo(),Lo=sr(),ME=Ft(),De=L(),VE=xe(),HE=U(),KE=Ne(),WE=Le(),zE=Un(),JE=Co(),YE=xo(),QE=No(),Kn=fp(),hp=Nt();q.Composer=jE.Composer;q.Document=BE.Document;q.Schema=UE.Schema;q.YAMLError=Lo.YAMLError;q.YAMLParseError=Lo.YAMLParseError;q.YAMLWarning=Lo.YAMLWarning;q.Alias=ME.Alias;q.isAlias=De.isAlias;q.isCollection=De.isCollection;q.isDocument=De.isDocument;q.isMap=De.isMap;q.isNode=De.isNode;q.isPair=De.isPair;q.isScalar=De.isScalar;q.isSeq=De.isSeq;q.Pair=VE.Pair;q.Scalar=HE.Scalar;q.YAMLMap=KE.YAMLMap;q.YAMLSeq=WE.YAMLSeq;q.CST=zE;q.Lexer=JE.Lexer;q.LineCounter=YE.LineCounter;q.Parser=QE.Parser;q.parse=Kn.parse;q.parseAllDocuments=Kn.parseAllDocuments;q.parseDocument=Kn.parseDocument;q.stringify=Kn.stringify;q.visit=hp.visit;q.visitAsync=hp.visitAsync});import{readFileSync as ef}from"node:fs";import{join as tf,resolve as ta}from"node:path";function Ta(e){let t={app:e,version:bf(it("__RED_BUILD_VERSION__",()=>"4.0.9")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"8091e7743f0244689a216447fe6773333c6640af")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-20T09:52:47-03:00")??"unknown",bundleAsset:it("__RED_BUNDLE_ASSET__",()=>"release.bundle.min.mjs")??"unknown"},r=it("__REDDB_SDK_VERSION__",()=>""),n=it("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function bf(e){return e.startsWith("v")?e.slice(1):e}function _a(e){return`${e.app} ${e.version} ${e.gitSha}`}function it(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function ka(e){return e==="single-object"?"rest":"graphql"}function va(e,t){return e==="stable-poll"?"rest":ka(t)}function Z(e){return{none:e}}function M(e,t,r,n,s,i,o){let a=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"read",cardinality:t,volatility:r,surface:o??va(r,t),budget:n,...a,...o?{only:o}:{},why:i}}function ee(e,t,r,n,s){let i=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"write",cardinality:"single-object",surface:t,budget:r,...i,why:n}}var Sa=[M("issue view","single-object","stable-poll","rest","graphql","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),M("pr view","single-object","stable-poll","rest","graphql","one pull request by number, polled per Worker per iteration"),M("repo view","single-object","stable-poll","rest","graphql","one repository's own metadata, repeatedly read while usually unchanged"),M("run view","single-object","stable-poll","rest",Z("Actions runs have no GraphQL resource"),"one Actions run repeatedly polled to terminal"),M("release view","single-object","stable-poll","rest",Z("release lookup has no GraphQL client method"),"one release by tag, repeatedly checked while usually absent or unchanged"),M("pr diff","single-object","one-shot","rest",Z("the complete diff is exposed as a REST media type"),"one pull request's diff, read once for review"),M("issue list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged issue collection; REST can make an unchanged poll free"),M("pr list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged pull-request collection; REST can make an unchanged poll free"),M("pr checks","multi-node","stable-poll","rest","graphql","check contexts are repeatedly polled while awaiting terminal state"),M("release list","multi-node","stable-poll","rest",Z("Releases has no GraphQL collection client method"),"release waits poll a usually-unchanged list"),M("run list","multi-node","stable-poll","rest",Z("Actions has no GraphQL collection client method"),"run waits poll a usually-unchanged list"),M("label list","multi-node","one-shot","graphql","rest","a label connection loaded once for the current operation"),M("issue list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"queue discovery polls usually-unchanged search results through the 30/min search connection"),M("pr list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"PR discovery polls usually-unchanged search results through the 30/min search connection"),M("search issues","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search prs","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search repos","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("api graphql","multi-node","one-shot","graphql",Z("the caller explicitly chose GraphQL"),"the caller supplies one explicit GraphQL query rather than a routed poll"),M("api rest","single-object","one-shot","rest",Z("the caller explicitly chose REST"),"the caller supplies one explicit REST path rather than a routed poll"),ee("issue create","rest","rest","the write plan POSTs to `repos/{o}/{r}/issues`; GraphQL exposes createIssue","graphql"),ee("issue edit","rest","rest","the write plan PATCHes labels and body; GraphQL exposes updateIssue","graphql"),ee("issue close","rest","rest","the write plan PATCHes issue state; GraphQL exposes closeIssue","graphql"),ee("issue reopen","graphql","graphql","gh uses reopenIssue; REST can PATCH the issue state to open","rest"),ee("issue comment","rest","rest","the write plan POSTs an issue comment; GraphQL exposes addComment","graphql"),ee("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation",Z("linked-branch creation has no REST mutation")),ee("pr create","rest","rest","the write plan POSTs a pull request; GraphQL exposes createPullRequest","graphql"),ee("pr comment","rest","rest","a pull request comment is an issue comment; GraphQL exposes addComment","graphql"),ee("pr merge","rest","rest","the default plan PUTs the merge; GraphQL exposes mergePullRequest","graphql"),ee("pr close","graphql","graphql","gh uses closePullRequest; REST can PATCH the pull request state","rest"),ee("pr edit","graphql","graphql","gh uses GraphQL mutations; REST can PATCH pull-request fields and issue labels","rest"),ee("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation",Z("GitHub exposes no REST ready-for-review mutation")),ee("pr update-branch","rest","rest","the write plan PUTs update-branch; GraphQL exposes updatePullRequestBranch","graphql"),ee("label create","rest","rest","the write plan POSTs a label; GraphQL exposes createLabel","graphql")],q_=new Map(Sa.map(e=>[e.key,e]));var ss="RED_GITHUB_REQUEST_TIMEOUT_MS",ot=class extends Error{subject;timeoutMs;constructor(t,r,n){super(`GitHub ${t} passed its ${r}ms deadline and was abandoned; raise ${ss} if this host is genuinely this slow`,n),this.name="GithubTimeoutError",this.subject=t,this.timeoutMs=r}};function Ra(e){return e instanceof ot}function _r(e=process.env){let t=e[ss];if(t===void 0||t.trim()==="")return 3e4;let r=Number(t);return!Number.isFinite(r)||r<0?3e4:Math.trunc(r)}async function kr(e,t,r){if(!Number.isFinite(t)||t<=0)return await r();let n,s=new Promise((o,a)=>{n=setTimeout(()=>a(new ot(e,t)),t),n.unref?.()}),i=Promise.resolve().then(r);i.catch(()=>{});try{return await Promise.race([i,s])}finally{n!==void 0&&clearTimeout(n)}}function is(e={}){let t=e.fetchImpl??fetch,r=e.timeoutMs??_r();return!Number.isFinite(r)||r<=0?t:async(n,s)=>{let i=AbortSignal.timeout(r),o=s?.signal??null,a=o==null?i:AbortSignal.any([o,i]),c=wf(n);try{return await kr(c,r,async()=>await t(n,{...s??{},signal:a}))}catch(l){throw Ra(l)?l:i.aborted&&o?.aborted!==!0?new ot(c,r,{cause:l}):l}}}function wf(e){let t=typeof e=="string"?e:e instanceof URL?e.href:typeof e.url=="string"?e.url:"request";try{return new URL(t).pathname}catch{return t}}var vr="off";var Aa="RED_GITHUB_BUDGET_GATE";function Ga(e){if(e===!0)return"on";if(typeof e!="string")return vr;let t=e.trim().toLowerCase();return t==="on"||t==="enabled"||t==="true"?"on":vr}function os(e){return(e??vr)==="on"}function as(e=process.env){return Ga(e[Aa])}import{execFile as Yf}from"node:child_process";import{promisify as Qf}from"node:util";var at=class extends SyntaxError{line;source;reason;constructor(t,r,n={}){super(t===0?r:`line ${t}: ${r}`,n.cause===void 0?void 0:{cause:n.cause}),this.name="ToonError",this.line=t,this.source=n.source,this.reason=r}};function ve(e,t,r={}){return new at(e,t,r)}var Ef=/(?:^\uFEFF?|\n) *#/,cs=class{value;constructor(t){if(Ef.test(t))throw new TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(t)}`);this.value=t}};function Me(e){return e instanceof cs}function Tf(e){return/^[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function _f(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw ve(0,"number is not representable in TOON");return String(e)}function Sr(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function te(e,t){if(Me(e))return e.value;if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return _f(e);if(typeof e=="string")return vf(e,t);throw ve(0,"not a primitive")}function kf(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function X(e){return kf(e)?e:Rr(e)}function vf(e,t){return ls(e,t)?Rr(e):e}function ls(e,t){return e===""||/^[ \t]|[ \t]$/.test(e)||e==="true"||e==="false"||e==="null"||Tf(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")||e.startsWith("#")}var Oa=/["\\\u0000-\u001f]/g;function Rr(e){return`"${Pa(e)}"`}function Pa(e){let t="",r=0;Oa.lastIndex=0;let n;for(;(n=Oa.exec(e))!==null;){let s=e.charCodeAt(n.index),i;s===34?i='\\"':s===92?i="\\\\":s===10?i="\\n":s===13?i="\\r":s===9?i="\\t":i=`\\u${s.toString(16).padStart(4,"0")}`,t+=e.slice(r,n.index)+i,r=n.index+1}return`${t}${e.slice(r)}`}var Ca={comma:",",tab:" ",pipe:"|"},Sf=Ca.comma;var Ar=1e3,$a=["type","kind","event"],Ve="|";var tk=Symbol("need line");var Of=/[\uD800-\uDFFF]/;function be(e){if(e===null)return null;if(Me(e))return e;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return be(t)}if(typeof e=="string")return Na(e,"string value"),e;if(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(be);if(e instanceof Set)return Array.from(e,be);if(e instanceof Map){let t={};for(let[r,n]of e)Gt(t,String(r),be(n));return t}if(J(e)){let t={};for(let r of Object.keys(e))Na(r,"object key"),Gt(t,r,be(e[r]));return t}return null}function Na(e,t){if(Of.test(e))for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n<55296||n>57343)continue;let s=e.charCodeAt(r+1);if(n<=56319&&s>=56320&&s<=57343){r+=1;continue}throw new TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${n.toString(16).toUpperCase()} at index ${r}`)}}function J(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ce(e){return e===null||Me(e)||["string","number","boolean"].includes(typeof e)}function Gt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function La(e){return encodeURIComponent(e)}function Da(e){if(!J(e))return;let t=Object.entries(e);if(t.length===0)return;let r=[];for(let[s,i]of t){let o=Cf(i);if(o===void 0)return;r.push([s,o])}let n=[];for(let[s,i]of r)Nf(n,s,i);return n.join("")}function Cf(e){if(!Array.isArray(e)||e.length===0||!e.every(J))return;let t=$f(e);if(t===void 0)return;let r=e.map(a=>a[t]),n=xf(r);if(n===void 0)return;let s=If(e,t),i=new Map;for(let a of e){let c=a[t];i.has(c)||i.set(c,[]);let l={};for(let[d,p]of Object.entries(a))if(d!==t&&!s.includes(d)&&!us(p,d,l))return;i.get(c).push(l)}let o=[];for(let a of n.cycle){let c=i.get(a),l=qf(c);if(l===void 0||l.length===0)return;o.push({fields:l,label:a,rows:c})}return{common:s,commonRows:e.map(a=>Object.fromEntries(s.map(c=>[c,a[c]]))),discriminator:t,groups:o,order:n,rows:e}}function $f(e){return $a.find(t=>e.every(r=>typeof r[t]=="string"))}function xf(e){if(!(e.length<12))for(let t=2;t<=Math.min(8,Math.floor(e.length/3));t+=1){if(e.length%t!==0)continue;let r=e.slice(0,t);if(new Set(r).size<2||!e.every((o,a)=>o===r[a%t]))continue;let n=e.length/t;if(n<3)continue;let s=e.map(La).join(","),i=`cycle(${r.map(La).join(",")})*${n}`;if(i.length<=s.length*.4)return{cycle:r,encoded:i,repeats:n}}}function If(e,t){let r=[],n=Object.keys(e[0]),s=n.indexOf(t)+1;for(let i of n.slice(s).filter(o=>o!==t)){if(!Lf(i)||!e.every(o=>Object.prototype.hasOwnProperty.call(o,i))||!e.every(o=>Sr(o[i])))break;r.push(i)}return r}function Nf(e,t,r){e.push(X(t),`:
142
142
  `),e.push(" order: ",te(r.order.encoded,Ve),`
143
143
  `),e.push(" discriminator: ",te(r.discriminator,Ve),`
144
144
  `),e.push(" rows: ",String(r.rows.length),`
@@ -25,7 +25,7 @@ var PP=Object.create;var Vu=Object.defineProperty;var IP=Object.getOwnPropertyDe
25
25
  `;return E+=k,a+=1,c+=1,l+=k.length,E},declareLane(b,y){if(d)throw Y(0,"TOONL encoder is closed");let E=gL(y),w=Sd(zt,E),k=g(b);return rw(k.fields,E)?"":(k.fields=E,tw(b,w))},pushTagged(b,y){if(d)throw Y(0,"TOONL encoder is closed");let E=g(b),w=ow(sw(y),E.fieldsByShape),k=Sd(zt,w),S=w.map(C=>ve(y[C],zt)),T="";return rw(E.fields,w)||(E.fields=w,T+=tw(b,k)),`${T}${b}:${S.join(zt)}
26
26
  `},end(){return d?"":(d=!0,f())}}}var iw,aw,cw,G4,N4,uw=_(()=>{Kt();ga();so();nn();iw=[zt,"|"," "],aw=8,cw=/^[A-Za-z0-9_-]+$/,G4=new TextEncoder,N4=new TextDecoder});var z,J=_(()=>{ga();so();Yb();Kt();ro();Qb();so();Zs();nn();ma();ga();Xb();uw();z=bd});function _L(e){return e==="no-op"?0:e==="usage"?2:1}function ee(e){return Buffer.from(`${M(Rd(e))}
27
27
  `)}function Rd(e){let t={command:e.command,category:e.category,exit_code:e.exitCode??_L(e.category),error:e.error,help:[e.help]};return e.validFlags&&e.validFlags.length>0&&(t.valid_flags=[...e.validFlags]),e.diagnostics&&(t.diagnostics=EL(e.diagnostics,3)),t}function qe(e,t,r){let s=([r,t].find(i=>i.trim())??"").trim(),o=s.toLowerCase();return/\bgh\b/.test(e)&&Qy(s)?{command:e,category:"transient",error:oo(s)||"GitHub API rate limit exceeded",help:Yy,diagnostics:s}:/\bgh\b/.test(e)&&(o.includes("gh_token")||o.includes("not logged in")||o.includes("authentication"))?{command:e,category:"real-error",error:oo(s)||"GitHub authentication failed",help:"gh auth login",diagnostics:s}:o.includes("not a git repository")?{command:e,category:"real-error",error:oo(s)||"not a git repository",help:"git status",diagnostics:s}:o.includes("repository not found")||o.includes("could not resolve host")?{command:e,category:"real-error",error:oo(s)||"repository is unavailable",help:e.startsWith("gh ")?"gh repo view":"git remote -v",diagnostics:s}:{command:e,category:"real-error",error:oo(s)||"command failed",help:`${e} --help`,diagnostics:s}}function dw(e,t,r,n){return ee({command:e,category:"usage",error:`unknown flag: ${t}`,help:n,validFlags:r})}function oo(e){return e.split(/\r?\n/,1)[0]?.trim()??""}function EL(e,t){return e.split(/\r?\n/).slice(0,t).join(`
28
- `).trim()}var bt=_(()=>{"use strict";Xy();J()});function Ea(e){let t={app:e,version:IL(Jn("__RED_BUILD_VERSION__",()=>"4.0.8")??"0.0.0-dev"),gitSha:Jn("__RED_BUILD_GIT_SHA__",()=>"4767ffba5cfef04cb196ab6dfe383ff3f9817243")??"unknown",buildTime:Jn("__RED_BUILD_TIME__",()=>"2026-08-20T09:32:28-03:00")??"unknown",bundleAsset:Jn("__RED_BUNDLE_ASSET__",()=>"rsp-core.bundle.min.mjs")??"unknown"},r=Jn("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=Jn("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function IL(e){return e.startsWith("v")?e.slice(1):e}function _w(e){return`${e.app} ${e.version} ${e.gitSha}`}function Jn(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Td=_(()=>{});import{isAbsolute as LL,join as Yt,resolve as xd}from"node:path";function DL(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function kw(e){return Yt(DL(e),Ew)}function Sw(e){return Yt(kw(e),"state")}function Rw(e){return Yt(kw(e),"tmp")}function ce(e){return Yt(Sw(e),"rsp")}function $L(e){return Yt(Sw(e),"red-skills.rdb")}function FL(e){return Yt(Rw(e),"red-skills.rdb")}function xw(e,t){let r=$L(e);if(t(r))return r;let n=FL(e);if(t(n))throw ML();return r}function ML(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}function Ow(e){return Yt(Rw(e),"waits")}function Aw(e){let t=e.overrideEnvVars??Od;for(let n of t){let s=e.env[n];if(s)return LL(s)?s:xd(e.startDir,s)}let r=xd(e.startDir);for(;;){if(e.exists(Yt(r,Ew)))return r;let n=Yt(r,".."),s=xd(n);if(s===r)break;r=s}return e.startDir}var Ew,GL,NL,Od,vw,Tw,et=_(()=>{Ew=".red",GL="MEMORY_ROOT",NL="RED_BRAIN_ROOT",Od=[GL,NL];vw=".red/state/red-skills.rdb";Tw=".red/tmp/red-skills.rdb"});function ge(e){return M(e)}var BL,jL,x3,Qt=_(()=>{J();et();BL=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],jL=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.toon",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.toon",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.toon",kind:"toon"}],x3=[...BL,...jL]});function io(e){let{values:t,rest:r}=Xr(e,{query:Cw.query},Pw);return{argv:r,query:t.query?.trim()||void 0}}function Iw(e){let{values:t,rest:r}=Xr(e,Cw,Pw);return{argv:r,query:t.query?.trim()||void 0,full:t.full===!0}}function qL(e,t){if(!t)return!0;let r=Ad(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(n=>r.includes(n))}function Le(e,t){return t?e.filter(r=>qL(r,t)):[...e]}function Xt(e,t){return Cd(e,t,{includeLegacyHelp:!0})}function Cd(e,t,r={}){let n=t.filter(Boolean);return n.length===0?e:{...e,...r.includeLegacyHelp?{help:n}:{},next_steps:n}}function Ad(e){return Array.isArray(e)?e.map(Ad).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(Ad).join(" "):String(e??"")}var Cw,Pw,ao=_(()=>{"use strict";Yu();Cw={query:{kind:"value",coerce:e=>e},full:{kind:"boolean"}},Pw={stopAtSeparator:!1}});var Aa={};se(Aa,{DEFAULT_RSP_MAX_OVERHEAD_MS:()=>ka,DEFAULT_RSP_MAX_SELF_STATE_BYTES:()=>Sa,DEFAULT_RSP_OVERHEAD_CEILING:()=>Zt,DEFAULT_RSP_OVERHEAD_CONSECUTIVE_BREACHES:()=>va,DEFAULT_RSP_OVERHEAD_COOLDOWN_MS:()=>Ta,DEFAULT_RSP_OVERHEAD_NET_LOSS_FLOOR_BYTES:()=>Ra,RSP_OVERHEAD_FAMILIES:()=>zL,RSP_OVERHEAD_LEDGER_FILE:()=>Nw,RSP_OVERHEAD_SCHEMA_VERSION:()=>Dw,classifyOverheadSample:()=>Ld,noteChildProcessMs:()=>Fw,noteSelfStateBytesRead:()=>lo,overheadCounters:()=>Fd,overheadFamilyDisabled:()=>YL,overheadHealth:()=>wr,overheadLedgerPath:()=>Gd,overheadMsOf:()=>$w,overheadTelemetryFields:()=>xa,readOverheadLedger:()=>co,readSelfStateFile:()=>Oa,readSelfStateFileSync:()=>ZL,recordOverheadSample:()=>Nd,resetOverheadCounters:()=>XL,resetOverheadLedger:()=>QL,startChildProcessTimer:()=>tt});import{existsSync as UL,mkdirSync as HL,readFileSync as Lw,renameSync as WL,writeFileSync as VL}from"node:fs";import{readFile as JL}from"node:fs/promises";import{dirname as KL,join as Gw}from"node:path";function $w(e){let t=e.wrapperMs-e.childMs;return Number.isFinite(t)?Math.max(0,Id(t)):0}function Ld(e,t=Zt){let r=$w(e),n=[];return r>t.maxOverheadMs&&n.push("wall-clock-ceiling"),e.selfStateBytesRead>t.maxSelfStateBytes&&n.push("self-state-byte-ceiling"),e.selfStateBytesRead>t.netLossFloorBytes&&e.selfStateBytesRead>e.bytesSaved&&n.push("overhead-exceeds-savings"),{overhead_ms:r,breached:n.length>0,reasons:n}}function xa(e,t=Zt){let r=Ld(e,t);return{wrapper_ms:Id(e.wrapperMs),overhead_ms:r.overhead_ms,child_ms:Id(Math.max(0,e.childMs)),self_state_bytes_read:Math.max(0,Math.trunc(e.selfStateBytesRead)),bytes_saved:Math.max(0,Math.trunc(e.bytesSaved)),overhead_breached:r.breached,overhead_breach_reasons:r.reasons.join(",")}}function Gd(e){return Gw(ce(e),Nw)}function co(e){try{let t=Lw(Gd(e),"utf8"),r=nG(t);if(sG(r))return r}catch{}return{version:1,families:{}}}function Nd(e,t,r=Zt,n=Date.now()){let s=co(e),o=Ld(t,r),i=s.families[t.family]??rG(t.family,n),a=Md(i,n)?Mw(i):i,c=o.breached?a.consecutive_breaches+1:0,l={...a,family:t.family,invocations:a.invocations+1,breaches:a.breaches+(o.breached?1:0),consecutive_breaches:c,breached:o.breached,reasons:o.reasons,last_overhead_ms:o.overhead_ms,last_self_state_bytes_read:Math.max(0,Math.trunc(t.selfStateBytesRead)),last_bytes_saved:Math.max(0,Math.trunc(t.bytesSaved)),updated_at:new Date(n).toISOString()};return o.breached?c>=r.consecutiveBreaches&&(l.disabled=!0,l.disabled_at=new Date(n).toISOString(),l.disabled_until=new Date(n+r.cooldownMs).toISOString(),l.disabled_reason=eG(t.family,c,o,r)):(l.disabled=!1,l.disabled_at=null,l.disabled_until=null,l.disabled_reason=null),s.families[t.family]=l,Bw(e,s),l}function YL(e,t,r=Date.now()){let n=co(e).families[t];return!n?.disabled||Md(n,r)?null:n}function QL(e,t){let r=co(e);return t?delete r.families[t]:r.families={},Bw(e,r),r}function wr(e,t=Zt,r=Date.now()){let n=Object.values(co(e).families).map(a=>Md(a,r)?Mw(a):a).sort((a,c)=>a.family.localeCompare(c.family)),s=n.filter(a=>a.disabled),o=n.filter(a=>a.consecutive_breaches>0),i=s.length>0||o.length>0?"red":"green";return{schema_version:Dw,verdict:i,summary:tG(i,s,o),ceiling:t,breaching_families:o,disabled_families:s,families:n}}function lo(e){Number.isFinite(e)&&e>0&&(Dd+=e)}function Fw(e){Number.isFinite(e)&&e>0&&($d+=e)}function Fd(){return{selfStateBytesRead:Dd,childMs:$d}}function XL(){Dd=0,$d=0}function tt(){let e=process.hrtime.bigint(),t=!1;return()=>{t||(t=!0,Fw(Number(process.hrtime.bigint()-e)/1e6))}}async function Oa(e){let t=await JL(e,"utf8");return lo(Buffer.byteLength(t)),t}function ZL(e){let t=Lw(e,"utf8");return lo(Buffer.byteLength(t)),t}function eG(e,t,r,n){let s=r.reasons.map(o=>o==="wall-clock-ceiling"?`added ${r.overhead_ms}ms > ${n.maxOverheadMs}ms`:o==="self-state-byte-ceiling"?`self-state read > ${n.maxSelfStateBytes}B`:"self-state read exceeded bytes saved").join("; ");return`rsp ${e} exceeded its overhead ceiling on ${t} consecutive invocations (${s}); wrapper self-disabled, commands pass through raw`}function tG(e,t,r){if(e==="green")return"every wrapper family is inside its overhead ceiling";let n=[];return t.length>0&&n.push(`self-disabled: ${t.map(s=>`${s.family} (${s.reasons.join(",")||"ceiling"})`).join(", ")}`),r.length>0&&n.push(`breaching: ${r.map(s=>`${s.family} x${s.consecutive_breaches}`).join(", ")}`),n.join("; ")}function Md(e,t){if(!e.disabled||!e.disabled_until)return!1;let r=Date.parse(e.disabled_until);return Number.isFinite(r)&&r<=t}function Mw(e){return{...e,disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,consecutive_breaches:0,breached:!1,reasons:[]}}function rG(e,t){return{family:e,invocations:0,breaches:0,consecutive_breaches:0,breached:!1,reasons:[],disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,last_overhead_ms:0,last_self_state_bytes_read:0,last_bytes_saved:0,updated_at:new Date(t).toISOString()}}function Bw(e,t){try{let r=Gd(e);if(!UL(Gw(e,".red")))return;HL(KL(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`;VL(n,`${M(t)}
28
+ `).trim()}var bt=_(()=>{"use strict";Xy();J()});function Ea(e){let t={app:e,version:IL(Jn("__RED_BUILD_VERSION__",()=>"4.0.9")??"0.0.0-dev"),gitSha:Jn("__RED_BUILD_GIT_SHA__",()=>"8091e7743f0244689a216447fe6773333c6640af")??"unknown",buildTime:Jn("__RED_BUILD_TIME__",()=>"2026-08-20T09:52:47-03:00")??"unknown",bundleAsset:Jn("__RED_BUNDLE_ASSET__",()=>"rsp-core.bundle.min.mjs")??"unknown"},r=Jn("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=Jn("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function IL(e){return e.startsWith("v")?e.slice(1):e}function _w(e){return`${e.app} ${e.version} ${e.gitSha}`}function Jn(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Td=_(()=>{});import{isAbsolute as LL,join as Yt,resolve as xd}from"node:path";function DL(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function kw(e){return Yt(DL(e),Ew)}function Sw(e){return Yt(kw(e),"state")}function Rw(e){return Yt(kw(e),"tmp")}function ce(e){return Yt(Sw(e),"rsp")}function $L(e){return Yt(Sw(e),"red-skills.rdb")}function FL(e){return Yt(Rw(e),"red-skills.rdb")}function xw(e,t){let r=$L(e);if(t(r))return r;let n=FL(e);if(t(n))throw ML();return r}function ML(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}function Ow(e){return Yt(Rw(e),"waits")}function Aw(e){let t=e.overrideEnvVars??Od;for(let n of t){let s=e.env[n];if(s)return LL(s)?s:xd(e.startDir,s)}let r=xd(e.startDir);for(;;){if(e.exists(Yt(r,Ew)))return r;let n=Yt(r,".."),s=xd(n);if(s===r)break;r=s}return e.startDir}var Ew,GL,NL,Od,vw,Tw,et=_(()=>{Ew=".red",GL="MEMORY_ROOT",NL="RED_BRAIN_ROOT",Od=[GL,NL];vw=".red/state/red-skills.rdb";Tw=".red/tmp/red-skills.rdb"});function ge(e){return M(e)}var BL,jL,x3,Qt=_(()=>{J();et();BL=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],jL=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.toon",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.toon",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.toon",kind:"toon"}],x3=[...BL,...jL]});function io(e){let{values:t,rest:r}=Xr(e,{query:Cw.query},Pw);return{argv:r,query:t.query?.trim()||void 0}}function Iw(e){let{values:t,rest:r}=Xr(e,Cw,Pw);return{argv:r,query:t.query?.trim()||void 0,full:t.full===!0}}function qL(e,t){if(!t)return!0;let r=Ad(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(n=>r.includes(n))}function Le(e,t){return t?e.filter(r=>qL(r,t)):[...e]}function Xt(e,t){return Cd(e,t,{includeLegacyHelp:!0})}function Cd(e,t,r={}){let n=t.filter(Boolean);return n.length===0?e:{...e,...r.includeLegacyHelp?{help:n}:{},next_steps:n}}function Ad(e){return Array.isArray(e)?e.map(Ad).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(Ad).join(" "):String(e??"")}var Cw,Pw,ao=_(()=>{"use strict";Yu();Cw={query:{kind:"value",coerce:e=>e},full:{kind:"boolean"}},Pw={stopAtSeparator:!1}});var Aa={};se(Aa,{DEFAULT_RSP_MAX_OVERHEAD_MS:()=>ka,DEFAULT_RSP_MAX_SELF_STATE_BYTES:()=>Sa,DEFAULT_RSP_OVERHEAD_CEILING:()=>Zt,DEFAULT_RSP_OVERHEAD_CONSECUTIVE_BREACHES:()=>va,DEFAULT_RSP_OVERHEAD_COOLDOWN_MS:()=>Ta,DEFAULT_RSP_OVERHEAD_NET_LOSS_FLOOR_BYTES:()=>Ra,RSP_OVERHEAD_FAMILIES:()=>zL,RSP_OVERHEAD_LEDGER_FILE:()=>Nw,RSP_OVERHEAD_SCHEMA_VERSION:()=>Dw,classifyOverheadSample:()=>Ld,noteChildProcessMs:()=>Fw,noteSelfStateBytesRead:()=>lo,overheadCounters:()=>Fd,overheadFamilyDisabled:()=>YL,overheadHealth:()=>wr,overheadLedgerPath:()=>Gd,overheadMsOf:()=>$w,overheadTelemetryFields:()=>xa,readOverheadLedger:()=>co,readSelfStateFile:()=>Oa,readSelfStateFileSync:()=>ZL,recordOverheadSample:()=>Nd,resetOverheadCounters:()=>XL,resetOverheadLedger:()=>QL,startChildProcessTimer:()=>tt});import{existsSync as UL,mkdirSync as HL,readFileSync as Lw,renameSync as WL,writeFileSync as VL}from"node:fs";import{readFile as JL}from"node:fs/promises";import{dirname as KL,join as Gw}from"node:path";function $w(e){let t=e.wrapperMs-e.childMs;return Number.isFinite(t)?Math.max(0,Id(t)):0}function Ld(e,t=Zt){let r=$w(e),n=[];return r>t.maxOverheadMs&&n.push("wall-clock-ceiling"),e.selfStateBytesRead>t.maxSelfStateBytes&&n.push("self-state-byte-ceiling"),e.selfStateBytesRead>t.netLossFloorBytes&&e.selfStateBytesRead>e.bytesSaved&&n.push("overhead-exceeds-savings"),{overhead_ms:r,breached:n.length>0,reasons:n}}function xa(e,t=Zt){let r=Ld(e,t);return{wrapper_ms:Id(e.wrapperMs),overhead_ms:r.overhead_ms,child_ms:Id(Math.max(0,e.childMs)),self_state_bytes_read:Math.max(0,Math.trunc(e.selfStateBytesRead)),bytes_saved:Math.max(0,Math.trunc(e.bytesSaved)),overhead_breached:r.breached,overhead_breach_reasons:r.reasons.join(",")}}function Gd(e){return Gw(ce(e),Nw)}function co(e){try{let t=Lw(Gd(e),"utf8"),r=nG(t);if(sG(r))return r}catch{}return{version:1,families:{}}}function Nd(e,t,r=Zt,n=Date.now()){let s=co(e),o=Ld(t,r),i=s.families[t.family]??rG(t.family,n),a=Md(i,n)?Mw(i):i,c=o.breached?a.consecutive_breaches+1:0,l={...a,family:t.family,invocations:a.invocations+1,breaches:a.breaches+(o.breached?1:0),consecutive_breaches:c,breached:o.breached,reasons:o.reasons,last_overhead_ms:o.overhead_ms,last_self_state_bytes_read:Math.max(0,Math.trunc(t.selfStateBytesRead)),last_bytes_saved:Math.max(0,Math.trunc(t.bytesSaved)),updated_at:new Date(n).toISOString()};return o.breached?c>=r.consecutiveBreaches&&(l.disabled=!0,l.disabled_at=new Date(n).toISOString(),l.disabled_until=new Date(n+r.cooldownMs).toISOString(),l.disabled_reason=eG(t.family,c,o,r)):(l.disabled=!1,l.disabled_at=null,l.disabled_until=null,l.disabled_reason=null),s.families[t.family]=l,Bw(e,s),l}function YL(e,t,r=Date.now()){let n=co(e).families[t];return!n?.disabled||Md(n,r)?null:n}function QL(e,t){let r=co(e);return t?delete r.families[t]:r.families={},Bw(e,r),r}function wr(e,t=Zt,r=Date.now()){let n=Object.values(co(e).families).map(a=>Md(a,r)?Mw(a):a).sort((a,c)=>a.family.localeCompare(c.family)),s=n.filter(a=>a.disabled),o=n.filter(a=>a.consecutive_breaches>0),i=s.length>0||o.length>0?"red":"green";return{schema_version:Dw,verdict:i,summary:tG(i,s,o),ceiling:t,breaching_families:o,disabled_families:s,families:n}}function lo(e){Number.isFinite(e)&&e>0&&(Dd+=e)}function Fw(e){Number.isFinite(e)&&e>0&&($d+=e)}function Fd(){return{selfStateBytesRead:Dd,childMs:$d}}function XL(){Dd=0,$d=0}function tt(){let e=process.hrtime.bigint(),t=!1;return()=>{t||(t=!0,Fw(Number(process.hrtime.bigint()-e)/1e6))}}async function Oa(e){let t=await JL(e,"utf8");return lo(Buffer.byteLength(t)),t}function ZL(e){let t=Lw(e,"utf8");return lo(Buffer.byteLength(t)),t}function eG(e,t,r,n){let s=r.reasons.map(o=>o==="wall-clock-ceiling"?`added ${r.overhead_ms}ms > ${n.maxOverheadMs}ms`:o==="self-state-byte-ceiling"?`self-state read > ${n.maxSelfStateBytes}B`:"self-state read exceeded bytes saved").join("; ");return`rsp ${e} exceeded its overhead ceiling on ${t} consecutive invocations (${s}); wrapper self-disabled, commands pass through raw`}function tG(e,t,r){if(e==="green")return"every wrapper family is inside its overhead ceiling";let n=[];return t.length>0&&n.push(`self-disabled: ${t.map(s=>`${s.family} (${s.reasons.join(",")||"ceiling"})`).join(", ")}`),r.length>0&&n.push(`breaching: ${r.map(s=>`${s.family} x${s.consecutive_breaches}`).join(", ")}`),n.join("; ")}function Md(e,t){if(!e.disabled||!e.disabled_until)return!1;let r=Date.parse(e.disabled_until);return Number.isFinite(r)&&r<=t}function Mw(e){return{...e,disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,consecutive_breaches:0,breached:!1,reasons:[]}}function rG(e,t){return{family:e,invocations:0,breaches:0,consecutive_breaches:0,breached:!1,reasons:[],disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,last_overhead_ms:0,last_self_state_bytes_read:0,last_bytes_saved:0,updated_at:new Date(t).toISOString()}}function Bw(e,t){try{let r=Gd(e);if(!UL(Gw(e,".red")))return;HL(KL(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`;VL(n,`${M(t)}
29
29
  `,{encoding:"utf8",mode:384}),WL(n,r)}catch{}}function nG(e){try{return JSON.parse(e)}catch{return z(e)}}function sG(e){return!Pd(e)||e.version!==1||!Pd(e.families)?!1:Object.values(e.families).every(oG)}function oG(e){return Pd(e)&&typeof e.family=="string"&&typeof e.consecutive_breaches=="number"&&typeof e.disabled=="boolean"}function Pd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Id(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var Nw,Dw,ka,Sa,Ra,va,Ta,zL,Zt,Dd,$d,we=_(()=>{"use strict";et();J();Nw="overhead-budget.toon",Dw="red.rsp.overhead.v1",ka=250,Sa=1024*1024,Ra=64*1024,va=3,Ta=6*60*60*1e3,zL=["git","gh","gh-api-json","vitest","cargo","cat","exec","proxy"],Zt={maxOverheadMs:ka,maxSelfStateBytes:Sa,netLossFloorBytes:Ra,consecutiveBreaches:va,cooldownMs:Ta};Dd=0,$d=0});function Uw(e){return e.trimStart().startsWith("{")?"json":"toon"}function jd(e){let t=0;for(;e[t]===`
30
30
  `||e[t]==="\r";)t+=1;let r=e.slice(t);if(r==="")return null;let n=Uw(r);if(n==="json"){let o=r.indexOf(`
31
31
  `);return o<0?null:{frame:r.slice(0,o),dialect:n,rest:r.slice(o+1)}}let s=r.indexOf(`
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
3
  import{spawn as L}from"node:child_process";import{isUtf8 as te}from"node:buffer";async function _(e,n=t=>t){let t=[],r=[];return e.stdout?.on("data",i=>t.push(Buffer.from(i))),e.stderr?.on("data",i=>r.push(Buffer.from(i))),await new Promise(i=>{let c=!1,o=async(a,s)=>{if(c)return;c=!0;let l=Buffer.concat(t),u=l;if(l.length>0&&te(l))try{u=await n(l)}catch{}if(process.stdout.write(u),process.stderr.write(Buffer.concat(r)),s){process.kill(process.pid,s),i(128);return}i(a??0)};e.once("error",a=>{r.push(Buffer.from(`${a instanceof Error?a.message:String(a)}
4
- `)),o(127,null)}),e.once("close",(a,s)=>void o(a,s))})}var re=new Set(["dashboard","stats","gains","show","git","gh","vitest","cargo","cat","exec","wait","doctor","status","sweep","setup","mcp","shell-init","server","warm-resident","gh-api-json","hook"]);function R(e){let n=e[0];if(n==="--full"||n==="--brief"||n==="--terse")return e[1]!=="--"||!e[2]?null:{kind:"argv",argv:[...e.slice(2)],level:n.slice(2)};if(!n||n.startsWith("-"))return n!=="--"||!e[1]?null:{kind:"argv",argv:[...e.slice(1)],level:"automatic"};if(n==="proxy"){if(process.env.RSP_PROXY_FAIL_INTERNAL==="1")return null;let t=e.indexOf("--"),r=t>=0?e.slice(1,t):[];if(r.some(a=>a!=="--full"&&a!=="--brief"&&a!=="--terse"))return null;let i=t>=0?e.slice(t+1):e.slice(1);if(i.length!==1||!i[0]?.trim())return null;let c=i[0];if(ie(c))return null;let o=r.includes("--terse")?"terse":r.includes("--brief")?"brief":r.includes("--full")?"full":"automatic";return{kind:"shell",commandLine:c,level:o}}return re.has(n)?null:{kind:"argv",argv:[...e],level:"automatic"}}async function I(e,n){let t=e.kind==="argv"?L(e.argv[0],e.argv.slice(1),{stdio:["inherit","pipe","pipe"]}):L(e.commandLine,{shell:!0,stdio:["inherit","pipe","pipe"]});return await _(t,n)}function ie(e){return/(?:^|&&|\|\||[;|])\s*(?:(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+|env)\s+)*(?:git\s+(?:status|log|diff|show|blame|branch\s+-av)(?:\s|$)|gh\s+(?:pr|issue|run)\s+(?:list|view)(?:\s|$)|vitest(?:\s|$)|cargo\s+test(?:\s|$)|(?:cat|head|tail)\s+)/.test(e)}function F(e){let n={app:e,version:oe(x("__RED_BUILD_VERSION__",()=>"4.0.8")??"0.0.0-dev"),gitSha:x("__RED_BUILD_GIT_SHA__",()=>"4767ffba5cfef04cb196ab6dfe383ff3f9817243")??"unknown",buildTime:x("__RED_BUILD_TIME__",()=>"2026-08-20T09:32:28-03:00")??"unknown",bundleAsset:x("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},t=x("__REDDB_SDK_VERSION__",()=>"1.23.1"),r=x("__REDDB_BINARY_TAG__",()=>"v1.23.1");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function oe(e){return e.startsWith("v")?e.slice(1):e}function N(e){return`${e.app} ${e.version} ${e.gitSha}`}function x(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var D={"=":"data",":=":{to:"data",typed:!0},":":"meta"},se=/^[a-z][a-z0-9+.-]*:\/\//i;function ce(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function ae(e=D){return Object.entries(e).map(([n,t])=>ce(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function ue(e){return/^-\d+(\.\d+)?$/.test(e)}function O(e){return!(!e||e.startsWith("-")&&!ue(e))}function k(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function P(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>P(t.trim())):e}function w(e,n){switch(n){case"boolean":return le(e);case"number":return fe(e);case"array":return e.split(",").map(t=>k(t.trim()));case"string":default:return e}}function le(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function fe(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function b(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function de(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function d(e,n){return{type:e,value:n}}function pe(e){let n=[],t=he(e);if(n.push(d("section-header","Usage:"),d("text"," "),d("usage-text",t),d("newline",`
4
+ `)),o(127,null)}),e.once("close",(a,s)=>void o(a,s))})}var re=new Set(["dashboard","stats","gains","show","git","gh","vitest","cargo","cat","exec","wait","doctor","status","sweep","setup","mcp","shell-init","server","warm-resident","gh-api-json","hook"]);function R(e){let n=e[0];if(n==="--full"||n==="--brief"||n==="--terse")return e[1]!=="--"||!e[2]?null:{kind:"argv",argv:[...e.slice(2)],level:n.slice(2)};if(!n||n.startsWith("-"))return n!=="--"||!e[1]?null:{kind:"argv",argv:[...e.slice(1)],level:"automatic"};if(n==="proxy"){if(process.env.RSP_PROXY_FAIL_INTERNAL==="1")return null;let t=e.indexOf("--"),r=t>=0?e.slice(1,t):[];if(r.some(a=>a!=="--full"&&a!=="--brief"&&a!=="--terse"))return null;let i=t>=0?e.slice(t+1):e.slice(1);if(i.length!==1||!i[0]?.trim())return null;let c=i[0];if(ie(c))return null;let o=r.includes("--terse")?"terse":r.includes("--brief")?"brief":r.includes("--full")?"full":"automatic";return{kind:"shell",commandLine:c,level:o}}return re.has(n)?null:{kind:"argv",argv:[...e],level:"automatic"}}async function I(e,n){let t=e.kind==="argv"?L(e.argv[0],e.argv.slice(1),{stdio:["inherit","pipe","pipe"]}):L(e.commandLine,{shell:!0,stdio:["inherit","pipe","pipe"]});return await _(t,n)}function ie(e){return/(?:^|&&|\|\||[;|])\s*(?:(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+|env)\s+)*(?:git\s+(?:status|log|diff|show|blame|branch\s+-av)(?:\s|$)|gh\s+(?:pr|issue|run)\s+(?:list|view)(?:\s|$)|vitest(?:\s|$)|cargo\s+test(?:\s|$)|(?:cat|head|tail)\s+)/.test(e)}function F(e){let n={app:e,version:oe(x("__RED_BUILD_VERSION__",()=>"4.0.9")??"0.0.0-dev"),gitSha:x("__RED_BUILD_GIT_SHA__",()=>"8091e7743f0244689a216447fe6773333c6640af")??"unknown",buildTime:x("__RED_BUILD_TIME__",()=>"2026-08-20T09:52:47-03:00")??"unknown",bundleAsset:x("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},t=x("__REDDB_SDK_VERSION__",()=>"1.23.1"),r=x("__REDDB_BINARY_TAG__",()=>"v1.23.1");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function oe(e){return e.startsWith("v")?e.slice(1):e}function N(e){return`${e.app} ${e.version} ${e.gitSha}`}function x(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var D={"=":"data",":=":{to:"data",typed:!0},":":"meta"},se=/^[a-z][a-z0-9+.-]*:\/\//i;function ce(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function ae(e=D){return Object.entries(e).map(([n,t])=>ce(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function ue(e){return/^-\d+(\.\d+)?$/.test(e)}function O(e){return!(!e||e.startsWith("-")&&!ue(e))}function k(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function P(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>P(t.trim())):e}function w(e,n){switch(n){case"boolean":return le(e);case"number":return fe(e);case"array":return e.split(",").map(t=>k(t.trim()));case"string":default:return e}}function le(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function fe(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function b(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function de(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function d(e,n){return{type:e,value:n}}function pe(e){let n=[],t=he(e);if(n.push(d("section-header","Usage:"),d("text"," "),d("usage-text",t),d("newline",`
5
5
  `),d("newline",`
6
6
  `)),e.positional&&e.positional.length>0){n.push(d("section-header","Arguments:"),d("newline",`
7
7
  `));for(let r of e.positional)if(r.description){let i=r.variadic?`${r.name}...`:r.name;n.push(d("indent"," "),d("positional-name",`<${i}>`)),r.required||n.push(d("positional-optional"," (optional)")),n.push(d("newline",`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/red-skills",
3
- "version": "4.0.8",
3
+ "version": "4.0.9",
4
4
  "description": "RedSkills core npm package: compatibility bin shims, marketplace manifests, host generators, and non-plugin supporting runtimes. Plugin bundles ship in @reddb-io/red-skills-<plugin> packages (ADR 0146).",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",