@reddb-io/red-skills 4.1.13 → 4.1.14
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.
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/opencode-host.bundle.min.mjs +1 -1
- package/dist/redskilled-mcp.bundle.min.mjs +1 -1
- package/dist/redskilled.bundle.min.mjs +2 -2
- package/dist/release.bundle.min.mjs +1 -1
- package/dist/rsp-core.bundle.min.mjs +1 -1
- package/dist/rsp.bundle.min.mjs +1 -1
- package/package.json +1 -1
|
@@ -50,7 +50,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
50
50
|
`:`[${n[c]}\r
|
|
51
51
|
]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function Qa(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??je(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===E.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Ya(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===E.ZodBranded&&e.keyType._def.type._def.typeName===E.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Xa(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function Qv(e,t){if(t.mapStrategy==="record")return Qa(e,t);let r=W(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||je(t),n=W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||je(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function eb(e){let t=e.values,n=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function tb(e){return e.target==="openAi"?void 0:{not:je({...e,currentPath:[...e.currentPath,"not"]})}}function rb(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Qi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ob(e,t){if(t.target==="openApi3")return nb(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Qi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=Qi[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return nb(e,t)}var nb=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>W(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ib(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Qi[e.innerType._def.typeName],nullable:!0}:{type:[Qi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function sb(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",lf(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,t):ie(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,t):ie(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,t));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,t);break}return r}function ab(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],i=e.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let u=vO(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=W(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let s=_O(e,t);return s!==void 0&&(n.additionalProperties=s),n}function _O(e,t){if(e.catchall._def.typeName!=="ZodNever")return W(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function vO(e){try{return e.isOptional()}catch{return!0}}var cb=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return W(e.innerType._def,t);let r=W(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:je(t)},r]}:je(t)};var ub=(e,t)=>{if(t.pipeStrategy==="input")return W(e.in._def,t);if(t.pipeStrategy==="output")return W(e.out._def,t);let r=W(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=W(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function lb(e,t){return W(e.type._def,t)}function db(e,t){let n={type:"array",uniqueItems:!0,items:W(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ie(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ie(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function fb(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:W(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>W(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function pb(e){return{not:je(e)}}function mb(e){return je(e)}var hb=(e,t)=>W(e.innerType._def,t);var gb=(e,t,r)=>{switch(t){case E.ZodString:return Ya(e,r);case E.ZodNumber:return sb(e,r);case E.ZodObject:return ab(e,r);case E.ZodBigInt:return Vv(e,r);case E.ZodBoolean:return Hv();case E.ZodDate:return df(e,r);case E.ZodUndefined:return pb(r);case E.ZodNull:return rb(r);case E.ZodArray:return Uv(e,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return ob(e,r);case E.ZodIntersection:return Kv(e,r);case E.ZodTuple:return fb(e,r);case E.ZodRecord:return Qa(e,r);case E.ZodLiteral:return Xv(e,r);case E.ZodEnum:return Gv(e);case E.ZodNativeEnum:return eb(e);case E.ZodNullable:return ib(e,r);case E.ZodOptional:return cb(e,r);case E.ZodMap:return Qv(e,r);case E.ZodSet:return db(e,r);case E.ZodLazy:return()=>e.getter()._def;case E.ZodPromise:return lb(e,r);case E.ZodNaN:case E.ZodNever:return tb(r);case E.ZodEffects:return Jv(e,r);case E.ZodAny:return je(r);case E.ZodUnknown:return mb(r);case E.ZodDefault:return Wv(e,r);case E.ZodBranded:return Xa(e,r);case E.ZodReadonly:return hb(e,r);case E.ZodCatch:return Bv(e,r);case E.ZodPipeline:return ub(e,r);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(t)}};function W(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==Zv)return a}if(n&&!r){let a=bO(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let i=gb(e,e.typeName,t),s=typeof i=="function"?W(i(),t):i;if(s&&wO(e,t,s),t.postProcess){let a=t.postProcess(s,e,t);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var bO=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ka(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),je(t)):t.$refStrategy==="seen"?je(t):void 0}},wO=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r);var mf=(e,t)=>{let r=Fv(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??je(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=W(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??je(r),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function xO(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function hf(e,t){return At(e)?Md(e,{target:xO(t?.target),io:t?.pipeStrategy??"input"}):mf(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function gf(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Pa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function yf(e,t){let r=Wr(e,t);if(!r.success)throw r.error;return r.data}var $O=6e4,ec=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ja,r=>{this._oncancel(r)}),this.setNotificationHandler(Ia,r=>{this._onprogress(r)}),this.setRequestHandler(Na,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ma,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(U.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Aa,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,h=new Z(d.error.code,d.error.message,d.error.data);l(h)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new Z(U.InvalidParams,`Task not found: ${i}`);if(!Kr(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Kr(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Gr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(qa,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new Z(U.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(La,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Z(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(Kr(o.status))throw new Z(U.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Z(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof Z?o:new Z(U.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Z.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Vi(i)||Rv(i)?this._onresponse(i):Gd(i)?this._onrequest(i,s):Tv(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Z.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[Gr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=Sv(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,h)=>{if(s.signal.aborted)throw new Z(U.ConnectionClosed,"Request was cancelled");let m={...h,relatedRequestId:t.id};i&&!m.relatedTask&&(m.relatedTask={taskId:i});let p=m.relatedTask?.taskId??i;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Vi(t))n(t);else{let s=new Z(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Vi(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Vi(t))o(t);else{let s=Z.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof Z?s:new Z(U.InternalError,String(s))}}return}let i;try{let s=await this.request(t,zo,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Z(U.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Kr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new Z(U.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Z(U.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Z?s:new Z(U.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=T=>{l(T)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(T){d(T);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,m={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),m.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Gr]:c}});let p=T=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(T)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`)));let z=T instanceof Z?T:new Z(U.RequestTimeout,String(T));l(z)};this._responseHandlers.set(h,T=>{if(!n?.signal?.aborted){if(T instanceof Error)return l(T);try{let z=Wr(r,T.result);z.success?u(z.data):l(z.error)}catch(z){l(z)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let y=n?.timeout??$O,v=()=>p(Z.fromError(U.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(h,y,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let P=c?.taskId;if(P){let T=z=>{let M=this._responseHandlers.get(h);M?M(z):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))};this._requestResolvers.set(h,T),this._enqueueTaskMessage(P,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(h),l(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(T=>{this._cleanupTimeout(h),l(T)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Da,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Za,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Ov,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Gr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Gr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Gr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=gf(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=yf(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=gf(t);this._notificationHandlers.set(n,o=>{let i=yf(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&Gd(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new Z(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new Z(U.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new Z(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new Z(U.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=Gi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Kr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new Z(U.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Kr(a.status))throw new Z(U.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let u=Gi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Kr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function yb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _b(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];yb(s)&&yb(i)?r[o]={...s,...i}:r[o]=i}return r}var u$=ea(nm(),1),l$=ea(c$(),1);function P1(){let e=new u$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,l$.default)(e),e}var Ic=class{constructor(t){this._ajv=t??P1()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Mc=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(h=>h.type==="tool_use").map(h=>h.id)),d=new Set(i.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==d.size||![...l].every(h=>d.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Yi,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},Co,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function d$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function f$(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Dc=class extends ec{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Xi.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ic,this.setRequestHandler(Yd,n=>this._oninitialize(n)),this.setNotificationHandler(Qd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(af,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=Xi.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Mc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=_b(this._capabilities,t)}setRequestHandler(t,r){let o=Jr(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(At(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=Wr(Oo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new Z(U.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,h=await Promise.resolve(r(c,u));if(d.task){let p=Wr(zo,h);if(!p.success){let y=p.error instanceof Error?p.error.message:String(p.error);throw new Z(U.InvalidParams,`Invalid task creation result: ${y}`)}return p.data}let m=Wr(Ja,h);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new Z(U.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){f$(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&d$(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:wv.includes(r)?r:Wd,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ca)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},cf,r):this.request({method:"sampling/createMessage",params:t},Yi,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},Co,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Co,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Z(U.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Z?s:new Z(U.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},uf,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var m$=Symbol.for("mcp.completable");function dm(e){return!!e&&typeof e=="object"&&m$ in e}function h$(e){return e[m$]?.complete}var p$;(function(e){e.Completable="McpCompletable"})(p$||(p$={}));var T1=/^[A-Za-z0-9._-]{1,128}$/;function R1(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!T1.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function z1(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function fm(e){let t=R1(e);return z1(e,t.warnings),t.isValid}var Ac=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var qc=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Dc(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ac(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Wa)),this.server.assertCanSetRequestHandler(sn(Oo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Wa,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=To(r.inputSchema);return o?hf(o,{strictUnions:!0,pipeStrategy:"input"}):E1})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=To(r.outputSchema);o&&(n.outputSchema=hf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Oo,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new Z(U.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new Z(U.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new Z(U.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof Z&&n.code===U.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=To(t.inputSchema)??t.inputSchema,s=await Sa(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=ka(a);throw new Z(U.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Z(U.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=To(t.outputSchema),i=await Sa(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ka(s);throw new Z(U.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(h=>setTimeout(h,l));let d=await n.taskStore.getTask(c);if(!d)throw new Z(U.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(sn(Ga)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ga,async t=>{switch(t.params.ref.type){case"ref/prompt":return Dv(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return Av(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Z(U.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new Z(U.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return zs;let i=Jr(n.argsSchema)?.[t.params.argument.name];if(!dm(i))return zs;let s=h$(i);if(!s)return zs;let a=await s(t.params.argument.value,t.params.context);return y$(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return zs;throw new Z(U.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return zs;let i=await o(t.params.argument.value,t.params.context);return y$(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Fa)),this.server.assertCanSetRequestHandler(sn(Ua)),this.server.assertCanSetRequestHandler(sn(Va)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Fa,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Ua,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Va,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Z(U.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new Z(U.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(Ha)),this.server.assertCanSetRequestHandler(sn(Ba)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ha,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?O1(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ba,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new Z(U.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new Z(U.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=To(n.argsSchema),i=await Sa(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",u=ka(c);throw new Z(U.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${u}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==t&&(delete this._registeredResourceTemplates[t],u.name&&(this._registeredResourceTemplates[u.name]=s)),typeof u.title<"u"&&(s.title=u.title),typeof u.template<"u"&&(s.resourceTemplate=u.template),typeof u.metadata<"u"&&(s.metadata=u.metadata),typeof u.callback<"u"&&(s.readCallback=u.callback),typeof u.enabled<"u"&&(s.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Hn(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Hn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let u=c instanceof bt?c._def?.innerType:c;return dm(u)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,u){fm(t);let l={title:r,description:n,inputSchema:g$(o),outputSchema:g$(i),annotations:s,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&fm(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Hn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(pm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!pm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},u,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var E1={type:"object",properties:{}};function _$(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function v$(e){return"_def"in e||"_zod"in e||_$(e)}function pm(e){return typeof e!="object"||e===null||v$(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(_$)}function g$(e){if(e){if(pm(e))return Hn(e);if(!v$(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function O1(e){let t=Jr(e);return t?Object.entries(t).map(([r,n])=>{let o=X_(n),i=Y_(n);return{name:r,description:o,required:!i}}):[]}function sn(e){let r=Jr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Pa(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function y$(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var zs={completion:{values:[],hasMore:!1}};import w$ from"node:process";var Zc=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
52
52
|
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),C1(r)}clear(){this._buffer=void 0}};function C1(e){return zv.parse(JSON.parse(e))}function b$(e){return JSON.stringify(e)+`
|
|
53
|
-
`}var Lc=class{constructor(t=w$.stdin,r=w$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Zc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=b$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function mm(e){let t={app:e,version:j1(Xo("__RED_BUILD_VERSION__",()=>"4.1.
|
|
53
|
+
`}var Lc=class{constructor(t=w$.stdin,r=w$.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Zc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=b$(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function mm(e){let t={app:e,version:j1(Xo("__RED_BUILD_VERSION__",()=>"4.1.14")??"0.0.0-dev"),gitSha:Xo("__RED_BUILD_GIT_SHA__",()=>"a2c2d45c9f89f44932e381ec4b99bf2aa5d25445")??"unknown",buildTime:Xo("__RED_BUILD_TIME__",()=>"2026-08-21T02:01:02-03:00")??"unknown",bundleAsset:Xo("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=Xo("__REDDB_SDK_VERSION__",()=>""),n=Xo("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function j1(e){return e.startsWith("v")?e.slice(1):e}function x$(e){return`${e.app} ${e.version} ${e.gitSha}`}function Xo(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var $$={"=":"data",":=":{to:"data",typed:!0},":":"meta"},N1=/^[a-z][a-z0-9+.-]*:\/\//i;function I1(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function M1(e=$$){return Object.entries(e).map(([t,r])=>I1(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function D1(e){return/^-\d+(\.\d+)?$/.test(e)}function Es(e){return!(!e||e.startsWith("-")&&!D1(e))}function Fc(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function S$(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(r=>S$(r.trim())):e}function no(e,t){switch(t){case"boolean":return A1(e);case"number":return q1(e);case"array":return e.split(",").map(r=>Fc(r.trim()));default:return e}}function A1(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function q1(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function an(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Z1(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function $e(e,t){return{type:e,value:t}}function L1(e){let t=[],r=U1(e);if(t.push($e("section-header","Usage:"),$e("text"," "),$e("usage-text",r),$e("newline",`
|
|
54
54
|
`),$e("newline",`
|
|
55
55
|
`)),e.positional&&e.positional.length>0){t.push($e("section-header","Arguments:"),$e("newline",`
|
|
56
56
|
`));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;t.push($e("indent"," "),$e("positional-name",`<${o}>`)),n.required||t.push($e("positional-optional"," (optional)")),t.push($e("newline",`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
-
import{mkdirSync as Pe,readFileSync as nn,writeFileSync as on}from"node:fs";import{dirname as sn,resolve as V}from"node:path";function W(e){let t={app:e,version:Ce(b("__RED_BUILD_VERSION__",()=>"4.1.
|
|
2
|
+
import{mkdirSync as Pe,readFileSync as nn,writeFileSync as on}from"node:fs";import{dirname as sn,resolve as V}from"node:path";function W(e){let t={app:e,version:Ce(b("__RED_BUILD_VERSION__",()=>"4.1.14")??"0.0.0-dev"),gitSha:b("__RED_BUILD_GIT_SHA__",()=>"a2c2d45c9f89f44932e381ec4b99bf2aa5d25445")??"unknown",buildTime:b("__RED_BUILD_TIME__",()=>"2026-08-21T02:01:02-03:00")??"unknown",bundleAsset:b("__RED_BUNDLE_ASSET__",()=>"opencode-host.bundle.min.mjs")??"unknown"},n=b("__REDDB_SDK_VERSION__",()=>""),s=b("__REDDB_BINARY_TAG__",()=>"");return n&&(t.reddbSdkVersion=n),s&&(t.reddbBinaryTag=s),t}function Ce(e){return e.startsWith("v")?e.slice(1):e}function G(e){return`${e.app} ${e.version} ${e.gitSha}`}function b(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ne={"=":"data",":=":{to:"data",typed:!0},":":"meta"},Te=/^[a-z][a-z0-9+.-]*:\/\//i;function Ie(e,t){return typeof t=="string"?{separator:e,to:t,typed:!1,prefix:!1}:{separator:e,to:t.to,typed:t.typed??!1,prefix:t.prefix??!1}}function je(e=ne){return Object.entries(e).map(([t,n])=>Ie(t,n)).sort((t,n)=>n.separator.length-t.separator.length)}function Fe(e){return/^-\d+(\.\d+)?$/.test(e)}function $(e){return!(!e||e.startsWith("-")&&!Fe(e))}function A(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e}function oe(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)&&e.trim()!==""?t:e.includes(",")?e.split(",").map(n=>oe(n.trim())):e}function k(e,t){switch(t){case"boolean":return Ne(e);case"number":return De(e);case"array":return e.split(",").map(n=>A(n.trim()));case"string":default:return e}}function Ne(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function De(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function _(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Me(e,t={}){return e.map(n=>{let s=t[n.type];return s?s(n.value):n.value}).join("")}function g(e,t){return{type:e,value:t}}function Le(e){let t=[],n=Ve(e);if(t.push(g("section-header","Usage:"),g("text"," "),g("usage-text",n),g("newline",`
|
|
3
3
|
`),g("newline",`
|
|
4
4
|
`)),e.positional&&e.positional.length>0){t.push(g("section-header","Arguments:"),g("newline",`
|
|
5
5
|
`));for(let s of e.positional)if(s.description){let o=s.variadic?`${s.name}...`:s.name;t.push(g("indent"," "),g("positional-name",`<${o}>`)),s.required||t.push(g("positional-optional"," (optional)")),t.push(g("newline",`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var Wdt=Object.create;var QW=Object.defineProperty;var Vdt=Object.getOwnPropertyDescriptor;var Kdt=Object.getOwnPropertyNames;var Zdt=Object.getPrototypeOf,Jdt=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vn=(e,t)=>{for(var r in t)QW(e,r,{get:t[r],enumerable:!0})},Qdt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kdt(t))!Jdt.call(e,o)&&o!==r&&QW(e,o,{get:()=>t[o],enumerable:!(n=Vdt(t,o))||n.enumerable});return e};var Ip=(e,t,r)=>(r=e!=null?Wdt(Zdt(e)):{},Qdt(t||!e||!e.__esModule?QW(r,"default",{value:e,enumerable:!0}):r,e));function YW(e){let t={app:e,version:Ydt(hk("__RED_BUILD_VERSION__",()=>"4.1.13")??"0.0.0-dev"),gitSha:hk("__RED_BUILD_GIT_SHA__",()=>"19ba7780d0a8be832373d24cce303d1833430d2d")??"unknown",buildTime:hk("__RED_BUILD_TIME__",()=>"2026-08-21T01:42:13-03:00")??"unknown",bundleAsset:hk("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=hk("__REDDB_SDK_VERSION__",()=>""),n=hk("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Ydt(e){return e.startsWith("v")?e.slice(1):e}function lSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function hk(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var XW=p(()=>{});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function yo(e){return e&&Object.assign(Hy,e),Hy}var uSe,t4,r4,Hl,Bm,Hy,qy=p(()=>{t4=Object.freeze({status:"aborted"});r4=Symbol("zod_brand"),Hl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Bm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(uSe=globalThis).__zod_globalConfig??(uSe.__zod_globalConfig={});Hy=globalThis.__zod_globalConfig});var Re={};Vn(Re,{BIGINT_FORMAT_RANGES:()=>p4,Class:()=>o4,NUMBER_FORMAT_RANGES:()=>d4,aborted:()=>Zm,allowsEval:()=>a4,assert:()=>opt,assertEqual:()=>ept,assertIs:()=>rpt,assertNever:()=>npt,assertNotEqual:()=>tpt,assignProp:()=>Vm,base64ToUint8Array:()=>pSe,base64urlToUint8Array:()=>kpt,cached:()=>yk,captureStackTrace:()=>A$,cleanEnum:()=>Spt,cleanRegex:()=>I0,clone:()=>Cs,cloneDef:()=>spt,createTransparentProxy:()=>ppt,defineLazy:()=>Jt,esc:()=>I$,escapeRegex:()=>$c,explicitlyAborted:()=>f4,extend:()=>hpt,finalizeIssue:()=>Ps,floatSafeRemainder:()=>i4,getElementAtPath:()=>apt,getEnumValues:()=>P0,getLengthableOrigin:()=>$0,getParsedType:()=>dpt,getSizableOrigin:()=>O0,hexToUint8Array:()=>wpt,isObject:()=>Gy,isPlainObject:()=>Km,issue:()=>bk,joinValues:()=>ne,jsonStringifyReplacer:()=>gk,merge:()=>ypt,mergeDefs:()=>Ap,normalizeParams:()=>Ie,nullish:()=>Wm,numKeys:()=>upt,objectClone:()=>ipt,omit:()=>mpt,optionalKeys:()=>u4,parsedType:()=>Ee,partial:()=>bpt,pick:()=>fpt,prefixIssues:()=>ca,primitiveTypes:()=>l4,promiseAllObject:()=>cpt,propertyKeyTypes:()=>A0,randomString:()=>lpt,required:()=>xpt,safeExtend:()=>gpt,shallowClone:()=>c4,slugify:()=>s4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>fSe,uint8ArrayToBase64url:()=>_pt,uint8ArrayToHex:()=>vpt,unwrapMessage:()=>C0});function ept(e){return e}function tpt(e){return e}function rpt(e){}function npt(e){throw new Error("Unexpected value in exhaustive check")}function opt(e){}function P0(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function gk(e,t){return typeof t=="bigint"?t.toString():t}function yk(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Wm(e){return e==null}function I0(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function i4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Jt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==dSe)return n===void 0&&(n=dSe,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function ipt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Vm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ap(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function spt(e){return Ap(e._zod.def)}function apt(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function cpt(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function lpt(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function I$(e){return JSON.stringify(e)}function s4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Gy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Km(e){if(Gy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Gy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function c4(e){return Km(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function upt(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function $c(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cs(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ppt(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function u4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function fpt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Ap(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Vm(this,"shape",s),s},checks:[]});return Cs(e,i)}function mpt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Ap(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Vm(this,"shape",s),s},checks:[]});return Cs(e,i)}function hpt(e,t){if(!Km(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Ap(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Vm(this,"shape",i),i}});return Cs(e,o)}function gpt(e,t){if(!Km(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Ap(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Vm(this,"shape",n),n}});return Cs(e,r)}function ypt(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Ap(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Vm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Cs(e,r)}function bpt(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Ap(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Vm(this,"shape",c),c},checks:[]});return Cs(t,s)}function xpt(e,t,r){let n=Ap(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Vm(this,"shape",i),i}});return Cs(t,n)}function Zm(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function f4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ca(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function C0(e){return typeof e=="string"?e:e?.message}function Ps(e,t,r){let n=e.message?e.message:C0(e.inst?._zod.def?.error?.(e))??C0(t?.error?.(e))??C0(r.customError?.(e))??C0(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function O0(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function $0(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function bk(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Spt(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function pSe(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function fSe(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function kpt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return pSe(t+r)}function _pt(e){return fSe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function wpt(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function vpt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var dSe,A$,a4,dpt,A0,l4,d4,p4,o4,ot=p(()=>{qy();dSe=Symbol("evaluating");A$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};a4=yk(()=>{if(Hy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});dpt=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},A0=new Set(["string","number","symbol"]),l4=new Set(["string","number","bigint","boolean","symbol","undefined"]);d4={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]},p4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};o4=class{constructor(...t){}}});function D0(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function N0(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function m4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function hSe(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function h4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${hSe(n.path)}`);return t.join(`
|
|
3
|
+
var Wdt=Object.create;var QW=Object.defineProperty;var Vdt=Object.getOwnPropertyDescriptor;var Kdt=Object.getOwnPropertyNames;var Zdt=Object.getPrototypeOf,Jdt=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vn=(e,t)=>{for(var r in t)QW(e,r,{get:t[r],enumerable:!0})},Qdt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kdt(t))!Jdt.call(e,o)&&o!==r&&QW(e,o,{get:()=>t[o],enumerable:!(n=Vdt(t,o))||n.enumerable});return e};var Ip=(e,t,r)=>(r=e!=null?Wdt(Zdt(e)):{},Qdt(t||!e||!e.__esModule?QW(r,"default",{value:e,enumerable:!0}):r,e));function YW(e){let t={app:e,version:Ydt(hk("__RED_BUILD_VERSION__",()=>"4.1.14")??"0.0.0-dev"),gitSha:hk("__RED_BUILD_GIT_SHA__",()=>"a2c2d45c9f89f44932e381ec4b99bf2aa5d25445")??"unknown",buildTime:hk("__RED_BUILD_TIME__",()=>"2026-08-21T02:01:02-03:00")??"unknown",bundleAsset:hk("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=hk("__REDDB_SDK_VERSION__",()=>""),n=hk("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Ydt(e){return e.startsWith("v")?e.slice(1):e}function lSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function hk(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var XW=p(()=>{});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function yo(e){return e&&Object.assign(Hy,e),Hy}var uSe,t4,r4,Hl,Bm,Hy,qy=p(()=>{t4=Object.freeze({status:"aborted"});r4=Symbol("zod_brand"),Hl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Bm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(uSe=globalThis).__zod_globalConfig??(uSe.__zod_globalConfig={});Hy=globalThis.__zod_globalConfig});var Re={};Vn(Re,{BIGINT_FORMAT_RANGES:()=>p4,Class:()=>o4,NUMBER_FORMAT_RANGES:()=>d4,aborted:()=>Zm,allowsEval:()=>a4,assert:()=>opt,assertEqual:()=>ept,assertIs:()=>rpt,assertNever:()=>npt,assertNotEqual:()=>tpt,assignProp:()=>Vm,base64ToUint8Array:()=>pSe,base64urlToUint8Array:()=>kpt,cached:()=>yk,captureStackTrace:()=>A$,cleanEnum:()=>Spt,cleanRegex:()=>I0,clone:()=>Cs,cloneDef:()=>spt,createTransparentProxy:()=>ppt,defineLazy:()=>Jt,esc:()=>I$,escapeRegex:()=>$c,explicitlyAborted:()=>f4,extend:()=>hpt,finalizeIssue:()=>Ps,floatSafeRemainder:()=>i4,getElementAtPath:()=>apt,getEnumValues:()=>P0,getLengthableOrigin:()=>$0,getParsedType:()=>dpt,getSizableOrigin:()=>O0,hexToUint8Array:()=>wpt,isObject:()=>Gy,isPlainObject:()=>Km,issue:()=>bk,joinValues:()=>ne,jsonStringifyReplacer:()=>gk,merge:()=>ypt,mergeDefs:()=>Ap,normalizeParams:()=>Ie,nullish:()=>Wm,numKeys:()=>upt,objectClone:()=>ipt,omit:()=>mpt,optionalKeys:()=>u4,parsedType:()=>Ee,partial:()=>bpt,pick:()=>fpt,prefixIssues:()=>ca,primitiveTypes:()=>l4,promiseAllObject:()=>cpt,propertyKeyTypes:()=>A0,randomString:()=>lpt,required:()=>xpt,safeExtend:()=>gpt,shallowClone:()=>c4,slugify:()=>s4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>fSe,uint8ArrayToBase64url:()=>_pt,uint8ArrayToHex:()=>vpt,unwrapMessage:()=>C0});function ept(e){return e}function tpt(e){return e}function rpt(e){}function npt(e){throw new Error("Unexpected value in exhaustive check")}function opt(e){}function P0(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function gk(e,t){return typeof t=="bigint"?t.toString():t}function yk(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Wm(e){return e==null}function I0(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function i4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Jt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==dSe)return n===void 0&&(n=dSe,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function ipt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Vm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ap(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function spt(e){return Ap(e._zod.def)}function apt(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function cpt(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function lpt(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function I$(e){return JSON.stringify(e)}function s4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Gy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Km(e){if(Gy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Gy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function c4(e){return Km(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function upt(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function $c(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cs(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function ppt(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function u4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function fpt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Ap(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Vm(this,"shape",s),s},checks:[]});return Cs(e,i)}function mpt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Ap(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Vm(this,"shape",s),s},checks:[]});return Cs(e,i)}function hpt(e,t){if(!Km(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Ap(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Vm(this,"shape",i),i}});return Cs(e,o)}function gpt(e,t){if(!Km(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Ap(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Vm(this,"shape",n),n}});return Cs(e,r)}function ypt(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Ap(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Vm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Cs(e,r)}function bpt(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Ap(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Vm(this,"shape",c),c},checks:[]});return Cs(t,s)}function xpt(e,t,r){let n=Ap(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Vm(this,"shape",i),i}});return Cs(t,n)}function Zm(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function f4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ca(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function C0(e){return typeof e=="string"?e:e?.message}function Ps(e,t,r){let n=e.message?e.message:C0(e.inst?._zod.def?.error?.(e))??C0(t?.error?.(e))??C0(r.customError?.(e))??C0(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function O0(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function $0(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function bk(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Spt(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function pSe(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function fSe(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function kpt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return pSe(t+r)}function _pt(e){return fSe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function wpt(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function vpt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var dSe,A$,a4,dpt,A0,l4,d4,p4,o4,ot=p(()=>{qy();dSe=Symbol("evaluating");A$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};a4=yk(()=>{if(Hy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});dpt=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},A0=new Set(["string","number","symbol"]),l4=new Set(["string","number","bigint","boolean","symbol","undefined"]);d4={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]},p4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};o4=class{constructor(...t){}}});function D0(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function N0(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function m4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function hSe(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function h4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${hSe(n.path)}`);return t.join(`
|
|
4
4
|
`)}var mSe,M0,la,g4=p(()=>{qy();ot();mSe=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,gk,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},M0=K("$ZodError",mSe),la=K("$ZodError",mSe,{Parent:Error})});var xk,O$,Sk,$$,kk,y4,_k,b4,M$,Rpt,D$,Tpt,N$,Cpt,z$,Ppt,L$,Ipt,F$,Apt,j$,Opt,U$,$pt,x4=p(()=>{qy();g4();ot();xk=e=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Hl;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ps(c,i,yo())));throw A$(a,o?.callee),a}return s.value},O$=xk(la),Sk=e=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ps(c,i,yo())));throw A$(a,o?.callee),a}return s.value},$$=Sk(la),kk=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Hl;return i.issues.length?{success:!1,error:new(e??M0)(i.issues.map(s=>Ps(s,o,yo())))}:{success:!0,data:i.value}},y4=kk(la),_k=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Ps(s,o,yo())))}:{success:!0,data:i.value}},b4=_k(la),M$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return xk(e)(t,r,o)},Rpt=M$(la),D$=e=>(t,r,n)=>xk(e)(t,r,n),Tpt=D$(la),N$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Sk(e)(t,r,o)},Cpt=N$(la),z$=e=>async(t,r,n)=>Sk(e)(t,r,n),Ppt=z$(la),L$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return kk(e)(t,r,o)},Ipt=L$(la),F$=e=>(t,r,n)=>kk(e)(t,r,n),Apt=F$(la),j$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return _k(e)(t,r,o)},Opt=j$(la),U$=e=>async(t,r,n)=>_k(e)(t,r,n),$pt=U$(la)});var Va={};Vn(Va,{base64:()=>D4,base64url:()=>H$,bigint:()=>H4,boolean:()=>G4,browserEmail:()=>Upt,cidrv4:()=>$4,cidrv6:()=>M4,cuid:()=>S4,cuid2:()=>k4,date:()=>L4,datetime:()=>j4,domain:()=>Gpt,duration:()=>R4,e164:()=>z4,email:()=>C4,emoji:()=>P4,extendedDuration:()=>Mpt,guid:()=>T4,hex:()=>Bpt,hostname:()=>qpt,html5Email:()=>Lpt,httpProtocol:()=>N4,idnEmail:()=>jpt,integer:()=>q4,ipv4:()=>I4,ipv6:()=>A4,ksuid:()=>v4,lowercase:()=>V4,mac:()=>O4,md5_base64:()=>Vpt,md5_base64url:()=>Kpt,md5_hex:()=>Wpt,nanoid:()=>E4,null:()=>B4,number:()=>q$,rfc5322Email:()=>Fpt,sha1_base64:()=>Jpt,sha1_base64url:()=>Qpt,sha1_hex:()=>Zpt,sha256_base64:()=>Xpt,sha256_base64url:()=>eft,sha256_hex:()=>Ypt,sha384_base64:()=>rft,sha384_base64url:()=>nft,sha384_hex:()=>tft,sha512_base64:()=>ift,sha512_base64url:()=>sft,sha512_hex:()=>oft,string:()=>U4,time:()=>F4,ulid:()=>_4,undefined:()=>W4,unicodeEmail:()=>gSe,uppercase:()=>K4,uuid:()=>By,uuid4:()=>Dpt,uuid6:()=>Npt,uuid7:()=>zpt,xid:()=>w4});function P4(){return new RegExp(Hpt,"u")}function bSe(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function F4(e){return new RegExp(`^${bSe(e)}$`)}function j4(e){let t=bSe({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${ySe}T(?:${n})$`)}function z0(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function L0(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var S4,k4,_4,w4,v4,E4,R4,Mpt,T4,By,Dpt,Npt,zpt,C4,Lpt,Fpt,gSe,jpt,Upt,Hpt,I4,A4,O4,$4,M4,D4,H$,qpt,Gpt,N4,z4,ySe,L4,U4,H4,q4,q$,G4,B4,W4,V4,K4,Bpt,Wpt,Vpt,Kpt,Zpt,Jpt,Qpt,Ypt,Xpt,eft,tft,rft,nft,oft,ift,sft,G$=p(()=>{ot();S4=/^[cC][0-9a-z]{6,}$/,k4=/^[0-9a-z]+$/,_4=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,w4=/^[0-9a-vA-V]{20}$/,v4=/^[A-Za-z0-9]{27}$/,E4=/^[a-zA-Z0-9_-]{21}$/,R4=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Mpt=/^[-+]?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)?)??$/,T4=/^([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})$/,By=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Dpt=By(4),Npt=By(6),zpt=By(7),C4=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Lpt=/^[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])?)*$/,Fpt=/^(([^<>()\[\]\\.,;:\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,}))$/,gSe=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,jpt=gSe,Upt=/^[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])?)*$/,Hpt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";I4=/^(?:(?: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])$/,A4=/^(([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}|:))$/,O4=e=>{let t=$c(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},$4=/^((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])$/,M4=/^(([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])$/,D4=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,H$=/^[A-Za-z0-9_-]*$/,qpt=/^(?=.{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])?)*\.?$/,Gpt=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,N4=/^https?$/,z4=/^\+[1-9]\d{6,14}$/,ySe="(?:(?:\\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])))",L4=new RegExp(`^${ySe}$`);U4=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},H4=/^-?\d+n?$/,q4=/^-?\d+$/,q$=/^-?\d+(?:\.\d+)?$/,G4=/^(?:true|false)$/i,B4=/^null$/i,W4=/^undefined$/i,V4=/^[^A-Z]*$/,K4=/^[^a-z]*$/,Bpt=/^[0-9a-fA-F]*$/;Wpt=/^[0-9a-fA-F]{32}$/,Vpt=z0(22,"=="),Kpt=L0(22),Zpt=/^[0-9a-fA-F]{40}$/,Jpt=z0(27,"="),Qpt=L0(27),Ypt=/^[0-9a-fA-F]{64}$/,Xpt=z0(43,"="),eft=L0(43),tft=/^[0-9a-fA-F]{96}$/,rft=z0(64,""),nft=L0(64),oft=/^[0-9a-fA-F]{128}$/,ift=z0(86,"=="),sft=L0(86)});function xSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues))}var un,SSe,B$,W$,Z4,J4,Q4,Y4,X4,eV,tV,rV,nV,wk,oV,iV,sV,aV,cV,lV,uV,dV,pV,V$=p(()=>{qy();G$();ot();un=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),SSe={number:"number",bigint:"bigint",object:"date"},B$=K("$ZodCheckLessThan",(e,t)=>{un.init(e,t);let r=SSe[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),W$=K("$ZodCheckGreaterThan",(e,t)=>{un.init(e,t);let r=SSe[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Z4=K("$ZodCheckMultipleOf",(e,t)=>{un.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):i4(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),J4=K("$ZodCheckNumberFormat",(e,t)=>{un.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=d4[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=q4)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Q4=K("$ZodCheckBigIntFormat",(e,t)=>{un.init(e,t);let[r,n]=p4[t.format];e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{let i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),Y4=K("$ZodCheckMaxSize",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Wm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;o.size<=t.maximum||n.issues.push({origin:O0(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),X4=K("$ZodCheckMinSize",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Wm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:O0(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),eV=K("$ZodCheckSizeEquals",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Wm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,i=o.size;if(i===t.size)return;let s=i>t.size;n.issues.push({origin:O0(o),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),tV=K("$ZodCheckMaxLength",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Wm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=$0(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),rV=K("$ZodCheckMinLength",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Wm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=$0(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),nV=K("$ZodCheckLengthEquals",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Wm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=$0(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),wk=K("$ZodCheckStringFormat",(e,t)=>{var r,n;un.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),oV=K("$ZodCheckRegex",(e,t)=>{wk.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),iV=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=V4),wk.init(e,t)}),sV=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=K4),wk.init(e,t)}),aV=K("$ZodCheckIncludes",(e,t)=>{un.init(e,t);let r=$c(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),cV=K("$ZodCheckStartsWith",(e,t)=>{un.init(e,t);let r=new RegExp(`^${$c(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),lV=K("$ZodCheckEndsWith",(e,t)=>{un.init(e,t);let r=new RegExp(`.*${$c(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});uV=K("$ZodCheckProperty",(e,t)=>{un.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>xSe(o,r,t.property));xSe(n,r,t.property)}}),dV=K("$ZodCheckMimeType",(e,t)=>{un.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),pV=K("$ZodCheckOverwrite",(e,t)=>{un.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var F0,fV=p(()=>{F0=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
|
|
5
5
|
`).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
|
|
6
6
|
`))}}});var mV,hV=p(()=>{mV={major:4,minor:4,patch:3}});function zV(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function NSe(e){if(!H$.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return zV(r)}function zSe(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}function _Se(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues)),t.value[r]=e.value}function Q$(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...ca(r,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function LSe(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=u4(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function FSe(e,t,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,l=c.def.type,u=c.optin==="optional",d=c.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(l==="never"){s.push(f);continue}let m=c.run({value:t[f],issues:[]},n);m instanceof Promise?e.push(m.then(y=>Q$(y,r,f,t,u,d))):Q$(m,r,f,t,u,d)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function wSe(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!Zm(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Ps(s,n,yo())))}),t)}function vSe(e,t,r,n){let o=e.filter(i=>i.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Ps(s,n,yo())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function gV(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Km(e)&&Km(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=gV(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=gV(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 ESe(e,t,r){let n=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),Zm(e))return e;let s=gV(t.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}function RSe(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function TSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues)),t.value[r]=e.value}function CSe(e,t,r,n,o){for(let i=0;i<r.length;i++){let s=e[i],a=i<n.length;if(s.issues.length){if(!a&&i>=o){t.value.length=i;break}t.issues.push(...ca(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=n.length&&(r[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}function PSe(e,t,r,n,o,i,s){e.issues.length&&(A0.has(typeof n)?r.issues.push(...ca(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map(a=>Ps(a,s,yo()))})),t.issues.length&&(A0.has(typeof n)?r.issues.push(...ca(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:t.issues.map(a=>Ps(a,s,yo()))})),r.value.set(e.value,t.value)}function ISe(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function ASe(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}function OSe(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function $Se(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function K$(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function Z$(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(i=>J$(e,i,t.out,r)):J$(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(i=>J$(e,i,t.in,r)):J$(e,o,t.in,r)}}function J$(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}function MSe(e){return e.value=Object.freeze(e.value),e}function DSe(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(bk(o))}}var At,Wy,Qr,yV,bV,xV,SV,kV,_V,wV,vV,EV,RV,TV,CV,PV,IV,AV,OV,$V,MV,DV,NV,LV,FV,jV,UV,HV,Y$,qV,j0,X$,GV,BV,WV,VV,KV,ZV,JV,QV,YV,XV,jSe,e6,U0,t6,r6,n6,eM,o6,i6,s6,a6,c6,l6,u6,tM,d6,p6,f6,m6,h6,g6,y6,b6,rM,H0,x6,S6,k6,_6,w6,v6,E6,R6=p(()=>{V$();qy();fV();x4();G$();ot();hV();ot();At=K("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=mV;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,a,c)=>{let l=Zm(s),u;for(let d of a){if(d._zod.def.when){if(f4(s)||!d._zod.def.when(s))continue}else if(l)continue;let f=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&c?.async===!1)throw new Hl;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==f&&(l||(l=Zm(s,f)))});else{if(s.issues.length===f)continue;l||(l=Zm(s,f))}}return u?u.then(()=>s):s},i=(s,a,c)=>{if(Zm(s))return s.aborted=!0,s;let l=o(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new Hl;return l.then(u=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>i(u,s,a)):i(l,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Hl;return c.then(l=>o(l,n,a))}return o(c,n,a)}}Jt(e,"~standard",()=>({validate:o=>{try{let i=y4(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return b4(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Wy=K("$ZodString",(e,t)=>{At.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??U4(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Qr=K("$ZodStringFormat",(e,t)=>{wk.init(e,t),Wy.init(e,t)}),yV=K("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=T4),Qr.init(e,t)}),bV=K("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=By(n))}else t.pattern??(t.pattern=By());Qr.init(e,t)}),xV=K("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=C4),Qr.init(e,t)}),SV=K("$ZodURL",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===N4.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),kV=K("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=P4()),Qr.init(e,t)}),_V=K("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=E4),Qr.init(e,t)}),wV=K("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=S4),Qr.init(e,t)}),vV=K("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=k4),Qr.init(e,t)}),EV=K("$ZodULID",(e,t)=>{t.pattern??(t.pattern=_4),Qr.init(e,t)}),RV=K("$ZodXID",(e,t)=>{t.pattern??(t.pattern=w4),Qr.init(e,t)}),TV=K("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=v4),Qr.init(e,t)}),CV=K("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=j4(t)),Qr.init(e,t)}),PV=K("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=L4),Qr.init(e,t)}),IV=K("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=F4(t)),Qr.init(e,t)}),AV=K("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=R4),Qr.init(e,t)}),OV=K("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=I4),Qr.init(e,t),e._zod.bag.format="ipv4"}),$V=K("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=A4),Qr.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),MV=K("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=O4(t.delimiter)),Qr.init(e,t),e._zod.bag.format="mac"}),DV=K("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=$4),Qr.init(e,t)}),NV=K("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=M4),Qr.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});LV=K("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=D4),Qr.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{zV(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});FV=K("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=H$),Qr.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{NSe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),jV=K("$ZodE164",(e,t)=>{t.pattern??(t.pattern=z4),Qr.init(e,t)});UV=K("$ZodJWT",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{zSe(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),HV=K("$ZodCustomStringFormat",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),Y$=K("$ZodNumber",(e,t)=>{At.init(e,t),e._zod.pattern=e._zod.bag.pattern??q$,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),qV=K("$ZodNumberFormat",(e,t)=>{J4.init(e,t),Y$.init(e,t)}),j0=K("$ZodBoolean",(e,t)=>{At.init(e,t),e._zod.pattern=G4,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),X$=K("$ZodBigInt",(e,t)=>{At.init(e,t),e._zod.pattern=H4,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),GV=K("$ZodBigIntFormat",(e,t)=>{Q4.init(e,t),X$.init(e,t)}),BV=K("$ZodSymbol",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),WV=K("$ZodUndefined",(e,t)=>{At.init(e,t),e._zod.pattern=W4,e._zod.values=new Set([void 0]),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),VV=K("$ZodNull",(e,t)=>{At.init(e,t),e._zod.pattern=B4,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),KV=K("$ZodAny",(e,t)=>{At.init(e,t),e._zod.parse=r=>r}),ZV=K("$ZodUnknown",(e,t)=>{At.init(e,t),e._zod.parse=r=>r}),JV=K("$ZodNever",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),QV=K("$ZodVoid",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),YV=K("$ZodDate",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});XV=K("$ZodArray",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>_Se(l,r,s))):_Se(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});jSe=K("$ZodObject",(e,t)=>{if(At.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=yk(()=>LSe(t));Jt(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let o=Gy,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!o(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let m=d[f],y=m._zod.optin==="optional",S=m._zod.optout==="optional",_=m._zod.run({value:l[f],issues:[]},c);_ instanceof Promise?u.push(_.then(R=>Q$(R,a,f,l,y,S))):Q$(_,a,f,l,y,S)}return i?FSe(u,l,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}}),e6=K("$ZodObjectJIT",(e,t)=>{jSe.init(e,t);let r=e._zod.parse,n=yk(()=>LSe(t)),o=f=>{let m=new F0(["shape","payload","ctx"]),y=n.value,S=C=>{let O=I$(C);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};m.write("const input = payload.value;");let _=Object.create(null),R=0;for(let C of y.keys)_[C]=`key_${R++}`;m.write("const newResult = {};");for(let C of y.keys){let O=_[C],M=I$(C),z=f[C],F=z?._zod?.optin==="optional",H=z?._zod?.optout==="optional";m.write(`const ${O} = ${S(C)};`),F&&H?m.write(`
|
|
@@ -164,7 +164,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
164
164
|
`}function nx(e,t){return t.map(Xr).join(e)}function Lpe(e){if(!Array.isArray(e)||e.length===0)throw xt(0,"TOONL header requires fields");return e.map(t=>{let r;try{[r]=Ys(String(t),0)}catch(n){throw ld(n)}if(r==="")throw xt(0,"TOONL header requires fields");return r})}function g2(e,t){return e!==null&&e.length===t.length&&e.every((r,n)=>r===t[n])}function y2(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw xt(0,"TOONL continuation cadence must be positive")}function Fpe(e,t,r){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&r>=e.continuationEveryBytes}function b2(e){if(e===null||typeof e!="object"||Array.isArray(e))throw xt(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw xt(0,"TOONL output requires object rows");if(t.some(r=>!uf(e[r])))throw xt(0,"TOONL rows must be flat objects");return t}function Gpe(e){return JSON.stringify([...e].sort())}function k2(e,t){let r=Gpe(e),n=t.get(r);return n!==void 0?n:(t.set(r,e),e)}function $t({delimiter:e=os,trailer:t=!0,continuationEveryRows:r,continuationEveryBytes:n}={}){Npe(e),y2(r),y2(n);let o=null,i="",s=new Map,a=0,l=0,c=0,d=new Map,u=!1,p={continuationEveryRows:r,continuationEveryBytes:n},f=()=>o===null||!t?"":`[=${a}]
|
|
165
165
|
`,h=()=>Fpe(p,l,c)?(l=0,c=0,m2(e,i,!0)):"",g=k=>{R2(k,0);let _=d.get(k);if(_===void 0){if(d.size>=w2)throw xt(0,"too many tagged lanes");_={fields:null,fieldsByShape:new Map},d.set(k,_)}return _};return{push(k){if(u)throw xt(0,"TOONL encoder is closed");let _=k2(b2(k),s),S="";(o===null||o.length!==_.length||o.some((E,O)=>E!==_[O]))&&(S+=f(),o=_,i=nx(e,o),a=0,l=0,c=0,S+=m2(e,i));let P=o.map(E=>Qr(k[E],e));S+=h();let A=`${P.join(e)}
|
|
166
166
|
`;return S+=A,a+=1,l+=1,c+=A.length,S},declareLane(k,_){if(u)throw xt(0,"TOONL encoder is closed");let S=Lpe(_),P=nx(os,S),A=g(k);return g2(A.fields,S)?"":(A.fields=S,h2(k,P))},pushTagged(k,_){if(u)throw xt(0,"TOONL encoder is closed");let S=g(k),P=k2(b2(_),S.fieldsByShape),A=nx(os,P),E=P.map(D=>Qr(_[D],os)),O="";return g2(S.fields,P)||(S.fields=P,O+=h2(k,A)),`${O}${k}:${E.join(os)}
|
|
167
|
-
`},end(){return u?"":(u=!0,f())}}}var kt=QS;function hl(e){let t={app:e,version:Upe(fd("__RED_BUILD_VERSION__",()=>"4.1.
|
|
167
|
+
`},end(){return u?"":(u=!0,f())}}}var kt=QS;function hl(e){let t={app:e,version:Upe(fd("__RED_BUILD_VERSION__",()=>"4.1.14")??"0.0.0-dev"),gitSha:fd("__RED_BUILD_GIT_SHA__",()=>"a2c2d45c9f89f44932e381ec4b99bf2aa5d25445")??"unknown",buildTime:fd("__RED_BUILD_TIME__",()=>"2026-08-21T02:01:02-03:00")??"unknown",bundleAsset:fd("__RED_BUNDLE_ASSET__",()=>"redskilled.bundle.min.mjs")??"unknown"},r=fd("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=fd("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Upe(e){return e.startsWith("v")?e.slice(1):e}function S2(e){return`${e.app} ${e.version} ${e.gitSha}`}function fd(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var x2={"=":"data",":=":{to:"data",typed:!0},":":"meta"},qpe=/^[a-z][a-z0-9+.-]*:\/\//i;function Wpe(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 Hpe(e=x2){return Object.entries(e).map(([t,r])=>Wpe(t,r)).sort((t,r)=>r.separator.length-t.separator.length)}function Kpe(e){return/^-\d+(\.\d+)?$/.test(e)}function mf(e){return!(!e||e.startsWith("-")&&!Kpe(e))}function Iy(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 E2(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=>E2(r.trim())):e}function gl(e,t){switch(t){case"boolean":return Vpe(e);case"number":return Jpe(e);case"array":return e.split(",").map(r=>Iy(r.trim()));case"string":default:return e}}function Vpe(e){let t=e.toLowerCase().trim();return t==="true"||t==="yes"||t==="1"||t==="on"}function Jpe(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let t=Number(e);if(Number.isNaN(t))throw new TypeError(`Cannot convert "${e}" to number`);return t}function Qs(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Zpe(e,t={}){return e.map(r=>{let n=t[r.type];return n?n(r.value):r.value}).join("")}function Wt(e,t){return{type:e,value:t}}function Ype(e){let t=[],r=Xpe(e);if(t.push(Wt("section-header","Usage:"),Wt("text"," "),Wt("usage-text",r),Wt("newline",`
|
|
168
168
|
`),Wt("newline",`
|
|
169
169
|
`)),e.positional&&e.positional.length>0){t.push(Wt("section-header","Arguments:"),Wt("newline",`
|
|
170
170
|
`));for(let n of e.positional)if(n.description){let o=n.variadic?`${n.name}...`:n.name;t.push(Wt("indent"," "),Wt("positional-name",`<${o}>`)),n.required||t.push(Wt("positional-optional"," (optional)")),t.push(Wt("newline",`
|
|
@@ -336,7 +336,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
336
336
|
|
|
337
337
|
`}${r}`;if(e.kind==="pull-request"){let o=t.split("/",1)[0];return{lookup:`repos/${t}/pulls?state=all&head=${encodeURIComponent(`${o}:${e.head}`)}&base=${encodeURIComponent(e.base)}&per_page=100`,path:`repos/${t}/pulls`,body:{head:e.head,base:e.base,title:e.title,body:n(e.body)}}}return e.issue!=null?{lookup:`repos/${t}/issues/${e.issue}/comments?per_page=100`,path:`repos/${t}/issues/${e.issue}/comments`,body:{body:n(e.body)}}:{lookup:`repos/${t}/issues?state=all&per_page=100`,path:`repos/${t}/issues`,body:{title:e.title,body:n(e.body),...e.labels==null||e.labels.length===0?{}:{labels:[...e.labels]}}}}function QMe(e){return`<!-- redskilled:github-outbox:${e} -->`}function rQ(e,t){return Array.isArray(e)?e.find(r=>r!=null&&typeof r=="object"&&typeof r.body=="string"&&r.body.includes(t))??null:null}async function XMe(e){if(e.write.kind!=="repository-push")throw new Error("repository push received a non-push write");let t=e.write,r=Buffer.from(`x-access-token:${e.credential.secret}`,"utf8").toString("base64"),n=`https://github.com/${e.project.projectLabel}.git`;return await new Promise((o,i)=>{JMe("git",["push",n,`${t.sha}:${t.ref}`],{cwd:e.project.workspacePath,env:{...process.env,GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.extraHeader",GIT_CONFIG_VALUE_0:`Authorization: Basic ${r}`,GIT_TERMINAL_PROMPT:"0"},windowsHide:!0,timeout:6e4},(s,a,l)=>s==null?o():i(new Error(`redskilled repository push to ${n} failed: ${String(l??"").trim()||s.message}`)))}),{pushed:!0,ref:t.ref,sha:t.sha}}var Gbt=xe.githubRead,Bbt=xe.githubWrite,Ubt=xe.githubCustodyHandoff,Qe=class extends Error{constructor(t){super(t),this.name="RedskilledGithubAuthorityError"}};function oQ(e){let t=eT({...e.freshMs==null?{}:{freshMs:e.freshMs},...e.capacity==null?{}:{capacity:e.capacity}}),r=e.clock??(()=>new Date().toISOString()),n=Math.max(1,e.refreshMs??e.freshMs??6e4),o=Math.max(1,e.capacity??512),i=new Map,s=new Set((e.configuredProfiles??[]).filter(UY)),a=new Map,l=new Map,c=(E,O,D)=>{l.set(vN(E.credentialProfile,O),D)},d=new Map,u=new Map,p=new Map,f=new Map,h=!1,g=E=>{h||(E.timer!=null&&clearTimeout(E.timer),E.timer=setTimeout(()=>{E.timer=void 0,_(E).catch(()=>{})},n),E.timer.unref?.())},k=(E,O,D)=>{let z=(p.get(E.scope)??0)+1;p.set(E.scope,z);let I={version:1,sequence:z,project_id:E.project.projectId,credential_profile:E.project.credentialProfile,read:E.read,fetched_at:D,value:O};for(let j of u.get(E.scope)??[])j(I)},_=async E=>{let O=i.get(E.key);if(O!=null)return O;let D=t.read(E.key,{now:r()}),z=RN(E.read),I=e.upstream({project:E.project,credential:E.credential,read:E.read,...E.validators==null||E.read.kind!=="rest"?{}:{conditional:E.validators}}).then(j=>{let W=r();if(j.notModified){let ue=E.answer??D.value;if(ue==null)throw new Error("redskilled GitHub upstream returned not-modified without a held cache answer");return E.answer={value:ue.value,budget:j.budget??ue.budget},E.validators=j.validators??E.validators,z!=null&&c(E.project,z,{facts:E.answer.budget,state:j.budget==null?"unavailable":"authoritative",observedAt:W}),t.put({key:E.key,kind:E.read.kind,value:E.answer,fetchedAt:W}),Bv(E.project,E.answer,"cache",{outcome:"fresh",fetched_at:W,age_ms:0,fresh_ms:t.read(E.key,{now:W}).fresh_ms})}let X={value:j.value,budget:j.budget},ce=E.answer==null||!eNe(E.answer.value,X.value);return E.answer=X,E.validators=j.validators,z!=null&&c(E.project,z,{facts:X.budget,state:X.budget==null?"unavailable":"authoritative",observedAt:W}),t.put({key:E.key,kind:E.read.kind,value:X,fetchedAt:W}),ce&&k(E,X.value,W),Bv(E.project,X,"upstream",{outcome:"fresh",fetched_at:W,age_ms:0,fresh_ms:t.read(E.key,{now:W}).fresh_ms})}).catch(j=>{if(z!=null&&c(E.project,z,{facts:D.value?.budget??E.answer?.budget??null,state:j instanceof Dr?"backpressured":"unavailable",observedAt:r(),...j instanceof Dr?{backpressure:j.fact}:{}}),j instanceof Dr&&E.read.kind!=="repository-fetch"&&D.hit&&D.value!=null&&D.fetched_at!=null&&D.age_ms!=null)return Bv(E.project,D.value,"cache",{outcome:D.outcome,fetched_at:D.fetched_at,age_ms:D.age_ms,fresh_ms:D.fresh_ms},j.fact);throw j}).finally(()=>{i.delete(E.key),g(E)});return i.set(E.key,I),I},S=()=>{for(;d.size>o;){let E=d.entries().next().value;if(E==null)return;let[O,D]=E;D.timer!=null&&clearTimeout(D.timer),d.delete(O),t.forget(O)}},P=e.outboxPath==null||e.writeUpstream==null?null:VY(e.outboxPath,e.writeUpstream,r),A=e.custodyPath==null||e.custodyUpstream==null?null:XY({path:e.custodyPath,upstream:e.custodyUpstream,clock:r,tickMs:Math.max(1,e.custodyTickMs??n),inertMs:Math.max(1,e.custodyInertMs??Math.max(n*3,6e4))});return{forProject(E,O){let D=nQ(E);if(typeof O.secret!="string"||O.secret.trim()==="")throw new Qe(`credential profile ${JSON.stringify(D.credentialProfile)} has no daemon-owned credential`);s.add(D.credentialProfile);let z=a.get(D.credentialProfile)??new Map;z.set(D.projectId,D.projectLabel),a.set(D.credentialProfile,z);let I=sNe(D),j=()=>{if(P==null)throw new Qe("this GitHub gateway has no durable write outbox");return P},W=()=>{if(A==null)throw new Qe("this GitHub gateway has no durable merge custodian");return A};return{async read(X){let ce=tNe(D,X),ue=RN(ce),ie=iNe(D,ce),Oe=r(),De=t.read(ie,{now:Oe});if(De.outcome==="fresh"&&De.value!=null&&De.fetched_at!=null&&De.age_ms!=null)return ue!=null&&c(D,ue,{facts:De.value.budget,state:"cached",observedAt:De.fetched_at}),Bv(D,De.value,"cache",{outcome:De.outcome,fetched_at:De.fetched_at,age_ms:De.age_ms,fresh_ms:De.fresh_ms});let et=i.get(ie);if(et!=null)return et;let Ye=d.get(ie);return Ye==null&&(Ye={key:ie,scope:I,project:D,credential:O,read:ce},d.set(ie,Ye),S()),_(Ye)},async refresh(){let X=[...d.values()].filter(ce=>ce.scope===I);return await Promise.all(X.map(ce=>_(ce))),X.length},async wake(X){aNe(X);let ce=f.get(I);if(ce==null&&(ce=new Set,f.set(I,ce)),ce.has(X.deliveryId))return 0;ce.add(X.deliveryId),ce.size>1024&&ce.delete(ce.values().next().value);let ue=[...d.values()].filter(ie=>ie.scope===I);return await Promise.all(ue.map(ie=>_(ie))),ue.length},subscribe(X){let ce=u.get(I);return ce==null&&(ce=new Set,u.set(I,ce)),ce.add(X),()=>{ce.delete(X),ce.size===0&&u.delete(I)}},write(X){return j().publish(D,O,EN(X))},resumeWrites(){return j().resume(D,O)},handoffMergeCustody(X){return W().handoff(D,O,X)},mergeCustodyStatus(){return W().status(D,O)}}},projectBudget(E){let O=nQ(E);return{version:1,scope:"project",project_id:O.projectId,project_label:O.projectLabel,credential_profile:O.credentialProfile,pools:wN(O.credentialProfile,l,r())}},hostBudget(){return{version:1,scope:"host-administration",profiles:[...s].sort().map(E=>{let D=[...a.get(E)??new Map].sort(([z],[I])=>z.localeCompare(I));return{credential_profile:E,project_ids:D.map(([z])=>z),project_labels:D.map(([,z])=>z),pools:wN(E,l,r())}})}},close(){h=!0;for(let E of d.values())E.timer!=null&&clearTimeout(E.timer);d.clear(),u.clear(),f.clear(),A?.close()}}}function iQ(e={}){let t=(e.origin??"https://api.github.com").replace(/\/+$/,""),r=e.graphqlEndpoint??`${t}/graphql`,n=e.fetchImpl??fetch,o=e.fetchRepository??tQ,i=e.clock??(()=>new Date().toISOString());return async s=>{if(s.read.kind==="repository-fetch")return{value:await o(s),budget:null};if(s.read.kind==="rest"){let p=s.project.projectLabel.split("/").map(encodeURIComponent).join("/"),f=s.conditional==null?{}:{...s.conditional.etag==null?{}:{"if-none-match":s.conditional.etag},...s.conditional.lastModified==null?{}:{"if-modified-since":s.conditional.lastModified}},h=await n(`${t}/repos/${p}/${s.read.path}`,{method:"GET",headers:{...Is(s.credential.secret),...f}}),g=s.read.path.replace(/^\/+/,"").startsWith("search/")?"search":"rest",k=qY(h.headers,s.conditional);if(h.status===304)return{value:void 0,budget:SN(g,h.headers),validators:k,notModified:!0};if(!h.ok)throw Gi("REST read",g,h,i(),s.project.credentialProfile);return{value:await Ju(h),budget:SN(g,h.headers),validators:k}}let[a,l]=s.project.projectLabel.split("/",2),c=`query RedskilledProjectRead { repository(owner: ${JSON.stringify(a)}, name: ${JSON.stringify(l)}) { ${s.read.selection} } rateLimit { limit remaining resetAt cost } }`,d=await n(r,{method:"POST",headers:{...Is(s.credential.secret),"content-type":"application/json"},body:JSON.stringify({query:c})});if(!d.ok)throw Gi("GraphQL read","graphql",d,i(),s.project.credentialProfile);let u=await d.json();if(u.errors?.some(lNe))throw Fv(s.project.credentialProfile);if(u.errors!=null&&u.errors.length>0)throw new Error("redskilled GitHub GraphQL read was refused upstream");return{value:u.data?.repository,budget:WY(u.data?.rateLimit)}}}function Bv(e,t,r,n,o){return{version:1,project_id:e.projectId,credential_profile:e.credentialProfile,source:r,cache:n,budget:t.budget,value:t.value,...o===void 0?{}:{backpressure:o,retry_at:o.retry_at}}}function nQ(e){if([e.projectId,e.projectLabel,e.workspacePath,e.credentialProfile].some(r=>typeof r!="string"||r.trim()===""))throw new Qe("a GitHub reader needs one resolved Project and credential profile");if(!/^[^/\s]+\/[^/\s]+$/.test(e.projectLabel))throw new Qe("the resolved Project has no canonical GitHub repository identity");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(e.credentialProfile))throw new Qe("the daemon-owned credential profile name is not publishable");return{...e}}function tNe(e,t){return t==null||typeof t!="object"?Bi("a GitHub read must be an object"):t.kind==="rest"?(AN(t,["kind","path"]),rNe(e,t)):t.kind==="graphql"?(AN(t,["kind","selection"]),nNe(t)):t.kind==="repository-fetch"?(AN(t,["kind","ref"]),oNe(t)):Bi("Project authority permits only REST, GraphQL, and repository-fetch reads")}function rNe(e,t){let r=typeof t.path=="string"?t.path.trim().replace(/^\/+/,""):"",n=`repos/${e.projectLabel}/`;if(r.startsWith("repos/")){if(!r.toLowerCase().startsWith(n.toLowerCase()))return Bi("a Project GitHub reader cannot address another repository");r=r.slice(n.length)}if(r===""||r.includes("\\")||r.split("/").some(i=>i===".."||i==="."))return Bi("a Project GitHub REST read needs one repository-relative path");let o=r.split(/[/?#]/,1)[0].toLowerCase();return["admin","applications","enterprises","installation","installations","orgs","rate_limit","user","users"].includes(o)?Bi("Project authority cannot use the GitHub gateway for host or account administration"):{kind:"rest",path:r}}function nNe(e){let t=typeof e.selection=="string"?e.selection.trim().replace(/\s+/g," "):"";return t===""?Bi("a Project GraphQL read needs a repository field selection"):/\b(query|mutation|subscription|repository|viewer|user|organization|enterprise|node|nodes|search|rateLimit)\b\s*(?:\(|\{)/i.test(t)||t.includes("$")?Bi("a Project GraphQL read may select fields only from its bound repository"):{kind:"graphql",selection:t}}function oNe(e){if(e.ref==null||e.ref.trim()==="")return{kind:"repository-fetch"};let t=e.ref.trim();return!/^refs\/(heads|tags)\/[A-Za-z0-9][A-Za-z0-9._\/-]*$/.test(t)||t.includes("..")||t.includes("//")||t.endsWith(".")||t.endsWith("/")||t.includes("@{")?Bi("a Project repository fetch may name only one ordinary branch or tag ref"):{kind:"repository-fetch",ref:t}}function iNe(e,t){let r=t.kind==="rest"?t.path:t.kind==="graphql"?t.selection:t.ref??"*";return JSON.stringify([e.projectId,e.credentialProfile,t.kind,r])}function sNe(e){return JSON.stringify([e.projectId,e.credentialProfile])}function aNe(e){(e==null||typeof e!="object"||Array.isArray(e)||Object.keys(e).length!==1||typeof e.deliveryId!="string"||e.deliveryId.trim()===""||e.deliveryId.length>256)&&Bi("a GitHub webhook wake may carry only one bounded delivery identifier")}function Bi(e){throw new Qe(e)}function AN(e,t){Object.keys(e).find(n=>!t.includes(n))!=null&&Bi("a Project GitHub read cannot carry Project, credential, remote, or host authority fields")}function lNe(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="FORBIDDEN"||t.extensions!=null&&typeof t.extensions=="object"&&t.extensions.type==="FORBIDDEN"}import{createHash as cNe}from"node:crypto";var dNe=["GET","HEAD"];function sQ(e){if(e==null||typeof e!="object"||Array.isArray(e))throw new Qe("a Project GitHub request needs one request");let t=e;if(Object.keys(t).length!==1||!("request"in t))throw new Qe("a Project GitHub request cannot name a Project, credential profile, remote, or host operation");if(t.request==null||typeof t.request!="object"||Array.isArray(t.request))throw new Qe("a Project GitHub request needs one request object");return{request:t.request}}function aQ(e,t){let r=t.method;if(!EY(r))return So("a Project GitHub request needs one ordinary HTTP method");gNe(t,["method","path","body","headers"]),mNe(t.headers);let n=pNe(e,t.path);return dNe.includes(r)?t.body!=null?So(`a ${r} request carries no body`):{mode:"read",path:n,read:{kind:"rest",path:n}}:{mode:"write",path:n,write:fNe(r,n,t.body)}}function uNe(e,t,r){return`ghreq-${cNe("sha256").update(JSON.stringify([e,t,r??null])).digest("hex").slice(0,48)}`}function IN(e,t,r){return r.mode==="read"?{version:1,mode:"read",method:e,path:t,answer:r.answer}:{version:1,mode:"write",method:e,path:t,answer:r.answer}}function pNe(e,t){let r=typeof t=="string"?t.trim().replace(/^\/+/,""):"",n=`repos/${e}/`;if(r.toLowerCase().startsWith("repos/")){if(!r.toLowerCase().startsWith(n.toLowerCase()))return So("a Project GitHub request cannot address another repository");r=r.slice(n.length)}return r===""||r.includes("\\")||r.split(/[/?#]/).some(o=>o===".."||o===".")?So("a Project GitHub request needs one repository-relative path"):r}function fNe(e,t,r){if(e!=="POST")return So(`the Project GitHub gateway schedules no ${e} write \u2014 its outbox publishes Issues, Issue comments and pull requests`);if(r!=null&&(typeof r!="object"||Array.isArray(r)))return So("a Project GitHub write needs one request body object");let n=r??{},o=t.split(/[?#]/,1)[0],i=/^issues\/([1-9][0-9]*)\/comments$/.exec(o),s=i!=null?{kind:"issue-publication",issue:Number(i[1]),body:Na(n.body,"an Issue comment needs a body")}:o==="issues"?{kind:"issue-publication",title:Na(n.title,"a new Issue needs a title"),body:Na(n.body,"a new Issue needs a body"),...n.labels==null?{}:{labels:hNe(n.labels)}}:o==="pulls"?{kind:"pull-request",head:Na(n.head,"a pull request needs a head branch"),base:Na(n.base,"a pull request needs a base branch"),title:Na(n.title,"a pull request needs a title"),body:Na(n.body,"a pull request needs a body")}:So(`the Project GitHub gateway schedules no write for ${JSON.stringify(o)} \u2014 its outbox publishes \`issues\`, \`issues/<number>/comments\` and \`pulls\``);return{idempotency_key:uNe(e,t,r),write:s}}function mNe(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))return So("a Project GitHub request needs one headers object");let t=Object.keys(e);t.length!==0&&So(`the Project GitHub gateway owns its own request headers \u2014 it authenticates, negotiates and conditions every call itself, so a caller may name none (received ${t.sort().join(", ")})`)}function Na(e,t){let r=typeof e=="string"?e:"";return r.trim()===""?So(t):r}function hNe(e){return Array.isArray(e)?e.map(t=>Na(t,"an Issue label must be one non-empty label name")):So("Issue labels must be a list of label names")}function gNe(e,t){Object.keys(e).find(n=>!t.includes(n))!=null&&So("a Project GitHub request carries only a method, a path, a body and headers")}function So(e){throw new Qe(e)}function Mt(e,t,r){return{method:e,params:t,handle:async o=>{try{return await r(o)}catch(i){if(i instanceof ne)throw i;let s=i instanceof Error?i.message:String(i);throw new ne(-32603,`${e} failed: ${s}`)}}}}var Uv=()=>({});function lQ(e){let t=[],r=new Map,n={};for(let o of e){for(let i of o.bindings){let s=r.get(i.method);if(s!=null)throw new Error(`${i.method} is claimed by both the ${s} and ${o.domain} ACP domains`);r.set(i.method,o.domain),t.push(i)}o.capability!=null&&(n={...n,...o.capability})}return{bindings:t,capabilities:n,domains:e.map(o=>o.domain)}}var cQ=xe.githubUpdate;function dQ(e,t){if(!yNe(e))return bNe();let r=Promise.resolve();return{close:e.subscribe(o=>{r=r.then(()=>t(cQ,o)).catch(()=>{})}),settled:()=>r}}function yNe(e){return e!=null&&typeof e=="object"&&typeof e.subscribe=="function"}function bNe(){return{close:()=>{},settled:async()=>{}}}async function uQ(e,t,r,n){try{let o=await e?.credentialForProject({projectId:t.projectId,projectLabel:t.projectLabel,workspacePath:t.workspacePath});if(e==null||o==null)throw ne.authRequired({version:1,kind:"github-credential-profile",reason:"missing-credentials",credential_profile:"personal"},"this Project has no resolvable daemon-owned GitHub credential profile");try{let i=e.gateway.forProject({projectId:t.projectId,projectLabel:t.projectLabel,workspacePath:t.workspacePath,credentialProfile:o.profile},o.credential);return r?.(i),await n(i)}catch(i){throw i instanceof Dr?new ne(-32001,i.message,{version:1,kind:"github-backpressure",project_id:t.projectId,credential_profile:o.profile,retry_at:i.fact.retry_at,fact:i.fact}):i}}catch(o){throw o instanceof cr?ne.authRequired(o.refusal,o.message):o}}function kNe(e,t,r){return async({params:{read:n}})=>{let o=t();return await uQ(e,o,r,i=>i.read(n))}}function _Ne(e,t,r){return async({params:{request:n}})=>{let o=t();return await uQ(e,o,r,async i=>{let s=aQ(o.projectLabel,n);return s.mode==="read"?IN(n.method,s.path,{mode:"read",answer:await i.read(s.read)}):IN(n.method,s.path,{mode:"write",answer:await i.write(s.write)})})}}function Dh(e,t){return async({params:r})=>{let n=t();try{let o=await e?.credentialForProject({projectId:n.projectId,projectLabel:n.projectLabel,workspacePath:n.workspacePath});if(e==null||o==null)throw ne.authRequired({version:1,kind:"github-credential-profile",reason:"missing-credentials",credential_profile:"personal"},"this Project has no resolvable daemon-owned GitHub credential profile");return await e.gateway.forProject({projectId:n.projectId,projectLabel:n.projectLabel,workspacePath:n.workspacePath,credentialProfile:o.profile},o.credential).write(r)}catch(o){throw o instanceof cr?ne.authRequired(o.refusal,o.message):o}}}function wNe(e,t){return async({params:r})=>{let{reader:n}=await vNe(e,t());return n.handoffMergeCustody(r)}}function pQ(e,t){return async()=>{if(e==null)return;let r=t(),n;try{n=await e.credentialForProject({projectId:r.projectId,projectLabel:r.projectLabel,workspacePath:r.workspacePath})}catch(i){if(i instanceof cr)return;throw i}if(n==null)return;let o=e.gateway.forProject({projectId:r.projectId,projectLabel:r.projectLabel,workspacePath:r.workspacePath,credentialProfile:n.profile},n.credential);return fQ(o)?o.mergeCustodyStatus():void 0}}async function vNe(e,t){let r=await e?.credentialForProject({projectId:t.projectId,projectLabel:t.projectLabel,workspacePath:t.workspacePath});if(e==null||r==null)throw ne.authRequired({version:1,kind:"github-credential-profile",reason:"missing-credentials",credential_profile:"personal"},"this Project has no resolvable daemon-owned GitHub credential profile");let n=e.gateway.forProject({projectId:t.projectId,projectLabel:t.projectLabel,workspacePath:t.workspacePath,credentialProfile:r.profile},r.credential);if(!fQ(n))throw new Qe("this GitHub gateway has no durable merge custodian");return{reader:n}}function fQ(e){return e!=null&&typeof e=="object"&&typeof e.handoffMergeCustody=="function"&&typeof e.mergeCustodyStatus=="function"}function RNe(e){if(e==null||typeof e!="object"||Array.isArray(e))throw new Qe("a Project GitHub gateway request needs one read");let t=e;if(Object.keys(t).length!==1||!("read"in t))throw new Qe("a Project GitHub request cannot name a Project, credential profile, remote, or host operation");if(t.read==null||typeof t.read!="object"||Array.isArray(t.read))throw new Qe("a Project GitHub gateway request needs one read object");return{read:t.read}}function SNe(e){if(e==null||typeof e!="object"||Array.isArray(e))throw new Qe("a Project GitHub write needs one mutation");let t=e;if(Object.keys(t).length!==2||!("idempotency_key"in t)||!("write"in t))throw new Qe("a Project GitHub write cannot name a Project, credential profile, remote, or host operation");if(t.write==null||typeof t.write!="object"||Array.isArray(t.write))throw new Qe("a Project GitHub write needs one mutation object");return t}function xNe(e){if(e==null||typeof e!="object"||Array.isArray(e))throw new Qe("merge custody needs one pull request handoff");let t=e,r=["pull_request","owner_ticket","branch","base"];if(Object.keys(t).length!==r.length||r.some(n=>!(n in t)))throw new Qe("a Project merge custody handoff cannot name a Project, credential profile, remote, or host operation");return t}function qv(e){let t=kNe(e.gateway,e.scopedProject,e.onReader),r=_Ne(e.gateway,e.scopedProject,e.onReader),n=Dh(e.gateway,e.scopedProject),o=wNe(e.gateway,e.scopedProject);return{domain:"github",bindings:[Mt(xe.githubRead,RNe,t),Mt(xe.githubRequest,sQ,r),Mt(xe.githubWrite,SNe,n),Mt(xe.githubCustodyHandoff,xNe,o)],...e.gateway==null?{}:{capability:{githubGateway:{version:1,methods:[xe.githubRead,xe.githubRequest,xe.githubWrite,xe.githubCustodyHandoff],notifications:[cQ]}}}}}import{randomUUID as y1e}from"node:crypto";var ckt=xe.brainCall;function mQ(e){return{domain:"brain",bindings:[Mt(xe.brainCall,SY,({params:t})=>e.store.call(t))],capability:{brain:{version:1,methods:[xe.brainCall],tools:jv}}}}var hQ=xe.projectBudget,gQ=xe.hostBudgets;function ENe(e,t){return async r=>{let n=t();try{let o=await e?.credentialForProject({projectId:n.projectId,projectLabel:n.projectLabel,workspacePath:n.workspacePath}),i=bQ(e?.gateway);if(o==null||i==null)throw ne.authRequired({version:1,kind:"github-credential-profile",reason:"missing-credentials"},"this Project has no observable daemon-owned GitHub credential budget");return i.projectBudget({projectId:n.projectId,projectLabel:n.projectLabel,workspacePath:n.workspacePath,credentialProfile:o.profile})}catch(o){throw o instanceof cr?ne.authRequired(o.refusal,o.message):o}}}function TNe(e,t){return async r=>{if(!t)throw ne.invalidRequest("this project-scoped ACP connection has no host-administrative authority");let n=bQ(e?.gateway);if(n==null)throw ne.invalidRequest("GitHub credential-budget projection is unavailable");return n.hostBudget()}}var yQ=Wu("credential-budget requests accept no caller-controlled authority fields");function bQ(e){return e==null||!("projectBudget"in e)||!("hostBudget"in e)?null:e}function kQ(e){let t=ENe(e.gateway,e.scopedProject),r=TNe(e.gateway,e.hostAdministration);return{domain:"budget",bindings:[Mt(hQ,yQ,t),Mt(gQ,yQ,r)],...e.gateway==null?{}:{capability:{credentialBudgets:{version:1,methods:[hQ,...e.hostAdministration?[gQ]:[]]}}}}}import{randomUUID as SLe}from"node:crypto";var sc="lane:go",PNe="lane:scout";function jh(){return{}}function _Q(e,t){let r=ANe(t);if(r===void 0)return e.dispatch;let n=INe(r);if(e.dispatch!=null&&!CNe(e.dispatch,n))throw new Error("this ACP session is already bound to a different targeted dispatch");return e.dispatch??=n,e.dispatch}function ANe(e){if(!Wv(e))return;let t=e.redskills;return Wv(t)?t.dispatch:void 0}function INe(e){if(!Wv(e)||e.version!==1)throw new Error("a targeted ACP dispatch must declare version 1");let t=e.workerKind;if(t!=="afk"&&t!=="go"&&t!=="scout")throw new Error("a targeted ACP dispatch must declare Worker kind afk, go, or scout");let r=e.ticket;if(!Number.isInteger(r)||Number(r)<=0)throw new Error("a targeted ACP dispatch requires a positive Ticket number");let n=e.selector;if(!Wv(n)||n.kind!=="issues")throw new Error("a targeted ACP dispatch requires an issues selector");let o=n.numbers;if(!Array.isArray(o)||o.length!==1||o[0]!==r)throw new Error("a targeted ACP dispatch selector must name exactly its Ticket");let i=typeof n.lane=="string"?n.lane.trim():"";if(i==="")throw new Error("a targeted ACP dispatch requires an explicit selector lane");let s=t==="go"?sc:t==="scout"?PNe:void 0;if(s!=null&&i!==s)throw new Error(`Worker kind ${t} requires selector lane ${s}`);return{version:1,workerKind:t,ticket:Number(r),selector:{kind:"issues",numbers:[Number(r)],lane:i}}}function CNe(e,t){return e.workerKind===t.workerKind&&e.ticket===t.ticket&&e.selector.kind===t.selector.kind&&e.selector.lane===t.selector.lane&&e.selector.numbers.length===t.selector.numbers.length&&e.selector.numbers.every((r,n)=>r===t.selector.numbers[n])}function Wv(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}import{randomBytes as UQ}from"node:crypto";import{constants as gLe,accessSync as yLe}from"node:fs";import{homedir as bLe}from"node:os";import{delimiter as kLe,isAbsolute as _Le,join as qQ}from"node:path";var $Ne=[{id:"redcode",label:"Redcode",kind:"native",command:["redcode","acp"]},{id:"claude-code",label:"Claude Code",kind:"adapter",artifact:{package:"@zed-industries/claude-code-acp",version:"0.16.2",integrity:"sha512-D8BJe6CCD49RtNFbZYPsfZOpQI8Z/EzhyYC9zAGMwN/HVunEtVY2sXqYl1iDSkkayzhqABfaDkDZfeqDM1T/aA==",entrypoint:"package/dist/index.js",bin:"claude-code-acp"}},{id:"codex",label:"Codex",kind:"adapter",artifact:{package:"@zed-industries/codex-acp",version:"0.16.0",integrity:"sha512-XKzqztT5R8Wg1BVFnk6/U4JVx5GNUaZgxpf9gP2Cw6BsknvJWh3aefcAGZQljgdMivRqczjNKYL4F6H65dc5vA==",entrypoint:"package/bin/codex-acp.js",bin:"codex-acp"}},{id:"pi",label:"Pi",kind:"adapter",artifact:{package:"pi-acp",version:"0.0.33",integrity:"sha512-vX9kY1tK14E72G4dBAx+RGCk/k7XPjTHls6dLUxA8WSkBav6B6JHuSBv3eusp50LCR/GTRsR2kIKsG0Z5jANzw==",entrypoint:"package/dist/index.js",bin:"pi-acp"}},{id:"opencode",label:"OpenCode",kind:"native",command:["opencode","acp"]}],Hv=class extends Error{constructor(r,n){super(`ACP Agent ${r} is not available: ${n}. Run redskilled ACP Agent provisioning for ${r}; redskilled will not substitute another Agent.`);this.agent=r;this.name="AcpAgentUnavailableError"}};function wQ(e){let t=$Ne.find(r=>r.id===e);if(t==null)throw new Hv(e,"it is not configured in the host catalog");if(t.kind==="native")return ONe(t);if(t.artifact.bin==null)throw new Hv(e,"its pinned adapter declares no launchable bin");return{agent:e,transport:"stdio",command:"npx",args:["-y","-p",`${t.artifact.package}@${t.artifact.version}`,t.artifact.bin]}}function ONe(e){return{agent:e.id,transport:"stdio",command:e.command[0],args:e.command.slice(1)}}import{chmod as zNe,copyFile as DNe,mkdir as jNe,stat as MNe}from"node:fs/promises";import{homedir as CN}from"node:os";import{join as Kv}from"node:path";function RQ(e,t,r=CN()){return e==="redcode"?{OPENCODE_DB:Kv(t,"redcode.db")}:e==="codex"?{CODEX_HOME:SQ(r)}:{}}function SQ(e=CN()){return Kv(Ft(e),"agent-homes","codex")}async function xQ(e,t=CN()){if(e!=="codex")return;let r=SQ(t);await jNe(r,{recursive:!0,mode:448});let n=Kv(r,"auth.json"),o=Kv(t,".codex","auth.json"),[i,s]=await Promise.all([vQ(n),vQ(o)]);if(s==null){if(i!=null)return;throw new Error("codex has no host login: ~/.codex/auth.json is absent. Run `codex login` as the operator first.")}(i==null||s>i)&&(await DNe(o,n),await zNe(n,384))}async function vQ(e){try{return(await MNe(e)).mtimeMs}catch{return null}}import{execFile as NNe}from"node:child_process";var LNe=12e4,FNe=/^[0-9a-f]{40}$/,GNe=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/;function BNe(e){let t=e.deliver??VNe;return async({params:r})=>{let n=PQ(e.held()),o=await AQ(e.gateway,n.project);await t({workerId:n.workerId,worktreePath:n.worktreePath,workspacePath:n.project.workspacePath,branch:r.branch,commit:r.commit});let i=await o.write({idempotency_key:r.idempotency_key,write:{kind:"repository-push",ref:`refs/heads/${r.branch}`,sha:r.commit}});return{version:1,worker_id:n.workerId,branch:r.branch,commit:r.commit,published_at:i.published_at}}}function UNe(e){return async({params:t})=>{let r=PQ(e.held()),n=await AQ(e.gateway,r.project),o=await n.write({idempotency_key:t.idempotency_key,write:{kind:"pull-request",head:t.branch,base:t.base,title:t.title,body:t.body}}),i=KNe(o.value),s=await HNe(n).handoffMergeCustody({pull_request:i,owner_ticket:t.owner_ticket,branch:t.branch,base:t.base});return{version:1,worker_id:r.workerId,pull_request:i,branch:t.branch,base:t.base,custody_state:s.state,handed_off_at:s.handed_off_at}}}function qNe(e){let t=IQ(e,["idempotency_key","branch","commit"],"a Worker publication"),r=t.commit;if(typeof r!="string"||!FNe.test(r))throw new Qe("a Worker publication names one full commit object name");return{idempotency_key:Mh(t.idempotency_key,"idempotency key"),branch:$N(t.branch),commit:r}}function WNe(e){let t=IQ(e,["idempotency_key","branch","base","title","body","owner_ticket"],"a Worker landing"),r=t.owner_ticket;if(typeof r!="number"||!Number.isSafeInteger(r)||r<=0)throw new Qe("a Worker landing names the Ticket that inherits the merge");return{idempotency_key:Mh(t.idempotency_key,"idempotency key"),branch:$N(t.branch),base:$N(t.base),title:Mh(t.title,"title"),body:Mh(t.body,"body"),owner_ticket:r}}function TQ(e){return{domain:"publication",bindings:[Mt(xe.publish,qNe,BNe(e)),Mt(xe.land,WNe,UNe(e))]}}function PQ(e){if(e!=null)return e;throw ne.invalidRequest({version:1,kind:"worker-not-held"},"redskilled does not hold the Worker this publication came from")}async function AQ(e,t){let r;try{r=await e?.credentialForProject({projectId:t.projectId,projectLabel:t.projectLabel,workspacePath:t.workspacePath})}catch(n){throw n instanceof cr?ne.authRequired(n.refusal,n.message):n}if(e==null||r==null)throw ne.authRequired({version:1,kind:"github-credential-profile",reason:"missing-credentials",credential_profile:"personal"},"this Project has no resolvable daemon-owned GitHub credential profile");return e.gateway.forProject({projectId:t.projectId,projectLabel:t.projectLabel,workspacePath:t.workspacePath,credentialProfile:r.profile},r.credential)}function HNe(e){let t=e;if(typeof t.handoffMergeCustody!="function")throw new Qe("this GitHub gateway has no durable merge custodian");return t}function KNe(e){let t=e?.number;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)throw new Qe("the opened pull request answered with no number to take custody of");return t}async function VNe(e){let t=`refs/redskilled/publications/${e.workerId}/${e.branch}`;await EQ(e.workspacePath,["fetch","--no-tags","--quiet","--",e.worktreePath,`+refs/heads/${e.branch}:${t}`]),await EQ(e.workspacePath,["cat-file","-e",`${e.commit}^{commit}`])}function EQ(e,t){return new Promise((r,n)=>{NNe("git",[...t],{cwd:e,encoding:"utf8",timeout:LNe,windowsHide:!0},(o,i,s)=>{if(o==null){r();return}n(new Qe(`redskilled could not deliver the Worker's publication: ${String(s).trim()||o.message}`))})})}function IQ(e,t,r){if(e==null||typeof e!="object"||Array.isArray(e))throw new Qe(`${r} needs one request object`);let n=e;if(Object.keys(n).length!==t.length||t.some(o=>!(o in n)))throw new Qe(`${r} cannot name a Project, credential profile, remote, Worker, or host operation`);return n}function Mh(e,t){if(typeof e!="string"||e.trim()==="")throw new Qe(`a Worker publication needs a ${t}`);return e}function $N(e){let t=Mh(e,"branch");if(!GNe.test(t)||t.includes("..")||t.includes("//")||t.endsWith(".")||t.endsWith("/")||t.includes("@{"))throw new Qe(`${JSON.stringify(t)} is not a branch redskilled can publish`);return t}import{randomUUID as JNe}from"node:crypto";import{mkdir as ZNe,readFile as YNe,rename as QNe,writeFile as XNe}from"node:fs/promises";import{dirname as $Q,join as eLe}from"node:path";function OQ(e){return eLe($Q(e),"redskilled.acp-sessions.toon")}async function zQ(e){let t=await tLe(e),r=Promise.resolve(),n=()=>{let i={version:1,sessions:[...t.values()]};return r=r.then(()=>rLe(e,i)),r},o=(i,s)=>{let a=t.get(i);if(a==null)throw new Error("unknown durable RedSkills ACP session");return t.set(i,{...a,entries:[...a.entries,{...s,sequence:a.entries.length+1}]}),n()};return{create(i,s){return t.set(i,{public_session_id:i,project_id:s.projectId,project_label:s.projectLabel,workspace_path:s.workspacePath,entries:[],session_evidence:[]}),n()},prompt(i,s){return o(i,{kind:"prompt",prompt:s})},update(i,s){return s.sessionUpdate!=="plan"?Promise.resolve():o(i,{kind:"plan",update:s})},worker(i,s,a,l){return o(i,{kind:"workflow-pointer",worker_id:s,worker_session_id:a,replacement:l})},evidence(i,s,a){let l=t.get(i);if(l==null)throw new Error("unknown durable RedSkills ACP session");return t.set(i,{...l,session_evidence:[...l.session_evidence,{worker_id:s,...a,retention:"evidence"}]}),n()},checkpoint(i,s,a){return o(i,{kind:"checkpoint",stop_reason:s.stopReason,...a==null?{}:{workflow_outcome:a}})},permission(i,s,a,l,c){let d=c==null?void 0:s.options.find(u=>u.optionId===c);return o(i,{kind:"permission",tool_call_id:s.toolCall.toolCallId,policy_key:a,decision:l,...d==null?{}:{option_id:d.optionId,option_kind:d.kind}})},recovery(i){let s=t.get(i);if(s==null)throw new Error("unknown durable RedSkills ACP session");return{version:1,source:"redskilled-public-journal",public_session_id:i,completed_turns:s.entries.filter(a=>a.kind==="checkpoint").length,entries:[...s.entries]}},retake(i,s){let a=t.get(i);if(!(a==null||a.project_id!==s))return{version:1,public_session_id:i,evidence:[...a.session_evidence]}}}}function DQ(e){let t=Vv(e),r=Vv(t?.redskills),n=Vv(r?.sessionEvidence),o=CQ(n?.provider),i=n?.availability,s=CQ(n?.reference);if(!(o==null||i!=="available"&&i!=="absent"&&i!=="inaccessible")&&!(i!=="absent"&&s==null))return{provider:o,availability:i,...s==null?{}:{reference:s}}}async function tLe(e){let t;try{t=await YNe(e,"utf8")}catch(n){if(n.code==="ENOENT")return new Map;throw n}let r=nLe(t);return oLe(r)?new Map(r.sessions.map(n=>[n.public_session_id,{...n,session_evidence:n.session_evidence??[]}])):new Map}async function rLe(e,t){await ZNe($Q(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.${JNe()}.tmp`;await XNe(r,`${Le(t)}
|
|
338
338
|
`,{encoding:"utf8",mode:384}),await QNe(r,e)}function nLe(e){let t=e.trim();if(!t)return null;try{return kt(t)}catch{return null}}function oLe(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&Array.isArray(t.sessions)&&t.sessions.every(r=>{if(r==null||typeof r!="object"||Array.isArray(r))return!1;let n=r;return typeof n.public_session_id=="string"&&typeof n.project_id=="string"&&typeof n.project_label=="string"&&typeof n.workspace_path=="string"&&Array.isArray(n.entries)&&(n.session_evidence==null||Array.isArray(n.session_evidence)&&n.session_evidence.every(iLe))})}function iLe(e){let t=Vv(e);return typeof t?.worker_id=="string"&&typeof t.provider=="string"&&(t.availability==="available"||t.availability==="absent"||t.availability==="inaccessible")&&t.retention==="evidence"&&(t.reference==null||typeof t.reference=="string")}function Vv(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function CQ(e){return typeof e=="string"&&e.trim()!==""?e:void 0}import{execFile as NQ}from"node:child_process";import{mkdir as jQ,rm as sLe}from"node:fs/promises";import{tmpdir as aLe,userInfo as lLe}from"node:os";import{join as ON}from"node:path";var LQ=12e4,cLe="red-skills",dLe="workers",uLe="worktree",Nh=class extends Error{constructor(t){super(t),this.name="WorkerWorkspaceError"}};function FQ(e={}){let t=e.uid??process.getuid?.()??lLe().username,r=String(t).trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(r==="")throw new Nh("redskilled cannot name a Worker workspace root without a user");return ON(e.tmpDir??aLe(),`${cLe}-${r}`,dLe)}function GQ(e,t){return ON(e,mLe(t))}async function BQ(e){let t=e.git??hLe,r=GQ(e.root,e.workerId),n=ON(r,uLe);if(await jQ(r,{recursive:!0,mode:448}),!(await t(e.projectWorkspacePath,["rev-parse","--is-inside-work-tree"])==="true"))return await jQ(n,{recursive:!0,mode:448}),{workerId:e.workerId,root:e.root,workspacePath:r,worktreePath:n};if(e.trunk!=null){let s=e.trunk,l=(MQ.get(e.projectWorkspacePath)??Promise.resolve()).then(async()=>{let c=s.branch??await t(e.projectWorkspacePath,["symbolic-ref","--short","HEAD"])??"main",d=fLe(s.remoteUrl),u=e.git!=null?await t(e.projectWorkspacePath,["fetch","--quiet",d,c])!==void 0?{ok:!0}:{ok:!1,detail:"the injected git runner refused"}:await pLe(e.projectWorkspacePath,["fetch","--quiet",d,c]);u.ok?await t(e.projectWorkspacePath,["reset","--hard","FETCH_HEAD"]):process.stderr.write(`redskilled: Worker ${e.workerId} forks a STALE mirror \u2014 the trunk fetch from ${d} failed (${u.detail}), so this Worker's base and its origin predate today's ${c}
|
|
339
|
-
`)}).catch(()=>{});MQ.set(e.projectWorkspacePath,l),await l}await t(e.projectWorkspacePath,["clone","--no-hardlinks","--quiet","--",e.projectWorkspacePath,n],!0);let i=await t(n,["rev-parse","HEAD"]);return{workerId:e.workerId,root:e.root,workspacePath:r,worktreePath:n,...i==null?{}:{baseCommit:i}}}var MQ=new Map;async function pLe(e,t){return await new Promise(r=>{NQ("git",[...t],{cwd:e,encoding:"utf8",timeout:LQ,windowsHide:!0},(n,o,i)=>{n==null?r({ok:!0}):r({ok:!1,detail:(i.trim()||n.message).slice(0,300)})})})}function fLe(e){let t=/^git@github\.com:(.+?)(?:\.git)?$/.exec(e);if(t!=null)return`https://github.com/${t[1]}.git`;let r=/^ssh:\/\/git@github\.com\/(.+?)(?:\.git)?$/.exec(e);return r!=null?`https://github.com/${r[1]}.git`:e}async function Lh(e){let t=GQ(e.root,e.workerId);if(e.workspacePath!==t)throw new Nh(`redskilled refuses to release ${JSON.stringify(e.workspacePath)}: Worker ${e.workerId} owns ${JSON.stringify(t)} under its host root`);await sLe(e.workspacePath,{recursive:!0,force:!0})}function mLe(e){let t=e.trim();if(t===""||t==="."||t===".."||/[/\\]/.test(t))throw new Nh(`invalid Worker id ${JSON.stringify(e)}: it would escape the host's workspace root.`);return t}async function hLe(e,t,r=!1){return await new Promise((n,o)=>{NQ("git",[...t],{cwd:e,encoding:"utf8",timeout:LQ,windowsHide:!0},(i,s)=>{if(i!=null){r?o(i):n(void 0);return}let a=s.trim();n(a===""?void 0:a)})})}async function ac(e,t,r,n,o,i,s,a){let l=UQ(6).toString("hex"),c=d3(e.paths,l),d=$i((e.hostState?.().workers??[]).map(I=>I.worker_id)),u=await BQ({root:e.workspaceRoot??FQ(),workerId:d,projectWorkspacePath:r.project.workspacePath,...r.project.remoteUrl==null?{}:{trunk:{remoteUrl:r.project.remoteUrl}}}),p=await CY(c),f=async I=>{throw p.server.close(),await As(c),await Lh(u).catch(()=>{}),I},h=RLe(r.request._meta)??"redcode",g;try{await xQ(h),g=e.startWorker(wLe(r.project,u,c,e.paths.runtimeDir,a?.workerKind,h))}catch(I){return await f(I)}let k;try{k=await Ku(p.connected,1e4,"native ACP Worker rendezvous")}catch(I){return await f(I)}p.server.close();let _="",S,P={},A=TQ({...e.githubGateway==null?{gateway:void 0}:{gateway:e.githubGateway},held:()=>{let I=P.worker;if(!(I==null||I.cleaned))return{workerId:I.workerId,worktreePath:u.worktreePath,project:r.project}}}),E=gv({name:"redskilled"}).onNotification(Te.client.session.update,async({params:I})=>{let j=I._meta?.redskills,W={...I,sessionId:n,_meta:{...I._meta??{},redskills:{...j??{},authority:"redskilled",workerId:g.worker.worker_id,...a==null?{}:{dispatch:a},...j?.lifecycle==null?{}:{lifecycle:{...j.lifecycle,workerId:g.worker.worker_id,...a==null?{}:{dispatch:a}}}}}};await t.update(n,I.update),await o(Te.client.session.update,W)}).onRequest(Te.client.session.requestPermission,({params:I})=>i({...I,sessionId:n})),O=e.githubGateway==null?void 0:qv({gateway:e.githubGateway,scopedProject:()=>r.project});for(let I of[...A.bindings,...O?.bindings??[]])E.onRequest(I.method,I.params,({params:j})=>I.handle({params:j,client:void 0}));let D=E.connect(Hu(k));try{let I=await D.agent.request(Te.agent.initialize,{protocolVersion:Li,clientCapabilities:{},clientInfo:{name:"redskilled",version:"1"},_meta:{redskills:{wireMajor:to}}});oc(I._meta,!0);let j=s?t.recovery(n):void 0,W=j==null?void 0:dN(r.request._meta,j),X=a==null?W:{...W??{},redskills:{...W?.redskills??{},dispatch:a}},ce=await D.agent.request(Te.agent.session.new,{cwd:u.worktreePath,mcpServers:r.request.mcpServers,...r.request.additionalDirectories==null?{}:{additionalDirectories:r.request.additionalDirectories},...X==null?{}:{_meta:X}});_=ce.sessionId,await t.worker(n,g.worker.worker_id,_,s);let ue=DQ(ce._meta);ue!=null&&(S=ue,await t.evidence(n,g.worker.worker_id,ue))}catch(I){throw D.close(),k.destroy(),await As(c),await Lh(u).catch(()=>{}),I}let z={workerId:g.worker.worker_id,workspace:u,evidence:{root:e.evidenceRoot??H9(bLe()),ttlMs:e.evidenceTtlMs??Gl,...g.worker.log_path==null?{}:{logPath:g.worker.log_path},...S==null?{}:{sessionArtifact:S}},downstreamSessionId:_,connection:D,socket:k,endpoint:c,publicSessionId:n,notify:o,...a==null?{}:{dispatch:a},cancelled:!1,cleaned:!1};return P.worker=z,z}function wLe(e,t,r,n,o,i="redcode"){let s=process.argv[1];if(s==null||s==="")throw new Error("redskilled cannot resolve its Worker entry");let a=vLe(wQ(i));return{worker_id:t.workerId,project_label:e.projectLabel,workspace_path:t.worktreePath,env:{...AY(o),...RQ(a.agent,t.workspacePath)},command:process.execPath,args:[...process.execArgv,s,"acp-worker","--socket",r,"--child-agent",a.agent,"--child-command",a.command,...a.args.
|
|
339
|
+
`)}).catch(()=>{});MQ.set(e.projectWorkspacePath,l),await l}await t(e.projectWorkspacePath,["clone","--no-hardlinks","--quiet","--",e.projectWorkspacePath,n],!0);let i=await t(n,["rev-parse","HEAD"]);return{workerId:e.workerId,root:e.root,workspacePath:r,worktreePath:n,...i==null?{}:{baseCommit:i}}}var MQ=new Map;async function pLe(e,t){return await new Promise(r=>{NQ("git",[...t],{cwd:e,encoding:"utf8",timeout:LQ,windowsHide:!0},(n,o,i)=>{n==null?r({ok:!0}):r({ok:!1,detail:(i.trim()||n.message).slice(0,300)})})})}function fLe(e){let t=/^git@github\.com:(.+?)(?:\.git)?$/.exec(e);if(t!=null)return`https://github.com/${t[1]}.git`;let r=/^ssh:\/\/git@github\.com\/(.+?)(?:\.git)?$/.exec(e);return r!=null?`https://github.com/${r[1]}.git`:e}async function Lh(e){let t=GQ(e.root,e.workerId);if(e.workspacePath!==t)throw new Nh(`redskilled refuses to release ${JSON.stringify(e.workspacePath)}: Worker ${e.workerId} owns ${JSON.stringify(t)} under its host root`);await sLe(e.workspacePath,{recursive:!0,force:!0})}function mLe(e){let t=e.trim();if(t===""||t==="."||t===".."||/[/\\]/.test(t))throw new Nh(`invalid Worker id ${JSON.stringify(e)}: it would escape the host's workspace root.`);return t}async function hLe(e,t,r=!1){return await new Promise((n,o)=>{NQ("git",[...t],{cwd:e,encoding:"utf8",timeout:LQ,windowsHide:!0},(i,s)=>{if(i!=null){r?o(i):n(void 0);return}let a=s.trim();n(a===""?void 0:a)})})}async function ac(e,t,r,n,o,i,s,a){let l=UQ(6).toString("hex"),c=d3(e.paths,l),d=$i((e.hostState?.().workers??[]).map(I=>I.worker_id)),u=await BQ({root:e.workspaceRoot??FQ(),workerId:d,projectWorkspacePath:r.project.workspacePath,...r.project.remoteUrl==null?{}:{trunk:{remoteUrl:r.project.remoteUrl}}}),p=await CY(c),f=async I=>{throw p.server.close(),await As(c),await Lh(u).catch(()=>{}),I},h=RLe(r.request._meta)??"redcode",g;try{await xQ(h),g=e.startWorker(wLe(r.project,u,c,e.paths.runtimeDir,a?.workerKind,h))}catch(I){return await f(I)}let k;try{k=await Ku(p.connected,1e4,"native ACP Worker rendezvous")}catch(I){return await f(I)}p.server.close();let _="",S,P={},A=TQ({...e.githubGateway==null?{gateway:void 0}:{gateway:e.githubGateway},held:()=>{let I=P.worker;if(!(I==null||I.cleaned))return{workerId:I.workerId,worktreePath:u.worktreePath,project:r.project}}}),E=gv({name:"redskilled"}).onNotification(Te.client.session.update,async({params:I})=>{let j=I._meta?.redskills,W={...I,sessionId:n,_meta:{...I._meta??{},redskills:{...j??{},authority:"redskilled",workerId:g.worker.worker_id,...a==null?{}:{dispatch:a},...j?.lifecycle==null?{}:{lifecycle:{...j.lifecycle,workerId:g.worker.worker_id,...a==null?{}:{dispatch:a}}}}}};await t.update(n,I.update),await o(Te.client.session.update,W)}).onRequest(Te.client.session.requestPermission,({params:I})=>i({...I,sessionId:n})),O=e.githubGateway==null?void 0:qv({gateway:e.githubGateway,scopedProject:()=>r.project});for(let I of[...A.bindings,...O?.bindings??[]])E.onRequest(I.method,I.params,({params:j})=>I.handle({params:j,client:void 0}));let D=E.connect(Hu(k));try{let I=await D.agent.request(Te.agent.initialize,{protocolVersion:Li,clientCapabilities:{},clientInfo:{name:"redskilled",version:"1"},_meta:{redskills:{wireMajor:to}}});oc(I._meta,!0);let j=s?t.recovery(n):void 0,W=j==null?void 0:dN(r.request._meta,j),X=a==null?W:{...W??{},redskills:{...W?.redskills??{},dispatch:a}},ce=await D.agent.request(Te.agent.session.new,{cwd:u.worktreePath,mcpServers:r.request.mcpServers,...r.request.additionalDirectories==null?{}:{additionalDirectories:r.request.additionalDirectories},...X==null?{}:{_meta:X}});_=ce.sessionId,await t.worker(n,g.worker.worker_id,_,s);let ue=DQ(ce._meta);ue!=null&&(S=ue,await t.evidence(n,g.worker.worker_id,ue))}catch(I){throw D.close(),k.destroy(),await As(c),await Lh(u).catch(()=>{}),I}let z={workerId:g.worker.worker_id,workspace:u,evidence:{root:e.evidenceRoot??H9(bLe()),ttlMs:e.evidenceTtlMs??Gl,...g.worker.log_path==null?{}:{logPath:g.worker.log_path},...S==null?{}:{sessionArtifact:S}},downstreamSessionId:_,connection:D,socket:k,endpoint:c,publicSessionId:n,notify:o,...a==null?{}:{dispatch:a},cancelled:!1,cleaned:!1};return P.worker=z,z}function wLe(e,t,r,n,o,i="redcode"){let s=process.argv[1];if(s==null||s==="")throw new Error("redskilled cannot resolve its Worker entry");let a=vLe(wQ(i));return{worker_id:t.workerId,project_label:e.projectLabel,workspace_path:t.worktreePath,env:{...AY(o),...RQ(a.agent,t.workspacePath)},command:process.execPath,args:[...process.execArgv,s,"acp-worker","--socket",r,"--child-agent",a.agent,"--child-command",a.command,...a.args.map(l=>`--child-arg=${l}`)],log_path:qQ(n,"acp-workers",`${UQ(6).toString("hex")}.toonl`)}}function vLe(e){if(_Le(e.command)||e.command.includes("/")||e.command.includes("\\"))return e;let t=process.platform==="win32"?(process.env.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";"):[""];for(let r of(process.env.PATH??"").split(kLe))if(r!=="")for(let n of t){let o=qQ(r,`${e.command}${n}`);try{return yLe(o,gLe.X_OK),{...e,command:o}}catch{}}return e}function RLe(e){let t=e?.redskills?.runner;return typeof t=="string"&&Ps.includes(t)?t:null}function WQ(e){return async t=>{let r=e.project(),n=SLe(),o={request:{cwd:r.workspacePath,mcpServers:[]},project:r,dispatchJournal:jh()};await e.sessionJournal.create(n,r),e.sessions.set(n,o);let i;try{i=await ac({paths:e.paths,startWorker:e.startWorker,hostState:e.hostState},e.sessionJournal,o,n,e.forward(n),s=>e.permission(n,s),!1,t)}catch(s){throw e.sessions.delete(n),s}return e.active.set(n,i),{worker_id:i.workerId,session_id:n}}}import{randomUUID as xLe}from"node:crypto";var g_t=xe.goDispatch;function ELe(e){let t=e.trim();if(t==="")throw ne.invalidParams({},"go_dispatch requires a non-empty demand");return{title:`/go: ${(t.split(`
|
|
340
340
|
`,1)[0]??"").trim().slice(0,72)||"dispatch"}`,body:["## Demand","",t,"","---","",`\u{1F916} Disposable dispatch Ticket, minted by \`${xe.goDispatch}\` into the`,`isolated \`${sc}\` lane \u2014 never \`ready-for-agent\`, so the running drain`,"cannot claim it. Its dedicated Worker owns it, and it closes with that Worker's PR."].join(`
|
|
341
341
|
`),labels:[sc]}}function TLe(e){return async t=>{let r=ELe(t.params.demand),n=await e.tracker.mint(r);if(!Number.isInteger(n)||n<=0)throw new Error(`the Ticket tracker answered ${String(n)} instead of a Ticket number`);let o={version:1,workerKind:"go",ticket:n,selector:{kind:"issues",numbers:[n],lane:sc}},i;try{i=await e.admit(o,t)}catch(s){try{await e.tracker.dispose?.(n)}catch(a){throw new AggregateError([s,a],`Worker admission failed and disposable Ticket #${n} could not be closed`)}throw s}return{version:1,worker_id:i.worker_id,ticket:n,lane:sc,...i.session_id==null?{}:{session_id:i.session_id}}}}function HQ(e){return{domain:"go",bindings:[Mt(xe.goDispatch,PY,TLe(e))],capability:{goDispatch:{version:TY.version,methods:[xe.goDispatch],lane:sc}}}}function KQ(e,t){let r=Dh(e,t);return{async mint(n){let o=await r({params:{idempotency_key:`go-dispatch:${xLe()}`,write:{kind:"issue-publication",title:n.title,body:n.body,labels:[...n.labels]}}});return PLe(o.value)}}}function PLe(e){let t=e!=null&&typeof e=="object"?e.number:void 0;if(!Number.isInteger(t)||Number(t)<=0)throw new Error("the Ticket tracker published no Ticket number for this dispatch");return Number(t)}var ALe=xe.hostState;function VQ(e){return{domain:"host",bindings:[Mt(ALe,Uv,()=>e.scopedState())]}}var R_t=xe.memoryCall;function JQ(e){return{domain:"memory",bindings:[Mt(xe.memoryCall,IY,({params:t})=>e.store.call(e.scopedProject(),t))],capability:{memory:{version:1,methods:[xe.memoryCall],tools:cN}}}}var A_t=xe.metrics,ILe=Wu("metrics requests accept no caller-controlled scope, window or series selector");function ZQ(e){let t=e.snapshot??ik;return{domain:"telemetry",bindings:[Mt(xe.metrics,ILe,()=>{if(!e.hostAdministration)throw ne.invalidRequest("this project-scoped ACP connection has no host-administrative authority");return t()})],...e.hostAdministration?{capability:{metrics:{version:1,methods:[xe.metrics]}}}:{}}}import{execFile as CLe}from"node:child_process";var $Le=3e4,zN="manual",OLe=".red/tmp/worktrees",QQ=["workers","go-workers","scout-workers"];function zLe(e){return`${OLe}/${zN}/${e}`}function XQ(e){let t=e.registeredCheckout();if(t==null)throw bN(Ch.checkoutNotRegistered,"redskilled holds no registration for this checkout's Project, so it can name neither its trunk nor its lanes; register the Project with the daemon before asking for a worktree");return t}function DLe(e){let t=e.git??eX;return async r=>{let n=XQ(e),o=n.trunk?.remote??"origin",i=r.params.base??n.trunk?.branch;if(i==null||i==="")throw bN(Ch.trunkUnknown,"this Project's registration states no trunk branch, so worktree_add has nothing to fork from; name a base, or re-register with explicit git coordinates");let s=zLe(r.params.slug),a=r.params.branch??`afk/${r.params.slug}`,l=`${o}/${i}`;return await t(n.checkout_root,["fetch",o,i]),await t(n.checkout_root,["worktree","add",s,"-b",a,l]),{version:1,kind:"interactive",path:s,branch:a,base:l,lane:zN,project_label:n.project_label}}}function jLe(e){let t=e.git??eX;return async()=>{let r=XQ(e),n=await t(r.checkout_root,["worktree","list","--porcelain"]),o=MLe(n).map(s=>NLe(r.checkout_root,s)),i=e.workerWorktrees().map(s=>({kind:"worker",path:s.path,branch:null,worker_id:s.worker_id}));return{version:1,project_label:r.project_label,worktrees:[...o,...i]}}}function MLe(e){let t=[],r,n=null,o=()=>{r!=null&&t.push({path:r,branch:n}),r=void 0,n=null};for(let i of e.split(`
|
|
342
342
|
`)){let s=i.trimEnd();s.startsWith("worktree ")?(o(),r=s.slice(9)):s.startsWith("branch ")&&(n=s.slice(7).replace(/^refs\/heads\//,""))}return o(),t}function NLe(e,t){let r=GLe(e,t.path),n=r===null?"unregistered":LLe(r),o=r===null?void 0:FLe(r);return{kind:n,path:t.path,branch:t.branch,...o===void 0?{}:{lane:o}}}function LLe(e){if(e==="")return"checkout";let t=e.split("/");return t[0]!==".red"||t[1]!=="tmp"||t[2]===void 0?"unregistered":t[2]==="worktrees"?t[3]===void 0?"unregistered":"interactive":QQ.includes(t[2])&&t.at(-1)==="worktree"?"worker":"unregistered"}function FLe(e){let t=e.split("/");if(!(t[0]!==".red"||t[1]!=="tmp"))return t[2]==="worktrees"?t[3]:QQ.includes(t[2]??"")?t[2]:void 0}function GLe(e,t){let[r,n]=[YQ(e),YQ(t)];return n===r?"":n.startsWith(`${r}/`)?n.slice(r.length+1):null}function YQ(e){return e.replace(/\\/g,"/").replace(/\/+$/,"")}function eX(e,t){return new Promise((r,n)=>{CLe("git",[...t],{cwd:e,encoding:"utf8",timeout:$Le,windowsHide:!0},(o,i,s)=>{if(o!=null){n(new Error(s.trim()||o.message));return}r(i)})})}function tX(e){return{domain:"worktree",bindings:[Mt(xe.worktreeAdd,NY,DLe(e)),Mt(xe.worktreeList,Wu("worktree_list names no checkout, Project or lane; the connection's registration decides"),jLe(e))],capability:{worktree:{version:MY.version,methods:[xe.worktreeAdd,xe.worktreeList],lane:zN}}}}import{randomUUID as t1e}from"node:crypto";import{mkdir as r1e,readFile as n1e,rename as o1e,writeFile as i1e}from"node:fs/promises";import{dirname as mX,join as s1e}from"node:path";var Bh=50,jN=15e3,nX=2*jN,BLe=32;function oX(e,t){if(t==null)return e;let r=new Map(t.projects.filter(n=>n.items!=null).map(n=>[n.project_label,{items:n.items,tickets:n.tickets??[]}]));return{...e,projects:e.projects.map(n=>{if(n.items!=null)return n;let o=r.get(n.project_label);return o==null?n:{...n,items:[...o.items],tickets:[...o.tickets]}})}}function ULe(e){return iX(e).map(t=>t.id)}function iX(e){let t=[];for(let r of e){if(t.length>=BLe)break;let n=r.number;typeof n!="number"||!Number.isInteger(n)||n<=0||t.push({id:String(n),title:typeof r.title=="string"?r.title:"",labels:Array.isArray(r.labels)?r.labels.map(o=>typeof o=="string"?o:o?.name).filter(o=>typeof o=="string"):[]})}return t}function qLe(e,t=Bh){if(MN(e),!Number.isInteger(t)||t<=0)throw new Error(`redskilled queue discovery needs a whole, positive batch size, not ${JSON.stringify(t)}`);let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function sX(e,t={}){let r=t.batchSize??Bh;if(MN(e),e.length>r)throw new Error(`redskilled queue discovery spans at most ${r} selectors in one query, and this batch holds ${e.length}: split it with planQueueDiscoveryBatches rather than dropping the remainder`);let n=e.map((s,a)=>({alias:`q${a}`,project:s}));return{query:["query RedskilledQueueDiscovery {"," rateLimit { remaining resetAt }",...n.map(({alias:s,project:a})=>` ${s}: search(query: ${JSON.stringify(a.selector)}, type: ISSUE, first: 1) { issueCount }`),"}"].join(`
|
|
@@ -138,7 +138,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
138
138
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
139
139
|
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Hn(s,r.start),s.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,s=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&r.sep&&!r.value){let o=[];for(let a=0;a<r.sep.length;++a){let c=r.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||r.value?(i.push(this.sourceToken),t.items.push({start:i}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):s||r.value?(i.push(this.sourceToken),t.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(qe(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(ap(r.key)&&!qe(r.sep,"newline")){let o=vt(r.start),a=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?r.sep=r.sep.concat(i,this.sourceToken):r.sep.push(this.sourceToken);else if(qe(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=vt(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||s?t.items.push({start:i,key:null,sep:[this.sourceToken]}):qe(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);s||r.value?(t.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!qe(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){Hn(s,r.start),s.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||qe(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:s,sep:[]}):r.sep?this.stack.push(s):Object.assign(r,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let s=Vn(n),i=vt(s);op(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
|
|
140
140
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
141
|
-
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cp.Parser=Io});var fp=P(ur=>{"use strict";var lp=To(),xE=tr(),lr=sr(),IE=bi(),NE=L(),LE=xo(),up=No();function dp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new LE.LineCounter||null,prettyErrors:t}}function qE(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=Array.from(i.compose(s.parse(e)));if(n&&r)for(let a of o)a.errors.forEach(lr.prettifyError(e,r)),a.warnings.forEach(lr.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function pp(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=null;for(let a of i.compose(s.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new lr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(lr.prettifyError(e,r)),o.warnings.forEach(lr.prettifyError(e,r))),o}function DE(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let s=pp(e,r);if(!s)return null;if(s.warnings.forEach(i=>IE.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},r))}function FE(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let s=Math.round(r);r=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=r??t??{};if(!s)return}return NE.isDocument(e)&&!n?e.toString(r):new xE.Document(e,n,r).toString(r)}ur.parse=DE;ur.parseAllDocuments=qE;ur.parseDocument=pp;ur.stringify=FE});var qo=P(q=>{"use strict";var jE=To(),BE=tr(),UE=eo(),Lo=sr(),ME=Ft(),De=L(),VE=xe(),HE=U(),KE=Ne(),WE=Le(),zE=Un(),JE=Co(),YE=xo(),QE=No(),Kn=fp(),hp=Nt();q.Composer=jE.Composer;q.Document=BE.Document;q.Schema=UE.Schema;q.YAMLError=Lo.YAMLError;q.YAMLParseError=Lo.YAMLParseError;q.YAMLWarning=Lo.YAMLWarning;q.Alias=ME.Alias;q.isAlias=De.isAlias;q.isCollection=De.isCollection;q.isDocument=De.isDocument;q.isMap=De.isMap;q.isNode=De.isNode;q.isPair=De.isPair;q.isScalar=De.isScalar;q.isSeq=De.isSeq;q.Pair=VE.Pair;q.Scalar=HE.Scalar;q.YAMLMap=KE.YAMLMap;q.YAMLSeq=WE.YAMLSeq;q.CST=zE;q.Lexer=JE.Lexer;q.LineCounter=YE.LineCounter;q.Parser=QE.Parser;q.parse=Kn.parse;q.parseAllDocuments=Kn.parseAllDocuments;q.parseDocument=Kn.parseDocument;q.stringify=Kn.stringify;q.visit=hp.visit;q.visitAsync=hp.visitAsync});import{readFileSync as ef}from"node:fs";import{join as tf,resolve as ta}from"node:path";function Ta(e){let t={app:e,version:bf(it("__RED_BUILD_VERSION__",()=>"4.1.13")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"19ba7780d0a8be832373d24cce303d1833430d2d")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-21T01:42:13-03:00")??"unknown",bundleAsset:it("__RED_BUNDLE_ASSET__",()=>"release.bundle.min.mjs")??"unknown"},r=it("__REDDB_SDK_VERSION__",()=>""),n=it("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function bf(e){return e.startsWith("v")?e.slice(1):e}function _a(e){return`${e.app} ${e.version} ${e.gitSha}`}function it(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function ka(e){return e==="single-object"?"rest":"graphql"}function va(e,t){return e==="stable-poll"?"rest":ka(t)}function Z(e){return{none:e}}function M(e,t,r,n,s,i,o){let a=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"read",cardinality:t,volatility:r,surface:o??va(r,t),budget:n,...a,...o?{only:o}:{},why:i}}function ee(e,t,r,n,s){let i=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"write",cardinality:"single-object",surface:t,budget:r,...i,why:n}}var Sa=[M("issue view","single-object","stable-poll","rest","graphql","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),M("pr view","single-object","stable-poll","rest","graphql","one pull request by number, polled per Worker per iteration"),M("repo view","single-object","stable-poll","rest","graphql","one repository's own metadata, repeatedly read while usually unchanged"),M("run view","single-object","stable-poll","rest",Z("Actions runs have no GraphQL resource"),"one Actions run repeatedly polled to terminal"),M("release view","single-object","stable-poll","rest",Z("release lookup has no GraphQL client method"),"one release by tag, repeatedly checked while usually absent or unchanged"),M("pr diff","single-object","one-shot","rest",Z("the complete diff is exposed as a REST media type"),"one pull request's diff, read once for review"),M("issue list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged issue collection; REST can make an unchanged poll free"),M("pr list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged pull-request collection; REST can make an unchanged poll free"),M("pr checks","multi-node","stable-poll","rest","graphql","check contexts are repeatedly polled while awaiting terminal state"),M("release list","multi-node","stable-poll","rest",Z("Releases has no GraphQL collection client method"),"release waits poll a usually-unchanged list"),M("run list","multi-node","stable-poll","rest",Z("Actions has no GraphQL collection client method"),"run waits poll a usually-unchanged list"),M("label list","multi-node","one-shot","graphql","rest","a label connection loaded once for the current operation"),M("issue list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"queue discovery polls usually-unchanged search results through the 30/min search connection"),M("pr list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"PR discovery polls usually-unchanged search results through the 30/min search connection"),M("search issues","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search prs","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search repos","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("api graphql","multi-node","one-shot","graphql",Z("the caller explicitly chose GraphQL"),"the caller supplies one explicit GraphQL query rather than a routed poll"),M("api rest","single-object","one-shot","rest",Z("the caller explicitly chose REST"),"the caller supplies one explicit REST path rather than a routed poll"),ee("issue create","rest","rest","the write plan POSTs to `repos/{o}/{r}/issues`; GraphQL exposes createIssue","graphql"),ee("issue edit","rest","rest","the write plan PATCHes labels and body; GraphQL exposes updateIssue","graphql"),ee("issue close","rest","rest","the write plan PATCHes issue state; GraphQL exposes closeIssue","graphql"),ee("issue reopen","graphql","graphql","gh uses reopenIssue; REST can PATCH the issue state to open","rest"),ee("issue comment","rest","rest","the write plan POSTs an issue comment; GraphQL exposes addComment","graphql"),ee("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation",Z("linked-branch creation has no REST mutation")),ee("pr create","rest","rest","the write plan POSTs a pull request; GraphQL exposes createPullRequest","graphql"),ee("pr comment","rest","rest","a pull request comment is an issue comment; GraphQL exposes addComment","graphql"),ee("pr merge","rest","rest","the default plan PUTs the merge; GraphQL exposes mergePullRequest","graphql"),ee("pr close","graphql","graphql","gh uses closePullRequest; REST can PATCH the pull request state","rest"),ee("pr edit","graphql","graphql","gh uses GraphQL mutations; REST can PATCH pull-request fields and issue labels","rest"),ee("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation",Z("GitHub exposes no REST ready-for-review mutation")),ee("pr update-branch","rest","rest","the write plan PUTs update-branch; GraphQL exposes updatePullRequestBranch","graphql"),ee("label create","rest","rest","the write plan POSTs a label; GraphQL exposes createLabel","graphql")],q_=new Map(Sa.map(e=>[e.key,e]));var ss="RED_GITHUB_REQUEST_TIMEOUT_MS",ot=class extends Error{subject;timeoutMs;constructor(t,r,n){super(`GitHub ${t} passed its ${r}ms deadline and was abandoned; raise ${ss} if this host is genuinely this slow`,n),this.name="GithubTimeoutError",this.subject=t,this.timeoutMs=r}};function Ra(e){return e instanceof ot}function _r(e=process.env){let t=e[ss];if(t===void 0||t.trim()==="")return 3e4;let r=Number(t);return!Number.isFinite(r)||r<0?3e4:Math.trunc(r)}async function kr(e,t,r){if(!Number.isFinite(t)||t<=0)return await r();let n,s=new Promise((o,a)=>{n=setTimeout(()=>a(new ot(e,t)),t),n.unref?.()}),i=Promise.resolve().then(r);i.catch(()=>{});try{return await Promise.race([i,s])}finally{n!==void 0&&clearTimeout(n)}}function is(e={}){let t=e.fetchImpl??fetch,r=e.timeoutMs??_r();return!Number.isFinite(r)||r<=0?t:async(n,s)=>{let i=AbortSignal.timeout(r),o=s?.signal??null,a=o==null?i:AbortSignal.any([o,i]),c=wf(n);try{return await kr(c,r,async()=>await t(n,{...s??{},signal:a}))}catch(l){throw Ra(l)?l:i.aborted&&o?.aborted!==!0?new ot(c,r,{cause:l}):l}}}function wf(e){let t=typeof e=="string"?e:e instanceof URL?e.href:typeof e.url=="string"?e.url:"request";try{return new URL(t).pathname}catch{return t}}var vr="off";var Aa="RED_GITHUB_BUDGET_GATE";function Ga(e){if(e===!0)return"on";if(typeof e!="string")return vr;let t=e.trim().toLowerCase();return t==="on"||t==="enabled"||t==="true"?"on":vr}function os(e){return(e??vr)==="on"}function as(e=process.env){return Ga(e[Aa])}import{execFile as Yf}from"node:child_process";import{promisify as Qf}from"node:util";var at=class extends SyntaxError{line;source;reason;constructor(t,r,n={}){super(t===0?r:`line ${t}: ${r}`,n.cause===void 0?void 0:{cause:n.cause}),this.name="ToonError",this.line=t,this.source=n.source,this.reason=r}};function ve(e,t,r={}){return new at(e,t,r)}var Ef=/(?:^\uFEFF?|\n) *#/,cs=class{value;constructor(t){if(Ef.test(t))throw new TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(t)}`);this.value=t}};function Me(e){return e instanceof cs}function Tf(e){return/^[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function _f(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw ve(0,"number is not representable in TOON");return String(e)}function Sr(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function te(e,t){if(Me(e))return e.value;if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return _f(e);if(typeof e=="string")return vf(e,t);throw ve(0,"not a primitive")}function kf(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function X(e){return kf(e)?e:Rr(e)}function vf(e,t){return ls(e,t)?Rr(e):e}function ls(e,t){return e===""||/^[ \t]|[ \t]$/.test(e)||e==="true"||e==="false"||e==="null"||Tf(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")||e.startsWith("#")}var Oa=/["\\\u0000-\u001f]/g;function Rr(e){return`"${Pa(e)}"`}function Pa(e){let t="",r=0;Oa.lastIndex=0;let n;for(;(n=Oa.exec(e))!==null;){let s=e.charCodeAt(n.index),i;s===34?i='\\"':s===92?i="\\\\":s===10?i="\\n":s===13?i="\\r":s===9?i="\\t":i=`\\u${s.toString(16).padStart(4,"0")}`,t+=e.slice(r,n.index)+i,r=n.index+1}return`${t}${e.slice(r)}`}var Ca={comma:",",tab:" ",pipe:"|"},Sf=Ca.comma;var Ar=1e3,$a=["type","kind","event"],Ve="|";var tk=Symbol("need line");var Of=/[\uD800-\uDFFF]/;function be(e){if(e===null)return null;if(Me(e))return e;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return be(t)}if(typeof e=="string")return Na(e,"string value"),e;if(typeof e=="boolean")return e;if(typeof e=="number")return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e=="bigint")return e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(be);if(e instanceof Set)return Array.from(e,be);if(e instanceof Map){let t={};for(let[r,n]of e)Gt(t,String(r),be(n));return t}if(J(e)){let t={};for(let r of Object.keys(e))Na(r,"object key"),Gt(t,r,be(e[r]));return t}return null}function Na(e,t){if(Of.test(e))for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n<55296||n>57343)continue;let s=e.charCodeAt(r+1);if(n<=56319&&s>=56320&&s<=57343){r+=1;continue}throw new TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${n.toString(16).toUpperCase()} at index ${r}`)}}function J(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ce(e){return e===null||Me(e)||["string","number","boolean"].includes(typeof e)}function Gt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function La(e){return encodeURIComponent(e)}function Da(e){if(!J(e))return;let t=Object.entries(e);if(t.length===0)return;let r=[];for(let[s,i]of t){let o=Cf(i);if(o===void 0)return;r.push([s,o])}let n=[];for(let[s,i]of r)Nf(n,s,i);return n.join("")}function Cf(e){if(!Array.isArray(e)||e.length===0||!e.every(J))return;let t=$f(e);if(t===void 0)return;let r=e.map(a=>a[t]),n=xf(r);if(n===void 0)return;let s=If(e,t),i=new Map;for(let a of e){let c=a[t];i.has(c)||i.set(c,[]);let l={};for(let[d,p]of Object.entries(a))if(d!==t&&!s.includes(d)&&!us(p,d,l))return;i.get(c).push(l)}let o=[];for(let a of n.cycle){let c=i.get(a),l=qf(c);if(l===void 0||l.length===0)return;o.push({fields:l,label:a,rows:c})}return{common:s,commonRows:e.map(a=>Object.fromEntries(s.map(c=>[c,a[c]]))),discriminator:t,groups:o,order:n,rows:e}}function $f(e){return $a.find(t=>e.every(r=>typeof r[t]=="string"))}function xf(e){if(!(e.length<12))for(let t=2;t<=Math.min(8,Math.floor(e.length/3));t+=1){if(e.length%t!==0)continue;let r=e.slice(0,t);if(new Set(r).size<2||!e.every((o,a)=>o===r[a%t]))continue;let n=e.length/t;if(n<3)continue;let s=e.map(La).join(","),i=`cycle(${r.map(La).join(",")})*${n}`;if(i.length<=s.length*.4)return{cycle:r,encoded:i,repeats:n}}}function If(e,t){let r=[],n=Object.keys(e[0]),s=n.indexOf(t)+1;for(let i of n.slice(s).filter(o=>o!==t)){if(!Lf(i)||!e.every(o=>Object.prototype.hasOwnProperty.call(o,i))||!e.every(o=>Sr(o[i])))break;r.push(i)}return r}function Nf(e,t,r){e.push(X(t),`:
|
|
141
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Vn(t),n=vt(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};cp.Parser=Io});var fp=P(ur=>{"use strict";var lp=To(),xE=tr(),lr=sr(),IE=bi(),NE=L(),LE=xo(),up=No();function dp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new LE.LineCounter||null,prettyErrors:t}}function qE(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=Array.from(i.compose(s.parse(e)));if(n&&r)for(let a of o)a.errors.forEach(lr.prettifyError(e,r)),a.warnings.forEach(lr.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function pp(e,t={}){let{lineCounter:r,prettyErrors:n}=dp(t),s=new up.Parser(r?.addNewLine),i=new lp.Composer(t),o=null;for(let a of i.compose(s.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new lr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(lr.prettifyError(e,r)),o.warnings.forEach(lr.prettifyError(e,r))),o}function DE(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let s=pp(e,r);if(!s)return null;if(s.warnings.forEach(i=>IE.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},r))}function FE(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let s=Math.round(r);r=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=r??t??{};if(!s)return}return NE.isDocument(e)&&!n?e.toString(r):new xE.Document(e,n,r).toString(r)}ur.parse=DE;ur.parseAllDocuments=qE;ur.parseDocument=pp;ur.stringify=FE});var qo=P(q=>{"use strict";var jE=To(),BE=tr(),UE=eo(),Lo=sr(),ME=Ft(),De=L(),VE=xe(),HE=U(),KE=Ne(),WE=Le(),zE=Un(),JE=Co(),YE=xo(),QE=No(),Kn=fp(),hp=Nt();q.Composer=jE.Composer;q.Document=BE.Document;q.Schema=UE.Schema;q.YAMLError=Lo.YAMLError;q.YAMLParseError=Lo.YAMLParseError;q.YAMLWarning=Lo.YAMLWarning;q.Alias=ME.Alias;q.isAlias=De.isAlias;q.isCollection=De.isCollection;q.isDocument=De.isDocument;q.isMap=De.isMap;q.isNode=De.isNode;q.isPair=De.isPair;q.isScalar=De.isScalar;q.isSeq=De.isSeq;q.Pair=VE.Pair;q.Scalar=HE.Scalar;q.YAMLMap=KE.YAMLMap;q.YAMLSeq=WE.YAMLSeq;q.CST=zE;q.Lexer=JE.Lexer;q.LineCounter=YE.LineCounter;q.Parser=QE.Parser;q.parse=Kn.parse;q.parseAllDocuments=Kn.parseAllDocuments;q.parseDocument=Kn.parseDocument;q.stringify=Kn.stringify;q.visit=hp.visit;q.visitAsync=hp.visitAsync});import{readFileSync as ef}from"node:fs";import{join as tf,resolve as ta}from"node:path";function Ta(e){let t={app:e,version:bf(it("__RED_BUILD_VERSION__",()=>"4.1.14")??"0.0.0-dev"),gitSha:it("__RED_BUILD_GIT_SHA__",()=>"a2c2d45c9f89f44932e381ec4b99bf2aa5d25445")??"unknown",buildTime:it("__RED_BUILD_TIME__",()=>"2026-08-21T02:01:02-03:00")??"unknown",bundleAsset:it("__RED_BUNDLE_ASSET__",()=>"release.bundle.min.mjs")??"unknown"},r=it("__REDDB_SDK_VERSION__",()=>""),n=it("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function bf(e){return e.startsWith("v")?e.slice(1):e}function _a(e){return`${e.app} ${e.version} ${e.gitSha}`}function it(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function ka(e){return e==="single-object"?"rest":"graphql"}function va(e,t){return e==="stable-poll"?"rest":ka(t)}function Z(e){return{none:e}}function M(e,t,r,n,s,i,o){let a=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"read",cardinality:t,volatility:r,surface:o??va(r,t),budget:n,...a,...o?{only:o}:{},why:i}}function ee(e,t,r,n,s){let i=typeof s=="string"?{fallback:s}:{fallback:null,noFallbackBecause:s.none};return{key:e,kind:"write",cardinality:"single-object",surface:t,budget:r,...i,why:n}}var Sa=[M("issue view","single-object","stable-poll","rest","graphql","one issue by number, repeatedly polled while usually unchanged; REST answers in one request"),M("pr view","single-object","stable-poll","rest","graphql","one pull request by number, polled per Worker per iteration"),M("repo view","single-object","stable-poll","rest","graphql","one repository's own metadata, repeatedly read while usually unchanged"),M("run view","single-object","stable-poll","rest",Z("Actions runs have no GraphQL resource"),"one Actions run repeatedly polled to terminal"),M("release view","single-object","stable-poll","rest",Z("release lookup has no GraphQL client method"),"one release by tag, repeatedly checked while usually absent or unchanged"),M("pr diff","single-object","one-shot","rest",Z("the complete diff is exposed as a REST media type"),"one pull request's diff, read once for review"),M("issue list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged issue collection; REST can make an unchanged poll free"),M("pr list","multi-node","stable-poll","rest","graphql","a repeatedly polled, usually-unchanged pull-request collection; REST can make an unchanged poll free"),M("pr checks","multi-node","stable-poll","rest","graphql","check contexts are repeatedly polled while awaiting terminal state"),M("release list","multi-node","stable-poll","rest",Z("Releases has no GraphQL collection client method"),"release waits poll a usually-unchanged list"),M("run list","multi-node","stable-poll","rest",Z("Actions has no GraphQL collection client method"),"run waits poll a usually-unchanged list"),M("label list","multi-node","one-shot","graphql","rest","a label connection loaded once for the current operation"),M("issue list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"queue discovery polls usually-unchanged search results through the 30/min search connection"),M("pr list (search)","multi-node","stable-poll","search",Z("search is ineligible for diverted traffic"),"PR discovery polls usually-unchanged search results through the 30/min search connection"),M("search issues","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search prs","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("search repos","multi-repository","one-shot","search",Z("search is ineligible for diverted traffic"),"a one-shot cross-repository read through the REST search endpoint, metered 30/min","rest"),M("api graphql","multi-node","one-shot","graphql",Z("the caller explicitly chose GraphQL"),"the caller supplies one explicit GraphQL query rather than a routed poll"),M("api rest","single-object","one-shot","rest",Z("the caller explicitly chose REST"),"the caller supplies one explicit REST path rather than a routed poll"),ee("issue create","rest","rest","the write plan POSTs to `repos/{o}/{r}/issues`; GraphQL exposes createIssue","graphql"),ee("issue edit","rest","rest","the write plan PATCHes labels and body; GraphQL exposes updateIssue","graphql"),ee("issue close","rest","rest","the write plan PATCHes issue state; GraphQL exposes closeIssue","graphql"),ee("issue reopen","graphql","graphql","gh uses reopenIssue; REST can PATCH the issue state to open","rest"),ee("issue comment","rest","rest","the write plan POSTs an issue comment; GraphQL exposes addComment","graphql"),ee("issue develop","graphql","graphql","linked-branch creation is a GraphQL mutation",Z("linked-branch creation has no REST mutation")),ee("pr create","rest","rest","the write plan POSTs a pull request; GraphQL exposes createPullRequest","graphql"),ee("pr comment","rest","rest","a pull request comment is an issue comment; GraphQL exposes addComment","graphql"),ee("pr merge","rest","rest","the default plan PUTs the merge; GraphQL exposes mergePullRequest","graphql"),ee("pr close","graphql","graphql","gh uses closePullRequest; REST can PATCH the pull request state","rest"),ee("pr edit","graphql","graphql","gh uses GraphQL mutations; REST can PATCH pull-request fields and issue labels","rest"),ee("pr ready","graphql","graphql","marking ready-for-review is a GraphQL mutation",Z("GitHub exposes no REST ready-for-review mutation")),ee("pr update-branch","rest","rest","the write plan PUTs update-branch; GraphQL exposes updatePullRequestBranch","graphql"),ee("label create","rest","rest","the write plan POSTs a label; GraphQL exposes createLabel","graphql")],q_=new Map(Sa.map(e=>[e.key,e]));var ss="RED_GITHUB_REQUEST_TIMEOUT_MS",ot=class extends Error{subject;timeoutMs;constructor(t,r,n){super(`GitHub ${t} passed its ${r}ms deadline and was abandoned; raise ${ss} if this host is genuinely this slow`,n),this.name="GithubTimeoutError",this.subject=t,this.timeoutMs=r}};function Ra(e){return e instanceof ot}function _r(e=process.env){let t=e[ss];if(t===void 0||t.trim()==="")return 3e4;let r=Number(t);return!Number.isFinite(r)||r<0?3e4:Math.trunc(r)}async function kr(e,t,r){if(!Number.isFinite(t)||t<=0)return await r();let n,s=new Promise((o,a)=>{n=setTimeout(()=>a(new ot(e,t)),t),n.unref?.()}),i=Promise.resolve().then(r);i.catch(()=>{});try{return await Promise.race([i,s])}finally{n!==void 0&&clearTimeout(n)}}function is(e={}){let t=e.fetchImpl??fetch,r=e.timeoutMs??_r();return!Number.isFinite(r)||r<=0?t:async(n,s)=>{let i=AbortSignal.timeout(r),o=s?.signal??null,a=o==null?i:AbortSignal.any([o,i]),c=wf(n);try{return await kr(c,r,async()=>await t(n,{...s??{},signal:a}))}catch(l){throw Ra(l)?l:i.aborted&&o?.aborted!==!0?new ot(c,r,{cause:l}):l}}}function wf(e){let t=typeof e=="string"?e:e instanceof URL?e.href:typeof e.url=="string"?e.url:"request";try{return new URL(t).pathname}catch{return t}}var vr="off";var Aa="RED_GITHUB_BUDGET_GATE";function Ga(e){if(e===!0)return"on";if(typeof e!="string")return vr;let t=e.trim().toLowerCase();return t==="on"||t==="enabled"||t==="true"?"on":vr}function os(e){return(e??vr)==="on"}function as(e=process.env){return Ga(e[Aa])}import{execFile as Yf}from"node:child_process";import{promisify as Qf}from"node:util";var at=class extends SyntaxError{line;source;reason;constructor(t,r,n={}){super(t===0?r:`line ${t}: ${r}`,n.cause===void 0?void 0:{cause:n.cause}),this.name="ToonError",this.line=t,this.source=n.source,this.reason=r}};function ve(e,t,r={}){return new at(e,t,r)}var Ef=/(?:^\uFEFF?|\n) *#/,cs=class{value;constructor(t){if(Ef.test(t))throw new TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(t)}`);this.value=t}};function Me(e){return e instanceof cs}function Tf(e){return/^[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function _f(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw ve(0,"number is not representable in TOON");return String(e)}function Sr(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function te(e,t){if(Me(e))return e.value;if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return _f(e);if(typeof e=="string")return vf(e,t);throw ve(0,"not a primitive")}function kf(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function X(e){return kf(e)?e:Rr(e)}function vf(e,t){return ls(e,t)?Rr(e):e}function ls(e,t){return e===""||/^[ \t]|[ \t]$/.test(e)||e==="true"||e==="false"||e==="null"||Tf(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")||e.startsWith("#")}var Oa=/["\\\u0000-\u001f]/g;function Rr(e){return`"${Pa(e)}"`}function Pa(e){let t="",r=0;Oa.lastIndex=0;let n;for(;(n=Oa.exec(e))!==null;){let s=e.charCodeAt(n.index),i;s===34?i='\\"':s===92?i="\\\\":s===10?i="\\n":s===13?i="\\r":s===9?i="\\t":i=`\\u${s.toString(16).padStart(4,"0")}`,t+=e.slice(r,n.index)+i,r=n.index+1}return`${t}${e.slice(r)}`}var Ca={comma:",",tab:" ",pipe:"|"},Sf=Ca.comma;var Ar=1e3,$a=["type","kind","event"],Ve="|";var tk=Symbol("need line");var Of=/[\uD800-\uDFFF]/;function be(e){if(e===null)return null;if(Me(e))return e;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return be(t)}if(typeof e=="string")return Na(e,"string value"),e;if(typeof e=="boolean")return e;if(typeof e=="number")return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e=="bigint")return e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(be);if(e instanceof Set)return Array.from(e,be);if(e instanceof Map){let t={};for(let[r,n]of e)Gt(t,String(r),be(n));return t}if(J(e)){let t={};for(let r of Object.keys(e))Na(r,"object key"),Gt(t,r,be(e[r]));return t}return null}function Na(e,t){if(Of.test(e))for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n<55296||n>57343)continue;let s=e.charCodeAt(r+1);if(n<=56319&&s>=56320&&s<=57343){r+=1;continue}throw new TypeError(`Cannot encode ${t} containing an unpaired surrogate U+${n.toString(16).toUpperCase()} at index ${r}`)}}function J(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ce(e){return e===null||Me(e)||["string","number","boolean"].includes(typeof e)}function Gt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function La(e){return encodeURIComponent(e)}function Da(e){if(!J(e))return;let t=Object.entries(e);if(t.length===0)return;let r=[];for(let[s,i]of t){let o=Cf(i);if(o===void 0)return;r.push([s,o])}let n=[];for(let[s,i]of r)Nf(n,s,i);return n.join("")}function Cf(e){if(!Array.isArray(e)||e.length===0||!e.every(J))return;let t=$f(e);if(t===void 0)return;let r=e.map(a=>a[t]),n=xf(r);if(n===void 0)return;let s=If(e,t),i=new Map;for(let a of e){let c=a[t];i.has(c)||i.set(c,[]);let l={};for(let[d,p]of Object.entries(a))if(d!==t&&!s.includes(d)&&!us(p,d,l))return;i.get(c).push(l)}let o=[];for(let a of n.cycle){let c=i.get(a),l=qf(c);if(l===void 0||l.length===0)return;o.push({fields:l,label:a,rows:c})}return{common:s,commonRows:e.map(a=>Object.fromEntries(s.map(c=>[c,a[c]]))),discriminator:t,groups:o,order:n,rows:e}}function $f(e){return $a.find(t=>e.every(r=>typeof r[t]=="string"))}function xf(e){if(!(e.length<12))for(let t=2;t<=Math.min(8,Math.floor(e.length/3));t+=1){if(e.length%t!==0)continue;let r=e.slice(0,t);if(new Set(r).size<2||!e.every((o,a)=>o===r[a%t]))continue;let n=e.length/t;if(n<3)continue;let s=e.map(La).join(","),i=`cycle(${r.map(La).join(",")})*${n}`;if(i.length<=s.length*.4)return{cycle:r,encoded:i,repeats:n}}}function If(e,t){let r=[],n=Object.keys(e[0]),s=n.indexOf(t)+1;for(let i of n.slice(s).filter(o=>o!==t)){if(!Lf(i)||!e.every(o=>Object.prototype.hasOwnProperty.call(o,i))||!e.every(o=>Sr(o[i])))break;r.push(i)}return r}function Nf(e,t,r){e.push(X(t),`:
|
|
142
142
|
`),e.push(" order: ",te(r.order.encoded,Ve),`
|
|
143
143
|
`),e.push(" discriminator: ",te(r.discriminator,Ve),`
|
|
144
144
|
`),e.push(" rows: ",String(r.rows.length),`
|
|
@@ -25,7 +25,7 @@ var PP=Object.create;var Vu=Object.defineProperty;var IP=Object.getOwnPropertyDe
|
|
|
25
25
|
`;return E+=k,a+=1,c+=1,l+=k.length,E},declareLane(b,y){if(d)throw Y(0,"TOONL encoder is closed");let E=gL(y),w=Sd(zt,E),k=g(b);return rw(k.fields,E)?"":(k.fields=E,tw(b,w))},pushTagged(b,y){if(d)throw Y(0,"TOONL encoder is closed");let E=g(b),w=ow(sw(y),E.fieldsByShape),k=Sd(zt,w),S=w.map(C=>ve(y[C],zt)),T="";return rw(E.fields,w)||(E.fields=w,T+=tw(b,k)),`${T}${b}:${S.join(zt)}
|
|
26
26
|
`},end(){return d?"":(d=!0,f())}}}var iw,aw,cw,G4,D4,uw=_(()=>{Kt();ga();so();nn();iw=[zt,"|"," "],aw=8,cw=/^[A-Za-z0-9_-]+$/,G4=new TextEncoder,D4=new TextDecoder});var z,J=_(()=>{ga();so();Yb();Kt();ro();Qb();so();Zs();nn();ma();ga();Xb();uw();z=bd});function _L(e){return e==="no-op"?0:e==="usage"?2:1}function ee(e){return Buffer.from(`${M(Rd(e))}
|
|
27
27
|
`)}function Rd(e){let t={command:e.command,category:e.category,exit_code:e.exitCode??_L(e.category),error:e.error,help:[e.help]};return e.validFlags&&e.validFlags.length>0&&(t.valid_flags=[...e.validFlags]),e.diagnostics&&(t.diagnostics=EL(e.diagnostics,3)),t}function qe(e,t,r){let s=([r,t].find(i=>i.trim())??"").trim(),o=s.toLowerCase();return/\bgh\b/.test(e)&&Qy(s)?{command:e,category:"transient",error:oo(s)||"GitHub API rate limit exceeded",help:Yy,diagnostics:s}:/\bgh\b/.test(e)&&(o.includes("gh_token")||o.includes("not logged in")||o.includes("authentication"))?{command:e,category:"real-error",error:oo(s)||"GitHub authentication failed",help:"gh auth login",diagnostics:s}:o.includes("not a git repository")?{command:e,category:"real-error",error:oo(s)||"not a git repository",help:"git status",diagnostics:s}:o.includes("repository not found")||o.includes("could not resolve host")?{command:e,category:"real-error",error:oo(s)||"repository is unavailable",help:e.startsWith("gh ")?"gh repo view":"git remote -v",diagnostics:s}:{command:e,category:"real-error",error:oo(s)||"command failed",help:`${e} --help`,diagnostics:s}}function dw(e,t,r,n){return ee({command:e,category:"usage",error:`unknown flag: ${t}`,help:n,validFlags:r})}function oo(e){return e.split(/\r?\n/,1)[0]?.trim()??""}function EL(e,t){return e.split(/\r?\n/).slice(0,t).join(`
|
|
28
|
-
`).trim()}var bt=_(()=>{"use strict";Xy();J()});function Ea(e){let t={app:e,version:IL(Jn("__RED_BUILD_VERSION__",()=>"4.1.
|
|
28
|
+
`).trim()}var bt=_(()=>{"use strict";Xy();J()});function Ea(e){let t={app:e,version:IL(Jn("__RED_BUILD_VERSION__",()=>"4.1.14")??"0.0.0-dev"),gitSha:Jn("__RED_BUILD_GIT_SHA__",()=>"a2c2d45c9f89f44932e381ec4b99bf2aa5d25445")??"unknown",buildTime:Jn("__RED_BUILD_TIME__",()=>"2026-08-21T02:01:02-03:00")??"unknown",bundleAsset:Jn("__RED_BUNDLE_ASSET__",()=>"rsp-core.bundle.min.mjs")??"unknown"},r=Jn("__REDDB_SDK_VERSION__",()=>"1.23.1"),n=Jn("__REDDB_BINARY_TAG__",()=>"v1.23.1");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function IL(e){return e.startsWith("v")?e.slice(1):e}function _w(e){return`${e.app} ${e.version} ${e.gitSha}`}function Jn(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var Td=_(()=>{});import{isAbsolute as LL,join as Yt,resolve as xd}from"node:path";function NL(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function kw(e){return Yt(NL(e),Ew)}function Sw(e){return Yt(kw(e),"state")}function Rw(e){return Yt(kw(e),"tmp")}function ce(e){return Yt(Sw(e),"rsp")}function $L(e){return Yt(Sw(e),"red-skills.rdb")}function FL(e){return Yt(Rw(e),"red-skills.rdb")}function xw(e,t){let r=$L(e);if(t(r))return r;let n=FL(e);if(t(n))throw ML();return r}function ML(){return new Error("Legacy shared store found at .red/tmp/red-skills.rdb. Run `rsp setup` to migrate it to .red/state/red-skills.rdb before using rsp, memory, or brain.")}function Ow(e){return Yt(Rw(e),"waits")}function Aw(e){let t=e.overrideEnvVars??Od;for(let n of t){let s=e.env[n];if(s)return LL(s)?s:xd(e.startDir,s)}let r=xd(e.startDir);for(;;){if(e.exists(Yt(r,Ew)))return r;let n=Yt(r,".."),s=xd(n);if(s===r)break;r=s}return e.startDir}var Ew,GL,DL,Od,vw,Tw,et=_(()=>{Ew=".red",GL="MEMORY_ROOT",DL="RED_BRAIN_ROOT",Od=[GL,DL];vw=".red/state/red-skills.rdb";Tw=".red/tmp/red-skills.rdb"});function ge(e){return M(e)}var BL,jL,x3,Qt=_(()=>{J();et();BL=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],jL=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/castle/history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.toonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.toonl",toonPath:".red/tmp/supervisors/default/supervisor.log.toonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.toon",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/state/statusline/statusline-cache.toon",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/state/statusline/statusline-repo-cache.toon",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.toon",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.toon",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.toon",kind:"toon"}],x3=[...BL,...jL]});function io(e){let{values:t,rest:r}=Xr(e,{query:Cw.query},Pw);return{argv:r,query:t.query?.trim()||void 0}}function Iw(e){let{values:t,rest:r}=Xr(e,Cw,Pw);return{argv:r,query:t.query?.trim()||void 0,full:t.full===!0}}function qL(e,t){if(!t)return!0;let r=Ad(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(n=>r.includes(n))}function Le(e,t){return t?e.filter(r=>qL(r,t)):[...e]}function Xt(e,t){return Cd(e,t,{includeLegacyHelp:!0})}function Cd(e,t,r={}){let n=t.filter(Boolean);return n.length===0?e:{...e,...r.includeLegacyHelp?{help:n}:{},next_steps:n}}function Ad(e){return Array.isArray(e)?e.map(Ad).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(Ad).join(" "):String(e??"")}var Cw,Pw,ao=_(()=>{"use strict";Yu();Cw={query:{kind:"value",coerce:e=>e},full:{kind:"boolean"}},Pw={stopAtSeparator:!1}});var Aa={};se(Aa,{DEFAULT_RSP_MAX_OVERHEAD_MS:()=>ka,DEFAULT_RSP_MAX_SELF_STATE_BYTES:()=>Sa,DEFAULT_RSP_OVERHEAD_CEILING:()=>Zt,DEFAULT_RSP_OVERHEAD_CONSECUTIVE_BREACHES:()=>va,DEFAULT_RSP_OVERHEAD_COOLDOWN_MS:()=>Ta,DEFAULT_RSP_OVERHEAD_NET_LOSS_FLOOR_BYTES:()=>Ra,RSP_OVERHEAD_FAMILIES:()=>zL,RSP_OVERHEAD_LEDGER_FILE:()=>Dw,RSP_OVERHEAD_SCHEMA_VERSION:()=>Nw,classifyOverheadSample:()=>Ld,noteChildProcessMs:()=>Fw,noteSelfStateBytesRead:()=>lo,overheadCounters:()=>Fd,overheadFamilyDisabled:()=>YL,overheadHealth:()=>wr,overheadLedgerPath:()=>Gd,overheadMsOf:()=>$w,overheadTelemetryFields:()=>xa,readOverheadLedger:()=>co,readSelfStateFile:()=>Oa,readSelfStateFileSync:()=>ZL,recordOverheadSample:()=>Dd,resetOverheadCounters:()=>XL,resetOverheadLedger:()=>QL,startChildProcessTimer:()=>tt});import{existsSync as UL,mkdirSync as HL,readFileSync as Lw,renameSync as WL,writeFileSync as VL}from"node:fs";import{readFile as JL}from"node:fs/promises";import{dirname as KL,join as Gw}from"node:path";function $w(e){let t=e.wrapperMs-e.childMs;return Number.isFinite(t)?Math.max(0,Id(t)):0}function Ld(e,t=Zt){let r=$w(e),n=[];return r>t.maxOverheadMs&&n.push("wall-clock-ceiling"),e.selfStateBytesRead>t.maxSelfStateBytes&&n.push("self-state-byte-ceiling"),e.selfStateBytesRead>t.netLossFloorBytes&&e.selfStateBytesRead>e.bytesSaved&&n.push("overhead-exceeds-savings"),{overhead_ms:r,breached:n.length>0,reasons:n}}function xa(e,t=Zt){let r=Ld(e,t);return{wrapper_ms:Id(e.wrapperMs),overhead_ms:r.overhead_ms,child_ms:Id(Math.max(0,e.childMs)),self_state_bytes_read:Math.max(0,Math.trunc(e.selfStateBytesRead)),bytes_saved:Math.max(0,Math.trunc(e.bytesSaved)),overhead_breached:r.breached,overhead_breach_reasons:r.reasons.join(",")}}function Gd(e){return Gw(ce(e),Dw)}function co(e){try{let t=Lw(Gd(e),"utf8"),r=nG(t);if(sG(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]??rG(t.family,n),a=Md(i,n)?Mw(i):i,c=o.breached?a.consecutive_breaches+1:0,l={...a,family:t.family,invocations:a.invocations+1,breaches:a.breaches+(o.breached?1:0),consecutive_breaches:c,breached:o.breached,reasons:o.reasons,last_overhead_ms:o.overhead_ms,last_self_state_bytes_read:Math.max(0,Math.trunc(t.selfStateBytesRead)),last_bytes_saved:Math.max(0,Math.trunc(t.bytesSaved)),updated_at:new Date(n).toISOString()};return o.breached?c>=r.consecutiveBreaches&&(l.disabled=!0,l.disabled_at=new Date(n).toISOString(),l.disabled_until=new Date(n+r.cooldownMs).toISOString(),l.disabled_reason=eG(t.family,c,o,r)):(l.disabled=!1,l.disabled_at=null,l.disabled_until=null,l.disabled_reason=null),s.families[t.family]=l,Bw(e,s),l}function YL(e,t,r=Date.now()){let n=co(e).families[t];return!n?.disabled||Md(n,r)?null:n}function QL(e,t){let r=co(e);return t?delete r.families[t]:r.families={},Bw(e,r),r}function wr(e,t=Zt,r=Date.now()){let n=Object.values(co(e).families).map(a=>Md(a,r)?Mw(a):a).sort((a,c)=>a.family.localeCompare(c.family)),s=n.filter(a=>a.disabled),o=n.filter(a=>a.consecutive_breaches>0),i=s.length>0||o.length>0?"red":"green";return{schema_version:Nw,verdict:i,summary:tG(i,s,o),ceiling:t,breaching_families:o,disabled_families:s,families:n}}function lo(e){Number.isFinite(e)&&e>0&&(Nd+=e)}function Fw(e){Number.isFinite(e)&&e>0&&($d+=e)}function Fd(){return{selfStateBytesRead:Nd,childMs:$d}}function XL(){Nd=0,$d=0}function tt(){let e=process.hrtime.bigint(),t=!1;return()=>{t||(t=!0,Fw(Number(process.hrtime.bigint()-e)/1e6))}}async function Oa(e){let t=await JL(e,"utf8");return lo(Buffer.byteLength(t)),t}function ZL(e){let t=Lw(e,"utf8");return lo(Buffer.byteLength(t)),t}function eG(e,t,r,n){let s=r.reasons.map(o=>o==="wall-clock-ceiling"?`added ${r.overhead_ms}ms > ${n.maxOverheadMs}ms`:o==="self-state-byte-ceiling"?`self-state read > ${n.maxSelfStateBytes}B`:"self-state read exceeded bytes saved").join("; ");return`rsp ${e} exceeded its overhead ceiling on ${t} consecutive invocations (${s}); wrapper self-disabled, commands pass through raw`}function tG(e,t,r){if(e==="green")return"every wrapper family is inside its overhead ceiling";let n=[];return t.length>0&&n.push(`self-disabled: ${t.map(s=>`${s.family} (${s.reasons.join(",")||"ceiling"})`).join(", ")}`),r.length>0&&n.push(`breaching: ${r.map(s=>`${s.family} x${s.consecutive_breaches}`).join(", ")}`),n.join("; ")}function Md(e,t){if(!e.disabled||!e.disabled_until)return!1;let r=Date.parse(e.disabled_until);return Number.isFinite(r)&&r<=t}function Mw(e){return{...e,disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,consecutive_breaches:0,breached:!1,reasons:[]}}function rG(e,t){return{family:e,invocations:0,breaches:0,consecutive_breaches:0,breached:!1,reasons:[],disabled:!1,disabled_at:null,disabled_until:null,disabled_reason:null,last_overhead_ms:0,last_self_state_bytes_read:0,last_bytes_saved:0,updated_at:new Date(t).toISOString()}}function Bw(e,t){try{let r=Gd(e);if(!UL(Gw(e,".red")))return;HL(KL(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`;VL(n,`${M(t)}
|
|
29
29
|
`,{encoding:"utf8",mode:384}),WL(n,r)}catch{}}function nG(e){try{return JSON.parse(e)}catch{return z(e)}}function sG(e){return!Pd(e)||e.version!==1||!Pd(e.families)?!1:Object.values(e.families).every(oG)}function oG(e){return Pd(e)&&typeof e.family=="string"&&typeof e.consecutive_breaches=="number"&&typeof e.disabled=="boolean"}function Pd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Id(e){return Number.isFinite(e)?Math.round(e*1e3)/1e3:0}var Dw,Nw,ka,Sa,Ra,va,Ta,zL,Zt,Nd,$d,we=_(()=>{"use strict";et();J();Dw="overhead-budget.toon",Nw="red.rsp.overhead.v1",ka=250,Sa=1024*1024,Ra=64*1024,va=3,Ta=6*60*60*1e3,zL=["git","gh","gh-api-json","vitest","cargo","cat","exec","proxy"],Zt={maxOverheadMs:ka,maxSelfStateBytes:Sa,netLossFloorBytes:Ra,consecutiveBreaches:va,cooldownMs:Ta};Nd=0,$d=0});function Uw(e){return e.trimStart().startsWith("{")?"json":"toon"}function jd(e){let t=0;for(;e[t]===`
|
|
30
30
|
`||e[t]==="\r";)t+=1;let r=e.slice(t);if(r==="")return null;let n=Uw(r);if(n==="json"){let o=r.indexOf(`
|
|
31
31
|
`);return o<0?null:{frame:r.slice(0,o),dialect:n,rest:r.slice(o+1)}}let s=r.indexOf(`
|
package/dist/rsp.bundle.min.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
3
|
import{spawn as L}from"node:child_process";import{isUtf8 as te}from"node:buffer";async function _(e,n=t=>t){let t=[],r=[];return e.stdout?.on("data",i=>t.push(Buffer.from(i))),e.stderr?.on("data",i=>r.push(Buffer.from(i))),await new Promise(i=>{let c=!1,o=async(a,s)=>{if(c)return;c=!0;let l=Buffer.concat(t),u=l;if(l.length>0&&te(l))try{u=await n(l)}catch{}if(process.stdout.write(u),process.stderr.write(Buffer.concat(r)),s){process.kill(process.pid,s),i(128);return}i(a??0)};e.once("error",a=>{r.push(Buffer.from(`${a instanceof Error?a.message:String(a)}
|
|
4
|
-
`)),o(127,null)}),e.once("close",(a,s)=>void o(a,s))})}var re=new Set(["dashboard","stats","gains","show","git","gh","vitest","cargo","cat","exec","wait","doctor","status","sweep","setup","mcp","shell-init","server","warm-resident","gh-api-json","hook"]);function R(e){let n=e[0];if(n==="--full"||n==="--brief"||n==="--terse")return e[1]!=="--"||!e[2]?null:{kind:"argv",argv:[...e.slice(2)],level:n.slice(2)};if(!n||n.startsWith("-"))return n!=="--"||!e[1]?null:{kind:"argv",argv:[...e.slice(1)],level:"automatic"};if(n==="proxy"){if(process.env.RSP_PROXY_FAIL_INTERNAL==="1")return null;let t=e.indexOf("--"),r=t>=0?e.slice(1,t):[];if(r.some(a=>a!=="--full"&&a!=="--brief"&&a!=="--terse"))return null;let i=t>=0?e.slice(t+1):e.slice(1);if(i.length!==1||!i[0]?.trim())return null;let c=i[0];if(ie(c))return null;let o=r.includes("--terse")?"terse":r.includes("--brief")?"brief":r.includes("--full")?"full":"automatic";return{kind:"shell",commandLine:c,level:o}}return re.has(n)?null:{kind:"argv",argv:[...e],level:"automatic"}}async function I(e,n){let t=e.kind==="argv"?L(e.argv[0],e.argv.slice(1),{stdio:["inherit","pipe","pipe"]}):L(e.commandLine,{shell:!0,stdio:["inherit","pipe","pipe"]});return await _(t,n)}function ie(e){return/(?:^|&&|\|\||[;|])\s*(?:(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+|env)\s+)*(?:git\s+(?:status|log|diff|show|blame|branch\s+-av)(?:\s|$)|gh\s+(?:pr|issue|run)\s+(?:list|view)(?:\s|$)|vitest(?:\s|$)|cargo\s+test(?:\s|$)|(?:cat|head|tail)\s+)/.test(e)}function F(e){let n={app:e,version:oe(x("__RED_BUILD_VERSION__",()=>"4.1.
|
|
4
|
+
`)),o(127,null)}),e.once("close",(a,s)=>void o(a,s))})}var re=new Set(["dashboard","stats","gains","show","git","gh","vitest","cargo","cat","exec","wait","doctor","status","sweep","setup","mcp","shell-init","server","warm-resident","gh-api-json","hook"]);function R(e){let n=e[0];if(n==="--full"||n==="--brief"||n==="--terse")return e[1]!=="--"||!e[2]?null:{kind:"argv",argv:[...e.slice(2)],level:n.slice(2)};if(!n||n.startsWith("-"))return n!=="--"||!e[1]?null:{kind:"argv",argv:[...e.slice(1)],level:"automatic"};if(n==="proxy"){if(process.env.RSP_PROXY_FAIL_INTERNAL==="1")return null;let t=e.indexOf("--"),r=t>=0?e.slice(1,t):[];if(r.some(a=>a!=="--full"&&a!=="--brief"&&a!=="--terse"))return null;let i=t>=0?e.slice(t+1):e.slice(1);if(i.length!==1||!i[0]?.trim())return null;let c=i[0];if(ie(c))return null;let o=r.includes("--terse")?"terse":r.includes("--brief")?"brief":r.includes("--full")?"full":"automatic";return{kind:"shell",commandLine:c,level:o}}return re.has(n)?null:{kind:"argv",argv:[...e],level:"automatic"}}async function I(e,n){let t=e.kind==="argv"?L(e.argv[0],e.argv.slice(1),{stdio:["inherit","pipe","pipe"]}):L(e.commandLine,{shell:!0,stdio:["inherit","pipe","pipe"]});return await _(t,n)}function ie(e){return/(?:^|&&|\|\||[;|])\s*(?:(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+|env)\s+)*(?:git\s+(?:status|log|diff|show|blame|branch\s+-av)(?:\s|$)|gh\s+(?:pr|issue|run)\s+(?:list|view)(?:\s|$)|vitest(?:\s|$)|cargo\s+test(?:\s|$)|(?:cat|head|tail)\s+)/.test(e)}function F(e){let n={app:e,version:oe(x("__RED_BUILD_VERSION__",()=>"4.1.14")??"0.0.0-dev"),gitSha:x("__RED_BUILD_GIT_SHA__",()=>"a2c2d45c9f89f44932e381ec4b99bf2aa5d25445")??"unknown",buildTime:x("__RED_BUILD_TIME__",()=>"2026-08-21T02:01:02-03:00")??"unknown",bundleAsset:x("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},t=x("__REDDB_SDK_VERSION__",()=>"1.23.1"),r=x("__REDDB_BINARY_TAG__",()=>"v1.23.1");return t&&(n.reddbSdkVersion=t),r&&(n.reddbBinaryTag=r),n}function oe(e){return e.startsWith("v")?e.slice(1):e}function N(e){return`${e.app} ${e.version} ${e.gitSha}`}function x(e,n){try{let t=n();return typeof t=="string"&&t.length>0?t:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var D={"=":"data",":=":{to:"data",typed:!0},":":"meta"},se=/^[a-z][a-z0-9+.-]*:\/\//i;function ce(e,n){return typeof n=="string"?{separator:e,to:n,typed:!1,prefix:!1}:{separator:e,to:n.to,typed:n.typed??!1,prefix:n.prefix??!1}}function ae(e=D){return Object.entries(e).map(([n,t])=>ce(n,t)).sort((n,t)=>t.separator.length-n.separator.length)}function ue(e){return/^-\d+(\.\d+)?$/.test(e)}function O(e){return!(!e||e.startsWith("-")&&!ue(e))}function k(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e}function P(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{}let n=Number(e);return!Number.isNaN(n)&&Number.isFinite(n)&&e.trim()!==""?n:e.includes(",")?e.split(",").map(t=>P(t.trim())):e}function w(e,n){switch(n){case"boolean":return le(e);case"number":return fe(e);case"array":return e.split(",").map(t=>k(t.trim()));case"string":default:return e}}function le(e){let n=e.toLowerCase().trim();return n==="true"||n==="yes"||n==="1"||n==="on"}function fe(e){if(e.trim()==="")throw new TypeError(`Cannot convert "${e}" to number`);let n=Number(e);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${e}" to number`);return n}function b(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function de(e,n={}){return e.map(t=>{let r=n[t.type];return r?r(t.value):t.value}).join("")}function d(e,n){return{type:e,value:n}}function pe(e){let n=[],t=he(e);if(n.push(d("section-header","Usage:"),d("text"," "),d("usage-text",t),d("newline",`
|
|
5
5
|
`),d("newline",`
|
|
6
6
|
`)),e.positional&&e.positional.length>0){n.push(d("section-header","Arguments:"),d("newline",`
|
|
7
7
|
`));for(let r of e.positional)if(r.description){let i=r.variadic?`${r.name}...`:r.name;n.push(d("indent"," "),d("positional-name",`<${i}>`)),r.required||n.push(d("positional-optional"," (optional)")),n.push(d("newline",`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reddb-io/red-skills",
|
|
3
|
-
"version": "4.1.
|
|
3
|
+
"version": "4.1.14",
|
|
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",
|