@reddb-io/red-skills 3.19.4 → 3.19.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,7 +50,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
50
50
  `:`[${n[c]}\r
51
51
  ]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Ya(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}=Xa(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}=Ka(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function Kv(e,t){if(t.mapStrategy==="record")return Ya(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 Xv(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 Yv(e){return e.target==="openAi"?void 0:{not:je({...e,currentPath:[...e.currentPath,"not"]})}}function Qv(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Yi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function tb(e,t){if(t.target==="openApi3")return eb(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Yi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Yi[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 eb(e,t)}var eb=(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 rb(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:Yi[e.innerType._def.typeName],nullable:!0}:{type:[Yi[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 nb(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",cf(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 ob(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=mO(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=pO(e,t);return s!==void 0&&(n.additionalProperties=s),n}function pO(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 mO(e){try{return e.isOptional()}catch{return!0}}var ib=(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 sb=(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 ab(e,t){return W(e.type._def,t)}function cb(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 ub(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 lb(e){return{not:je(e)}}function db(e){return je(e)}var fb=(e,t)=>W(e.innerType._def,t);var pb=(e,t,r)=>{switch(t){case E.ZodString:return Xa(e,r);case E.ZodNumber:return nb(e,r);case E.ZodObject:return ob(e,r);case E.ZodBigInt:return Lv(e,r);case E.ZodBoolean:return Fv();case E.ZodDate:return uf(e,r);case E.ZodUndefined:return lb(r);case E.ZodNull:return Qv(r);case E.ZodArray:return Zv(e,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return tb(e,r);case E.ZodIntersection:return Wv(e,r);case E.ZodTuple:return ub(e,r);case E.ZodRecord:return Ya(e,r);case E.ZodLiteral:return Jv(e,r);case E.ZodEnum:return Bv(e);case E.ZodNativeEnum:return Xv(e);case E.ZodNullable:return rb(e,r);case E.ZodOptional:return ib(e,r);case E.ZodMap:return Kv(e,r);case E.ZodSet:return cb(e,r);case E.ZodLazy:return()=>e.getter()._def;case E.ZodPromise:return ab(e,r);case E.ZodNaN:case E.ZodNever:return Yv(r);case E.ZodEffects:return Hv(e,r);case E.ZodAny:return je(r);case E.ZodUnknown:return db(r);case E.ZodDefault:return Vv(e,r);case E.ZodBranded:return Ka(e,r);case E.ZodReadonly:return fb(e,r);case E.ZodCatch:return Uv(e,r);case E.ZodPipeline:return sb(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!==Dv)return a}if(n&&!r){let a=hO(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=pb(e,e.typeName,t),s=typeof i=="function"?W(i(),t):i;if(s&&gO(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var hO=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ga(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}},gO=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var ff=(e,t)=>{let r=qv(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 yO(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function pf(e,t){return At(e)?Md(e,{target:yO(t?.target),io:t?.pipeStrategy??"input"}):ff(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function mf(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ka(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function hf(e,t){let r=Wr(e,t);if(!r.success)throw r.error;return r.data}var _O=6e4,Qa=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(Ca,r=>{this._oncancel(r)}),this.setNotificationHandler(Ma,r=>{this._onprogress(r)}),this.setRequestHandler(ja,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Na,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(Da,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(Aa,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(Za,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),Ui(i)||kv(i)?this._onresponse(i):Wd(i)?this._onrequest(i,s):Sv(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=wv(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),Ui(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(Ui(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),Ui(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(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));let R=T instanceof Z?T:new Z(U.RequestTimeout,String(T));l(R)};this._responseHandlers.set(h,T=>{if(!n?.signal?.aborted){if(T instanceof Error)return l(T);try{let R=Wr(r,T.result);R.success?u(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let y=n?.timeout??_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=R=>{let I=this._responseHandlers.get(h);I?I(R):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(R=>{this._cleanupTimeout(h),l(R)})}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},Ia,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},qa,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},zv,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=mf(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=hf(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=mf(t);this._notificationHandlers.set(n,o=>{let i=hf(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"&&Wd(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=Ji.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=Ji.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Kr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function mb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function hb(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];mb(s)&&mb(i)?r[o]={...s,...i}:r[o]=i}return r}var s$=Qs(tm(),1),a$=Qs(i$(),1);function w1(){let e=new s$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,a$.default)(e),e}var Mc=class{constructor(t){this._ajv=t??w1()}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 Nc=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},Xi,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},Oo,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 c$(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 u$(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 Ic=class extends Qa{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ki.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 Mc,this.setRequestHandler(Kd,n=>this._oninitialize(n)),this.setNotificationHandler(Xd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(of,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=Ki.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Nc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=hb(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(Eo,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(Wa,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){u$(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&c$(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:_v.includes(r)?r:Hd,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"},Oa)}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},sf,r):this.request({method:"sampling/createMessage",params:t},Xi,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},Oo,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},Oo,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},af,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 d$=Symbol.for("mcp.completable");function um(e){return!!e&&typeof e=="object"&&d$ in e}function f$(e){return e[d$]?.complete}var l$;(function(e){e.Completable="McpCompletable"})(l$||(l$={}));var x1=/^[A-Za-z0-9._-]{1,128}$/;function $1(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"),!x1.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 S1(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 lm(e){let t=$1(e);return S1(e,t.warnings),t.isValid}var Dc=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 Ac=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 Ic(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Dc(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(Ba)),this.server.assertCanSetRequestHandler(sn(Eo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ba,()=>({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=Po(r.inputSchema);return o?pf(o,{strictUnions:!0,pipeStrategy:"input"}):k1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Po(r.outputSchema);o&&(n.outputSchema=pf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Eo,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=Po(t.inputSchema)??t.inputSchema,s=await $a(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=Sa(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=Po(t.outputSchema),i=await $a(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=Sa(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(Ja)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ja,async t=>{switch(t.params.ref.type){case"ref/prompt":return Mv(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Nv(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(!um(i))return zs;let s=f$(i);if(!s)return zs;let a=await s(t.params.argument.value,t.params.context);return m$(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 m$(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(La)),this.server.assertCanSetRequestHandler(sn(Fa)),this.server.assertCanSetRequestHandler(sn(Ua)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(La,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(Fa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ua,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(Va)),this.server.assertCanSetRequestHandler(sn(Ha)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Va,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?P1(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ha,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=Po(n.argsSchema),i=await $a(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=Sa(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:Vn(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=Vn(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 um(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,u){lm(t);let l={title:r,description:n,inputSchema:p$(o),outputSchema:p$(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"&&lm(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=Vn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Vn(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(dm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!dm(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 k1={type:"object",properties:{}};function h$(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function g$(e){return"_def"in e||"_zod"in e||h$(e)}function dm(e){return typeof e!="object"||e===null||g$(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(h$)}function p$(e){if(e){if(dm(e))return Vn(e);if(!g$(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function P1(e){let t=Jr(e);return t?Object.entries(t).map(([r,n])=>{let o=J_(n),i=G_(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=ka(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function m$(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var zs={completion:{values:[],hasMore:!1}};import _$ from"node:process";var qc=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),T1(r)}clear(){this._buffer=void 0}};function T1(e){return Pv.parse(JSON.parse(e))}function y$(e){return JSON.stringify(e)+`
53
- `}var Zc=class{constructor(t=_$.stdin,r=_$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new qc,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=y$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function fm(e){let t={app:e,version:z1(Ko("__RED_BUILD_VERSION__",()=>"3.19.4")??"0.0.0-dev"),gitSha:Ko("__RED_BUILD_GIT_SHA__",()=>"cbccb19444939c8c3079b4d6bbfe0109662235e7")??"unknown",buildTime:Ko("__RED_BUILD_TIME__",()=>"2026-08-18T09:27:29-03:00")??"unknown",bundleAsset:Ko("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Ko("__REDDB_SDK_VERSION__",()=>""),n=Ko("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function z1(e){return e.startsWith("v")?e.slice(1):e}function v$(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ko(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var b$={"=":"data",":=":{to:"data",typed:!0},":":"meta"},R1=/^[a-z][a-z0-9+.-]*:\/\//i;function E1(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 O1(e=b$){return Object.entries(e).map(([t,r])=>E1(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function C1(e){return/^-\d+(\.\d+)?$/.test(e)}function Rs(e){return!(!e||e.startsWith("-")&&!C1(e))}function Lc(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 w$(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=>w$(r.trim())):e}function ro(e,t){switch(t){case"boolean":return j1(e);case"number":return M1(e);case"array":return e.split(",").map(r=>Lc(r.trim()));default:return e}}function j1(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function M1(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 N1(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 I1(e){let t=[],r=A1(e);if(t.push($e("section-header","Usage:"),$e("text"," "),$e("usage-text",r),$e("newline",`
53
+ `}var Zc=class{constructor(t=_$.stdin,r=_$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new qc,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=y$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function fm(e){let t={app:e,version:z1(Ko("__RED_BUILD_VERSION__",()=>"3.19.5")??"0.0.0-dev"),gitSha:Ko("__RED_BUILD_GIT_SHA__",()=>"626a28473edeee992fcf6425dedbca84448343fd")??"unknown",buildTime:Ko("__RED_BUILD_TIME__",()=>"2026-08-18T09:41:17-03:00")??"unknown",bundleAsset:Ko("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Ko("__REDDB_SDK_VERSION__",()=>""),n=Ko("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function z1(e){return e.startsWith("v")?e.slice(1):e}function v$(e){return`${e.app} ${e.version} ${e.gitSha}`}function Ko(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var b$={"=":"data",":=":{to:"data",typed:!0},":":"meta"},R1=/^[a-z][a-z0-9+.-]*:\/\//i;function E1(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 O1(e=b$){return Object.entries(e).map(([t,r])=>E1(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function C1(e){return/^-\d+(\.\d+)?$/.test(e)}function Rs(e){return!(!e||e.startsWith("-")&&!C1(e))}function Lc(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 w$(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=>w$(r.trim())):e}function ro(e,t){switch(t){case"boolean":return j1(e);case"number":return M1(e);case"array":return e.split(",").map(r=>Lc(r.trim()));default:return e}}function j1(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function M1(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 N1(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 I1(e){let t=[],r=A1(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 $e,readFileSync as Bt,writeFileSync as Kt}from"node:fs";import{dirname as zt,resolve as U}from"node:path";function L(e){let t={app:e,version:Se(b("__RED_BUILD_VERSION__",()=>"3.19.4")??"0.0.0-dev"),gitSha:b("__RED_BUILD_GIT_SHA__",()=>"cbccb19444939c8c3079b4d6bbfe0109662235e7")??"unknown",buildTime:b("__RED_BUILD_TIME__",()=>"2026-08-18T09:27:29-03:00")??"unknown",bundleAsset:b("__RED_BUNDLE_ASSET__",()=>"opencode-host.bundle.min.mjs")??"unknown"},o=b("__REDDB_SDK_VERSION__",()=>""),n=b("__REDDB_BINARY_TAG__",()=>"");return o&&(t.reddbSdkVersion=o),n&&(t.reddbBinaryTag=n),t}function Se(e){return e.startsWith("v")?e.slice(1):e}function V(e){return`${e.app} ${e.version} ${e.gitSha}`}function b(e,t){try{let o=t();return typeof o=="string"&&o.length>0?o:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var X={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Pe=/^[a-z][a-z0-9+.-]*:\/\//i;function Ee(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 Re(e=X){return Object.entries(e).map(([t,o])=>Ee(t,o)).sort((t,o)=>o.separator.length-t.separator.length)}function Ce(e){return/^-\d+(\.\d+)?$/.test(e)}function O(e){return!(!e||e.startsWith("-")&&!Ce(e))}function R(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 Q(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(o=>Q(o.trim())):e}function x(e,t){switch(t){case"boolean":return Ae(e);case"number":return Ie(e);case"array":return e.split(",").map(o=>R(o.trim()));case"string":default:return e}}function Ae(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function Ie(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 w(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function je(e,t={}){return e.map(o=>{let n=t[o.type];return n?n(o.value):o.value}).join("")}function m(e,t){return{type:e,value:t}}function Fe(e){let t=[],o=Ne(e);if(t.push(m("section-header","Usage:"),m("text"," "),m("usage-text",o),m("newline",`
2
+ import{mkdirSync as $e,readFileSync as Bt,writeFileSync as Kt}from"node:fs";import{dirname as zt,resolve as U}from"node:path";function L(e){let t={app:e,version:Se(b("__RED_BUILD_VERSION__",()=>"3.19.5")??"0.0.0-dev"),gitSha:b("__RED_BUILD_GIT_SHA__",()=>"626a28473edeee992fcf6425dedbca84448343fd")??"unknown",buildTime:b("__RED_BUILD_TIME__",()=>"2026-08-18T09:41:17-03:00")??"unknown",bundleAsset:b("__RED_BUNDLE_ASSET__",()=>"opencode-host.bundle.min.mjs")??"unknown"},o=b("__REDDB_SDK_VERSION__",()=>""),n=b("__REDDB_BINARY_TAG__",()=>"");return o&&(t.reddbSdkVersion=o),n&&(t.reddbBinaryTag=n),t}function Se(e){return e.startsWith("v")?e.slice(1):e}function V(e){return`${e.app} ${e.version} ${e.gitSha}`}function b(e,t){try{let o=t();return typeof o=="string"&&o.length>0?o:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var X={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Pe=/^[a-z][a-z0-9+.-]*:\/\//i;function Ee(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 Re(e=X){return Object.entries(e).map(([t,o])=>Ee(t,o)).sort((t,o)=>o.separator.length-t.separator.length)}function Ce(e){return/^-\d+(\.\d+)?$/.test(e)}function O(e){return!(!e||e.startsWith("-")&&!Ce(e))}function R(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 Q(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(o=>Q(o.trim())):e}function x(e,t){switch(t){case"boolean":return Ae(e);case"number":return Ie(e);case"array":return e.split(",").map(o=>R(o.trim()));case"string":default:return e}}function Ae(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function Ie(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 w(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function je(e,t={}){return e.map(o=>{let n=t[o.type];return n?n(o.value):o.value}).join("")}function m(e,t){return{type:e,value:t}}function Fe(e){let t=[],o=Ne(e);if(t.push(m("section-header","Usage:"),m("text"," "),m("usage-text",o),m("newline",`
3
3
  `),m("newline",`
4
4
  `)),e.positional&&e.positional.length>0){t.push(m("section-header","Arguments:"),m("newline",`
5
5
  `));for(let n of e.positional)if(n.description){let s=n.variadic?`${n.name}...`:n.name;t.push(m("indent"," "),m("positional-name",`<${s}>`)),n.required||t.push(m("positional-optional"," (optional)")),t.push(m("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 hht=Object.create;var n6=Object.defineProperty;var ght=Object.getOwnPropertyDescriptor;var yht=Object.getOwnPropertyNames;var bht=Object.getPrototypeOf,xht=Object.prototype.hasOwnProperty;var Wn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var p=(t,e)=>()=>(t&&(e=t(t=0)),e);var ee=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Mn=(t,e)=>{for(var r in e)n6(t,r,{get:e[r],enumerable:!0})},kht=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yht(e))!xht.call(t,o)&&o!==r&&n6(t,o,{get:()=>e[o],enumerable:!(n=ght(e,o))||n.enumerable});return t};var hd=(t,e,r)=>(r=t!=null?hht(bht(t)):{},kht(e||!t||!t.__esModule?n6(r,"default",{value:t,enumerable:!0}):r,t));function o6(t){let e={app:t,version:_ht(xw("__RED_BUILD_VERSION__",()=>"3.19.4")??"0.0.0-dev"),gitSha:xw("__RED_BUILD_GIT_SHA__",()=>"cbccb19444939c8c3079b4d6bbfe0109662235e7")??"unknown",buildTime:xw("__RED_BUILD_TIME__",()=>"2026-08-18T09:27:29-03:00")??"unknown",bundleAsset:xw("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=xw("__REDDB_SDK_VERSION__",()=>""),n=xw("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function _ht(t){return t.startsWith("v")?t.slice(1):t}function Bwe(t){return`${t.app} ${t.version} ${t.gitSha}`}function xw(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var i6=p(()=>{});var Ne,gr,s6,a6=p(()=>{Ne={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},gr={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},s6={cancel_request:"$/cancel_request"}});function K(t,e,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(t))return;a._zod.traits.add(t),e(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:t});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(t)}),Object.defineProperty(s,"name",{value:t}),s}function To(t){return t&&Object.assign(_b,t),_b}var qwe,c6,l6,iu,_h,_b,wb=p(()=>{c6=Object.freeze({status:"aborted"});l6=Symbol("zod_brand"),iu=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},_h=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(qwe=globalThis).__zod_globalConfig??(qwe.__zod_globalConfig={});_b=globalThis.__zod_globalConfig});var Te={};Mn(Te,{BIGINT_FORMAT_RANGES:()=>x6,Class:()=>d6,NUMBER_FORMAT_RANGES:()=>b6,aborted:()=>Eh,allowsEval:()=>m6,assert:()=>Tht,assertEqual:()=>Sht,assertIs:()=>Eht,assertNever:()=>Rht,assertNotEqual:()=>vht,assignProp:()=>Sh,base64ToUint8Array:()=>Kwe,base64urlToUint8Array:()=>Wht,cached:()=>_w,captureStackTrace:()=>cD,cleanEnum:()=>Hht,cleanRegex:()=>Y0,clone:()=>js,cloneDef:()=>Pht,createTransparentProxy:()=>Dht,defineLazy:()=>sr,esc:()=>aD,escapeRegex:()=>Kc,explicitlyAborted:()=>k6,extend:()=>zht,finalizeIssue:()=>Fs,floatSafeRemainder:()=>p6,getElementAtPath:()=>Aht,getEnumValues:()=>Q0,getLengthableOrigin:()=>tT,getParsedType:()=>Mht,getSizableOrigin:()=>eT,hexToUint8Array:()=>qht,isObject:()=>Sb,isPlainObject:()=>vh,issue:()=>ww,joinValues:()=>ne,jsonStringifyReplacer:()=>kw,merge:()=>Fht,mergeDefs:()=>rf,normalizeParams:()=>Oe,nullish:()=>wh,numKeys:()=>$ht,objectClone:()=>Cht,omit:()=>Lht,optionalKeys:()=>y6,parsedType:()=>Re,partial:()=>Uht,pick:()=>Nht,prefixIssues:()=>ba,primitiveTypes:()=>g6,promiseAllObject:()=>Iht,propertyKeyTypes:()=>X0,randomString:()=>Oht,required:()=>Ght,safeExtend:()=>jht,shallowClone:()=>h6,slugify:()=>f6,stringifyPrimitive:()=>Ee,uint8ArrayToBase64:()=>Zwe,uint8ArrayToBase64url:()=>Bht,uint8ArrayToHex:()=>Vht,unwrapMessage:()=>J0});function Sht(t){return t}function vht(t){return t}function Eht(t){}function Rht(t){throw new Error("Unexpected value in exhaustive check")}function Tht(t){}function Q0(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function ne(t,e="|"){return t.map(r=>Ee(r)).join(e)}function kw(t,e){return typeof e=="bigint"?e.toString():e}function _w(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function wh(t){return t==null}function Y0(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function p6(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function sr(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==Vwe)return n===void 0&&(n=Vwe,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Cht(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Sh(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function rf(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function Pht(t){return rf(t._zod.def)}function Aht(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Iht(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function Oht(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function aD(t){return JSON.stringify(t)}function f6(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Sb(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vh(t){if(Sb(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Sb(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function h6(t){return vh(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function $ht(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Kc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function js(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Oe(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Dht(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ee(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function y6(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Nht(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=rf(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return Sh(this,"shape",s),s},checks:[]});return js(t,i)}function Lht(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=rf(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return Sh(this,"shape",s),s},checks:[]});return js(t,i)}function zht(t,e){if(!vh(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let i=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=rf(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return Sh(this,"shape",i),i}});return js(t,o)}function jht(t,e){if(!vh(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=rf(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Sh(this,"shape",n),n}});return js(t,r)}function Fht(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=rf(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Sh(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return js(t,r)}function Uht(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=rf(e._zod.def,{get shape(){let a=e._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]=t?new t({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=t?new t({type:"optional",innerType:a[l]}):a[l];return Sh(this,"shape",c),c},checks:[]});return js(e,s)}function Ght(t,e,r){let n=rf(e._zod.def,{get shape(){let o=e._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 t({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new t({type:"nonoptional",innerType:o[s]});return Sh(this,"shape",i),i}});return js(e,n)}function Eh(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function k6(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function ba(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function J0(t){return typeof t=="string"?t:t?.message}function Fs(t,e,r){let n=t.message?t.message:J0(t.inst?._zod.def?.error?.(t))??J0(e?.error?.(t))??J0(r.customError?.(t))??J0(r.localeError?.(t))??"Invalid input",{inst:o,continue:i,input:s,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}function eT(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function tT(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Re(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function ww(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Hht(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Kwe(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Zwe(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function Wht(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return Kwe(e+r)}function Bht(t){return Zwe(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qht(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function Vht(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Vwe,cD,m6,Mht,X0,g6,b6,x6,d6,ct=p(()=>{wb();Vwe=Symbol("evaluating");cD="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};m6=_w(()=>{if(_b.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});Mht=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},X0=new Set(["string","number","symbol"]),g6=new Set(["string","number","bigint","boolean","symbol","undefined"]);b6={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]},x6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};d6=class{constructor(...e){}}});function nT(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function oT(t,e=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(e(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(e(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(t),r}function _6(t,e=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(e(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(e(c)),d++}}};return n(t),r}function Qwe(t){let e=[],r=t.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function w6(t){let e=[],r=[...t.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${Qwe(n.path)}`);return e.join(`
3
+ var hht=Object.create;var n6=Object.defineProperty;var ght=Object.getOwnPropertyDescriptor;var yht=Object.getOwnPropertyNames;var bht=Object.getPrototypeOf,xht=Object.prototype.hasOwnProperty;var Wn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var p=(t,e)=>()=>(t&&(e=t(t=0)),e);var ee=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Mn=(t,e)=>{for(var r in e)n6(t,r,{get:e[r],enumerable:!0})},kht=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yht(e))!xht.call(t,o)&&o!==r&&n6(t,o,{get:()=>e[o],enumerable:!(n=ght(e,o))||n.enumerable});return t};var hd=(t,e,r)=>(r=t!=null?hht(bht(t)):{},kht(e||!t||!t.__esModule?n6(r,"default",{value:t,enumerable:!0}):r,t));function o6(t){let e={app:t,version:_ht(xw("__RED_BUILD_VERSION__",()=>"3.19.5")??"0.0.0-dev"),gitSha:xw("__RED_BUILD_GIT_SHA__",()=>"626a28473edeee992fcf6425dedbca84448343fd")??"unknown",buildTime:xw("__RED_BUILD_TIME__",()=>"2026-08-18T09:41:17-03:00")??"unknown",bundleAsset:xw("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=xw("__REDDB_SDK_VERSION__",()=>""),n=xw("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function _ht(t){return t.startsWith("v")?t.slice(1):t}function Bwe(t){return`${t.app} ${t.version} ${t.gitSha}`}function xw(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var i6=p(()=>{});var Ne,gr,s6,a6=p(()=>{Ne={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},gr={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},s6={cancel_request:"$/cancel_request"}});function K(t,e,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(t))return;a._zod.traits.add(t),e(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:t});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(t)}),Object.defineProperty(s,"name",{value:t}),s}function To(t){return t&&Object.assign(_b,t),_b}var qwe,c6,l6,iu,_h,_b,wb=p(()=>{c6=Object.freeze({status:"aborted"});l6=Symbol("zod_brand"),iu=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},_h=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(qwe=globalThis).__zod_globalConfig??(qwe.__zod_globalConfig={});_b=globalThis.__zod_globalConfig});var Te={};Mn(Te,{BIGINT_FORMAT_RANGES:()=>x6,Class:()=>d6,NUMBER_FORMAT_RANGES:()=>b6,aborted:()=>Eh,allowsEval:()=>m6,assert:()=>Tht,assertEqual:()=>Sht,assertIs:()=>Eht,assertNever:()=>Rht,assertNotEqual:()=>vht,assignProp:()=>Sh,base64ToUint8Array:()=>Kwe,base64urlToUint8Array:()=>Wht,cached:()=>_w,captureStackTrace:()=>cD,cleanEnum:()=>Hht,cleanRegex:()=>Y0,clone:()=>js,cloneDef:()=>Pht,createTransparentProxy:()=>Dht,defineLazy:()=>sr,esc:()=>aD,escapeRegex:()=>Kc,explicitlyAborted:()=>k6,extend:()=>zht,finalizeIssue:()=>Fs,floatSafeRemainder:()=>p6,getElementAtPath:()=>Aht,getEnumValues:()=>Q0,getLengthableOrigin:()=>tT,getParsedType:()=>Mht,getSizableOrigin:()=>eT,hexToUint8Array:()=>qht,isObject:()=>Sb,isPlainObject:()=>vh,issue:()=>ww,joinValues:()=>ne,jsonStringifyReplacer:()=>kw,merge:()=>Fht,mergeDefs:()=>rf,normalizeParams:()=>Oe,nullish:()=>wh,numKeys:()=>$ht,objectClone:()=>Cht,omit:()=>Lht,optionalKeys:()=>y6,parsedType:()=>Re,partial:()=>Uht,pick:()=>Nht,prefixIssues:()=>ba,primitiveTypes:()=>g6,promiseAllObject:()=>Iht,propertyKeyTypes:()=>X0,randomString:()=>Oht,required:()=>Ght,safeExtend:()=>jht,shallowClone:()=>h6,slugify:()=>f6,stringifyPrimitive:()=>Ee,uint8ArrayToBase64:()=>Zwe,uint8ArrayToBase64url:()=>Bht,uint8ArrayToHex:()=>Vht,unwrapMessage:()=>J0});function Sht(t){return t}function vht(t){return t}function Eht(t){}function Rht(t){throw new Error("Unexpected value in exhaustive check")}function Tht(t){}function Q0(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function ne(t,e="|"){return t.map(r=>Ee(r)).join(e)}function kw(t,e){return typeof e=="bigint"?e.toString():e}function _w(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function wh(t){return t==null}function Y0(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function p6(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function sr(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==Vwe)return n===void 0&&(n=Vwe,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Cht(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Sh(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function rf(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function Pht(t){return rf(t._zod.def)}function Aht(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Iht(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function Oht(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function aD(t){return JSON.stringify(t)}function f6(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Sb(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vh(t){if(Sb(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Sb(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function h6(t){return vh(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function $ht(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Kc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function js(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function Oe(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Dht(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ee(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function y6(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Nht(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=rf(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return Sh(this,"shape",s),s},checks:[]});return js(t,i)}function Lht(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=rf(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return Sh(this,"shape",s),s},checks:[]});return js(t,i)}function zht(t,e){if(!vh(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let i=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=rf(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return Sh(this,"shape",i),i}});return js(t,o)}function jht(t,e){if(!vh(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=rf(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Sh(this,"shape",n),n}});return js(t,r)}function Fht(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=rf(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Sh(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return js(t,r)}function Uht(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=rf(e._zod.def,{get shape(){let a=e._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]=t?new t({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=t?new t({type:"optional",innerType:a[l]}):a[l];return Sh(this,"shape",c),c},checks:[]});return js(e,s)}function Ght(t,e,r){let n=rf(e._zod.def,{get shape(){let o=e._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 t({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new t({type:"nonoptional",innerType:o[s]});return Sh(this,"shape",i),i}});return js(e,n)}function Eh(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function k6(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function ba(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function J0(t){return typeof t=="string"?t:t?.message}function Fs(t,e,r){let n=t.message?t.message:J0(t.inst?._zod.def?.error?.(t))??J0(e?.error?.(t))??J0(r.customError?.(t))??J0(r.localeError?.(t))??"Invalid input",{inst:o,continue:i,input:s,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}function eT(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function tT(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Re(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function ww(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Hht(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Kwe(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Zwe(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function Wht(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return Kwe(e+r)}function Bht(t){return Zwe(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qht(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function Vht(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Vwe,cD,m6,Mht,X0,g6,b6,x6,d6,ct=p(()=>{wb();Vwe=Symbol("evaluating");cD="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};m6=_w(()=>{if(_b.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});Mht=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},X0=new Set(["string","number","symbol"]),g6=new Set(["string","number","bigint","boolean","symbol","undefined"]);b6={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]},x6={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};d6=class{constructor(...e){}}});function nT(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function oT(t,e=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(e(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(e(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(t),r}function _6(t,e=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(e(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(e(c)),d++}}};return n(t),r}function Qwe(t){let e=[],r=t.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function w6(t){let e=[],r=[...t.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${Qwe(n.path)}`);return e.join(`
4
4
  `)}var Jwe,rT,xa,S6=p(()=>{wb();ct();Jwe=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,kw,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},rT=K("$ZodError",Jwe),xa=K("$ZodError",Jwe,{Parent:Error})});var Sw,lD,vw,uD,Ew,v6,Rw,E6,dD,Zht,pD,Jht,fD,Qht,mD,Yht,hD,Xht,gD,egt,yD,tgt,bD,rgt,R6=p(()=>{wb();S6();ct();Sw=t=>(e,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new iu;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(c=>Fs(c,i,To())));throw cD(a,o?.callee),a}return s.value},lD=Sw(xa),vw=t=>async(e,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(c=>Fs(c,i,To())));throw cD(a,o?.callee),a}return s.value},uD=vw(xa),Ew=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new iu;return i.issues.length?{success:!1,error:new(t??rT)(i.issues.map(s=>Fs(s,o,To())))}:{success:!0,data:i.value}},v6=Ew(xa),Rw=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>Fs(s,o,To())))}:{success:!0,data:i.value}},E6=Rw(xa),dD=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Sw(t)(e,r,o)},Zht=dD(xa),pD=t=>(e,r,n)=>Sw(t)(e,r,n),Jht=pD(xa),fD=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return vw(t)(e,r,o)},Qht=fD(xa),mD=t=>async(e,r,n)=>vw(t)(e,r,n),Yht=mD(xa),hD=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ew(t)(e,r,o)},Xht=hD(xa),gD=t=>(e,r,n)=>Ew(t)(e,r,n),egt=gD(xa),yD=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Rw(t)(e,r,o)},tgt=yD(xa),bD=t=>async(e,r,n)=>Rw(t)(e,r,n),rgt=bD(xa)});var lc={};Mn(lc,{base64:()=>G6,base64url:()=>xD,bigint:()=>Z6,boolean:()=>Q6,browserEmail:()=>ugt,cidrv4:()=>F6,cidrv6:()=>U6,cuid:()=>T6,cuid2:()=>C6,date:()=>B6,datetime:()=>V6,domain:()=>fgt,duration:()=>$6,e164:()=>W6,email:()=>D6,emoji:()=>N6,extendedDuration:()=>ngt,guid:()=>M6,hex:()=>mgt,hostname:()=>pgt,html5Email:()=>agt,httpProtocol:()=>H6,idnEmail:()=>lgt,integer:()=>J6,ipv4:()=>L6,ipv6:()=>z6,ksuid:()=>I6,lowercase:()=>eK,mac:()=>j6,md5_base64:()=>ggt,md5_base64url:()=>ygt,md5_hex:()=>hgt,nanoid:()=>O6,null:()=>Y6,number:()=>kD,rfc5322Email:()=>cgt,sha1_base64:()=>xgt,sha1_base64url:()=>kgt,sha1_hex:()=>bgt,sha256_base64:()=>wgt,sha256_base64url:()=>Sgt,sha256_hex:()=>_gt,sha384_base64:()=>Egt,sha384_base64url:()=>Rgt,sha384_hex:()=>vgt,sha512_base64:()=>Cgt,sha512_base64url:()=>Pgt,sha512_hex:()=>Tgt,string:()=>K6,time:()=>q6,ulid:()=>P6,undefined:()=>X6,unicodeEmail:()=>Ywe,uppercase:()=>tK,uuid:()=>vb,uuid4:()=>ogt,uuid6:()=>igt,uuid7:()=>sgt,xid:()=>A6});function N6(){return new RegExp(dgt,"u")}function eSe(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function q6(t){return new RegExp(`^${eSe(t)}$`)}function V6(t){let e=eSe({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Xwe}T(?:${n})$`)}function iT(t,e){return new RegExp(`^[A-Za-z0-9+/]{${t}}${e}$`)}function sT(t){return new RegExp(`^[A-Za-z0-9_-]{${t}}$`)}var T6,C6,P6,A6,I6,O6,$6,ngt,M6,vb,ogt,igt,sgt,D6,agt,cgt,Ywe,lgt,ugt,dgt,L6,z6,j6,F6,U6,G6,xD,pgt,fgt,H6,W6,Xwe,B6,K6,Z6,J6,kD,Q6,Y6,X6,eK,tK,mgt,hgt,ggt,ygt,bgt,xgt,kgt,_gt,wgt,Sgt,vgt,Egt,Rgt,Tgt,Cgt,Pgt,_D=p(()=>{ct();T6=/^[cC][0-9a-z]{6,}$/,C6=/^[0-9a-z]+$/,P6=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,A6=/^[0-9a-vA-V]{20}$/,I6=/^[A-Za-z0-9]{27}$/,O6=/^[a-zA-Z0-9_-]{21}$/,$6=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ngt=/^[-+]?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)?)??$/,M6=/^([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})$/,vb=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[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)$/,ogt=vb(4),igt=vb(6),sgt=vb(7),D6=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,agt=/^[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])?)*$/,cgt=/^(([^<>()\[\]\\.,;:\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,}))$/,Ywe=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,lgt=Ywe,ugt=/^[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])?)*$/,dgt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";L6=/^(?:(?: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])$/,z6=/^(([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}|:))$/,j6=t=>{let e=Kc(t??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},F6=/^((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])$/,U6=/^(([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])$/,G6=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xD=/^[A-Za-z0-9_-]*$/,pgt=/^(?=.{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])?)*\.?$/,fgt=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,H6=/^https?$/,W6=/^\+[1-9]\d{6,14}$/,Xwe="(?:(?:\\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])))",B6=new RegExp(`^${Xwe}$`);K6=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Z6=/^-?\d+n?$/,J6=/^-?\d+$/,kD=/^-?\d+(?:\.\d+)?$/,Q6=/^(?:true|false)$/i,Y6=/^null$/i,X6=/^undefined$/i,eK=/^[^A-Z]*$/,tK=/^[^a-z]*$/,mgt=/^[0-9a-fA-F]*$/;hgt=/^[0-9a-fA-F]{32}$/,ggt=iT(22,"=="),ygt=sT(22),bgt=/^[0-9a-fA-F]{40}$/,xgt=iT(27,"="),kgt=sT(27),_gt=/^[0-9a-fA-F]{64}$/,wgt=iT(43,"="),Sgt=sT(43),vgt=/^[0-9a-fA-F]{96}$/,Egt=iT(64,""),Rgt=sT(64),Tgt=/^[0-9a-fA-F]{128}$/,Cgt=iT(86,"=="),Pgt=sT(86)});function tSe(t,e,r){t.issues.length&&e.issues.push(...ba(r,t.issues))}var kn,rSe,wD,SD,rK,nK,oK,iK,sK,aK,cK,lK,uK,Tw,dK,pK,fK,mK,hK,gK,yK,bK,xK,vD=p(()=>{wb();_D();ct();kn=K("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),rSe={number:"number",bigint:"bigint",object:"date"},wD=K("$ZodCheckLessThan",(t,e)=>{kn.init(t,e);let r=rSe[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),SD=K("$ZodCheckGreaterThan",(t,e)=>{kn.init(t,e);let r=rSe[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),rK=K("$ZodCheckMultipleOf",(t,e)=>{kn.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):p6(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),nK=K("$ZodCheckNumberFormat",(t,e)=>{kn.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,i]=b6[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=o,a.maximum=i,r&&(a.pattern=J6)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});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:t,origin:n,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:t,continue:!e.abort})}}),oK=K("$ZodCheckBigIntFormat",(t,e)=>{kn.init(t,e);let[r,n]=x6[e.format];t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,i.minimum=r,i.maximum=n}),t._zod.check=o=>{let i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:t,continue:!e.abort})}}),iK=K("$ZodCheckMaxSize",(t,e)=>{var r;kn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!wh(o)&&o.size!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;o.size<=e.maximum||n.issues.push({origin:eT(o),code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),sK=K("$ZodCheckMinSize",(t,e)=>{var r;kn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!wh(o)&&o.size!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;o.size>=e.minimum||n.issues.push({origin:eT(o),code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),aK=K("$ZodCheckSizeEquals",(t,e)=>{var r;kn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!wh(o)&&o.size!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.size,o.maximum=e.size,o.size=e.size}),t._zod.check=n=>{let o=n.value,i=o.size;if(i===e.size)return;let s=i>e.size;n.issues.push({origin:eT(o),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),cK=K("$ZodCheckMaxLength",(t,e)=>{var r;kn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!wh(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let s=tT(o);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),lK=K("$ZodCheckMinLength",(t,e)=>{var r;kn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!wh(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let s=tT(o);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),uK=K("$ZodCheckLengthEquals",(t,e)=>{var r;kn.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!wh(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,i=o.length;if(i===e.length)return;let s=tT(o),a=i>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Tw=K("$ZodCheckStringFormat",(t,e)=>{var r,n;kn.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),dK=K("$ZodCheckRegex",(t,e)=>{Tw.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),pK=K("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=eK),Tw.init(t,e)}),fK=K("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=tK),Tw.init(t,e)}),mK=K("$ZodCheckIncludes",(t,e)=>{kn.init(t,e);let r=Kc(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),hK=K("$ZodCheckStartsWith",(t,e)=>{kn.init(t,e);let r=new RegExp(`^${Kc(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),gK=K("$ZodCheckEndsWith",(t,e)=>{kn.init(t,e);let r=new RegExp(`.*${Kc(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});yK=K("$ZodCheckProperty",(t,e)=>{kn.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>tSe(o,r,e.property));tSe(n,r,e.property)}}),bK=K("$ZodCheckMimeType",(t,e)=>{kn.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,inst:t,continue:!e.abort})}}),xK=K("$ZodCheckOverwrite",(t,e)=>{kn.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var aT,kK=p(()=>{aT=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.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 e=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,o.join(`
6
6
  `))}}});var _K,wK=p(()=>{_K={major:4,minor:4,patch:3}});function WK(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function bSe(t){if(!xD.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return WK(r)}function xSe(t,e=null){try{let r=t.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||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function oSe(t,e,r){t.issues.length&&e.issues.push(...ba(r,t.issues)),e.value[r]=t.value}function CD(t,e,r,n,o,i){let s=r in n;if(t.issues.length){if(o&&i&&!s)return;e.issues.push(...ba(r,t.issues))}if(!s&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?s&&(e.value[r]=void 0):e.value[r]=t.value}function kSe(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=y6(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function _Se(t,e,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 e){if(f==="__proto__"||a.has(f))continue;if(l==="never"){s.push(f);continue}let m=c.run({value:e[f],issues:[]},n);m instanceof Promise?t.push(m.then(b=>CD(b,r,f,e,u,d))):CD(m,r,f,e,u,d)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:i}),t.length?Promise.all(t).then(()=>r):r}function iSe(t,e,r,n){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;let o=t.filter(i=>!Eh(i));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(s=>Fs(s,n,To())))}),e)}function sSe(t,e,r,n){let o=t.filter(i=>i.issues.length===0);return o.length===1?(e.value=o[0].value,e):(o.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(s=>Fs(s,n,To())))}):e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:[],inclusive:!1}),e)}function SK(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(vh(t)&&vh(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let s=SK(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],s=SK(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 aSe(t,e,r){let n=new Map,o;for(let a of e.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 t.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 t.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&t.issues.push({...o,keys:i}),Eh(t))return t;let s=SK(e.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}function cSe(t,e){for(let r=t.length-1;r>=0;r--)if(t[r]._zod[e]!=="optional")return r+1;return 0}function lSe(t,e,r){t.issues.length&&e.issues.push(...ba(r,t.issues)),e.value[r]=t.value}function uSe(t,e,r,n,o){for(let i=0;i<r.length;i++){let s=t[i],a=i<n.length;if(s.issues.length){if(!a&&i>=o){e.value.length=i;break}e.issues.push(...ba(i,s.issues))}e.value[i]=s.value}for(let i=e.value.length-1;i>=n.length&&(r[i]._zod.optout==="optional"&&e.value[i]===void 0);i--)e.value.length=i;return e}function dSe(t,e,r,n,o,i,s){t.issues.length&&(X0.has(typeof n)?r.issues.push(...ba(n,t.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:t.issues.map(a=>Fs(a,s,To()))})),e.issues.length&&(X0.has(typeof n)?r.issues.push(...ba(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:e.issues.map(a=>Fs(a,s,To()))})),r.value.set(t.value,e.value)}function pSe(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function fSe(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}function mSe(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function hSe(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function ED(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}function RD(t,e,r){if(t.issues.length)return t.aborted=!0,t;if((r.direction||"forward")==="forward"){let o=e.transform(t.value,t);return o instanceof Promise?o.then(i=>TD(t,i,e.out,r)):TD(t,o,e.out,r)}else{let o=e.reverseTransform(t.value,t);return o instanceof Promise?o.then(i=>TD(t,i,e.in,r)):TD(t,o,e.in,r)}}function TD(t,e,r,n){return t.issues.length?(t.aborted=!0,t):r._zod.run({value:e,issues:t.issues},n)}function gSe(t){return t.value=Object.freeze(t.value),t}function ySe(t,e,r,n){if(!t){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),e.issues.push(ww(o))}}var jt,Eb,un,vK,EK,RK,TK,CK,PK,AK,IK,OK,$K,MK,DK,NK,LK,zK,jK,FK,UK,GK,HK,BK,qK,VK,KK,ZK,PD,JK,cT,AD,QK,YK,XK,e3,t3,r3,n3,o3,i3,s3,wSe,a3,lT,c3,l3,u3,ID,d3,p3,f3,m3,h3,g3,y3,OD,b3,x3,k3,_3,w3,S3,v3,E3,$D,uT,R3,T3,C3,P3,A3,I3,O3,$3=p(()=>{vD();wb();kK();R6();_D();ct();wK();ct();jt=K("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=_K;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,a,c)=>{let l=Eh(s),u;for(let d of a){if(d._zod.def.when){if(k6(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 iu;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==f&&(l||(l=Eh(s,f)))});else{if(s.issues.length===f)continue;l||(l=Eh(s,f))}}return u?u.then(()=>s):s},i=(s,a,c)=>{if(Eh(s))return s.aborted=!0,s;let l=o(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new iu;return l.then(u=>t._zod.parse(u,c))}return t._zod.parse(l,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let l=t._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=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new iu;return c.then(l=>o(l,n,a))}return o(c,n,a)}}sr(t,"~standard",()=>({validate:o=>{try{let i=v6(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return E6(t,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Eb=K("$ZodString",(t,e)=>{jt.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??K6(t._zod.bag),t._zod.parse=(r,n)=>{if(e.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:t}),r}}),un=K("$ZodStringFormat",(t,e)=>{Tw.init(t,e),Eb.init(t,e)}),vK=K("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=M6),un.init(t,e)}),EK=K("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=vb(n))}else e.pattern??(e.pattern=vb());un.init(t,e)}),RK=K("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=D6),un.init(t,e)}),TK=K("$ZodURL",(t,e)=>{un.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===H6.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let o=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),CK=K("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=N6()),un.init(t,e)}),PK=K("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=O6),un.init(t,e)}),AK=K("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=T6),un.init(t,e)}),IK=K("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=C6),un.init(t,e)}),OK=K("$ZodULID",(t,e)=>{e.pattern??(e.pattern=P6),un.init(t,e)}),$K=K("$ZodXID",(t,e)=>{e.pattern??(e.pattern=A6),un.init(t,e)}),MK=K("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=I6),un.init(t,e)}),DK=K("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=V6(e)),un.init(t,e)}),NK=K("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=B6),un.init(t,e)}),LK=K("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=q6(e)),un.init(t,e)}),zK=K("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=$6),un.init(t,e)}),jK=K("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=L6),un.init(t,e),t._zod.bag.format="ipv4"}),FK=K("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=z6),un.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),UK=K("$ZodMAC",(t,e)=>{e.pattern??(e.pattern=j6(e.delimiter)),un.init(t,e),t._zod.bag.format="mac"}),GK=K("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=F6),un.init(t,e)}),HK=K("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=U6),un.init(t,e),t._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:t,continue:!e.abort})}}});BK=K("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=G6),un.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{WK(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});qK=K("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=xD),un.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{bSe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),VK=K("$ZodE164",(t,e)=>{e.pattern??(e.pattern=W6),un.init(t,e)});KK=K("$ZodJWT",(t,e)=>{un.init(t,e),t._zod.check=r=>{xSe(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),ZK=K("$ZodCustomStringFormat",(t,e)=>{un.init(t,e),t._zod.check=r=>{e.fn(r.value)||r.issues.push({code:"invalid_format",format:e.format,input:r.value,inst:t,continue:!e.abort})}}),PD=K("$ZodNumber",(t,e)=>{jt.init(t,e),t._zod.pattern=t._zod.bag.pattern??kD,t._zod.parse=(r,n)=>{if(e.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:t,...i?{received:i}:{}}),r}}),JK=K("$ZodNumberFormat",(t,e)=>{nK.init(t,e),PD.init(t,e)}),cT=K("$ZodBoolean",(t,e)=>{jt.init(t,e),t._zod.pattern=Q6,t._zod.parse=(r,n)=>{if(e.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:t}),r}}),AD=K("$ZodBigInt",(t,e)=>{jt.init(t,e),t._zod.pattern=Z6,t._zod.parse=(r,n)=>{if(e.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:t}),r}}),QK=K("$ZodBigIntFormat",(t,e)=>{oK.init(t,e),AD.init(t,e)}),YK=K("$ZodSymbol",(t,e)=>{jt.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:t}),r}}),XK=K("$ZodUndefined",(t,e)=>{jt.init(t,e),t._zod.pattern=X6,t._zod.values=new Set([void 0]),t._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:t}),r}}),e3=K("$ZodNull",(t,e)=>{jt.init(t,e),t._zod.pattern=Y6,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),t3=K("$ZodAny",(t,e)=>{jt.init(t,e),t._zod.parse=r=>r}),r3=K("$ZodUnknown",(t,e)=>{jt.init(t,e),t._zod.parse=r=>r}),n3=K("$ZodNever",(t,e)=>{jt.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),o3=K("$ZodVoid",(t,e)=>{jt.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:t}),r}}),i3=K("$ZodDate",(t,e)=>{jt.init(t,e),t._zod.parse=(r,n)=>{if(e.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:t}),r}});s3=K("$ZodArray",(t,e)=>{jt.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>oSe(l,r,s))):oSe(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});wSe=K("$ZodObject",(t,e)=>{if(jt.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=_w(()=>kSe(e));sr(t._zod,"propValues",()=>{let a=e.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=Sb,i=e.catchall,s;t._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:t}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let m=d[f],b=m._zod.optin==="optional",k=m._zod.optout==="optional",w=m._zod.run({value:l[f],issues:[]},c);w instanceof Promise?u.push(w.then(S=>CD(S,a,f,l,b,k))):CD(w,a,f,l,b,k)}return i?_Se(u,l,a,c,n.value,t):u.length?Promise.all(u).then(()=>a):a}}),a3=K("$ZodObjectJIT",(t,e)=>{wSe.init(t,e);let r=t._zod.parse,n=_w(()=>kSe(e)),o=f=>{let m=new aT(["shape","payload","ctx"]),b=n.value,k=P=>{let $=aD(P);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};m.write("const input = payload.value;");let w=Object.create(null),S=0;for(let P of b.keys)w[P]=`key_${S++}`;m.write("const newResult = {};");for(let P of b.keys){let $=w[P],M=aD(P),z=f[P],j=z?._zod?.optin==="optional",G=z?._zod?.optout==="optional";m.write(`const ${$} = ${k(P)};`),j&&G?m.write(`
@@ -157,7 +157,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
157
157
  `}function W_(e,t){return t.map(Rr).join(e)}function FZ(e){if(!Array.isArray(e)||e.length===0)throw at(0,"TOONL header requires fields");return e.map(t=>{let r;try{[r]=zi(String(t),0)}catch(n){throw nl(n)}if(r==="")throw at(0,"TOONL header requires fields");return r})}function SD(e,t){return e!==null&&e.length===t.length&&e.every((r,n)=>r===t[n])}function ED(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw at(0,"TOONL continuation cadence must be positive")}function GZ(e,t,r){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&r>=e.continuationEveryBytes}function TD(e){if(e===null||typeof e!="object"||Array.isArray(e))throw at(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw at(0,"TOONL output requires object rows");if(t.some(r=>!wd(e[r])))throw at(0,"TOONL rows must be flat objects");return t}function BZ(e){return JSON.stringify([...e].sort())}function PD(e,t){let r=BZ(e),n=t.get(r);return n!==void 0?n:(t.set(r,e),e)}function It({delimiter:e=qo,trailer:t=!0,continuationEveryRows:r,continuationEveryBytes:n}={}){LZ(e),ED(r),ED(n);let o=null,i="",s=new Map,a=0,l=0,c=0,d=new Map,u=!1,p={continuationEveryRows:r,continuationEveryBytes:n},g=()=>o===null||!t?"":`[=${a}]
158
158
  `,m=()=>GZ(p,l,c)?(l=0,c=0,RD(e,i,!0)):"",b=k=>{$D(k,0);let v=d.get(k);if(v===void 0){if(d.size>=ID)throw at(0,"too many tagged lanes");v={fields:null,fieldsByShape:new Map},d.set(k,v)}return v};return{push(k){if(u)throw at(0,"TOONL encoder is closed");let v=PD(TD(k),s),T="";(o===null||o.length!==v.length||o.some((E,$)=>E!==v[$]))&&(T+=g(),o=v,i=W_(e,o),a=0,l=0,c=0,T+=RD(e,i));let I=o.map(E=>vr(k[E],e));T+=m();let z=`${I.join(e)}
159
159
  `;return T+=z,a+=1,l+=1,c+=z.length,T},declareLane(k,v){if(u)throw at(0,"TOONL encoder is closed");let T=FZ(v),I=W_(qo,T),z=b(k);return SD(z.fields,T)?"":(z.fields=T,xD(k,I))},pushTagged(k,v){if(u)throw at(0,"TOONL encoder is closed");let T=b(k),I=PD(TD(v),T.fieldsByShape),z=W_(qo,I),E=I.map(L=>vr(v[L],qo)),$="";return SD(T.fields,I)||(T.fields=I,$+=xD(k,z)),`${$}${k}:${E.join(qo)}
160
- `},end(){return u?"":(u=!0,g())}}}var vt=F_;function cl(e){let t={app:e,version:UZ(ll("__RED_BUILD_VERSION__",()=>"3.19.4")??"0.0.0-dev"),gitSha:ll("__RED_BUILD_GIT_SHA__",()=>"cbccb19444939c8c3079b4d6bbfe0109662235e7")??"unknown",buildTime:ll("__RED_BUILD_TIME__",()=>"2026-08-18T09:27:29-03:00")??"unknown",bundleAsset:ll("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},r=ll("__REDDB_SDK_VERSION__",()=>""),n=ll("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function UZ(e){return e.startsWith("v")?e.slice(1):e}function CD(e){return`${e.app} ${e.version} ${e.gitSha}`}function ll(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var OD={"=":"data",":=":{to:"data",typed:!0},":":"meta"},HZ=/^[a-z][a-z0-9+.-]*:\/\//i;function WZ(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 qZ(e=OD){return Object.entries(e).map(([t,r])=>WZ(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function VZ(e){return/^-\d+(\.\d+)?$/.test(e)}function xd(e){return!(!e||e.startsWith("-")&&!VZ(e))}function Uf(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 jD(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=>jD(r.trim())):e}function js(e,t){switch(t){case"boolean":return KZ(e);case"number":return JZ(e);case"array":return e.split(",").map(r=>Uf(r.trim()));case"string":default:return e}}function KZ(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function JZ(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 Ii(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function ZZ(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function Rt(e,t){return{type:e,value:t}}function YZ(e){let t=[],r=XZ(e);if(t.push(Rt("section-header","Usage:"),Rt("text"," "),Rt("usage-text",r),Rt("newline",`
160
+ `},end(){return u?"":(u=!0,g())}}}var vt=F_;function cl(e){let t={app:e,version:UZ(ll("__RED_BUILD_VERSION__",()=>"3.19.5")??"0.0.0-dev"),gitSha:ll("__RED_BUILD_GIT_SHA__",()=>"626a28473edeee992fcf6425dedbca84448343fd")??"unknown",buildTime:ll("__RED_BUILD_TIME__",()=>"2026-08-18T09:41:17-03:00")??"unknown",bundleAsset:ll("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},r=ll("__REDDB_SDK_VERSION__",()=>""),n=ll("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function UZ(e){return e.startsWith("v")?e.slice(1):e}function CD(e){return`${e.app} ${e.version} ${e.gitSha}`}function ll(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var OD={"=":"data",":=":{to:"data",typed:!0},":":"meta"},HZ=/^[a-z][a-z0-9+.-]*:\/\//i;function WZ(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 qZ(e=OD){return Object.entries(e).map(([t,r])=>WZ(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function VZ(e){return/^-\d+(\.\d+)?$/.test(e)}function xd(e){return!(!e||e.startsWith("-")&&!VZ(e))}function Uf(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 jD(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=>jD(r.trim())):e}function js(e,t){switch(t){case"boolean":return KZ(e);case"number":return JZ(e);case"array":return e.split(",").map(r=>Uf(r.trim()));case"string":default:return e}}function KZ(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function JZ(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 Ii(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function ZZ(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function Rt(e,t){return{type:e,value:t}}function YZ(e){let t=[],r=XZ(e);if(t.push(Rt("section-header","Usage:"),Rt("text"," "),Rt("usage-text",r),Rt("newline",`
161
161
  `),Rt("newline",`
162
162
  `)),e.positional&&e.positional.length>0){t.push(Rt("section-header","Arguments:"),Rt("newline",`
163
163
  `));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;t.push(Rt("indent"," "),Rt("positional-name",`<${o}>`)),n.required||t.push(Rt("positional-optional"," (optional)")),t.push(Rt("newline",`
@@ -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__",()=>"3.19.4")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"cbccb19444939c8c3079b4d6bbfe0109662235e7")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-18T09:27:29-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 ke(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 ke(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 ke(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__",()=>"3.19.5")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"626a28473edeee992fcf6425dedbca84448343fd")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-18T09:41:17-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 ke(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 ke(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 ke(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 AP=Object.create;var Vu=Object.defineProperty;var CP=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=mL(y),w=Sd(zt,E),k=g(b);return tw(k.fields,E)?"":(k.fields=E,ew(b,w))},pushTagged(b,y){if(d)throw Y(0,"TOONL encoder is closed");let E=g(b),w=sw(nw(y),E.fieldsByShape),k=Sd(zt,w),S=w.map(C=>ve(y[C],zt)),T="";return tw(E.fields,w)||(E.fields=w,T+=ew(b,k)),`${T}${b}:${S.join(zt)}
26
26
  `},end(){return d?"":(d=!0,f())}}}var ow,iw,aw,I3,L3,lw=_(()=>{Kt();ga();so();nn();ow=[zt,"|"," "],iw=8,aw=/^[A-Za-z0-9_-]+$/,I3=new TextEncoder,L3=new TextDecoder});var z,J=_(()=>{ga();so();zb();Kt();ro();Yb();so();Zs();nn();ma();ga();Qb();lw();z=bd});function bL(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??bL(e.category),error:e.error,help:[e.help]};return e.validFlags&&e.validFlags.length>0&&(t.valid_flags=[...e.validFlags]),e.diagnostics&&(t.diagnostics=wL(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)&&Yy(s)?{command:e,category:"transient",error:oo(s)||"GitHub API rate limit exceeded",help:zy,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 uw(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 wL(e,t){return e.split(/\r?\n/).slice(0,t).join(`
28
- `).trim()}var bt=_(()=>{"use strict";Qy();J()});function Ea(e){let t={app:e,version:CL(Jn("__RED_BUILD_VERSION__",()=>"3.19.4")??"0.0.0-dev"),gitSha:Jn("__RED_BUILD_GIT_SHA__",()=>"cbccb19444939c8c3079b4d6bbfe0109662235e7")??"unknown",buildTime:Jn("__RED_BUILD_TIME__",()=>"2026-08-18T09:27:29-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 CL(e){return e.startsWith("v")?e.slice(1):e}function ww(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 PL,join as Yt,resolve as xd}from"node:path";function GL(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function Ew(e){return Yt(GL(e),_w)}function kw(e){return Yt(Ew(e),"state")}function Sw(e){return Yt(Ew(e),"tmp")}function ce(e){return Yt(kw(e),"rsp")}function DL(e){return Yt(kw(e),"red-skills.rdb")}function $L(e){return Yt(Sw(e),"red-skills.rdb")}function Tw(e,t){let r=DL(e);if(t(r))return r;let n=$L(e);if(t(n))throw NL();return r}function NL(){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 xw(e){return Yt(Sw(e),"waits")}function Ow(e){let t=e.overrideEnvVars??Od;for(let n of t){let s=e.env[n];if(s)return PL(s)?s:xd(e.startDir,s)}let r=xd(e.startDir);for(;;){if(e.exists(Yt(r,_w)))return r;let n=Yt(r,".."),s=xd(n);if(s===r)break;r=s}return e.startDir}var _w,IL,LL,Od,Rw,vw,Ze=_(()=>{_w=".red",IL="MEMORY_ROOT",LL="RED_BRAIN_ROOT",Od=[IL,LL];Rw=".red/state/red-skills.rdb";vw=".red/tmp/red-skills.rdb"});function ge(e){return M(e)}var FL,ML,v4,Qt=_(()=>{J();Ze();FL=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],ML=[{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"}],v4=[...FL,...ML]});function io(e){let{values:t,rest:r}=Xr(e,{query:Aw.query},Cw);return{argv:r,query:t.query?.trim()||void 0}}function Pw(e){let{values:t,rest:r}=Xr(e,Aw,Cw);return{argv:r,query:t.query?.trim()||void 0,full:t.full===!0}}function BL(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=>BL(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 Aw,Cw,ao=_(()=>{"use strict";Yu();Aw={query:{kind:"value",coerce:e=>e},full:{kind:"boolean"}},Cw={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:()=>JL,RSP_OVERHEAD_LEDGER_FILE:()=>Gw,RSP_OVERHEAD_SCHEMA_VERSION:()=>Dw,classifyOverheadSample:()=>Ld,noteChildProcessMs:()=>Nw,noteSelfStateBytesRead:()=>lo,overheadCounters:()=>Fd,overheadFamilyDisabled:()=>KL,overheadHealth:()=>br,overheadLedgerPath:()=>Gd,overheadMsOf:()=>$w,overheadTelemetryFields:()=>xa,readOverheadLedger:()=>co,readSelfStateFile:()=>Oa,readSelfStateFileSync:()=>QL,recordOverheadSample:()=>Dd,resetOverheadCounters:()=>YL,resetOverheadLedger:()=>zL,startChildProcessTimer:()=>et});import{existsSync as jL,mkdirSync as qL,readFileSync as Iw,renameSync as UL,writeFileSync as HL}from"node:fs";import{readFile as WL}from"node:fs/promises";import{dirname as VL,join as Lw}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 Lw(ce(e),Gw)}function co(e){try{let t=Iw(Gd(e),"utf8"),r=tG(t);if(rG(r))return r}catch{}return{version:1,families:{}}}function Dd(e,t,r=Zt,n=Date.now()){let s=co(e),o=Ld(t,r),i=s.families[t.family]??eG(t.family,n),a=Md(i,n)?Fw(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=XL(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,Mw(e,s),l}function KL(e,t,r=Date.now()){let n=co(e).families[t];return!n?.disabled||Md(n,r)?null:n}function zL(e,t){let r=co(e);return t?delete r.families[t]:r.families={},Mw(e,r),r}function br(e,t=Zt,r=Date.now()){let n=Object.values(co(e).families).map(a=>Md(a,r)?Fw(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:ZL(i,s,o),ceiling:t,breaching_families:o,disabled_families:s,families:n}}function lo(e){Number.isFinite(e)&&e>0&&($d+=e)}function Nw(e){Number.isFinite(e)&&e>0&&(Nd+=e)}function Fd(){return{selfStateBytesRead:$d,childMs:Nd}}function YL(){$d=0,Nd=0}function et(){let e=process.hrtime.bigint(),t=!1;return()=>{t||(t=!0,Nw(Number(process.hrtime.bigint()-e)/1e6))}}async function Oa(e){let t=await WL(e,"utf8");return lo(Buffer.byteLength(t)),t}function QL(e){let t=Iw(e,"utf8");return lo(Buffer.byteLength(t)),t}function XL(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 ZL(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 Fw(e){return{...e,disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,consecutive_breaches:0,breached:!1,reasons:[]}}function eG(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 Mw(e,t){try{let r=Gd(e);if(!jL(Lw(e,".red")))return;qL(VL(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`;HL(n,`${M(t)}
28
+ `).trim()}var bt=_(()=>{"use strict";Qy();J()});function Ea(e){let t={app:e,version:CL(Jn("__RED_BUILD_VERSION__",()=>"3.19.5")??"0.0.0-dev"),gitSha:Jn("__RED_BUILD_GIT_SHA__",()=>"626a28473edeee992fcf6425dedbca84448343fd")??"unknown",buildTime:Jn("__RED_BUILD_TIME__",()=>"2026-08-18T09:41:17-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 CL(e){return e.startsWith("v")?e.slice(1):e}function ww(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 PL,join as Yt,resolve as xd}from"node:path";function GL(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function Ew(e){return Yt(GL(e),_w)}function kw(e){return Yt(Ew(e),"state")}function Sw(e){return Yt(Ew(e),"tmp")}function ce(e){return Yt(kw(e),"rsp")}function DL(e){return Yt(kw(e),"red-skills.rdb")}function $L(e){return Yt(Sw(e),"red-skills.rdb")}function Tw(e,t){let r=DL(e);if(t(r))return r;let n=$L(e);if(t(n))throw NL();return r}function NL(){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 xw(e){return Yt(Sw(e),"waits")}function Ow(e){let t=e.overrideEnvVars??Od;for(let n of t){let s=e.env[n];if(s)return PL(s)?s:xd(e.startDir,s)}let r=xd(e.startDir);for(;;){if(e.exists(Yt(r,_w)))return r;let n=Yt(r,".."),s=xd(n);if(s===r)break;r=s}return e.startDir}var _w,IL,LL,Od,Rw,vw,Ze=_(()=>{_w=".red",IL="MEMORY_ROOT",LL="RED_BRAIN_ROOT",Od=[IL,LL];Rw=".red/state/red-skills.rdb";vw=".red/tmp/red-skills.rdb"});function ge(e){return M(e)}var FL,ML,v4,Qt=_(()=>{J();Ze();FL=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],ML=[{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"}],v4=[...FL,...ML]});function io(e){let{values:t,rest:r}=Xr(e,{query:Aw.query},Cw);return{argv:r,query:t.query?.trim()||void 0}}function Pw(e){let{values:t,rest:r}=Xr(e,Aw,Cw);return{argv:r,query:t.query?.trim()||void 0,full:t.full===!0}}function BL(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=>BL(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 Aw,Cw,ao=_(()=>{"use strict";Yu();Aw={query:{kind:"value",coerce:e=>e},full:{kind:"boolean"}},Cw={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:()=>JL,RSP_OVERHEAD_LEDGER_FILE:()=>Gw,RSP_OVERHEAD_SCHEMA_VERSION:()=>Dw,classifyOverheadSample:()=>Ld,noteChildProcessMs:()=>Nw,noteSelfStateBytesRead:()=>lo,overheadCounters:()=>Fd,overheadFamilyDisabled:()=>KL,overheadHealth:()=>br,overheadLedgerPath:()=>Gd,overheadMsOf:()=>$w,overheadTelemetryFields:()=>xa,readOverheadLedger:()=>co,readSelfStateFile:()=>Oa,readSelfStateFileSync:()=>QL,recordOverheadSample:()=>Dd,resetOverheadCounters:()=>YL,resetOverheadLedger:()=>zL,startChildProcessTimer:()=>et});import{existsSync as jL,mkdirSync as qL,readFileSync as Iw,renameSync as UL,writeFileSync as HL}from"node:fs";import{readFile as WL}from"node:fs/promises";import{dirname as VL,join as Lw}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 Lw(ce(e),Gw)}function co(e){try{let t=Iw(Gd(e),"utf8"),r=tG(t);if(rG(r))return r}catch{}return{version:1,families:{}}}function Dd(e,t,r=Zt,n=Date.now()){let s=co(e),o=Ld(t,r),i=s.families[t.family]??eG(t.family,n),a=Md(i,n)?Fw(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=XL(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,Mw(e,s),l}function KL(e,t,r=Date.now()){let n=co(e).families[t];return!n?.disabled||Md(n,r)?null:n}function zL(e,t){let r=co(e);return t?delete r.families[t]:r.families={},Mw(e,r),r}function br(e,t=Zt,r=Date.now()){let n=Object.values(co(e).families).map(a=>Md(a,r)?Fw(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:ZL(i,s,o),ceiling:t,breaching_families:o,disabled_families:s,families:n}}function lo(e){Number.isFinite(e)&&e>0&&($d+=e)}function Nw(e){Number.isFinite(e)&&e>0&&(Nd+=e)}function Fd(){return{selfStateBytesRead:$d,childMs:Nd}}function YL(){$d=0,Nd=0}function et(){let e=process.hrtime.bigint(),t=!1;return()=>{t||(t=!0,Nw(Number(process.hrtime.bigint()-e)/1e6))}}async function Oa(e){let t=await WL(e,"utf8");return lo(Buffer.byteLength(t)),t}function QL(e){let t=Iw(e,"utf8");return lo(Buffer.byteLength(t)),t}function XL(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 ZL(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 Fw(e){return{...e,disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,consecutive_breaches:0,breached:!1,reasons:[]}}function eG(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 Mw(e,t){try{let r=Gd(e);if(!jL(Lw(e,".red")))return;qL(VL(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`;HL(n,`${M(t)}
29
29
  `,{encoding:"utf8",mode:384}),UL(n,r)}catch{}}function tG(e){try{return JSON.parse(e)}catch{return z(e)}}function rG(e){return!Pd(e)||e.version!==1||!Pd(e.families)?!1:Object.values(e.families).every(nG)}function nG(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 Gw,Dw,ka,Sa,Ra,va,Ta,JL,Zt,$d,Nd,we=_(()=>{"use strict";Ze();J();Gw="overhead-budget.toon",Dw="red.rsp.overhead.v1",ka=250,Sa=1024*1024,Ra=64*1024,va=3,Ta=6*60*60*1e3,JL=["git","gh","gh-api-json","vitest","cargo","cat","exec","proxy"],Zt={maxOverheadMs:ka,maxSelfStateBytes:Sa,netLossFloorBytes:Ra,consecutiveBreaches:va,cooldownMs:Ta};$d=0,Nd=0});function qw(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=qw(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__",()=>"3.19.4")??"0.0.0-dev"),gitSha:x("__RED_BUILD_GIT_SHA__",()=>"cbccb19444939c8c3079b4d6bbfe0109662235e7")??"unknown",buildTime:x("__RED_BUILD_TIME__",()=>"2026-08-18T09:27:29-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__",()=>"3.19.5")??"0.0.0-dev"),gitSha:x("__RED_BUILD_GIT_SHA__",()=>"626a28473edeee992fcf6425dedbca84448343fd")??"unknown",buildTime:x("__RED_BUILD_TIME__",()=>"2026-08-18T09:41:17-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": "3.19.4",
3
+ "version": "3.19.5",
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",
@@ -159,8 +159,37 @@ record_manifest() {
159
159
  printf '%s\n' "$path" >> "$MANIFEST_TMP"
160
160
  }
161
161
 
162
+ # A re-install replaces the manifest wholesale, so anything the PREVIOUS
163
+ # install recorded and this one did not reproduce — a skill renamed or
164
+ # removed upstream, a hook module that stopped shipping — would linger on the
165
+ # host forever, still loaded next to its successor (a stale `view` beside
166
+ # `memory-view`, 3.19.4). Prune those entries before the new manifest lands;
167
+ # only paths under the manifest's own root are ever touched.
168
+ prune_stale_manifest_paths() {
169
+ previous="$1"
170
+ next="$2"
171
+ allowed_root="$(dirname "$previous")"
172
+ [ -f "$previous" ] || return 0
173
+ while IFS= read -r path || [ -n "$path" ]; do
174
+ case "$path" in
175
+ ""|\#*) continue ;;
176
+ esac
177
+ grep -qxF -- "$path" "$next" && continue
178
+ case "$path" in
179
+ "$allowed_root"/*)
180
+ if [ -e "$path" ] || [ -L "$path" ]; then
181
+ run_rm "$path"
182
+ log "pruned stale $path (recorded by the previous install, not produced by this one)"
183
+ fi
184
+ ;;
185
+ *) log "(note) skipped stale manifest path outside $allowed_root: $path" ;;
186
+ esac
187
+ done < "$previous"
188
+ }
189
+
162
190
  finish_manifest() {
163
191
  [ -n "$MANIFEST_TMP" ] || return 0
192
+ prune_stale_manifest_paths "$MANIFEST_FILE" "$MANIFEST_TMP"
164
193
  mv "$MANIFEST_TMP" "$MANIFEST_FILE"
165
194
  log "wrote uninstall manifest $MANIFEST_FILE"
166
195
  }