@reddb-io/red-skills 2.33.5 → 2.33.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -74,7 +74,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
74
74
  `:`[${n[c]}\r
75
75
  ]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function uc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=cc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ac(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function C_(t,e){if(e.mapStrategy==="record")return uc(t,e);let r=Q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Be(e),n=Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function O_(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function N_(t){return t.target==="openAi"?void 0:{not:Be({...t,currentPath:[...t.currentPath,"not"]})}}function j_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var is={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function M_(t,e){if(e.target==="openApi3")return D_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in is&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=is[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return D_(t,e)}var D_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Q(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function A_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:is[t.innerType._def.typeName],nullable:!0}:{type:[is[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function q_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",gf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?he(r,"minimum",n.value,n.message,e):he(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),he(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?he(r,"maximum",n.value,n.message,e):he(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),he(r,"maximum",n.value,n.message,e));break;case"multipleOf":he(r,"multipleOf",n.value,n.message,e);break}return r}function Z_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let l=Mz(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let f=Q(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});f!==void 0&&(n.properties[a]=f,l||o.push(a))}o.length&&(n.required=o);let s=Dz(t,e);return s!==void 0&&(n.additionalProperties=s),n}function Dz(t,e){if(t.catchall._def.typeName!=="ZodNever")return Q(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mz(t){try{return t.isOptional()}catch{return!0}}var L_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Q(t.innerType._def,e);let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Be(e)},r]}:Be(e)};var F_=(t,e)=>{if(e.pipeStrategy==="input")return Q(t.in._def,e);if(e.pipeStrategy==="output")return Q(t.out._def,e);let r=Q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function U_(t,e){return Q(t.type._def,e)}function V_(t,e){let n={type:"array",uniqueItems:!0,items:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&he(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&he(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function H_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function B_(t){return{not:Be(t)}}function W_(t){return Be(t)}var J_=(t,e)=>Q(t.innerType._def,e);var K_=(t,e,r)=>{switch(e){case D.ZodString:return cc(t,r);case D.ZodNumber:return q_(t,r);case D.ZodObject:return Z_(t,r);case D.ZodBigInt:return $_(t,r);case D.ZodBoolean:return k_();case D.ZodDate:return yf(t,r);case D.ZodUndefined:return B_(r);case D.ZodNull:return j_(r);case D.ZodArray:return x_(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return M_(t,r);case D.ZodIntersection:return z_(t,r);case D.ZodTuple:return H_(t,r);case D.ZodRecord:return uc(t,r);case D.ZodLiteral:return E_(t,r);case D.ZodEnum:return R_(t);case D.ZodNativeEnum:return O_(t);case D.ZodNullable:return A_(t,r);case D.ZodOptional:return L_(t,r);case D.ZodMap:return C_(t,r);case D.ZodSet:return V_(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return U_(t,r);case D.ZodNaN:case D.ZodNever:return N_(r);case D.ZodEffects:return P_(t,r);case D.ZodAny:return Be(r);case D.ZodUnknown:return W_(r);case D.ZodDefault:return T_(t,r);case D.ZodBranded:return ac(t,r);case D.ZodReadonly:return J_(t,r);case D.ZodCatch:return S_(t,r);case D.ZodPipeline:return F_(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}};function Q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==v_)return a}if(n&&!r){let a=Az(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=K_(t,t.typeName,e),s=typeof i=="function"?Q(i(),e):i;if(s&&qz(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var Az=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Be(e)):e.$refStrategy==="seen"?Be(e):void 0}},qz=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var bf=(t,e)=>{let r=w_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,f])=>({...c,[l]:Q(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Be(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Be(r),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Zz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function wf(t,e){return Kt(t)?Fd(t,{target:Zz(e?.target),io:e?.pipeStrategy??"input"}):bf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function xf(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $f(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var Lz=6e4,lc=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ua,r=>{this._oncancel(r)}),this.setNotificationHandler(Ha,r=>{this._onprogress(r)}),this.setRequestHandler(Va,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ba,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ja,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,f=this._requestResolvers.get(l);if(f)if(this._requestResolvers.delete(l),a.type==="response")f(c);else{let p=c,w=new B(p.error.code,p.error.message,p.error.data);f(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new B(G.InvalidParams,`Task not found: ${i}`);if(!cn(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(cn(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[an]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Ka,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new B(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Xa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(cn(o.status))throw new B(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new B(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof B?o:new B(G.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Gi(i)||a_(i)?this._onresponse(i):tf(i)?this._onrequest(i,s):s_(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=B.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[an]?.taskId;if(n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(f).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=n_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};i&&(p.relatedTask={taskId:i}),await this.notification(f,p)},sendRequest:async(f,p,w)=>{if(s.signal.aborted)throw new B(G.ConnectionClosed,"Request was cancelled");let b={...w,relatedRequestId:e.id};i&&!b.relatedTask&&(b.relatedTask={taskId:i});let g=b.relatedTask?.taskId??i;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(f,p,b)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async f=>{if(s.signal.aborted)return;let p={result:f,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async f=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:G.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Gi(e))n(e);else{let s=new B(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Gi(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Gi(e))o(e);else{let s=B.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}return}let i;try{let s=await this.request(e,jo,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new B(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},cn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new B(G.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(G.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,f)=>{let p=O=>{f(O)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(O){p(O);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(b.params={...b.params,task:a}),c&&(b.params={...b.params,_meta:{...b.params?._meta||{},[an]:c}});let g=O=>{this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(O)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`)));let z=O instanceof B?O:new B(G.RequestTimeout,String(O));f(z)};this._responseHandlers.set(w,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return f(O);try{let z=on(r,O.result);z.success?l(z.data):f(z.error)}catch(z){f(z)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let x=n?.timeout??Lz,S=()=>g(B.fromError(G.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(w,x,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let N=c?.taskId;if(N){let O=z=>{let Z=this._responseHandlers.get(w);Z?Z(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,O),this._enqueueTaskMessage(N,{type:"request",message:b,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),f(z)})}else this._transport.send(b,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(O=>{this._cleanupTimeout(w),f(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Wa,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ga,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},l_,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[an]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[an]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[an]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=xf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=$f(e,o);return Promise.resolve(r(s,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=xf(e);this._notificationHandlers.set(n,o=>{let i=$f(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&tf(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new B(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new B(G.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new B(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=ts.parse({method:"notifications/tasks/status",params:a});await this.notification(c),cn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new B(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(cn(a.status))throw new B(G.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=ts.parse({method:"notifications/tasks/status",params:c});await this.notification(l),cn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function G_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X_(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let s=r[o];G_(s)&&G_(i)?r[o]={...s,...i}:r[o]=i}return r}var Fw=la(um(),1),Uw=la(Lw(),1);function Vj(){let t=new Fw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Uw.default)(t),t}var Hc=class{constructor(e){this._ajv=e??Vj()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Bc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(f=>f.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(f=>f.type==="tool_use");if(s){if(i.some(f=>f.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let f=new Set(c.filter(w=>w.type==="tool_use").map(w=>w.id)),p=new Set(i.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(f.size!==p.size||![...f].every(w=>p.has(w)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},os,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},Ao,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Vw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Hw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Wc=class extends lc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ns.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Hc,this.setRequestHandler(of,n=>this._oninitialize(n)),this.setNotificationHandler(sf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(pf,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=ns.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Bc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=X_(this._capabilities,e)}setRequestHandler(e,r){let o=sn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Kt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,l)=>{let f=on(Mo,c);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new B(G.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:p}=f.data,w=await Promise.resolve(r(c,l));if(p.task){let g=on(jo,w);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new B(G.InvalidParams,`Invalid task creation result: ${x}`)}return g.data}let b=on(oc,w);if(!b.success){let g=b.error instanceof Error?b.error.message:String(b.error);throw new B(G.InvalidParams,`Invalid tools/call result: ${g}`)}return b.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Hw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Vw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:e_.includes(r)?r:Qd,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Fa)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(l=>l.type==="tool_use");if(i){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==f.size||![...l].every(p=>f.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},mf,r):this.request({method:"sampling/createMessage",params:e},os,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Ao,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Ao,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new B(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof B?s:new B(G.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},hf,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Ww=Symbol.for("mcp.completable");function ym(t){return!!t&&typeof t=="object"&&Ww in t}function Jw(t){return t[Ww]?.complete}var Bw;(function(t){t.Completable="McpCompletable"})(Bw||(Bw={}));var Hj=/^[A-Za-z0-9._-]{1,128}$/;function Bj(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Hj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Wj(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function _m(t){let e=Bj(t);return Wj(t,e.warnings),e.isValid}var Jc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Kc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Wc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Jc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(nc)),this.server.assertCanSetRequestHandler(yn(Mo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(nc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Oo(r.inputSchema);return o?wf(o,{strictUnions:!0,pipeStrategy:"input"}):Jj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Oo(r.outputSchema);o&&(n.outputSchema=wf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Mo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new B(G.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new B(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof B&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let i=Oo(e.inputSchema)??e.inputSchema,s=await Na(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=ja(a);throw new B(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Oo(e.outputSchema),i=await Na(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ja(s);throw new B(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(e.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,f=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(w=>setTimeout(w,f));let p=await n.taskStore.getTask(c);if(!p)throw new B(G.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(yn(ic)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ic,async e=>{switch(e.params.ref.type){case"ref/prompt":return g_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return y_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return js;let i=sn(n.argsSchema)?.[e.params.argument.name];if(!ym(i))return js;let s=Jw(i);if(!s)return js;let a=await s(e.params.argument.value,e.params.context);return Gw(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return js;throw new B(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return js;let i=await o(e.params.argument.value,e.params.context);return Gw(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(Ya)),this.server.assertCanSetRequestHandler(yn(Qa)),this.server.assertCanSetRequestHandler(yn(ec)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ya,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Qa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ec,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(G.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new B(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(tc)),this.server.assertCanSetRequestHandler(yn(rc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(tc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Kj(r.argsSchema):void 0}))})),this.server.setRequestHandler(rc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Oo(n.argsSchema),i=await Na(o,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=ja(c);throw new B(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,n,o,i){let s={name:e,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(e,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Qn(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Qn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,o&&Object.values(o).some(c=>{let l=c instanceof zt?c._def?.innerType:c;return ym(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,r,n,o,i,s,a,c,l){_m(e);let f={title:r,description:n,inputSchema:Kw(o),outputSchema:Kw(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>f.update({enabled:!1}),enable:()=>f.update({enabled:!0}),remove:()=>f.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&_m(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=f)),typeof p.title<"u"&&(f.title=p.title),typeof p.description<"u"&&(f.description=p.description),typeof p.paramsSchema<"u"&&(f.inputSchema=Qn(p.paramsSchema)),typeof p.outputSchema<"u"&&(f.outputSchema=Qn(p.outputSchema)),typeof p.callback<"u"&&(f.handler=p.callback),typeof p.annotations<"u"&&(f.annotations=p.annotations),typeof p._meta<"u"&&(f._meta=p._meta),typeof p.enabled<"u"&&(f.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=f,this.setToolRequestHandlers(),this.sendToolListChanged(),f}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(vm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!vm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,i,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(e,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(e,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Jj={type:"object",properties:{}};function Xw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Yw(t){return"_def"in t||"_zod"in t||Xw(t)}function vm(t){return typeof t!="object"||t===null||Yw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Xw)}function Kw(t){if(t){if(vm(t))return Qn(t);if(!Yw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Kj(t){let e=sn(t);return e?Object.entries(e).map(([r,n])=>{let o=Ey(n),i=Iy(n);return{name:r,description:o,required:!i}}):[]}function yn(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Gw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var js={completion:{values:[],hasMore:!1}};import ex from"node:process";var Gc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
76
76
  `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Gj(r)}clear(){this._buffer=void 0}};function Gj(t){return c_.parse(JSON.parse(t))}function Qw(t){return JSON.stringify(t)+`
77
- `}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.33.5")??"0.0.0-dev"),gitSha:ni("__RED_BUILD_GIT_SHA__",()=>"6ef5daf4fc41cc2b6f117cbb366b92f53caa8594")??"unknown",buildTime:ni("__RED_BUILD_TIME__",()=>"2026-07-12T15:21:43-03:00")??"unknown",bundleAsset:ni("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=ni("__REDDB_SDK_VERSION__",()=>""),n=ni("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function Xj(t){return t.startsWith("v")?t.slice(1):t}function rx(t){return`${t.app} ${t.version} ${t.gitSha}`}function ni(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var bm={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function nx(){let t=process.env.CODE_NAV_SERVERS;if(!t)return bm;try{let e=JSON.parse(t),r={...bm};for(let[n,o]of Object.entries(e))r[n]={...r[n]??{},...o};return r}catch(e){return process.stderr.write(`code-nav: failed to parse CODE_NAV_SERVERS, using defaults: ${String(e)}
77
+ `}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.33.7")??"0.0.0-dev"),gitSha:ni("__RED_BUILD_GIT_SHA__",()=>"1df8f1f70e01908504ddf08c07d85ae00a44090a")??"unknown",buildTime:ni("__RED_BUILD_TIME__",()=>"2026-07-12T16:04:46-03:00")??"unknown",bundleAsset:ni("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=ni("__REDDB_SDK_VERSION__",()=>""),n=ni("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function Xj(t){return t.startsWith("v")?t.slice(1):t}function rx(t){return`${t.app} ${t.version} ${t.gitSha}`}function ni(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var bm={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function nx(){let t=process.env.CODE_NAV_SERVERS;if(!t)return bm;try{let e=JSON.parse(t),r={...bm};for(let[n,o]of Object.entries(e))r[n]={...r[n]??{},...o};return r}catch(e){return process.stderr.write(`code-nav: failed to parse CODE_NAV_SERVERS, using defaults: ${String(e)}
78
78
  `),bm}}function ox(t){let e=new Map;for(let[r,n]of Object.entries(t))for(let o of n.extensions)e.set(o,r);return e}var $i=la(jk(),1),xt=la(Jh(),1);import{spawn as t1}from"node:child_process";import{readFile as r1}from"node:fs/promises";import{pathToFileURL as Dk,fileURLToPath as n1}from"node:url";import{resolve as o1}from"node:path";var Hs=class{constructor(e,r){this.spec=e;this.rootPath=r}spec;rootPath;proc;conn;ready;openDocs=new Set;async ensureStarted(){return this.ready?this.ready:(this.ready=this.start(),this.ready)}async start(){let e=t1(this.spec.command,this.spec.args,{cwd:this.rootPath,stdio:["pipe","pipe","pipe"]});this.proc=e,await new Promise((i,s)=>{e.once("spawn",()=>i()),e.once("error",a=>s(new Error(`failed to spawn '${this.spec.command}': ${a.message}`)))}),e.stderr.on("data",i=>{process.stderr.write(`[${this.spec.command}] ${i.toString()}`)}),e.once("exit",()=>{try{this.conn?.dispose()}catch{}});let r=(0,$i.createProtocolConnection)(new $i.StreamMessageReader(e.stdout),new $i.StreamMessageWriter(e.stdin));this.conn=r,r.listen();let n=Dk(this.rootPath).toString(),o={processId:process.pid,rootUri:n,workspaceFolders:[{uri:n,name:"workspace"}],capabilities:{textDocument:{definition:{linkSupport:!0},references:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},hover:{contentFormat:["markdown","plaintext"]}},workspace:{symbol:{}}}};await r.sendRequest(xt.InitializeRequest.type,o),await r.sendNotification(xt.InitializedNotification.type,{})}async ensureOpen(e){let r=o1(this.rootPath,e),n=Dk(r).toString();if(this.openDocs.has(n))return n;let o=await r1(r,"utf8");return await this.conn.sendNotification(xt.DidOpenTextDocumentNotification.type,{textDocument:{uri:n,languageId:this.spec.languageId,version:1,text:o}}),this.openDocs.add(n),n}async definition(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e),i=await this.conn.sendRequest(xt.DefinitionRequest.type,{textDocument:{uri:o},position:{line:r,character:n}});return i1(i)}async references(e,r,n,o){await this.ensureStarted();let i=await this.ensureOpen(e);return await this.conn.sendRequest(xt.ReferencesRequest.type,{textDocument:{uri:i},position:{line:r,character:n},context:{includeDeclaration:o}})??[]}async documentSymbols(e){await this.ensureStarted();let r=await this.ensureOpen(e);return await this.conn.sendRequest(xt.DocumentSymbolRequest.type,{textDocument:{uri:r}})??[]}async hover(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e);return this.conn.sendRequest(xt.HoverRequest.type,{textDocument:{uri:o},position:{line:r,character:n}})}async workspaceSymbols(e){return await this.ensureStarted(),await this.conn.sendRequest(xt.WorkspaceSymbolRequest.type,{query:e})??[]}dispose(){try{this.conn?.dispose()}catch{}this.proc?.kill()}};function i1(t){return t?(Array.isArray(t)?t:[t]).map(r=>"targetUri"in r?{uri:r.targetUri,range:r.targetSelectionRange}:r):[]}function Kh(t,e){try{let r=n1(t);return(r.startsWith(e)?r.slice(e.length).replace(/^[/\\]/,""):r)||r}catch{return t}}var Ws=process.env.CODE_NAV_ROOT??process.cwd(),Bs=nx(),Mk=ox(Bs),ki=new Map;function Au(t){let e=s1(t),r=Mk.get(e);if(!r)throw new Error(`no language server configured for '${e}'. Configured extensions: ${[...Mk.keys()].join(", ")||"(none)"}.`);let n=ki.get(r);return n||(n=new Hs(Bs[r],Ws),ki.set(r,n)),n}function a1(){for(let t of Object.keys(Bs))ki.has(t)||ki.set(t,new Hs(Bs[t],Ws));return[...ki.values()]}function Xh(t,e){return`${Kh(t,Ws)}:${e.start.line+1}:${e.start.character+1}`}var Gh=tx("code-nav"),Si=new Kc({name:"code-nav",version:Gh.version}),qu={file:tn.string().describe("Workspace-relative path to the source file."),line:tn.number().int().describe("Zero-based line number."),character:tn.number().int().describe("Zero-based character offset on the line.")};Si.registerTool("goto_definition",{title:"Go to definition",description:"Resolve the symbol at a file position to its definition(s). Returns file:line:column locations. Use this instead of grepping for a name.",inputSchema:qu},async({file:t,line:e,character:r})=>{let n=await Au(t).definition(t,e,r);return n.length===0?Cr("No definition found."):Cr(n.map(o=>Xh(o.uri,o.range)).join(`
79
79
  `))});Si.registerTool("find_references",{title:"Find references",description:"Find every reference to the symbol at a file position across the workspace. Semantic \u2014 matches the actual symbol, not text.",inputSchema:{...qu,includeDeclaration:tn.boolean().optional().describe("Include the declaration itself (default true).")}},async({file:t,line:e,character:r,includeDeclaration:n})=>{let o=await Au(t).references(t,e,r,n??!0);return o.length===0?Cr("No references found."):Cr(`${o.length} reference(s):
80
80
  `+o.map(i=>Xh(i.uri,i.range)).join(`
@@ -15,7 +15,7 @@ ${i}
15
15
  ${n}
16
16
 
17
17
  </details>
18
- `}var jY=h(()=>{"use strict"});var Ve,Ke,rt,Ea,HC,vg,WC,Fx,OR,Lye,Uye,NR,dM,PR,GY,$ye,iu,fM,Lx,Ux,Hye,sc,Rg,qY,zY,su,VY,MR,jC,YY,FR,Wye,jye,Gye,qye,zye,cn=h(()=>{"use strict";Ve="ready-for-agent",Ke="running",rt="ready-for-human",Ea="contested",HC="ready-for-review",vg="lane:go",WC="lane:scout",Fx="landing:manual",OR="needs-triage",Lye="needs-info",Uye="wontfix",NR="triage:summon",dM="type:spec",PR="priority:urgent",GY="priority:high",$ye="bug",iu="blocked:validation",fM="blocked:validation-infra",Lx="blocked:stalled",Ux="blocked:crashed",Hye="blocked:signal-killed",sc="blocked:dependency",Rg="blocked:spec",qY="blocked:quota",zY="blocked:runner-transient",su="blocked:merge-conflict",VY="blocked:ci",MR="blocked:policy",jC="blocked:infra",YY="blocked:trunk-diverged",FR="blocked:sensitive-path",Wye="blocked:main-red-untracked",jye="blocked:base-stale",Gye="blocked:budget",qye="type:scout",zye="runner-error"});function pM(e){switch(e){case"exhausted":return qY;case"runner-transient":return zY;case"merge-conflict":return su;case"ci-failed":case"ci-pending":return VY;case"blocked":return Rg;case"feedback-failed":return iu;case"feedback-failed-infra":return fM;case"no-sentinel":return Ux;case"signal-killed":return Hye;case"hook-aborted":return MR;case"stalled":return Lx;case"budget-exceeded":return Gye;case"trunk-diverged":return YY;case"sensitive-path":return FR;case"main-red-untracked":return Wye;case"base-stale":return jye;case"infra":return jC;case"done":case"claim-lost":case"review-requested":case"manual-landing":return null}}function Tl(e){switch(e){case"done":return"done";case"no-sentinel":case"signal-killed":return"no-sentinel";case"merge-conflict":return"merge-conflict";case"blocked":case"feedback-failed":case"feedback-failed-infra":case"ci-failed":case"ci-pending":case"hook-aborted":case"exhausted":case"runner-transient":case"claim-lost":case"stalled":case"budget-exceeded":case"trunk-diverged":case"sensitive-path":case"main-red-untracked":case"base-stale":case"infra":case"review-requested":case"manual-landing":return"blocked"}}function JY(e){switch(e){case"exhausted":return"quota";case"runner-transient":return"runner-transient";case"no-sentinel":case"signal-killed":return"crashed";case"hook-aborted":return"policy";case"merge-conflict":return"merge-conflict";case"feedback-failed-infra":return"validation-infra";case"ci-failed":case"ci-pending":case"blocked":case"feedback-failed":case"stalled":case"budget-exceeded":case"trunk-diverged":case"sensitive-path":case"main-red-untracked":case"base-stale":case"infra":case"done":case"claim-lost":case"review-requested":case"manual-landing":return null}}var KY=h(()=>{"use strict";cn()});function LR(e,t){let r=Fpt[e];if(!r)return null;let n=t[r.knob];if(n!==void 0){let o=Number(n);if(Number.isInteger(o)&&o>0)return o}return r.defaultCap}function Vye(e,t,r){let n=LR(e,r);return n===null?"escalate":t<n?"retry":"escalate"}var Fpt,ZY=h(()=>{"use strict";Fpt={"merge-conflict":{knob:"RED_AFK_RETRY_MERGE",defaultCap:3},crashed:{knob:"RED_AFK_RETRY_CRASH",defaultCap:1},quota:{knob:"RED_AFK_RETRY_QUOTA",defaultCap:3},"runner-transient":{knob:"RED_AFK_RETRY_RUNNER_TRANSIENT",defaultCap:3},policy:{knob:"RED_AFK_RETRY_POLICY",defaultCap:1},stalled:{knob:"RED_AFK_RETRY_STALLED",defaultCap:3},"validation-infra":{knob:"RED_AFK_RETRY_VALIDATION_INFRA",defaultCap:2},drift:{knob:"RED_AFK_RETRY_DRIFT",defaultCap:2}}});function Lpt(e){return e==="stalled"?"stalled":JY(e)}function tf(e,t,r,n={}){let o=pM(e),i=Tl(e),s=n.stalledRecoverable===!1?JY(e):Lpt(e),a=s===null?null:LR(s,r),c=s===null?"escalate":Vye(s,t,r);if(c==="retry")return{decision:c,removeLabels:[Ke],addLabels:[Ve],typedLabel:o,envelopeStatus:i,escalationComment:null,cap:a};let u=o!==null?[rt,o]:[rt],l=a!==null?`\u{1F916} /afk escalating to ready-for-human: ${o??`blocked:${s}`} retry budget exhausted (attempt ${t}/${a}).`:null;return{decision:c,removeLabels:[Ke],addLabels:u,typedLabel:o,envelopeStatus:i,escalationComment:l,cap:a}}var mM=h(()=>{"use strict";KY();ZY();cn()});function hM(e){return e.filter(t=>t.startsWith("blocked:"))}function $pt(e,t,r){let n=new Set(e);for(let o of t)n.delete(o);for(let o of r)n.add(o);return[...n]}function Yye(e){let t=e.includes(Ve),r=e.includes(Ke),n=e.includes(rt),o=e.includes(Fx),i=e.includes(Ea),s=hM(e),a=s.length>0;return s.length>1||i&&(!r||t||n||a||o)||(t||r)&&a||t&&r||o&&!n&&!t&&!r?"illegal":i?"contested":o&&n?"landing:manual":r?"claimed/active":t?"ready-for-agent":s[0]===sc?"blocked:dependency":s[0]===iu||s[0]===fM?"blocked:validation":"ready-for-human"}function Hpt(e){let t=hM(e);if(t.length>1)return`mixed blocked:* labels [${t.join(", ")}]`;if(e.includes(Ea)){if(!e.includes(Ke))return`${Ea} must ride ${Ke}`;if(e.includes(Ve)||e.includes(rt)||e.includes(Fx)||t.length>0)return`${Ea} cannot ride queued, human, manual-landing, or blocked state`}return(e.includes(Ve)||e.includes(Ke))&&t.length>0?`queued/active issue cannot also carry blocked:* label ${t[0]}`:e.includes(Ve)&&e.includes(Ke)?`issue cannot carry both ${Ve} and ${Ke}`:e.includes(Fx)&&!e.includes(rt)&&!e.includes(Ve)&&!e.includes(Ke)?`${Fx} must ride a queued, active, or human-parked issue`:null}function tm(e){let t=Yye(e.fromLabels),r=$pt(e.fromLabels,e.removeLabels,e.addLabels),n=Yye(r),o=Hpt(r);if(o!==null)throw new GC(e.edge,t,"illegal",o);if(!Upt.find(s=>s.edge===e.edge&&(s.from==="*"||s.from===t)&&s.to===n))throw new GC(e.edge,t,n,`no legal row for edge "${e.edge}" from ${t} to ${n}`);return r}var Upt,GC,gM=h(()=>{"use strict";cn();Upt=[{edge:"claim",from:"*",to:"claimed/active"},{edge:"contest",from:"claimed/active",to:"contested"},{edge:"contest-reclaimed",from:"contested",to:"claimed/active"},{edge:"contest-expired",from:"contested",to:"ready-for-agent"},{edge:"retry",from:"claimed/active",to:"ready-for-agent"},{edge:"dependency-unblocked",from:"blocked:dependency",to:"ready-for-agent"},{edge:"dependency-blocked",from:"ready-for-agent",to:"blocked:dependency"},{edge:"preflight-blocked",from:"*",to:"ready-for-human"},{edge:"validation-blocked",from:"claimed/active",to:"blocked:validation"},{edge:"human-blocked",from:"*",to:"ready-for-human"},{edge:"human-blocked",from:"*",to:"blocked:validation"},{edge:"human-delegable",from:"*",to:"ready-for-agent"},{edge:"manual-landing",from:"claimed/active",to:"landing:manual"},{edge:"close",from:"claimed/active",to:"closed"},{edge:"close",from:"landing:manual",to:"closed"},{edge:"requeue",from:"ready-for-human",to:"ready-for-agent"},{edge:"requeue",from:"blocked:validation",to:"ready-for-agent"},{edge:"requeue-mixed-blocked-refusal",from:"*",to:"illegal"}],GC=class extends Error{constructor(r,n,o,i){super(`illegal issue lifecycle transition "${r}": ${n} -> ${o}: ${i}`);this.edge=r;this.from=n;this.to=o;this.reason=i;this.name="IllegalIssueLifecycleTransitionError"}}});function UR(e,t){return Math.min(t.halfOpenBaseS*Math.pow(2,e),t.halfOpenCapS)}function Jye(e,t,r,n){return e<=0?!1:r-e>=UR(t,n)}var XY,Kye=h(()=>{"use strict";XY={halfOpenBaseS:60,halfOpenCapS:3600}});function exe(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001F]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function jpt(e){return e==="true"||e==="false"||e==="null"}function rm(e){if(e===null)return null;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return rm(t)}if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e=="bigint")return e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(rm);if(e instanceof Set)return Array.from(e).map(rm);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,r])=>[String(t),rm(r)]));if(Gpt(e)){let t={};for(let r in e)Object.hasOwn(e,r)&&(t[r]=rm(e[r]));return t}return null}function $x(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Bg(e){return Array.isArray(e)}function Dl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $R(e){return Object.keys(e).length===0}function Gpt(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function HR(e){return e.length===0||e.every(t=>$x(t))}function qpt(e){return e.length===0||e.every(t=>Bg(t))}function txe(e){return e.length===0||e.every(t=>Dl(t))}function Ypt(e){return/^[A-Z_][\w.]*$/i.test(e)}function Jpt(e){return/^[A-Z_]\w*$/i.test(e)}function Kpt(e,t=YC){return!(!e||e!==e.trim()||jpt(e)||Zpt(e)||e.includes(":")||e.includes('"')||e.includes("\\")||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith("-"))}function Zpt(e){return zpt.test(e)||Vpt.test(e)}function Xpt(e,t,r,n,o,i,s){if(n.keyFolding!=="safe"||!Dl(t))return;let{segments:a,tail:c,leafValue:u}=emt(e,t,s??n.flattenDepth);if(a.length<2||!a.every(f=>Jpt(f)))return;let l=tmt(a),d=i?`${i}.${l}`:l;if(!r.includes(l)&&!(o&&o.has(d)))return{foldedKey:l,remainder:c,leafValue:u,segmentCount:a.length}}function emt(e,t,r){let n=[e],o=t;for(;n.length<r&&Dl(o);){let i=Object.keys(o);if(i.length!==1)break;let s=i[0],a=o[s];n.push(s),o=a}return!Dl(o)||$R(o)?{segments:n,tail:void 0,leafValue:o}:{segments:n,tail:o,leafValue:o}}function tmt(e){return e.join(".")}function zC(e,t){return e===null?Wpt:typeof e=="boolean"||typeof e=="number"?String(e):rmt(e,t)}function rmt(e,t=YC){return Kpt(e,t)?e:`"${exe(e)}"`}function VC(e){return Ypt(e)?e:`"${exe(e)}"`}function rxe(e,t=YC){return e.map(r=>zC(r,t)).join(t)}function Hx(e,t){let r=t?.key,n=t?.fields,o=t?.delimiter??",",i="";if(r!=null&&(i+=VC(r)),i+=`[${e}${o!==YC?o:""}]`,n){let s=n.map(a=>VC(a));i+=`{${s.join(o)}}`}return i+=":",i}function*nmt(e,t,r){if($x(e)){let n=zC(e,t.delimiter);n!==""&&(yield n);return}Bg(e)?yield*eJ(void 0,e,r,t):Dl(e)&&(yield*qC(e,r,t))}function*qC(e,t,r,n,o,i){let s=Object.keys(e);t===0&&!n&&(n=new Set(s.filter(c=>c.includes("."))));let a=i??r.flattenDepth;for(let[c,u]of Object.entries(e))yield*omt(c,u,t,r,s,n,o,a)}function*omt(e,t,r,n,o,i,s,a){let c=s?`${s}.${e}`:e,u=a??n.flattenDepth;if(n.keyFolding==="safe"&&o){let d=Xpt(e,t,o,n,i,s,u);if(d){let{foldedKey:f,remainder:p,leafValue:m,segmentCount:g}=d,A=VC(f);if(p===void 0){if($x(m)){yield ac(r,`${A}: ${zC(m,n.delimiter)}`,n.indent);return}else if(Bg(m)){yield*eJ(f,m,r,n);return}else if(Dl(m)&&$R(m)){yield ac(r,`${A}:`,n.indent);return}}if(Dl(p)){yield ac(r,`${A}:`,n.indent);let E=u-g,y=s?`${s}.${f}`:f;yield*qC(p,r+1,n,i,y,E);return}}}let l=VC(e);$x(t)?yield ac(r,`${l}: ${zC(t,n.delimiter)}`,n.indent):Bg(t)?yield*eJ(e,t,r,n):Dl(t)&&(yield ac(r,`${l}:`,n.indent),$R(t)||(yield*qC(t,r+1,n,i,c,u)))}function*eJ(e,t,r,n){if(t.length===0){yield ac(r,e!=null?`${VC(e)}: []`:"[]",n.indent);return}if(HR(t)){yield ac(r,yM(t,n.delimiter,e),n.indent);return}if(qpt(t)&&t.every(o=>HR(o))){yield*imt(e,t,r,n);return}if(txe(t)){let o=nxe(t);o?yield*smt(e,t,o,r,n):yield*Zye(e,t,r,n);return}yield*Zye(e,t,r,n)}function*imt(e,t,r,n){yield ac(r,Hx(t.length,{key:e,delimiter:n.delimiter}),n.indent);for(let o of t)if(HR(o)){let i=yM(o,n.delimiter);yield rf(r+1,i,n.indent)}}function yM(e,t,r){let n=Hx(e.length,{key:r,delimiter:t}),o=rxe(e,t);return e.length===0?n:`${n} ${o}`}function*smt(e,t,r,n,o){yield ac(n,Hx(t.length,{key:e,fields:r,delimiter:o.delimiter}),o.indent),yield*oxe(t,r,n+1,o)}function nxe(e){if(e.length===0)return;let t=e[0],r=Object.keys(t);if(r.length!==0&&amt(e,r))return r}function amt(e,t){for(let r of e){if(Object.keys(r).length!==t.length)return!1;for(let n of t)if(!(n in r)||!$x(r[n]))return!1}return!0}function*oxe(e,t,r,n){for(let o of e)yield ac(r,rxe(t.map(i=>o[i]),n.delimiter),n.indent)}function*Zye(e,t,r,n){yield ac(r,Hx(t.length,{key:e,delimiter:n.delimiter}),n.indent);for(let o of t)yield*tJ(o,r+1,n)}function*cmt(e,t,r){if($R(e)){yield ac(t,"-",r.indent);return}let n=Object.entries(e),[o,i]=n[0],s=n.slice(1);if(Bg(i)&&txe(i)){let c=nxe(i);if(c){yield rf(t,Hx(i.length,{key:o,fields:c,delimiter:r.delimiter}),r.indent),yield*oxe(i,c,t+2,r),s.length>0&&(yield*qC(Object.fromEntries(s),t+1,r));return}}let a=VC(o);if($x(i))yield rf(t,`${a}: ${zC(i,r.delimiter)}`,r.indent);else if(Bg(i))if(i.length===0)yield rf(t,`${a}: []`,r.indent);else if(HR(i))yield rf(t,`${a}${yM(i,r.delimiter)}`,r.indent);else{yield rf(t,`${a}${Hx(i.length,{delimiter:r.delimiter})}`,r.indent);for(let c of i)yield*tJ(c,t+2,r)}else Dl(i)&&(yield rf(t,`${a}:`,r.indent),$R(i)||(yield*qC(i,t+2,r)));s.length>0&&(yield*qC(Object.fromEntries(s),t+1,r))}function*tJ(e,t,r){if($x(e))yield rf(t,zC(e,r.delimiter),r.indent);else if(Bg(e))if(HR(e))yield rf(t,yM(e,r.delimiter),r.indent);else{yield rf(t,Hx(e.length,{delimiter:r.delimiter}),r.indent);for(let n of e)yield*tJ(n,t+1,r)}else Dl(e)&&(yield*cmt(e,t,r))}function ac(e,t,r){return" ".repeat(r*e)+t}function rf(e,t,r){return ac(e,"- "+t,r)}function umt(e,t){let r=t("",e,[]);return r===void 0?AM(e,t,[]):AM(rm(r),t,[])}function AM(e,t,r){return Dl(e)?lmt(e,t,r):Bg(e)?dmt(e,t,r):e}function lmt(e,t,r){let n={};for(let[o,i]of Object.entries(e)){let s=[...r,o],a=t(o,i,s);a!==void 0&&(n[o]=AM(rm(a),t,s))}return n}function dmt(e,t,r){let n=[];for(let o=0;o<e.length;o++){let i=e[o],s=[...r,o],a=t(String(o),i,s);if(a===void 0)continue;let c=rm(a);n.push(AM(c,t,s))}return n}function Ns(e,t){return Array.from(ixe(e,t)).join(`
18
+ `}var jY=h(()=>{"use strict"});var Ve,Ke,rt,Ea,HC,vg,WC,Fx,OR,Lye,Uye,NR,dM,PR,GY,$ye,iu,fM,Lx,Ux,Hye,sc,Rg,qY,zY,su,VY,MR,jC,YY,FR,Wye,jye,Gye,qye,zye,cn=h(()=>{"use strict";Ve="ready-for-agent",Ke="running",rt="ready-for-human",Ea="contested",HC="ready-for-review",vg="lane:go",WC="lane:scout",Fx="landing:manual",OR="needs-triage",Lye="needs-info",Uye="wontfix",NR="triage:summon",dM="type:spec",PR="priority:urgent",GY="priority:high",$ye="bug",iu="blocked:validation",fM="blocked:validation-infra",Lx="blocked:stalled",Ux="blocked:crashed",Hye="blocked:signal-killed",sc="blocked:dependency",Rg="blocked:spec",qY="blocked:quota",zY="blocked:runner-transient",su="blocked:merge-conflict",VY="blocked:ci",MR="blocked:policy",jC="blocked:infra",YY="blocked:trunk-diverged",FR="blocked:sensitive-path",Wye="blocked:main-red-untracked",jye="blocked:base-stale",Gye="blocked:budget",qye="type:scout",zye="runner-error"});function pM(e){switch(e){case"exhausted":return qY;case"runner-transient":return zY;case"merge-conflict":return su;case"ci-failed":case"ci-pending":return VY;case"blocked":return Rg;case"feedback-failed":return iu;case"feedback-failed-infra":return fM;case"no-sentinel":return Ux;case"signal-killed":return Hye;case"hook-aborted":return MR;case"stalled":return Lx;case"budget-exceeded":return Gye;case"trunk-diverged":return YY;case"sensitive-path":return FR;case"main-red-untracked":return Wye;case"base-stale":return jye;case"infra":return jC;case"done":case"claim-lost":case"review-requested":case"manual-landing":return null}}function Tl(e){switch(e){case"done":return"done";case"no-sentinel":case"signal-killed":return"no-sentinel";case"merge-conflict":return"merge-conflict";case"blocked":case"feedback-failed":case"feedback-failed-infra":case"ci-failed":case"ci-pending":case"hook-aborted":case"exhausted":case"runner-transient":case"claim-lost":case"stalled":case"budget-exceeded":case"trunk-diverged":case"sensitive-path":case"main-red-untracked":case"base-stale":case"infra":case"review-requested":case"manual-landing":return"blocked"}}function JY(e){switch(e){case"exhausted":return"quota";case"runner-transient":return"runner-transient";case"no-sentinel":case"signal-killed":return"crashed";case"hook-aborted":return"policy";case"merge-conflict":return"merge-conflict";case"feedback-failed-infra":return"validation-infra";case"ci-failed":case"ci-pending":case"blocked":case"feedback-failed":case"stalled":case"budget-exceeded":case"trunk-diverged":case"sensitive-path":case"main-red-untracked":case"base-stale":case"infra":case"done":case"claim-lost":case"review-requested":case"manual-landing":return null}}var KY=h(()=>{"use strict";cn()});function LR(e,t){let r=Fpt[e];if(!r)return null;let n=t[r.knob];if(n!==void 0){let o=Number(n);if(Number.isInteger(o)&&o>0)return o}return r.defaultCap}function Vye(e,t,r){let n=LR(e,r);return n===null?"escalate":t<n?"retry":"escalate"}var Fpt,ZY=h(()=>{"use strict";Fpt={"merge-conflict":{knob:"RED_AFK_RETRY_MERGE",defaultCap:3},crashed:{knob:"RED_AFK_RETRY_CRASH",defaultCap:1},quota:{knob:"RED_AFK_RETRY_QUOTA",defaultCap:3},"runner-transient":{knob:"RED_AFK_RETRY_RUNNER_TRANSIENT",defaultCap:3},policy:{knob:"RED_AFK_RETRY_POLICY",defaultCap:1},stalled:{knob:"RED_AFK_RETRY_STALLED",defaultCap:3},"validation-infra":{knob:"RED_AFK_RETRY_VALIDATION_INFRA",defaultCap:2},drift:{knob:"RED_AFK_RETRY_DRIFT",defaultCap:2}}});function Lpt(e){return e==="stalled"?"stalled":JY(e)}function tf(e,t,r,n={}){let o=pM(e),i=Tl(e),s=n.stalledRecoverable===!1?JY(e):Lpt(e),a=s===null?null:LR(s,r),c=s===null?"escalate":Vye(s,t,r);if(c==="retry")return{decision:c,removeLabels:[Ke],addLabels:[Ve],typedLabel:o,envelopeStatus:i,escalationComment:null,cap:a};let u=o!==null?[rt,o]:[rt],l=a!==null?`\u{1F916} /afk escalating to ready-for-human: ${o??`blocked:${s}`} retry budget exhausted (attempt ${t}/${a}).`:null;return{decision:c,removeLabels:[Ke],addLabels:u,typedLabel:o,envelopeStatus:i,escalationComment:l,cap:a}}var mM=h(()=>{"use strict";KY();ZY();cn()});function hM(e){return e.filter(t=>t.startsWith("blocked:"))}function $pt(e,t,r){let n=new Set(e);for(let o of t)n.delete(o);for(let o of r)n.add(o);return[...n]}function Yye(e){let t=e.includes(Ve),r=e.includes(Ke),n=e.includes(rt),o=e.includes(Fx),i=e.includes(Ea),s=hM(e),a=s.length>0;return s.length>1||i&&(!r||t||n||a||o)||(t||r)&&a||t&&r||o&&!n&&!t&&!r&&!a?"illegal":i?"contested":r?"claimed/active":t?"ready-for-agent":s[0]===sc?"blocked:dependency":s[0]===iu||s[0]===fM?"blocked:validation":o&&n?"landing:manual":"ready-for-human"}function Hpt(e){let t=hM(e);if(t.length>1)return`mixed blocked:* labels [${t.join(", ")}]`;if(e.includes(Ea)){if(!e.includes(Ke))return`${Ea} must ride ${Ke}`;if(e.includes(Ve)||e.includes(rt)||e.includes(Fx)||t.length>0)return`${Ea} cannot ride queued, human, manual-landing, or blocked state`}return(e.includes(Ve)||e.includes(Ke))&&t.length>0?`queued/active issue cannot also carry blocked:* label ${t[0]}`:e.includes(Ve)&&e.includes(Ke)?`issue cannot carry both ${Ve} and ${Ke}`:e.includes(Fx)&&!e.includes(rt)&&!e.includes(Ve)&&!e.includes(Ke)&&t.length===0?`${Fx} must ride a queued, active, human-parked, or blocked issue`:null}function tm(e){let t=Yye(e.fromLabels),r=$pt(e.fromLabels,e.removeLabels,e.addLabels),n=Yye(r),o=Hpt(r);if(o!==null)throw new GC(e.edge,t,"illegal",o);if(!Upt.find(s=>s.edge===e.edge&&(s.from==="*"||s.from===t)&&s.to===n))throw new GC(e.edge,t,n,`no legal row for edge "${e.edge}" from ${t} to ${n}`);return r}var Upt,GC,gM=h(()=>{"use strict";cn();Upt=[{edge:"claim",from:"*",to:"claimed/active"},{edge:"contest",from:"claimed/active",to:"contested"},{edge:"contest-reclaimed",from:"contested",to:"claimed/active"},{edge:"contest-expired",from:"contested",to:"ready-for-agent"},{edge:"retry",from:"claimed/active",to:"ready-for-agent"},{edge:"dependency-unblocked",from:"blocked:dependency",to:"ready-for-agent"},{edge:"dependency-blocked",from:"ready-for-agent",to:"blocked:dependency"},{edge:"preflight-blocked",from:"*",to:"ready-for-human"},{edge:"validation-blocked",from:"claimed/active",to:"blocked:validation"},{edge:"human-blocked",from:"*",to:"ready-for-human"},{edge:"human-blocked",from:"*",to:"blocked:validation"},{edge:"human-delegable",from:"*",to:"ready-for-agent"},{edge:"manual-landing",from:"claimed/active",to:"landing:manual"},{edge:"close",from:"claimed/active",to:"closed"},{edge:"close",from:"landing:manual",to:"closed"},{edge:"requeue",from:"ready-for-human",to:"ready-for-agent"},{edge:"requeue",from:"blocked:validation",to:"ready-for-agent"},{edge:"requeue-mixed-blocked-refusal",from:"*",to:"illegal"}],GC=class extends Error{constructor(r,n,o,i){super(`illegal issue lifecycle transition "${r}": ${n} -> ${o}: ${i}`);this.edge=r;this.from=n;this.to=o;this.reason=i;this.name="IllegalIssueLifecycleTransitionError"}}});function UR(e,t){return Math.min(t.halfOpenBaseS*Math.pow(2,e),t.halfOpenCapS)}function Jye(e,t,r,n){return e<=0?!1:r-e>=UR(t,n)}var XY,Kye=h(()=>{"use strict";XY={halfOpenBaseS:60,halfOpenCapS:3600}});function exe(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001F]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function jpt(e){return e==="true"||e==="false"||e==="null"}function rm(e){if(e===null)return null;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return rm(t)}if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e=="bigint")return e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(rm);if(e instanceof Set)return Array.from(e).map(rm);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,r])=>[String(t),rm(r)]));if(Gpt(e)){let t={};for(let r in e)Object.hasOwn(e,r)&&(t[r]=rm(e[r]));return t}return null}function $x(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Bg(e){return Array.isArray(e)}function Dl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function $R(e){return Object.keys(e).length===0}function Gpt(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function HR(e){return e.length===0||e.every(t=>$x(t))}function qpt(e){return e.length===0||e.every(t=>Bg(t))}function txe(e){return e.length===0||e.every(t=>Dl(t))}function Ypt(e){return/^[A-Z_][\w.]*$/i.test(e)}function Jpt(e){return/^[A-Z_]\w*$/i.test(e)}function Kpt(e,t=YC){return!(!e||e!==e.trim()||jpt(e)||Zpt(e)||e.includes(":")||e.includes('"')||e.includes("\\")||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith("-"))}function Zpt(e){return zpt.test(e)||Vpt.test(e)}function Xpt(e,t,r,n,o,i,s){if(n.keyFolding!=="safe"||!Dl(t))return;let{segments:a,tail:c,leafValue:u}=emt(e,t,s??n.flattenDepth);if(a.length<2||!a.every(f=>Jpt(f)))return;let l=tmt(a),d=i?`${i}.${l}`:l;if(!r.includes(l)&&!(o&&o.has(d)))return{foldedKey:l,remainder:c,leafValue:u,segmentCount:a.length}}function emt(e,t,r){let n=[e],o=t;for(;n.length<r&&Dl(o);){let i=Object.keys(o);if(i.length!==1)break;let s=i[0],a=o[s];n.push(s),o=a}return!Dl(o)||$R(o)?{segments:n,tail:void 0,leafValue:o}:{segments:n,tail:o,leafValue:o}}function tmt(e){return e.join(".")}function zC(e,t){return e===null?Wpt:typeof e=="boolean"||typeof e=="number"?String(e):rmt(e,t)}function rmt(e,t=YC){return Kpt(e,t)?e:`"${exe(e)}"`}function VC(e){return Ypt(e)?e:`"${exe(e)}"`}function rxe(e,t=YC){return e.map(r=>zC(r,t)).join(t)}function Hx(e,t){let r=t?.key,n=t?.fields,o=t?.delimiter??",",i="";if(r!=null&&(i+=VC(r)),i+=`[${e}${o!==YC?o:""}]`,n){let s=n.map(a=>VC(a));i+=`{${s.join(o)}}`}return i+=":",i}function*nmt(e,t,r){if($x(e)){let n=zC(e,t.delimiter);n!==""&&(yield n);return}Bg(e)?yield*eJ(void 0,e,r,t):Dl(e)&&(yield*qC(e,r,t))}function*qC(e,t,r,n,o,i){let s=Object.keys(e);t===0&&!n&&(n=new Set(s.filter(c=>c.includes("."))));let a=i??r.flattenDepth;for(let[c,u]of Object.entries(e))yield*omt(c,u,t,r,s,n,o,a)}function*omt(e,t,r,n,o,i,s,a){let c=s?`${s}.${e}`:e,u=a??n.flattenDepth;if(n.keyFolding==="safe"&&o){let d=Xpt(e,t,o,n,i,s,u);if(d){let{foldedKey:f,remainder:p,leafValue:m,segmentCount:g}=d,A=VC(f);if(p===void 0){if($x(m)){yield ac(r,`${A}: ${zC(m,n.delimiter)}`,n.indent);return}else if(Bg(m)){yield*eJ(f,m,r,n);return}else if(Dl(m)&&$R(m)){yield ac(r,`${A}:`,n.indent);return}}if(Dl(p)){yield ac(r,`${A}:`,n.indent);let E=u-g,y=s?`${s}.${f}`:f;yield*qC(p,r+1,n,i,y,E);return}}}let l=VC(e);$x(t)?yield ac(r,`${l}: ${zC(t,n.delimiter)}`,n.indent):Bg(t)?yield*eJ(e,t,r,n):Dl(t)&&(yield ac(r,`${l}:`,n.indent),$R(t)||(yield*qC(t,r+1,n,i,c,u)))}function*eJ(e,t,r,n){if(t.length===0){yield ac(r,e!=null?`${VC(e)}: []`:"[]",n.indent);return}if(HR(t)){yield ac(r,yM(t,n.delimiter,e),n.indent);return}if(qpt(t)&&t.every(o=>HR(o))){yield*imt(e,t,r,n);return}if(txe(t)){let o=nxe(t);o?yield*smt(e,t,o,r,n):yield*Zye(e,t,r,n);return}yield*Zye(e,t,r,n)}function*imt(e,t,r,n){yield ac(r,Hx(t.length,{key:e,delimiter:n.delimiter}),n.indent);for(let o of t)if(HR(o)){let i=yM(o,n.delimiter);yield rf(r+1,i,n.indent)}}function yM(e,t,r){let n=Hx(e.length,{key:r,delimiter:t}),o=rxe(e,t);return e.length===0?n:`${n} ${o}`}function*smt(e,t,r,n,o){yield ac(n,Hx(t.length,{key:e,fields:r,delimiter:o.delimiter}),o.indent),yield*oxe(t,r,n+1,o)}function nxe(e){if(e.length===0)return;let t=e[0],r=Object.keys(t);if(r.length!==0&&amt(e,r))return r}function amt(e,t){for(let r of e){if(Object.keys(r).length!==t.length)return!1;for(let n of t)if(!(n in r)||!$x(r[n]))return!1}return!0}function*oxe(e,t,r,n){for(let o of e)yield ac(r,rxe(t.map(i=>o[i]),n.delimiter),n.indent)}function*Zye(e,t,r,n){yield ac(r,Hx(t.length,{key:e,delimiter:n.delimiter}),n.indent);for(let o of t)yield*tJ(o,r+1,n)}function*cmt(e,t,r){if($R(e)){yield ac(t,"-",r.indent);return}let n=Object.entries(e),[o,i]=n[0],s=n.slice(1);if(Bg(i)&&txe(i)){let c=nxe(i);if(c){yield rf(t,Hx(i.length,{key:o,fields:c,delimiter:r.delimiter}),r.indent),yield*oxe(i,c,t+2,r),s.length>0&&(yield*qC(Object.fromEntries(s),t+1,r));return}}let a=VC(o);if($x(i))yield rf(t,`${a}: ${zC(i,r.delimiter)}`,r.indent);else if(Bg(i))if(i.length===0)yield rf(t,`${a}: []`,r.indent);else if(HR(i))yield rf(t,`${a}${yM(i,r.delimiter)}`,r.indent);else{yield rf(t,`${a}${Hx(i.length,{delimiter:r.delimiter})}`,r.indent);for(let c of i)yield*tJ(c,t+2,r)}else Dl(i)&&(yield rf(t,`${a}:`,r.indent),$R(i)||(yield*qC(i,t+2,r)));s.length>0&&(yield*qC(Object.fromEntries(s),t+1,r))}function*tJ(e,t,r){if($x(e))yield rf(t,zC(e,r.delimiter),r.indent);else if(Bg(e))if(HR(e))yield rf(t,yM(e,r.delimiter),r.indent);else{yield rf(t,Hx(e.length,{delimiter:r.delimiter}),r.indent);for(let n of e)yield*tJ(n,t+1,r)}else Dl(e)&&(yield*cmt(e,t,r))}function ac(e,t,r){return" ".repeat(r*e)+t}function rf(e,t,r){return ac(e,"- "+t,r)}function umt(e,t){let r=t("",e,[]);return r===void 0?AM(e,t,[]):AM(rm(r),t,[])}function AM(e,t,r){return Dl(e)?lmt(e,t,r):Bg(e)?dmt(e,t,r):e}function lmt(e,t,r){let n={};for(let[o,i]of Object.entries(e)){let s=[...r,o],a=t(o,i,s);a!==void 0&&(n[o]=AM(rm(a),t,s))}return n}function dmt(e,t,r){let n=[];for(let o=0;o<e.length;o++){let i=e[o],s=[...r,o],a=t(String(o),i,s);if(a===void 0)continue;let c=rm(a);n.push(AM(c,t,s))}return n}function Ns(e,t){return Array.from(ixe(e,t)).join(`
19
19
  `)}function ixe(e,t){let r=rm(e),n=fmt(t);return nmt(n.replacer?umt(r,n.replacer):r,n,0)}function fmt(e){return{indent:e?.indent??2,delimiter:e?.delimiter??YC,keyFolding:e?.keyFolding??"off",flattenDepth:e?.flattenDepth??Number.POSITIVE_INFINITY,replacer:e?.replacer}}var Wpt,Xye,YC,zpt,Vpt,gEr,rJ=h(()=>{Wpt="null",Xye={comma:",",tab:" ",pipe:"|"},YC=Xye.comma;zpt=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Vpt=/^0\d+$/;gEr=Symbol("quotedKey")});function pmt(e){return Object.entries(e).filter(([t])=>t!=="summary")}function xM(e,t,r){return Ns(Object.fromEntries([...pmt(e),["summary",t]]),r)}var Wx=h(()=>{"use strict";rJ();rJ()});function sxe(e){if(e===void 0||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function mmt(e,t){if(t===void 0||t<=0)return;let r=Math.max(0,e),n=r/t;return{tier:n>=1?"HARD_STOP":n>=.9?"CRITICAL":n>=.75?"WARNING":"OK",spentUsd:r,limitUsd:t,percent:n}}function JC(e=process.env,t=()=>""){let r=(n,o)=>{let i=e[n];return i!==void 0&&/^[0-9]+$/.test(i)?Number(i):o};return{target:r("RED_AFK_TARGET",Fr.target),fastDeathThresholdS:r("RED_AFK_FAST_DEATH_S",Fr.fastDeathThresholdS),circuitK:r("RED_AFK_CIRCUIT_K",Fr.circuitK),circuitWindowS:r("RED_AFK_CIRCUIT_WINDOW_S",Fr.circuitWindowS),stallThresholdS:r("RED_AFK_STALL_THRESHOLD_S",Fr.stallThresholdS),stallKillThresholdS:r("RED_AFK_STALL_KILL_THRESHOLD_S",Fr.stallKillThresholdS),runner:e.RED_AFK_RUNNER&&e.RED_AFK_RUNNER.length>0?e.RED_AFK_RUNNER:Fr.runner,pollIntervalS:r("RED_AFK_POLL_S",Fr.pollIntervalS),eventFallbackS:r("RED_AFK_WAKE_FALLBACK_S",Fr.eventFallbackS)||Fr.eventFallbackS,tickTimeoutS:r("RED_AFK_TICK_TIMEOUT_S",Fr.tickTimeoutS)||Fr.tickTimeoutS,supervisorStaleS:r("RED_AFK_SUPERVISOR_STALE_S",Fr.supervisorStaleS)||Fr.supervisorStaleS,progressStaleS:r("RED_AFK_SUPERVISOR_PROGRESS_STALE_S",Fr.progressStaleS)||Fr.progressStaleS,halfOpenBaseS:r("RED_AFK_HALF_OPEN_BASE_S",Fr.halfOpenBaseS),halfOpenCapS:r("RED_AFK_HALF_OPEN_CAP_S",Fr.halfOpenCapS),unblockSweepIntervalS:r("RED_AFK_UNBLOCK_SWEEP_INTERVAL_S",Fr.unblockSweepIntervalS)||Fr.unblockSweepIntervalS,supervisorMaxRestarts:r("RED_AFK_SUPERVISOR_MAX_RESTARTS",Fr.supervisorMaxRestarts)||Fr.supervisorMaxRestarts,supervisorRestartWindowS:r("RED_AFK_SUPERVISOR_RESTART_WINDOW_S",Fr.supervisorRestartWindowS)||Fr.supervisorRestartWindowS,drainBudgetUsd:sxe(e.RED_AFK_DRAIN_MAX_COST_USD)??sxe(t("afk.drain.max_cost_usd")),reapContestWindowS:r("RED_AFK_REAP_CONTEST_WINDOW_S",Fr.reapContestWindowS)}}function iJ(e){if(e.stallKillThresholdS<=e.stallThresholdS)throw new Error(`RED_AFK_STALL_KILL_THRESHOLD_S (${e.stallKillThresholdS}) must be > RED_AFK_STALL_THRESHOLD_S (${e.stallThresholdS})`)}function hmt(e){if(e.supervisorStaleS<=e.tickTimeoutS)throw new Error(`RED_AFK_SUPERVISOR_STALE_S (${e.supervisorStaleS}) must be > RED_AFK_TICK_TIMEOUT_S (${e.tickTimeoutS})`)}function gmt(e){if(e.progressStaleS<=e.supervisorStaleS)throw new Error(`RED_AFK_SUPERVISOR_PROGRESS_STALE_S (${e.progressStaleS}) must be > RED_AFK_SUPERVISOR_STALE_S (${e.supervisorStaleS})`)}function EM(e,t,r,n){return e.pid===null||!e.pidAlive?"absent":e.lastHeartbeatEpoch===null?"healthy":t-e.lastHeartbeatEpoch>=r||e.lastProgressEpoch!==null&&t-e.lastProgressEpoch>=n&&e.slotsBusy>0?"quiescent":"healthy"}function Amt(e,t,r,n){let o=r-t;if(!(t>0&&o<n.fastDeathThresholdS))return{deaths:[...e],count:e.length,fastDeath:!1,trip:!1};let s=[...e,r].filter(c=>r-c<=n.circuitWindowS),a=s.length;return{deaths:s,count:a,fastDeath:!0,trip:a>=n.circuitK}}function ymt(){return{pid:null,spawnEpoch:0,deaths:[],parked:!1,tripEpoch:0,swept:!1,stalled:!1,stallSinceEpoch:0,reaped:!1,spawning:!1,idleParked:!1,backoffStep:0,halfOpen:!1,contest:null}}function uxe(e){return{slots:Array.from({length:e},()=>ymt()),lastProgressEpoch:0,lastUnblockSweepEpoch:0,wakeStats:Nye(),drainBudgetHardStopped:!1}}function xmt(e,t,r,n,o){let i=[`slot: ${t}`,`worker IDs: ${r}`,`fast deaths: ${n}`,`supervisor log: ${o}`].join(`
20
20
  `);return $C({status:"discarded",worker:e,duration:`runner-broken, slot parked after ${n} fast deaths`,diff:"discarded",attempt:1,sections:[{name:"summary",body:i}]})}function Emt(e){return $C({status:"no-sentinel",worker:e.workerId.length>0?e.workerId:"unknown",duration:`${e.durationS}s \xB7 stall-reaped`,diff:"stall-reaped",attempt:e.attempt,sections:[{name:"notes",body:e.notes.length>0?e.notes:"(no agent notes recorded before stall-reap)"},{name:"log",body:e.logTail,fenced:!0}]})}function bmt(e){return $C({status:"no-sentinel",worker:e.workerId.length>0?e.workerId:"unknown",duration:`${e.durationS}s \xB7 orchestrator died mid-attempt`,diff:"crashed",attempt:e.attempt,sections:[{name:"notes",body:e.notes.length>0?e.notes:"(no agent notes recorded before the orchestrator died)"},{name:"log",body:e.logTail,fenced:!0}]})}function Smt(e){return e.issue!==null&&e.ghOk&&e.stillRunning}async function axe(e,t){if(e===null||e.issue===null||!t.gh.crashedClaimState)return null;let r;try{r=await t.gh.crashedClaimState(e.issue)}catch{return null}if(!Smt({issue:e.issue,ghOk:r.ghOk,stillRunning:r.stillRunning}))return null;r.envelopePosted||await t.gh.comment(e.issue,bmt(e));let n=tf("no-sentinel",e.attempt,t.recoveryEnv??{});return n.decision==="retry"?await t.gh.editLabels(e.issue,n.addLabels,n.removeLabels):(n.typedLabel!==null&&await t.gh.ensureLabel(n.typedLabel),await t.gh.editLabels(e.issue,n.addLabels,[...n.removeLabels,Ve]),n.escalationComment!==null&&await t.gh.comment(e.issue,n.escalationComment)),e.issue}function Cmt(e,t){let r=0,n=0,o=0;for(let i of e.slots)i.parked||i.idleParked?o+=1:i.pid===null?n+=1:t.proc.isAlive(i.pid)?r+=1:n+=1;return{slotsBusy:r,slotsFree:n,slotsTotal:e.slots.length,slotsParked:o}}function Imt(e){return new Date(e*1e3).toISOString()}function wmt(e,t){let r=[];for(let n=0;n<e.slots.length;n++){let o=e.slots[n];if(o.idleParked)r.push({index:n,status:"idle-parked"});else if(o.parked&&o.halfOpen)r.push({index:n,status:"half-open"});else if(o.parked){let i=o.tripEpoch>0?o.tripEpoch+UR(o.backoffStep,t):void 0;r.push({index:n,status:"open",...i!==void 0?{retryAt:i}:{}})}}return r}async function kmt(e,t,r,n,o){let i=r.queueDepth,s=t.now(),a={ts:Imt(s),epoch:s,lastProgressEpoch:e.lastProgressEpoch,runner:n,readyForAgent:i,...Cmt(e,t),spawnsThisTick:r.respawned.length,...r.drainBudget?{drainBudget:r.drainBudget}:{},slotDetails:wmt(e,o)};try{await t.emitFleetHeartbeat?.(a)}catch{}return a}async function vmt(e,t,r,n){if(t.swept)return;t.swept=!0;let o=r.fs.parkedSlotWork(e,t.pid),i=o.workers.map(c=>c.workerId).join(","),s=t.deaths.length;if(r.dispatchFleetHook)try{await r.dispatchFleetHook("on_circuit_trip",{event:"on_circuit_trip",runner:n.runner,slot:e,...t.pid!==null?{pid:t.pid}:{},...i.length>0?{worker_ids:i}:{},death_count:s,supervisor_log:o.supervisorLogPath})}catch{}if(o.workers.length===0)return;o.workers.some(c=>c.pairs.some(u=>u.issue!==null))&&await r.gh.ensureRunnerErrorLabel();for(let c of o.workers)for(let u of c.pairs){if(u.issue!==null){let l=xmt(n.runner,e,i,s,o.supervisorLogPath);await r.gh.comment(u.issue,l),await r.gh.editLabels(u.issue,[Ve,zye],[rt,Ke])}await r.fs.removeDir(u.dir)}}async function Rmt(e,t,r,n=Fr){if(t.reaped)return;t.reaped=!0;let o=t.pid,i=r.fs.resolveIterDir(e),s=!0;if(o!==null&&r.proc.isAlive(o)&&(s=await r.proc.killTree(o)!==!1),t.pid=null,t.stalled=!1,t.stallSinceEpoch=0,i&&i.issue!==null){await r.gh.comment(i.issue,Emt(i));let a=tf("stalled",i.attempt,r.recoveryEnv??{});a.decision==="retry"?await Bmt(e,t,i,r,n.reapContestWindowS)||await r.gh.editLabels(i.issue,a.addLabels,a.removeLabels):(a.typedLabel!==null&&await r.gh.ensureLabel(a.typedLabel),await r.gh.editLabels(i.issue,a.addLabels,[...a.removeLabels,Ve]),a.escalationComment!==null&&await r.gh.comment(i.issue,a.escalationComment))}i&&s&&await r.fs.teardownIterDir(i)}async function lxe(e,t){try{return await e.attemptBranchHead?.(t)}catch{return}}function nJ(e,t,r){e.log?.(Ns({schema_version:"red.afk.reap_contest.v1",event:t,...r}))}async function Bmt(e,t,r,n,o){if(r.issue===null||!r.branch||o<=0)return!1;let i=n.now(),s=i+o,a=await lxe(n,r.branch);return tm({edge:"contest",fromLabels:[Ke],removeLabels:[],addLabels:[Ea]}),await n.gh.editLabels(r.issue,[Ea],[]),t.contest={issue:r.issue,branch:r.branch,headAtReap:a,openedEpoch:i,deadlineEpoch:s},nJ(n,"opened",{slot:e,issue:r.issue,branch:r.branch,head_at_reap:a,deadline_epoch:s}),!0}async function _mt(e,t,r,n=Fr){let o=t.contest;if(o===null)return null;let i=r.now(),s=await lxe(r,o.branch);return i<=o.deadlineEpoch&&o.headAtReap!==void 0&&s!==void 0&&s!==o.headAtReap?(tm({edge:"contest-reclaimed",fromLabels:[Ke,Ea],removeLabels:[Ea],addLabels:[]}),await r.gh.editLabels(o.issue,[],[Ea]),t.contest=null,nJ(r,"reclaimed",{slot:e,issue:o.issue,branch:o.branch,head_at_reap:o.headAtReap,head_at_resolution:s}),"reclaimed"):i<o.deadlineEpoch?"pending":(tm({edge:"contest-expired",fromLabels:[Ke,Ea],removeLabels:[Ke,Ea],addLabels:[Ve]}),await r.gh.editLabels(o.issue,[Ve],[Ke,Ea]),t.contest=null,nJ(r,"expired",{slot:e,issue:o.issue,branch:o.branch,head_at_reap:o.headAtReap,head_at_resolution:s}),"expired")}async function Tmt(e,t,r){let n=t.now(),o=[];for(let i=0;i<e.slots.length;i+=1){let s=e.slots[i];if(s.parked||s.idleParked||!(s.spawnEpoch>0)||!(n-s.spawnEpoch>=r.stallThresholdS))continue;let a=t.fs.workerLivenessVerdict(i,r.stallThresholdS*1e3);if(a!==null&&a.status==="stalled"){if(!s.stalled){s.stalled=!0;let l=a.laneAgeMs!==void 0?n-Math.round(a.laneAgeMs/1e3):n;if(s.stallSinceEpoch=l,t.dispatchFleetHook)try{await t.dispatchFleetHook("on_stall_detected",{event:"on_stall_detected",runner:r.runner,slot:i,...s.pid!==null?{pid:s.pid}:{},stall_since:l,idle_seconds:a.laneAgeMs!==void 0?Math.round(a.laneAgeMs/1e3):0})}catch{}}let u=s.stallSinceEpoch;if(u>0&&n-u>=r.stallKillThresholdS&&!s.reaped){let l=s.pid,d=l!==null?UC(t.proc.inspectTree(l)):{activeDescendant:!1,cpuPct:0};if(uM({idleSeconds:n-u,idleThresholdSeconds:r.stallKillThresholdS,activeDescendant:d.activeDescendant,cpuPct:d.cpuPct})==="kill"){let p=!1;if(t.dispatchFleetHook)try{p=(await t.dispatchFleetHook("on_stall_reap",{event:"on_stall_reap",runner:r.runner,slot:i,...l!==null?{pid:l}:{},idle_seconds:n-u,stall_since:u})).vetoed}catch{}p||(await Rmt(i,s,t,r),o.push(i))}}}else s.stalled&&(s.stalled=!1,s.stallSinceEpoch=0)}return o}function dxe(e,t,r){if(r.drainBudgetUsd===void 0)return;let n=0;try{n=t.fs.fleetCostUsd?.()??0}catch{n=0}let o=mmt(n,r.drainBudgetUsd);return o?.tier==="HARD_STOP"&&(e.drainBudgetHardStopped=!0),o}function fxe(e,t,r,n){!r||e.lastDrainBudgetTier===r.tier||(e.lastDrainBudgetTier=r.tier,t.log?.(Ns({schema_version:"red.afk.drain_budget.v1",tier:r.tier,spent_usd:Number(r.spentUsd.toFixed(4)),limit_usd:Number(r.limitUsd.toFixed(4)),percent:Number((r.percent*100).toFixed(2)),ready_for_agent:n,action:r.tier==="HARD_STOP"?"hard_stop_no_new_spawns_inflight_finish":r.tier==="CRITICAL"?"new_spawns_downgrade_one_model_tier":"observe"})))}function pxe(e,t){if(e.drainBudgetHardStopped||t?.tier==="HARD_STOP")return"hard-stop";if(t?.tier==="CRITICAL")return{taskTierDowngrade:!0}}async function oJ(e,t,r,n){let o=pxe(r,n);return o==="hard-stop"?null:o?t.proc.spawnSlot(e,o):t.proc.spawnSlot(e)}async function Dmt(e,t,r,n,o=0,i){let s=async()=>i==="hard-stop"?null:i?r.proc.spawnSlot(e,i):r.proc.spawnSlot(e);if(t.parked&&t.halfOpen){let d=r.now(),f=t.spawnEpoch>0?d-t.spawnEpoch:0,p=t.spawnEpoch>0&&f<n.fastDeathThresholdS;if(t.halfOpen=!1,t.pid=null,p)return t.backoffStep++,t.tripEpoch=d,r.log?.(`circuit re-parked: slot ${e} probe fast-death (${f}s), next backoff=${UR(t.backoffStep,n)}s step=${t.backoffStep}`),{parked:!0};t.parked=!1,t.backoffStep=0,t.tripEpoch=0,t.swept=!1,t.deaths=[],r.log?.(`circuit closed: slot ${e} probe succeeded (${f}s), backoff reset`),t.spawning=!0;try{let m=await s();if(m===null)return{parked:!0};t.pid=m.pid,t.spawnEpoch=m.spawnEpoch}finally{t.spawning=!1}if(t.stalled=!1,t.stallSinceEpoch=0,t.reaped=!1,r.dispatchFleetHook)try{await r.dispatchFleetHook("on_slot_spawn",{event:"on_slot_spawn",runner:n.runner,slot:e,...t.pid!==null?{pid:t.pid}:{}})}catch{}return{parked:!1}}if((r.proc.lastExitCode?.(e)??null)===0){if(o===0)return t.pid=null,t.idleParked=!0,{parked:!0};t.spawning=!0;try{let d=await s();if(d===null)return t.pid=null,{parked:!0};t.pid=d.pid,t.spawnEpoch=d.spawnEpoch}finally{t.spawning=!1}if(t.stalled=!1,t.stallSinceEpoch=0,t.reaped=!1,r.dispatchFleetHook)try{await r.dispatchFleetHook("on_slot_spawn",{event:"on_slot_spawn",runner:n.runner,slot:e,...t.pid!==null?{pid:t.pid}:{}}),await r.dispatchFleetHook("on_respawn",{event:"on_respawn",runner:n.runner,slot:e,...t.pid!==null?{pid:t.pid}:{}})}catch{}return{parked:!1}}let u=r.now(),l=Amt(t.deaths,t.spawnEpoch,u,n);if(t.deaths=l.deaths,l.trip)return t.parked=!0,t.tripEpoch=u,await vmt(e,t,r,n),t.pid=null,{parked:!0};t.spawning=!0;try{let d=await s();if(d===null)return t.pid=null,{parked:!0};t.pid=d.pid,t.spawnEpoch=d.spawnEpoch}finally{t.spawning=!1}if(t.stalled=!1,t.stallSinceEpoch=0,t.reaped=!1,r.dispatchFleetHook)try{await r.dispatchFleetHook("on_slot_spawn",{event:"on_slot_spawn",runner:n.runner,slot:e,...t.pid!==null?{pid:t.pid}:{}}),await r.dispatchFleetHook("on_respawn",{event:"on_respawn",runner:n.runner,slot:e,...t.pid!==null?{pid:t.pid}:{}})}catch{}return{parked:!1}}async function Qmt(e,t){if(!t.proc.spawnReconcileWorker||!t.gh.findReconcileCandidate)return null;let r=e.slots.findIndex(s=>!s.parked&&s.pid===null);if(r<0)return null;let n=null;try{n=await t.gh.findReconcileCandidate()}catch{return null}if(n===null)return null;let o=await t.proc.spawnReconcileWorker(r,n),i=e.slots[r];return i.pid=o.pid,i.spawnEpoch=o.spawnEpoch,i.stalled=!1,i.stallSinceEpoch=0,i.reaped=!1,r}async function Omt(e,t,r,n){let o={respawned:[],deaths:[],parked:[],idleParked:[],halfOpened:[],reaped:[],crashReconciled:[],reconciledSlots:[],unblocked:[],stopped:!1,queueDepth:0,abandoned:!1};if(n())return await Nmt(e,t),o.stopped=!0,o;let i=0;try{i=await t.gh.readyQueueDepth?.()??0}catch{i=0}o.queueDepth=i;let s=dxe(e,t,r);o.drainBudget=s,fxe(e,t,s,i);let a=pxe(e,s);for(let u=0;u<e.slots.length;u+=1)await _mt(u,e.slots[u],t,r);for(let u=0;u<e.slots.length;u+=1){let l=e.slots[u];if(!(!l.idleParked||i===0)&&a!=="hard-stop"){l.idleParked=!1,l.spawning=!0;try{let d=await oJ(u,t,e,s);if(d===null)continue;l.pid=d.pid,l.spawnEpoch=d.spawnEpoch,l.stalled=!1,l.stallSinceEpoch=0,l.reaped=!1}finally{l.spawning=!1}if(o.respawned.push(u),t.dispatchFleetHook)try{await t.dispatchFleetHook("on_slot_spawn",{event:"on_slot_spawn",runner:r.runner,slot:u,...l.pid!==null?{pid:l.pid}:{}})}catch{}}}{let u=t.now();for(let l=0;l<e.slots.length;l+=1){let d=e.slots[l];if(!(!d.parked||d.halfOpen||d.spawning)&&a!=="hard-stop"&&Jye(d.tripEpoch,d.backoffStep,u,r)){t.log?.(`circuit half-open: slot ${l} cooldown expired, spawning probe (backoff=${UR(d.backoffStep,r)}s step=${d.backoffStep})`),d.halfOpen=!0,d.spawning=!0;try{let f=await oJ(l,t,e,s);if(f===null)continue;d.pid=f.pid,d.spawnEpoch=f.spawnEpoch,d.stalled=!1,d.stallSinceEpoch=0,d.reaped=!1}finally{d.spawning=!1}if(o.halfOpened.push(l),t.dispatchFleetHook)try{await t.dispatchFleetHook("on_slot_spawn",{event:"on_slot_spawn",runner:r.runner,slot:l,...d.pid!==null?{pid:d.pid}:{}})}catch{}}}}for(let u=0;u<e.slots.length;u+=1){let l=e.slots[u];if(l.parked&&!l.halfOpen||l.idleParked||l.spawning)continue;let d=l.pid;if(d===null||!t.proc.isAlive(d)){if(d!==null&&t.log?.(`dead slot reconciled: slot ${u} pid=${d}`),t.dispatchFleetHook)try{await t.dispatchFleetHook("on_slot_death",{event:"on_slot_death",runner:r.runner,slot:u,...d!==null?{pid:d}:{}})}catch{}let f=t.fs.resolveIterDir(u);if(o.deaths.push(u),a==="hard-stop"){l.pid=null,l.stalled=!1,l.stallSinceEpoch=0,l.reaped=!1;try{let m=await axe(f,t);m!==null&&o.crashReconciled.push(m)}catch{}continue}let{parked:p}=await Dmt(u,l,t,r,i,a);if(p)l.idleParked?o.idleParked.push(u):o.parked.push(u);else{o.respawned.push(u);try{let m=await axe(f,t);m!==null&&o.crashReconciled.push(m)}catch{}}}}let c=await Tmt(e,t,r);if(o.reaped=c,a!=="hard-stop"){let u=await Qmt(e,t);u!==null&&o.reconciledSlots.push(u)}if(t.unblockSweep){let u=t.now();if(e.lastUnblockSweepEpoch===0||u-e.lastUnblockSweepEpoch>=r.unblockSweepIntervalS){e.lastUnblockSweepEpoch=u;try{o.unblocked=await t.unblockSweep()}catch{}}}return o}async function Nmt(e,t){for(let r of e.slots){let n=r.pid;n!==null&&t.proc.isAlive(n)&&await t.proc.killTree(n)}}async function mxe(e,t,r,n){if(iJ(r),hmt(r),gmt(r),t.bootSweeps)try{await t.bootSweeps()}catch(i){t.log?.(`boot sweeps failed: ${i instanceof Error?i.message:String(i)} \u2014 spawning workers anyway`)}if(t.dispatchFleetHook){let i=!1;try{i=(await t.dispatchFleetHook("pre_fleet",{event:"pre_fleet",runner:r.runner})).aborted}catch(s){t.log?.(`pre_fleet hook threw: ${s instanceof Error?s.message:String(s)} \u2014 spawning workers anyway`)}if(i){t.log?.("pre_fleet hook aborted boot \u2014 fleet will not spawn");return}}let o=dxe(e,t,r);fxe(e,t,o,0);for(let i=0;i<e.slots.length;i+=1){let s=e.slots[i],a=await oJ(i,t,e,o);if(a!==null&&(s.pid=a.pid,s.spawnEpoch=a.spawnEpoch,t.dispatchFleetHook))try{await t.dispatchFleetHook("on_slot_spawn",{event:"on_slot_spawn",runner:r.runner,slot:i,...s.pid!==null?{pid:s.pid}:{}})}catch{}}for(;;){let i=await Pmt(()=>Omt(e,t,r,n),r.tickTimeoutS*1e3,t.proc.sleep,t.log);i.abandoned||(e.lastProgressEpoch=t.now());let s=await kmt(e,t,i,r.runner,r);if(t.log?.(`tick: slots=${e.slots.length} respawned=${i.respawned.length} deaths=${i.deaths.length} parked=${i.parked.length} idle-parked=${i.idleParked.length} half-opened=${i.halfOpened.length} reaped=${i.reaped.length} unblocked=${i.unblocked.length} crash-reconciled=${i.crashReconciled.length} ready=${s.readyForAgent} busy=${s.slotsBusy} free=${s.slotsFree}`),i.stopped){if(t.dispatchFleetHook)try{await t.dispatchFleetHook("post_fleet",{event:"post_fleet",runner:r.runner})}catch(u){t.log?.(`post_fleet hook threw: ${u instanceof Error?u.message:String(u)}`)}return}let a=t.wake?r.eventFallbackS:r.pollIntervalS,c=await Oye({fallbackMs:a*1e3,sleep:t.proc.sleep,wake:t.wake});Pye(e.wakeStats,c),c==="event"&&t.log?.(`wake: event-driven (idle wakes reduced \u2014 ${e.wakeStats.event}/${e.wakeStats.total} wakes event-driven)`)}}function cxe(){return{respawned:[],deaths:[],parked:[],idleParked:[],halfOpened:[],reaped:[],crashReconciled:[],reconciledSlots:[],unblocked:[],stopped:!1,queueDepth:0,abandoned:!0}}async function Pmt(e,t,r,n){let o=Symbol("tick-timeout");try{let i=await Promise.race([e(),r(t).then(()=>o)]);return i===o?(n?.(`tick exceeded ${Math.round(t/1e3)}s \u2014 abandoning this pass, loop continues`),cxe()):i}catch(i){return n?.(`tick threw: ${i instanceof Error?i.message:String(i)} \u2014 loop continues`),cxe()}}var Fr,KC=h(()=>{"use strict";lM();Mye();jY();mM();cn();gM();Kye();Wx();Fr={target:2,fastDeathThresholdS:30,circuitK:5,circuitWindowS:90,stallThresholdS:600,stallKillThresholdS:1800,runner:"claude",pollIntervalS:15,eventFallbackS:60,tickTimeoutS:120,supervisorStaleS:300,progressStaleS:900,halfOpenBaseS:XY.halfOpenBaseS,halfOpenCapS:XY.halfOpenCapS,unblockSweepIntervalS:60,supervisorMaxRestarts:5,supervisorRestartWindowS:300,reapContestWindowS:30}});import{createHash as Lmt}from"node:crypto";import{hostname as Umt}from"node:os";function Hmt(e){return Lmt("md5").update(e).digest("hex").slice(0,$mt)}function aJ(){return Hmt(Umt())}function WR(){return`${aJ()}:`}function gxe(e){return`${WR()}${e}`}var $mt,bM=h(()=>{"use strict";$mt=12});var rr,cJ,Te,nf,jR=h(()=>{(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},e.getValidEnumValues=o=>{let i=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(let s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=n,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(rr||(rr={}));(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(cJ||(cJ={}));Te=rr.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),nf=e=>{switch(typeof e){case"undefined":return Te.undefined;case"string":return Te.string;case"number":return Number.isNaN(e)?Te.nan:Te.number;case"boolean":return Te.boolean;case"function":return Te.function;case"bigint":return Te.bigint;case"symbol":return Te.symbol;case"object":return Array.isArray(e)?Te.array:e===null?Te.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Te.promise:typeof Map<"u"&&e instanceof Map?Te.map:typeof Set<"u"&&e instanceof Set?Te.set:typeof Date<"u"&&e instanceof Date?Te.date:Te.object;default:return Te.unknown}}});var me,Wmt,ba,SM=h(()=>{jR();me=rr.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Wmt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ba=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(i){return i.message},n={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,rr.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];r[i]=r[i]||[],r[i].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ba.create=e=>new ba(e)});var jmt,nm,uJ=h(()=>{SM();jR();jmt=(e,t)=>{let r;switch(e.code){case me.invalid_type:e.received===Te.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case me.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,rr.jsonStringifyReplacer)}`;break;case me.unrecognized_keys:r=`Unrecognized key(s) in object: ${rr.joinValues(e.keys,", ")}`;break;case me.invalid_union:r="Invalid input";break;case me.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${rr.joinValues(e.options)}`;break;case me.invalid_enum_value:r=`Invalid enum value. Expected ${rr.joinValues(e.options)}, received '${e.received}'`;break;case me.invalid_arguments:r="Invalid function arguments";break;case me.invalid_return_type:r="Invalid function return type";break;case me.invalid_date:r="Invalid date";break;case me.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:rr.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case me.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case me.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case me.custom:r="Invalid input";break;case me.invalid_intersection_types:r="Intersection results could not be merged";break;case me.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case me.not_finite:r="Number must be finite";break;default:r=t.defaultError,rr.assertNever(e)}return{message:r}},nm=jmt});function Gmt(e){Axe=e}function ZC(){return Axe}var Axe,CM=h(()=>{uJ();Axe=nm});function ke(e,t){let r=ZC(),n=GR({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===nm?void 0:nm].filter(o=>!!o)});e.common.issues.push(n)}var GR,qmt,Wi,dt,jx,fs,IM,wM,_g,XC,lJ=h(()=>{CM();uJ();GR=e=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...o,path:i,message:a}},qmt=[];Wi=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let o of r){if(o.status==="aborted")return dt;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let o of r){let i=await o.key,s=await o.value;n.push({key:i,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let o of r){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return dt;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(n[i.value]=s.value)}return{status:t.value,value:n}}},dt=Object.freeze({status:"aborted"}),jx=e=>({status:"dirty",value:e}),fs=e=>({status:"valid",value:e}),IM=e=>e.status==="aborted",wM=e=>e.status==="dirty",_g=e=>e.status==="valid",XC=e=>typeof Promise<"u"&&e instanceof Promise});var yxe=h(()=>{});var Ge,xxe=h(()=>{(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Ge||(Ge={}))});function Qt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function Cxe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function uht(e){return new RegExp(`^${Cxe(e)}$`)}function Ixe(e){let t=`${Sxe}T${Cxe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function lht(e,t){return!!((t==="v4"||!t)&&rht.test(e)||(t==="v6"||!t)&&oht.test(e))}function dht(e,t){if(!Zmt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function fht(e,t){return!!((t==="v4"||!t)&&nht.test(e)||(t==="v6"||!t)&&iht.test(e))}function pht(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,i=Number.parseInt(e.toFixed(o).replace(".","")),s=Number.parseInt(t.toFixed(o).replace(".",""));return i%s/10**o}function eI(e){if(e instanceof Sa){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=au.create(eI(n))}return new Sa({...e._def,shape:()=>t})}else return e instanceof sm?new sm({...e._def,type:eI(e.element)}):e instanceof au?au.create(eI(e.unwrap())):e instanceof sf?sf.create(eI(e.unwrap())):e instanceof of?of.create(e.items.map(t=>eI(t))):e}function fJ(e,t){let r=nf(e),n=nf(t);if(e===t)return{valid:!0,data:e};if(r===Te.object&&n===Te.object){let o=rr.objectKeys(t),i=rr.objectKeys(e).filter(a=>o.indexOf(a)!==-1),s={...e,...t};for(let a of i){let c=fJ(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Te.array&&n===Te.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let i=0;i<e.length;i++){let s=e[i],a=t[i],c=fJ(s,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===Te.date&&n===Te.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function wxe(e,t){return new tE({values:e,typeName:ht.ZodEnum,...Qt(t)})}function bxe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function kxe(e,t={},r){return e?Dg.create().superRefine((n,o)=>{let i=e(n);if(i instanceof Promise)return i.then(s=>{if(!s){let a=bxe(t,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!i){let s=bxe(t,n),a=s.fatal??r??!0;o.addIssue({code:"custom",...s,fatal:a})}}):Dg.create()}var cu,Exe,Gt,zmt,Vmt,Ymt,Jmt,Kmt,Zmt,Xmt,eht,tht,dJ,rht,nht,oht,iht,sht,aht,Sxe,cht,Tg,Gx,qx,zx,Vx,tI,Yx,Jx,Dg,im,Ql,rI,sm,Sa,Kx,om,kM,Zx,of,vM,nI,oI,RM,Xx,eE,tE,rE,Qg,uu,au,sf,nE,oE,iI,mht,qR,zR,iE,hht,ht,ght,vxe,Rxe,Aht,yht,Bxe,xht,Eht,bht,Sht,Cht,Iht,wht,kht,vht,Rht,Bht,_ht,Tht,Dht,Qht,Oht,Nht,Pht,Mht,Fht,Lht,Uht,$ht,Hht,Wht,jht,Ght,qht,zht,Vht,Yht,Jht,Kht,Zht,_xe=h(()=>{SM();CM();xxe();lJ();jR();cu=class{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Exe=(e,t)=>{if(_g(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ba(e.common.issues);return this._error=r,this._error}}};Gt=class{get description(){return this._def.description}_getType(t){return nf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:nf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Wi,ctx:{common:t.parent.common,data:t.data,parsedType:nf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(XC(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nf(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Exe(n,o)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return _g(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>_g(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:nf(t)},o=this._parse({data:t,path:n.path,parent:n}),i=await(XC(o)?o:Promise.resolve(o));return Exe(n,i)}refine(t,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,i)=>{let s=t(o),a=()=>i.addIssue({code:me.custom,...n(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new uu({schema:this,typeName:ht.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return au.create(this,this._def)}nullable(){return sf.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sm.create(this)}promise(){return Qg.create(this,this._def)}or(t){return Kx.create([this,t],this._def)}and(t){return Zx.create(this,t,this._def)}transform(t){return new uu({...Qt(this._def),schema:this,typeName:ht.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new nE({...Qt(this._def),innerType:this,defaultValue:r,typeName:ht.ZodDefault})}brand(){return new qR({typeName:ht.ZodBranded,type:this,...Qt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new oE({...Qt(this._def),innerType:this,catchValue:r,typeName:ht.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return zR.create(this,t)}readonly(){return iE.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zmt=/^c[^\s-]{8,}$/i,Vmt=/^[0-9a-z]+$/,Ymt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Jmt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Kmt=/^[a-z0-9_-]{21}$/i,Zmt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Xmt=/^[-+]?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)?)??$/,eht=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tht="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rht=/^(?:(?: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])$/,nht=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,oht=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,iht=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sht=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,aht=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sxe="((\\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])))",cht=new RegExp(`^${Sxe}$`);Tg=class e extends Gt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Te.string){let i=this._getOrReturnCtx(t);return ke(i,{code:me.invalid_type,expected:Te.string,received:i.parsedType}),dt}let n=new Wi,o;for(let i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(o=this._getOrReturnCtx(t,o),ke(o,{code:me.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")t.data.length>i.value&&(o=this._getOrReturnCtx(t,o),ke(o,{code:me.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let s=t.data.length>i.value,a=t.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(t,o),s?ke(o,{code:me.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&ke(o,{code:me.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")eht.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"email",code:me.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")dJ||(dJ=new RegExp(tht,"u")),dJ.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"emoji",code:me.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Jmt.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"uuid",code:me.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Kmt.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"nanoid",code:me.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")zmt.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"cuid",code:me.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Vmt.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"cuid2",code:me.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Ymt.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"ulid",code:me.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),ke(o,{validation:"url",code:me.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"regex",code:me.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(t,o),ke(o,{code:me.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(o=this._getOrReturnCtx(t,o),ke(o,{code:me.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(o=this._getOrReturnCtx(t,o),ke(o,{code:me.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Ixe(i).test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{code:me.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?cht.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{code:me.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?uht(i).test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{code:me.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Xmt.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"duration",code:me.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?lht(t.data,i.version)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"ip",code:me.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?dht(t.data,i.alg)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"jwt",code:me.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?fht(t.data,i.version)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"cidr",code:me.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?sht.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"base64",code:me.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?aht.test(t.data)||(o=this._getOrReturnCtx(t,o),ke(o,{validation:"base64url",code:me.invalid_string,message:i.message}),n.dirty()):rr.assertNever(i);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:me.invalid_string,...Ge.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ge.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ge.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ge.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ge.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Ge.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ge.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ge.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ge.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Ge.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Ge.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Ge.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ge.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Ge.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...Ge.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...Ge.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Ge.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Ge.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Ge.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Ge.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Ge.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Ge.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Ge.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Ge.errToObj(r)})}nonempty(t){return this.min(1,Ge.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Tg.create=e=>new Tg({checks:[],typeName:ht.ZodString,coerce:e?.coerce??!1,...Qt(e)});Gx=class e extends Gt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Te.number){let i=this._getOrReturnCtx(t);return ke(i,{code:me.invalid_type,expected:Te.number,received:i.parsedType}),dt}let n,o=new Wi;for(let i of this._def.checks)i.kind==="int"?rr.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),ke(n,{code:me.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(n=this._getOrReturnCtx(t,n),ke(n,{code:me.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),ke(n,{code:me.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?pht(t.data,i.value)!==0&&(n=this._getOrReturnCtx(t,n),ke(n,{code:me.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),ke(n,{code:me.not_finite,message:i.message}),o.dirty()):rr.assertNever(i);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Ge.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Ge.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Ge.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Ge.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ge.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ge.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ge.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ge.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ge.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ge.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Ge.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Ge.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ge.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ge.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&rr.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};Gx.create=e=>new Gx({checks:[],typeName:ht.ZodNumber,coerce:e?.coerce||!1,...Qt(e)});qx=class e extends Gt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Te.bigint)return this._getInvalidInput(t);let n,o=new Wi;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(n=this._getOrReturnCtx(t,n),ke(n,{code:me.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(n=this._getOrReturnCtx(t,n),ke(n,{code:me.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),ke(n,{code:me.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):rr.assertNever(i);return{status:o.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return ke(r,{code:me.invalid_type,expected:Te.bigint,received:r.parsedType}),dt}gte(t,r){return this.setLimit("min",t,!0,Ge.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Ge.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Ge.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Ge.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ge.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ge.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ge.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ge.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ge.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Ge.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};qx.create=e=>new qx({checks:[],typeName:ht.ZodBigInt,coerce:e?.coerce??!1,...Qt(e)});zx=class extends Gt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Te.boolean){let n=this._getOrReturnCtx(t);return ke(n,{code:me.invalid_type,expected:Te.boolean,received:n.parsedType}),dt}return fs(t.data)}};zx.create=e=>new zx({typeName:ht.ZodBoolean,coerce:e?.coerce||!1,...Qt(e)});Vx=class e extends Gt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Te.date){let i=this._getOrReturnCtx(t);return ke(i,{code:me.invalid_type,expected:Te.date,received:i.parsedType}),dt}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return ke(i,{code:me.invalid_date}),dt}let n=new Wi,o;for(let i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(o=this._getOrReturnCtx(t,o),ke(o,{code:me.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(o=this._getOrReturnCtx(t,o),ke(o,{code:me.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):rr.assertNever(i);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:Ge.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Ge.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Vx.create=e=>new Vx({checks:[],coerce:e?.coerce||!1,typeName:ht.ZodDate,...Qt(e)});tI=class extends Gt{_parse(t){if(this._getType(t)!==Te.symbol){let n=this._getOrReturnCtx(t);return ke(n,{code:me.invalid_type,expected:Te.symbol,received:n.parsedType}),dt}return fs(t.data)}};tI.create=e=>new tI({typeName:ht.ZodSymbol,...Qt(e)});Yx=class extends Gt{_parse(t){if(this._getType(t)!==Te.undefined){let n=this._getOrReturnCtx(t);return ke(n,{code:me.invalid_type,expected:Te.undefined,received:n.parsedType}),dt}return fs(t.data)}};Yx.create=e=>new Yx({typeName:ht.ZodUndefined,...Qt(e)});Jx=class extends Gt{_parse(t){if(this._getType(t)!==Te.null){let n=this._getOrReturnCtx(t);return ke(n,{code:me.invalid_type,expected:Te.null,received:n.parsedType}),dt}return fs(t.data)}};Jx.create=e=>new Jx({typeName:ht.ZodNull,...Qt(e)});Dg=class extends Gt{constructor(){super(...arguments),this._any=!0}_parse(t){return fs(t.data)}};Dg.create=e=>new Dg({typeName:ht.ZodAny,...Qt(e)});im=class extends Gt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return fs(t.data)}};im.create=e=>new im({typeName:ht.ZodUnknown,...Qt(e)});Ql=class extends Gt{_parse(t){let r=this._getOrReturnCtx(t);return ke(r,{code:me.invalid_type,expected:Te.never,received:r.parsedType}),dt}};Ql.create=e=>new Ql({typeName:ht.ZodNever,...Qt(e)});rI=class extends Gt{_parse(t){if(this._getType(t)!==Te.undefined){let n=this._getOrReturnCtx(t);return ke(n,{code:me.invalid_type,expected:Te.void,received:n.parsedType}),dt}return fs(t.data)}};rI.create=e=>new rI({typeName:ht.ZodVoid,...Qt(e)});sm=class e extends Gt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==Te.array)return ke(r,{code:me.invalid_type,expected:Te.array,received:r.parsedType}),dt;if(o.exactLength!==null){let s=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(s||a)&&(ke(r,{code:s?me.too_big:me.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(ke(r,{code:me.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(ke(r,{code:me.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>o.type._parseAsync(new cu(r,s,r.path,a)))).then(s=>Wi.mergeArray(n,s));let i=[...r.data].map((s,a)=>o.type._parseSync(new cu(r,s,r.path,a)));return Wi.mergeArray(n,i)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Ge.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Ge.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Ge.toString(r)}})}nonempty(t){return this.min(1,t)}};sm.create=(e,t)=>new sm({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ht.ZodArray,...Qt(t)});Sa=class e extends Gt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=rr.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Te.object){let u=this._getOrReturnCtx(t);return ke(u,{code:me.invalid_type,expected:Te.object,received:u.parsedType}),dt}let{status:n,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ql&&this._def.unknownKeys==="strip"))for(let u in o.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let l=i[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new cu(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Ql){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(ke(o,{code:me.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new cu(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Wi.mergeObjectSync(n,u)):Wi.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Ge.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:Ge.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ht.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of rr.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of rr.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return eI(this)}partial(t){let r={};for(let n of rr.objectKeys(this.shape)){let o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of rr.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof au;)i=i._def.innerType;r[n]=i}return new e({...this._def,shape:()=>r})}keyof(){return wxe(rr.objectKeys(this.shape))}};Sa.create=(e,t)=>new Sa({shape:()=>e,unknownKeys:"strip",catchall:Ql.create(),typeName:ht.ZodObject,...Qt(t)});Sa.strictCreate=(e,t)=>new Sa({shape:()=>e,unknownKeys:"strict",catchall:Ql.create(),typeName:ht.ZodObject,...Qt(t)});Sa.lazycreate=(e,t)=>new Sa({shape:e,unknownKeys:"strip",catchall:Ql.create(),typeName:ht.ZodObject,...Qt(t)});Kx=class extends Gt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new ba(a.ctx.common.issues));return ke(r,{code:me.invalid_union,unionErrors:s}),dt}if(r.common.async)return Promise.all(n.map(async i=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await i._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!i&&(i={result:l,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(i)return r.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(c=>new ba(c));return ke(r,{code:me.invalid_union,unionErrors:a}),dt}}get options(){return this._def.options}};Kx.create=(e,t)=>new Kx({options:e,typeName:ht.ZodUnion,...Qt(t)});om=e=>e instanceof Xx?om(e.schema):e instanceof uu?om(e.innerType()):e instanceof eE?[e.value]:e instanceof tE?e.options:e instanceof rE?rr.objectValues(e.enum):e instanceof nE?om(e._def.innerType):e instanceof Yx?[void 0]:e instanceof Jx?[null]:e instanceof au?[void 0,...om(e.unwrap())]:e instanceof sf?[null,...om(e.unwrap())]:e instanceof qR||e instanceof iE?om(e.unwrap()):e instanceof oE?om(e._def.innerType):[],kM=class e extends Gt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Te.object)return ke(r,{code:me.invalid_type,expected:Te.object,received:r.parsedType}),dt;let n=this.discriminator,o=r.data[n],i=this.optionsMap.get(o);return i?r.common.async?i._parseAsync({data:r.data,path:r.path,parent:r}):i._parseSync({data:r.data,path:r.path,parent:r}):(ke(r,{code:me.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),dt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let o=new Map;for(let i of r){let s=om(i.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,i)}}return new e({typeName:ht.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...Qt(n)})}};Zx=class extends Gt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=(i,s)=>{if(IM(i)||IM(s))return dt;let a=fJ(i.value,s.value);return a.valid?((wM(i)||wM(s))&&r.dirty(),{status:r.value,value:a.data}):(ke(n,{code:me.invalid_intersection_types}),dt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Zx.create=(e,t,r)=>new Zx({left:e,right:t,typeName:ht.ZodIntersection,...Qt(r)});of=class e extends Gt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Te.array)return ke(n,{code:me.invalid_type,expected:Te.array,received:n.parsedType}),dt;if(n.data.length<this._def.items.length)return ke(n,{code:me.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),dt;!this._def.rest&&n.data.length>this._def.items.length&&(ke(n,{code:me.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let i=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new cu(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(i).then(s=>Wi.mergeArray(r,s)):Wi.mergeArray(r,i)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};of.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new of({items:e,typeName:ht.ZodTuple,rest:null,...Qt(t)})};vM=class e extends Gt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Te.object)return ke(n,{code:me.invalid_type,expected:Te.object,received:n.parsedType}),dt;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in n.data)o.push({key:i._parse(new cu(n,a,n.path,a)),value:s._parse(new cu(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Wi.mergeObjectAsync(r,o):Wi.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Gt?new e({keyType:t,valueType:r,typeName:ht.ZodRecord,...Qt(n)}):new e({keyType:Tg.create(),valueType:t,typeName:ht.ZodRecord,...Qt(r)})}},nI=class extends Gt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Te.map)return ke(n,{code:me.invalid_type,expected:Te.map,received:n.parsedType}),dt;let o=this._def.keyType,i=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new cu(n,a,n.path,[u,"key"])),value:i._parse(new cu(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return dt;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return dt;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};nI.create=(e,t,r)=>new nI({valueType:t,keyType:e,typeName:ht.ZodMap,...Qt(r)});oI=class e extends Gt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Te.set)return ke(n,{code:me.invalid_type,expected:Te.set,received:n.parsedType}),dt;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(ke(n,{code:me.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(ke(n,{code:me.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let i=this._def.valueType;function s(c){let u=new Set;for(let l of c){if(l.status==="aborted")return dt;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>i._parse(new cu(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:Ge.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Ge.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};oI.create=(e,t)=>new oI({valueType:e,minSize:null,maxSize:null,typeName:ht.ZodSet,...Qt(t)});RM=class e extends Gt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Te.function)return ke(r,{code:me.invalid_type,expected:Te.function,received:r.parsedType}),dt;function n(a,c){return GR({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ZC(),nm].filter(u=>!!u),issueData:{code:me.invalid_arguments,argumentsError:c}})}function o(a,c){return GR({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ZC(),nm].filter(u=>!!u),issueData:{code:me.invalid_return_type,returnTypeError:c}})}let i={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Qg){let a=this;return fs(async function(...c){let u=new ba([]),l=await a._def.args.parseAsync(c,i).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(d,i).catch(p=>{throw u.addIssue(o(d,p)),u})})}else{let a=this;return fs(function(...c){let u=a._def.args.safeParse(c,i);if(!u.success)throw new ba([n(c,u.error)]);let l=Reflect.apply(s,this,u.data),d=a._def.returns.safeParse(l,i);if(!d.success)throw new ba([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:of.create(t).rest(im.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||of.create([]).rest(im.create()),returns:r||im.create(),typeName:ht.ZodFunction,...Qt(n)})}},Xx=class extends Gt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Xx.create=(e,t)=>new Xx({getter:e,typeName:ht.ZodLazy,...Qt(t)});eE=class extends Gt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return ke(r,{received:r.data,code:me.invalid_literal,expected:this._def.value}),dt}return{status:"valid",value:t.data}}get value(){return this._def.value}};eE.create=(e,t)=>new eE({value:e,typeName:ht.ZodLiteral,...Qt(t)});tE=class e extends Gt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return ke(r,{expected:rr.joinValues(n),received:r.parsedType,code:me.invalid_type}),dt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return ke(r,{received:r.data,code:me.invalid_enum_value,options:n}),dt}return fs(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};tE.create=wxe;rE=class extends Gt{_parse(t){let r=rr.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Te.string&&n.parsedType!==Te.number){let o=rr.objectValues(r);return ke(n,{expected:rr.joinValues(o),received:n.parsedType,code:me.invalid_type}),dt}if(this._cache||(this._cache=new Set(rr.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=rr.objectValues(r);return ke(n,{received:n.data,code:me.invalid_enum_value,options:o}),dt}return fs(t.data)}get enum(){return this._def.values}};rE.create=(e,t)=>new rE({values:e,typeName:ht.ZodNativeEnum,...Qt(t)});Qg=class extends Gt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Te.promise&&r.common.async===!1)return ke(r,{code:me.invalid_type,expected:Te.promise,received:r.parsedType}),dt;let n=r.parsedType===Te.promise?r.data:Promise.resolve(r.data);return fs(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Qg.create=(e,t)=>new Qg({type:e,typeName:ht.ZodPromise,...Qt(t)});uu=class extends Gt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ht.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{ke(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(n.data,i);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return dt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?dt:c.status==="dirty"?jx(c.value):r.value==="dirty"?jx(c.value):c});{if(r.value==="aborted")return dt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?dt:a.status==="dirty"?jx(a.value):r.value==="dirty"?jx(a.value):a}}if(o.type==="refinement"){let s=a=>{let c=o.refinement(a,i);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?dt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?dt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!_g(s))return dt;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>_g(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:r.value,value:a})):dt);rr.assertNever(o)}};uu.create=(e,t,r)=>new uu({schema:e,typeName:ht.ZodEffects,effect:t,...Qt(r)});uu.createWithPreprocess=(e,t,r)=>new uu({schema:t,effect:{type:"preprocess",transform:e},typeName:ht.ZodEffects,...Qt(r)});au=class extends Gt{_parse(t){return this._getType(t)===Te.undefined?fs(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};au.create=(e,t)=>new au({innerType:e,typeName:ht.ZodOptional,...Qt(t)});sf=class extends Gt{_parse(t){return this._getType(t)===Te.null?fs(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};sf.create=(e,t)=>new sf({innerType:e,typeName:ht.ZodNullable,...Qt(t)});nE=class extends Gt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Te.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};nE.create=(e,t)=>new nE({innerType:e,typeName:ht.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Qt(t)});oE=class extends Gt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return XC(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ba(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ba(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};oE.create=(e,t)=>new oE({innerType:e,typeName:ht.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Qt(t)});iI=class extends Gt{_parse(t){if(this._getType(t)!==Te.nan){let n=this._getOrReturnCtx(t);return ke(n,{code:me.invalid_type,expected:Te.nan,received:n.parsedType}),dt}return{status:"valid",value:t.data}}};iI.create=e=>new iI({typeName:ht.ZodNaN,...Qt(e)});mht=Symbol("zod_brand"),qR=class extends Gt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},zR=class e extends Gt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?dt:i.status==="dirty"?(r.dirty(),jx(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?dt:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:ht.ZodPipeline})}},iE=class extends Gt{_parse(t){let r=this._def.innerType._parse(t),n=o=>(_g(o)&&(o.value=Object.freeze(o.value)),o);return XC(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};iE.create=(e,t)=>new iE({innerType:e,typeName:ht.ZodReadonly,...Qt(t)});hht={object:Sa.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ht||(ht={}));ght=(e,t={message:`Input not instance of ${e.name}`})=>kxe(r=>r instanceof e,t),vxe=Tg.create,Rxe=Gx.create,Aht=iI.create,yht=qx.create,Bxe=zx.create,xht=Vx.create,Eht=tI.create,bht=Yx.create,Sht=Jx.create,Cht=Dg.create,Iht=im.create,wht=Ql.create,kht=rI.create,vht=sm.create,Rht=Sa.create,Bht=Sa.strictCreate,_ht=Kx.create,Tht=kM.create,Dht=Zx.create,Qht=of.create,Oht=vM.create,Nht=nI.create,Pht=oI.create,Mht=RM.create,Fht=Xx.create,Lht=eE.create,Uht=tE.create,$ht=rE.create,Hht=Qg.create,Wht=uu.create,jht=au.create,Ght=sf.create,qht=uu.createWithPreprocess,zht=zR.create,Vht=()=>vxe().optional(),Yht=()=>Rxe().optional(),Jht=()=>Bxe().optional(),Kht={string:e=>Tg.create({...e,coerce:!0}),number:e=>Gx.create({...e,coerce:!0}),boolean:e=>zx.create({...e,coerce:!0}),bigint:e=>qx.create({...e,coerce:!0}),date:e=>Vx.create({...e,coerce:!0})},Zht=dt});var Ee={};tr(Ee,{BRAND:()=>mht,DIRTY:()=>jx,EMPTY_PATH:()=>qmt,INVALID:()=>dt,NEVER:()=>Zht,OK:()=>fs,ParseStatus:()=>Wi,Schema:()=>Gt,ZodAny:()=>Dg,ZodArray:()=>sm,ZodBigInt:()=>qx,ZodBoolean:()=>zx,ZodBranded:()=>qR,ZodCatch:()=>oE,ZodDate:()=>Vx,ZodDefault:()=>nE,ZodDiscriminatedUnion:()=>kM,ZodEffects:()=>uu,ZodEnum:()=>tE,ZodError:()=>ba,ZodFirstPartyTypeKind:()=>ht,ZodFunction:()=>RM,ZodIntersection:()=>Zx,ZodIssueCode:()=>me,ZodLazy:()=>Xx,ZodLiteral:()=>eE,ZodMap:()=>nI,ZodNaN:()=>iI,ZodNativeEnum:()=>rE,ZodNever:()=>Ql,ZodNull:()=>Jx,ZodNullable:()=>sf,ZodNumber:()=>Gx,ZodObject:()=>Sa,ZodOptional:()=>au,ZodParsedType:()=>Te,ZodPipeline:()=>zR,ZodPromise:()=>Qg,ZodReadonly:()=>iE,ZodRecord:()=>vM,ZodSchema:()=>Gt,ZodSet:()=>oI,ZodString:()=>Tg,ZodSymbol:()=>tI,ZodTransformer:()=>uu,ZodTuple:()=>of,ZodType:()=>Gt,ZodUndefined:()=>Yx,ZodUnion:()=>Kx,ZodUnknown:()=>im,ZodVoid:()=>rI,addIssueToContext:()=>ke,any:()=>Cht,array:()=>vht,bigint:()=>yht,boolean:()=>Bxe,coerce:()=>Kht,custom:()=>kxe,date:()=>xht,datetimeRegex:()=>Ixe,defaultErrorMap:()=>nm,discriminatedUnion:()=>Tht,effect:()=>Wht,enum:()=>Uht,function:()=>Mht,getErrorMap:()=>ZC,getParsedType:()=>nf,instanceof:()=>ght,intersection:()=>Dht,isAborted:()=>IM,isAsync:()=>XC,isDirty:()=>wM,isValid:()=>_g,late:()=>hht,lazy:()=>Fht,literal:()=>Lht,makeIssue:()=>GR,map:()=>Nht,nan:()=>Aht,nativeEnum:()=>$ht,never:()=>wht,null:()=>Sht,nullable:()=>Ght,number:()=>Rxe,object:()=>Rht,objectUtil:()=>cJ,oboolean:()=>Jht,onumber:()=>Yht,optional:()=>jht,ostring:()=>Vht,pipeline:()=>zht,preprocess:()=>qht,promise:()=>Hht,quotelessJson:()=>Wmt,record:()=>Oht,set:()=>Pht,setErrorMap:()=>Gmt,strictObject:()=>Bht,string:()=>vxe,symbol:()=>Eht,transformer:()=>Wht,tuple:()=>Qht,undefined:()=>bht,union:()=>_ht,unknown:()=>Iht,util:()=>rr,void:()=>kht});var pJ=h(()=>{CM();lJ();yxe();jR();_xe();SM()});var BM=h(()=>{pJ();pJ()});function Dxe(e){let t=e[Xht];if(typeof t=="string"&&t.length>0)return{ANTHROPIC_API_KEY:t,ANTHROPIC_BASE_URL:egt,CLAUDE_CODE_SIMPLE:tgt}}var Xht,egt,Txe,tgt,Qxe=h(()=>{"use strict";Xht="MINIMAX_API_KEY",egt="https://api.minimax.io/anthropic",Txe="MiniMax-M3",tgt="1"});function Oxe(e){for(let t of rgt){let r=e[t];if(typeof r=="string"&&r.length>0)return{envVar:t,keyValue:r}}}function Nxe(e){return e?{[e.envVar]:e.keyValue}:void 0}var rgt,Pxe=h(()=>{"use strict";rgt=["OPENAI_API_KEY","MINIMAX_API_KEY","OPENROUTER_API_KEY"]});function sI(e){return e==="codex"||e==="opencode"||e==="claude-minimax"?e:"claude"}function VR(e){return TM[e].structuredOutput===!0}var mJ,_M,hJ,TM,YR=h(()=>{"use strict";Qxe();Pxe();mJ=["low","medium","high","xhigh"],_M=["low","medium","high","xhigh","max"],hJ=["low"],TM={claude:{efforts:_M,channel:"effort",factory:"claudeCode",structuredOutput:!0},codex:{efforts:mJ,channel:"effort",factory:"codex"},opencode:{efforts:_M,channel:"variant",factory:"opencode",resolveAuthEnv:e=>Nxe(Oxe(e))},"claude-minimax":{efforts:hJ,channel:"effort",factory:"claudeCode",forcedModel:Txe,defaultEffort:"low",resolveAuthEnv:Dxe}}});import{readFileSync as ngt}from"node:fs";function ogt(e){let t=Mxe.indexOf(e);return t<=0?"validate":Mxe[t-1]}function Fxe(){return{...DM}}function sgt(e){let t={},r=[],n=[],o={};for(let i of e.split(`
21
21
  `)){i=i.replace(/\r$/,"");let s=i;if(!/".*"/.test(s)&&!/'.*'/.test(s)){let m=s.indexOf("#");m>=0&&(s=s.slice(0,m))}if(s.replace(/\s/g,"")==="")continue;let c=(s.match(/^\s*/)?.[0]??"").length;if(c%2!==0)throw new af;let u=s.slice(c).replace(/\s+$/,"");if(/^-(\s|$)/.test(u)){for(;n.length>0&&n[n.length-1]>=c;)r.pop(),n.pop();if(r.length===0)throw new af;let m=u.slice(1).replace(/^\s+/,"");if(m==="")throw new af;if(m[0]==='"'||m[0]==="'"){let E=m[0],y=m.indexOf(E,1);if(y>0){let b=m.slice(y+1).trimStart();(b===""||b.startsWith("#"))&&(m=m.slice(0,y+1))}}if(m.startsWith('"')){if(!m.endsWith('"')||m.length<2)throw new af;m=m.slice(1,-1)}else if(m.startsWith("'")){if(!m.endsWith("'")||m.length<2)throw new af;m=m.slice(1,-1)}let g=r.join("."),A=o[g]??0;o[g]=A+1,t[`${g}.${A}`]=m;continue}if(!/^[a-zA-Z_][a-zA-Z0-9_-]*:/.test(u))throw new af;let l=u.indexOf(":"),d=u.slice(0,l),f=u.slice(l+1).replace(/^\s+/,"");if(f[0]==='"'||f[0]==="'"){let m=f[0],g=f.indexOf(m,1);if(g>0){let A=f.slice(g+1).trimStart();(A===""||A.startsWith("#"))&&(f=f.slice(0,g+1))}}if(f.startsWith('"')){if(!f.endsWith('"')||f.length<2)throw new af;f=f.slice(1,-1)}else if(f.startsWith("'")){if(!f.endsWith("'")||f.length<2)throw new af;f=f.slice(1,-1)}for(;n.length>0&&n[n.length-1]>=c;)r.pop(),n.pop();let p=r.length>0?`${r.join(".")}.${d}`:d;f===""?(r.push(d),n.push(c)):t[p]=f}return t}function Cr(e,t={}){let r=t.read??agt,n=t.warn??cgt,o=Fxe(),i=r(e);if(i===void 0)return o;let s;try{s=sgt(i)}catch{return n(`[afk:config] warn: malformed YAML in ${e} \u2014 using defaults`),Fxe()}let a=new Set;for(let[c,u]of Object.entries(s))o[c]=u,a.add(c);for(let[c,u]of Object.entries(s)){let l=/^plugins\.dev\.(.+)$/.exec(c);if(!l)continue;let d=l[1],f=d==="afk"||d.startsWith("afk.")?d:`dev.${d}`;o[f]=u,a.add(f)}return a.size>0&&(o["\0explicit"]=Array.from(a).join("")),o}function Pe(e,t){return e[t]??""}function Lxe(e,t,r){let n=`afk.models.${e}.${t}.${r}`;return Object.prototype.hasOwnProperty.call(DM,n)?n:void 0}function Uxe(e,t){return igt.includes(e)?e:t}function Ca(e,t,r="think",n={}){let o=sI(t),i=QM.includes(r)?r:"think",s=n.RED_AFK_TASK_TIER_DOWNGRADE==="1"?ogt(i):i,a=Lxe(o,s,"model"),c=Lxe(o,s,"effort"),u=DM[a],l=DM[c],d=Pe(e,a),f=Pe(e,`afk.models.${o}.base.model`),p=Pe(e,`afk.models.${o}.base.effort`),m=Pe(e,`afk.models.${o}`),g=Pe(e,"afk.model"),A=Pe(e,c),E=new Set((e["\0explicit"]??"").split("").filter(Boolean)),y=(n.RED_AFK_MODEL??"").trim(),b=(n.RED_AFK_EFFORT??"").trim(),I=d&&(d!==u||E.has(a))?d:f||m||g||u,w=A&&(A!==l||E.has(c))?A:p||l;return{model:y.length>0?y:I,effort:b.length>0?Uxe(b,l):Uxe(w,l)}}function OM(e){let t=[];for(let n=0;;n++){let o=e[`afk.backpressure.${n}`];if(o===void 0)break;o.trim()!==""&&t.push(o)}if(t.length>0)return t;let r=e["afk.backpressure"];return r&&r.trim()!==""?[r]:[]}function $xe(e){let t=[];for(let n=0;;n++){let o=e[`afk.post_attempt_format.${n}`];if(o===void 0)break;o.trim()!==""&&t.push(o)}if(t.length>0)return t;let r=e["afk.post_attempt_format"];return r&&r.trim()!==""?[r]:[]}function Hxe(e=process.env){let t=(e.RED_AFK_MERGE_CI_TIMEOUT_S??"").trim(),r=Number.parseInt(t,10);return Number.isInteger(r)&&r>0?r:ugt}var DM,QM,Mxe,igt,Ebr,af,agt,cgt,ugt,Mo=h(()=>{"use strict";BM();YR();DM={"afk.default_runner":"claude","afk.fleet.target":"2","afk.models.claude.validate.model":"claude-haiku-4-5","afk.models.claude.validate.effort":"low","afk.models.claude.simple.model":"claude-sonnet-4-6","afk.models.claude.simple.effort":"high","afk.models.claude.complex.model":"claude-opus-4-8","afk.models.claude.complex.effort":"medium","afk.models.claude.think.model":"claude-opus-4-8","afk.models.claude.think.effort":"high","afk.models.codex.validate.model":"gpt-5.5","afk.models.codex.validate.effort":"low","afk.models.codex.simple.model":"gpt-5.5","afk.models.codex.simple.effort":"high","afk.models.codex.complex.model":"gpt-5.5","afk.models.codex.complex.effort":"medium","afk.models.codex.think.model":"gpt-5.5","afk.models.codex.think.effort":"high","afk.models.opencode.validate.model":"openrouter/anthropic/claude-3.5-haiku","afk.models.opencode.validate.effort":"low","afk.models.opencode.simple.model":"openrouter/anthropic/claude-sonnet-4","afk.models.opencode.simple.effort":"high","afk.models.opencode.complex.model":"openrouter/anthropic/claude-opus-4","afk.models.opencode.complex.effort":"medium","afk.models.opencode.think.model":"openrouter/anthropic/claude-opus-4","afk.models.opencode.think.effort":"high","afk.models.claude-minimax.validate.model":"MiniMax-M3","afk.models.claude-minimax.validate.effort":"low","afk.models.claude-minimax.simple.model":"MiniMax-M3","afk.models.claude-minimax.simple.effort":"low","afk.models.claude-minimax.complex.model":"MiniMax-M3","afk.models.claude-minimax.complex.effort":"low","afk.models.claude-minimax.think.model":"MiniMax-M3","afk.models.claude-minimax.think.effort":"low","afk.hooks.defaults.cargo":"true","afk.hooks.defaults.gradle":"true","afk.feedback.rebase_on_base":"false","afk.merge.wait_for_review":"false","afk.merge.review_check":"CodeRabbit","afk.merge.ci_aware":"false","afk.merge.native_queue":"false","afk.merge.land_lock":"true","afk.worktree_launches_pull_request":"true","afk.review_gate.enabled":"false","afk.review_gate.threshold":"complex","afk.release.channel":"stable","afk.claim_reaper.refresh_s":"300","afk.claim_reaper.stale_tolerance":"3","afk.claim_reaper.grace_s":"300","afk.claim_reaper.recent_commit_s":"2700","afk.worktree_pool.enabled":"false","afk.worktree_pool.max_size":"4","afk.worktree_pool.lease_ttl_s":"3600","afk.worktree_pool.min_idle_s":"1800","afk.companion.iteration_churn":"8","afk.companion.waiting_windows":"20","afk.companion.diff_drift_loc":"4000","afk.companion.min_progress_loc":"5","afk.notes_loop.enabled":"false","afk.notes_loop.max_iterations":"4","afk.notes_loop.inner_max_iterations":"0","afk.notes_loop.token_budget":"0","afk.notes_loop.wall_clock_s":"0","afk.landing.cascade_rebase":"true","dev.lock.primary-branch":"false","dev.triage.external_pr_surface.enabled":"false","dev.trunk":"main"},QM=["validate","simple","complex","think"],Mxe=QM;igt=["low","medium","high","xhigh","max"],Ebr=Ee.record(Ee.string()),af=class extends Error{constructor(t="malformed YAML"){super(t),this.name="MalformedConfigError"}};agt=e=>{try{return ngt(e,"utf8")}catch{return}},cgt=e=>{process.stderr.write(`${e}
@@ -823,7 +823,7 @@ requeued to ready-for-agent${e.activeBlocker?` (cleared active blocker: ${e.acti
823
823
  `)},w)}catch(k){return process.stderr.write(`[afk] respond failed: ${k instanceof Error?k.message:String(k)}
824
824
  `),1}return r.write(`Respond #${o}: ${v.action}${v.verb?` (/dev ${v.verb})`:""}.
825
825
  `),0}TC();function kyr(e){let t=e.indexOf("--runner");return(t>=0?e[t+1]:void 0)==="claude"?"claude":"codex"}function vyr(e){let t=$P(void 0,{runner:e});return JSON.stringify(e==="codex"?{systemMessage:t}:{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:t}})}async function Dft(e){let t=kyr(e),r=$P(void 0,{runner:t});return process.stdout.write(e.includes("--hook")?vyr(t):r),e.includes("--hook")&&process.stdout.write(`
826
- `),0}import{existsSync as cxr,statSync as uxr}from"node:fs";import{join as Vft,basename as lxr}from"node:path";function _Y(e){let t={app:e,version:Ryr(TR("__RED_BUILD_VERSION__",()=>"2.33.5")??"0.0.0-dev"),gitSha:TR("__RED_BUILD_GIT_SHA__",()=>"6ef5daf4fc41cc2b6f117cbb366b92f53caa8594")??"unknown",buildTime:TR("__RED_BUILD_TIME__",()=>"2026-07-12T15:21:43-03:00")??"unknown",bundleAsset:TR("__RED_BUNDLE_ASSET__",()=>"dev.bundle.min.mjs")??"unknown"},r=TR("__REDDB_SDK_VERSION__",()=>""),n=TR("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Ryr(e){return e.startsWith("v")?e.slice(1):e}function Qft(e){return`${e.app} ${e.version} ${e.gitSha}`}function TR(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function TY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.floor(e/1e3)}k`:String(e)}function Pft(e){let t=(r,n)=>{let o=(Math.round(r*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${n}`};return e>=1e9?t(e/1e9,"B"):e>=1e6?t(e/1e6,"M"):e>=1e3?t(e/1e3,"k"):String(e>0?e:0)}function Mft(e){let t=e.toLowerCase();for(let r of["opus","sonnet","haiku","fable"])if(t.includes(r))return r;return e}function Byr(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60);if(r<60)return`${r}m${t%60}s`;let n=Math.floor(r/60);return n<24?`${n}h${r%60}m`:`${Math.floor(n/24)}d${n%24}h`}function DR(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let r=Math.floor(t/60),n=t%60;return n>0?`${r}h${n}m`:`${r}h`}function Oft(e){let t=e.basename;if(e.branch){let r=e.branch;return r.length>28&&(r=`${r.slice(0,27)}\u2026`),`${t} (${r})`}return e.detachedSha?`${t} (detached ${e.detachedSha})`:t}function _yr(e){return!e||!e.model?null:e.effort?`${e.model}\xB7${e.effort}`:e.model}function Nft(e){if(!e)return null;let t=e.contextTokens;if(t===void 0||t===0)return null;let r=TY(t);return e.contextPercent===void 0?r:`${r} ${Math.round(e.contextPercent)}%`}function Tyr(e){if(!e||e.workers<=0)return[];let t=[],r=(i,s)=>{t.push({label:i,value:s,suffix:""})};if(e.workers>0&&r("wrk=",String(e.workers)),e.sourceCounts&&e.sourceCounts.length>0)for(let{origin:i,count:s}of e.sourceCounts)r(`${i}=`,String(s));let n=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";if(e.queue>0&&t.push({label:"rdy=",value:String(e.queue),suffix:n}),e.human>0){let i=n&&e.queue===0?n:"";t.push({label:"hmn=",value:String(e.human),suffix:i})}e.blocked>0&&r("blk=",String(e.blocked));let o=[];return e.added>0&&o.push(`+${e.added}`),e.removed>0&&o.push(`-${e.removed}`),o.length&&r("loc=",e.locIsPeak?`~${o.join(" ")}`:o.join(" ")),e.waiting!==void 0&&e.waiting>0&&r("wai=",String(e.waiting)),e.tokens!==void 0&&e.tokens>0&&r("tok=",TY(e.tokens)),e.costUsd!==void 0&&e.costUsd>0&&r("usd=",e.costUsd.toFixed(2)),e.issues.forEach((i,s)=>{let a=e.phases?.[s],c=e.aliveMs?.[s],u=a?`\xB7${a}`:"";c!==void 0&&c>0&&(u+=`\xB7${Byr(c)}`),t.push({label:"#",value:String(i),suffix:u})}),t}function Dyr(e){if(!e)return null;let t=[];return e.usage5h!==void 0&&t.push(`5h=${Math.round(e.usage5h)}%`),e.usage7d!==void 0&&t.push(`7d=${Math.round(e.usage7d)}%`),t.length?t.join(" "):null}function Qyr(e){if(!e)return null;let t=[],r=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(`prs=${e.openPrs}${r}`),e.todayPrs&&e.todayPrs>0){let o=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(`cpr=${e.todayPrs}${o}`)}if(e.openIssues&&e.openIssues>0){let o=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(`iss=${e.openIssues}${o}`)}let n=[];return e.localAdded&&e.localAdded>0&&n.push(`+${e.localAdded}`),e.localRemoved&&e.localRemoved>0&&n.push(`-${e.localRemoved}`),n.length&&t.push(`loc=${n.join(" ")}`),t.length?t.join(" "):null}function Oyr(e){if(!e||!e.openIssues||e.openIssues<=0)return null;let t=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";return`iss=${e.openIssues}${t}`}function fye(e){if(!e)return null;let t=e.runner||"?",r=Math.max(0,Math.floor(e.busy)),n=Math.max(0,Math.floor(e.total)),o=Math.max(0,Math.floor(e.queue)),i=[`flt=${t} ${r}/${n} busy`,`q=${o}`];return e.parked!==void 0&&e.parked>0&&i.push(`park=${Math.floor(e.parked)}`),i.join(" \xB7 ")}function Nyr(e){let t=Tyr(e);return t.length===0?null:t.map(r=>`${r.label}${r.value}${r.suffix}`).join(" ")}function Fft(e,t="full"){if(t==="short"){let u=[Oft(e.project)],l=Nft(e.claude);l!==null&&u.push(`ctx=${l}`);let d=Oyr(e.repo);return d!==null&&u.push(d),u.join(" \xB7 ")}let r=[Oft(e.project)],n=_yr(e.claude);n!==null&&r.push(n);let o=Nft(e.claude);o!==null&&r.push(o);let i=Dyr(e.claude);i!==null&&r.push(i);let s=Qyr(e.repo);s!==null&&r.push(s);let a=fye(e.fleet);a!==null&&r.push(a);let c=Nyr(e.afk);return c!==null&&r.push(c),r.join(" \xB7 ")}var Pyr="\x1B[48;2;114;47;55m",Myr="\x1B[48;2;88;36;42m",Uft="\x1B[49m",PC="\x1B[38;2;255;255;255m",$ft="\x1B[38;2;255;214;214m",Hft="\x1B[39m",OY="\x1B[38;2;224;138;148m",DY="\x1B[38;2;201;150;158m",Fyr="\x1B[38;2;240;200;120m",Wft="\x1B[1m",jft="\x1B[22m",Gft="\x1B[0m",Lyr=28,Uyr=" ",QY=["workerId","run","org","iss","phase","elapsed","loc","tks","tls","rsn","txt"],$yr=["workerId","iss","phase","elapsed"],Hyr=new Set(["requeue"]),Wyr=new Set(["gate","push-pr","merge","cascade"]),jyr=e=>e.replace(/\x1b\[[0-9;]*m/g,"");function qft(e){return jyr(e).length}function Gyr(e,t){return e+" ".repeat(Math.max(0,t-qft(e)))}var Px=(e,t)=>`${$ft}${e}=${Hft}${t}${OY}`;function qyr(e,t){let r=[];return e&&e>0&&r.push(`+${e}`),t&&t>0&&r.push(`-${t}`),r.length?r.join(" "):null}function zyr(e){return e.runner==="claude"&&e.tokens===0?"\u2014":Pft(e.tokens)}function Vyr(e,t=!0){let r="";if(e.branch){let o=e.branch.length>Lyr?`${e.branch.slice(0,27)}\u2026`:e.branch;r=` ${DY}(${o})${PC}`}else e.detachedSha&&(r=` ${DY}(detached ${e.detachedSha})${PC}`);let n=t&&e.version?` ${DY}v${e.version}${PC}`:"";return`${Fyr}\xBB${PC} ${Wft}${e.basename}${jft}${r}${n}`}function Yyr(e){return!e||!e.model?null:e.effort?`${e.model}${DY}\xB7${PC}${e.effort}`:e.model}function Lft(e){if(!e||!e.contextTokens)return null;let t=TY(e.contextTokens),r=e.contextPercent===void 0?t:`${t} ${Math.round(e.contextPercent)}%`;return Px("ctx",r)}function Jyr(e){if(!e)return[];let t=[];return e.usage5h!==void 0&&t.push(Px("5h",`${Math.round(e.usage5h)}%`)),e.usage7d!==void 0&&t.push(Px("7d",`${Math.round(e.usage7d)}%`)),t}function Kyr(e){if(!e)return[];let t=[],r=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(Px("prs",String(e.openPrs))+r),e.todayPrs&&e.todayPrs>0){let n=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(Px("cpr",String(e.todayPrs))+n)}if(e.openIssues&&e.openIssues>0){let n=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(Px("iss",String(e.openIssues))+n)}return t}function Zyr(e){if(!e)return[];let t=qyr(e.localAdded,e.localRemoved);return t?[Px("loc",t)]:[]}function Xyr(e){let t=fye(e);return t?[t]:[]}function exr(e,t,r,n,o="full"){let i=`${Myr}${PC} ${Vyr(e,o==="full")} `,s=Yyr(t);o==="full"&&s!==null&&(i+=`${Pyr}${PC} ${s} `),i+=`${Uft}${OY}`;let a=o==="short"?[Lft(t),r&&r.openIssues&&r.openIssues>0?Px("iss",String(r.openIssues))+(r.cacheAgeS!==void 0?` (${DR(r.cacheAgeS)})`:""):null].filter(c=>c!==null):[Lft(t),...Jyr(t),...Kyr(r),...Zyr(r),...Xyr(n)].filter(c=>c!==null);return a.length&&(i+=` ${a.join(" ")}`),`${i}${Gft}`}function txr(e,t){return[e,t].filter(Boolean).join("\xB7")}function rxr(e,t){let r=Odt(e,t),n=[r.runner,r.model?Mft(r.model):void 0,r.effort].filter(s=>!!s).join(" "),o=Wyr.has(r.phase),i=o||r.origin!==void 0&&Hyr.has(r.origin);return{workerId:r.workerId,run:`run=${n}`,org:`org=${o?"landing":r.origin||"afk"}`,iss:r.issue===null?"":`iss=${String(r.issue)}`,phase:r.issue===null?"":txr(r.phase,r.activity),elapsed:r.elapsed,loc:i?"":`loc=${rM(r.added,r.removed)}`,tks:i?"":`tks=${zyr(r)}`,tls:i?"":`tls=${String(r.tools)}`,rsn:i?"":`rsn=${String(r.reasoning)}`,txt:i?"":`txt=${String(r.text)}`}}function nxr(e,t=QY){let r=Object.fromEntries(QY.map(n=>[n,0]));for(let n of e)for(let o of t)r[o]=Math.max(r[o],qft(n[o]));return r}function oxr(e,t){if(e==="workerId")return`${Wft}${t}${jft}`;let r=t.indexOf("=");return r>0?`${$ft}${t.slice(0,r+1)}${Hft}${t.slice(r+1)}${OY}`:t}function ixr(e,t,r=QY){let n=r.map(o=>oxr(o,Gyr(e[o],t[o])));return`${Uft}${OY}${n.join(Uyr)}${Gft}`}function sxr(e,t,r="full"){let n=e.map(s=>rxr(s,t)),o=r==="short"?$yr:QY,i=nxr(n,o);return n.map(s=>ixr(s,i,o))}function axr(e,t={}){let r=t.preset??"full",n=[exr(e.project,e.claude,e.repo,e.fleet,r)],o=t.now??0;return n.push(...sxr(t.workers??[],o,r)),n.join(`
826
+ `),0}import{existsSync as cxr,statSync as uxr}from"node:fs";import{join as Vft,basename as lxr}from"node:path";function _Y(e){let t={app:e,version:Ryr(TR("__RED_BUILD_VERSION__",()=>"2.33.7")??"0.0.0-dev"),gitSha:TR("__RED_BUILD_GIT_SHA__",()=>"1df8f1f70e01908504ddf08c07d85ae00a44090a")??"unknown",buildTime:TR("__RED_BUILD_TIME__",()=>"2026-07-12T16:04:46-03:00")??"unknown",bundleAsset:TR("__RED_BUNDLE_ASSET__",()=>"dev.bundle.min.mjs")??"unknown"},r=TR("__REDDB_SDK_VERSION__",()=>""),n=TR("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Ryr(e){return e.startsWith("v")?e.slice(1):e}function Qft(e){return`${e.app} ${e.version} ${e.gitSha}`}function TR(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}function TY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.floor(e/1e3)}k`:String(e)}function Pft(e){let t=(r,n)=>{let o=(Math.round(r*10)/10).toFixed(1);return`${o.endsWith(".0")?o.slice(0,-2):o}${n}`};return e>=1e9?t(e/1e9,"B"):e>=1e6?t(e/1e6,"M"):e>=1e3?t(e/1e3,"k"):String(e>0?e:0)}function Mft(e){let t=e.toLowerCase();for(let r of["opus","sonnet","haiku","fable"])if(t.includes(r))return r;return e}function Byr(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60);if(r<60)return`${r}m${t%60}s`;let n=Math.floor(r/60);return n<24?`${n}h${r%60}m`:`${Math.floor(n/24)}d${n%24}h`}function DR(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let r=Math.floor(t/60),n=t%60;return n>0?`${r}h${n}m`:`${r}h`}function Oft(e){let t=e.basename;if(e.branch){let r=e.branch;return r.length>28&&(r=`${r.slice(0,27)}\u2026`),`${t} (${r})`}return e.detachedSha?`${t} (detached ${e.detachedSha})`:t}function _yr(e){return!e||!e.model?null:e.effort?`${e.model}\xB7${e.effort}`:e.model}function Nft(e){if(!e)return null;let t=e.contextTokens;if(t===void 0||t===0)return null;let r=TY(t);return e.contextPercent===void 0?r:`${r} ${Math.round(e.contextPercent)}%`}function Tyr(e){if(!e||e.workers<=0)return[];let t=[],r=(i,s)=>{t.push({label:i,value:s,suffix:""})};if(e.workers>0&&r("wrk=",String(e.workers)),e.sourceCounts&&e.sourceCounts.length>0)for(let{origin:i,count:s}of e.sourceCounts)r(`${i}=`,String(s));let n=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";if(e.queue>0&&t.push({label:"rdy=",value:String(e.queue),suffix:n}),e.human>0){let i=n&&e.queue===0?n:"";t.push({label:"hmn=",value:String(e.human),suffix:i})}e.blocked>0&&r("blk=",String(e.blocked));let o=[];return e.added>0&&o.push(`+${e.added}`),e.removed>0&&o.push(`-${e.removed}`),o.length&&r("loc=",e.locIsPeak?`~${o.join(" ")}`:o.join(" ")),e.waiting!==void 0&&e.waiting>0&&r("wai=",String(e.waiting)),e.tokens!==void 0&&e.tokens>0&&r("tok=",TY(e.tokens)),e.costUsd!==void 0&&e.costUsd>0&&r("usd=",e.costUsd.toFixed(2)),e.issues.forEach((i,s)=>{let a=e.phases?.[s],c=e.aliveMs?.[s],u=a?`\xB7${a}`:"";c!==void 0&&c>0&&(u+=`\xB7${Byr(c)}`),t.push({label:"#",value:String(i),suffix:u})}),t}function Dyr(e){if(!e)return null;let t=[];return e.usage5h!==void 0&&t.push(`5h=${Math.round(e.usage5h)}%`),e.usage7d!==void 0&&t.push(`7d=${Math.round(e.usage7d)}%`),t.length?t.join(" "):null}function Qyr(e){if(!e)return null;let t=[],r=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(`prs=${e.openPrs}${r}`),e.todayPrs&&e.todayPrs>0){let o=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(`cpr=${e.todayPrs}${o}`)}if(e.openIssues&&e.openIssues>0){let o=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(`iss=${e.openIssues}${o}`)}let n=[];return e.localAdded&&e.localAdded>0&&n.push(`+${e.localAdded}`),e.localRemoved&&e.localRemoved>0&&n.push(`-${e.localRemoved}`),n.length&&t.push(`loc=${n.join(" ")}`),t.length?t.join(" "):null}function Oyr(e){if(!e||!e.openIssues||e.openIssues<=0)return null;let t=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";return`iss=${e.openIssues}${t}`}function fye(e){if(!e)return null;let t=e.runner||"?",r=Math.max(0,Math.floor(e.busy)),n=Math.max(0,Math.floor(e.total)),o=Math.max(0,Math.floor(e.queue)),i=[`flt=${t} ${r}/${n} busy`,`q=${o}`];return e.parked!==void 0&&e.parked>0&&i.push(`park=${Math.floor(e.parked)}`),i.join(" \xB7 ")}function Nyr(e){let t=Tyr(e);return t.length===0?null:t.map(r=>`${r.label}${r.value}${r.suffix}`).join(" ")}function Fft(e,t="full"){if(t==="short"){let u=[Oft(e.project)],l=Nft(e.claude);l!==null&&u.push(`ctx=${l}`);let d=Oyr(e.repo);return d!==null&&u.push(d),u.join(" \xB7 ")}let r=[Oft(e.project)],n=_yr(e.claude);n!==null&&r.push(n);let o=Nft(e.claude);o!==null&&r.push(o);let i=Dyr(e.claude);i!==null&&r.push(i);let s=Qyr(e.repo);s!==null&&r.push(s);let a=fye(e.fleet);a!==null&&r.push(a);let c=Nyr(e.afk);return c!==null&&r.push(c),r.join(" \xB7 ")}var Pyr="\x1B[48;2;114;47;55m",Myr="\x1B[48;2;88;36;42m",Uft="\x1B[49m",PC="\x1B[38;2;255;255;255m",$ft="\x1B[38;2;255;214;214m",Hft="\x1B[39m",OY="\x1B[38;2;224;138;148m",DY="\x1B[38;2;201;150;158m",Fyr="\x1B[38;2;240;200;120m",Wft="\x1B[1m",jft="\x1B[22m",Gft="\x1B[0m",Lyr=28,Uyr=" ",QY=["workerId","run","org","iss","phase","elapsed","loc","tks","tls","rsn","txt"],$yr=["workerId","iss","phase","elapsed"],Hyr=new Set(["requeue"]),Wyr=new Set(["gate","push-pr","merge","cascade"]),jyr=e=>e.replace(/\x1b\[[0-9;]*m/g,"");function qft(e){return jyr(e).length}function Gyr(e,t){return e+" ".repeat(Math.max(0,t-qft(e)))}var Px=(e,t)=>`${$ft}${e}=${Hft}${t}${OY}`;function qyr(e,t){let r=[];return e&&e>0&&r.push(`+${e}`),t&&t>0&&r.push(`-${t}`),r.length?r.join(" "):null}function zyr(e){return e.runner==="claude"&&e.tokens===0?"\u2014":Pft(e.tokens)}function Vyr(e,t=!0){let r="";if(e.branch){let o=e.branch.length>Lyr?`${e.branch.slice(0,27)}\u2026`:e.branch;r=` ${DY}(${o})${PC}`}else e.detachedSha&&(r=` ${DY}(detached ${e.detachedSha})${PC}`);let n=t&&e.version?` ${DY}v${e.version}${PC}`:"";return`${Fyr}\xBB${PC} ${Wft}${e.basename}${jft}${r}${n}`}function Yyr(e){return!e||!e.model?null:e.effort?`${e.model}${DY}\xB7${PC}${e.effort}`:e.model}function Lft(e){if(!e||!e.contextTokens)return null;let t=TY(e.contextTokens),r=e.contextPercent===void 0?t:`${t} ${Math.round(e.contextPercent)}%`;return Px("ctx",r)}function Jyr(e){if(!e)return[];let t=[];return e.usage5h!==void 0&&t.push(Px("5h",`${Math.round(e.usage5h)}%`)),e.usage7d!==void 0&&t.push(Px("7d",`${Math.round(e.usage7d)}%`)),t}function Kyr(e){if(!e)return[];let t=[],r=e.cacheAgeS!==void 0?` (${DR(e.cacheAgeS)})`:"";if(e.openPrs&&e.openPrs>0&&t.push(Px("prs",String(e.openPrs))+r),e.todayPrs&&e.todayPrs>0){let n=r&&(!e.openPrs||e.openPrs===0)?r:"";t.push(Px("cpr",String(e.todayPrs))+n)}if(e.openIssues&&e.openIssues>0){let n=r&&(!e.openPrs||e.openPrs===0)&&(!e.todayPrs||e.todayPrs===0)?r:"";t.push(Px("iss",String(e.openIssues))+n)}return t}function Zyr(e){if(!e)return[];let t=qyr(e.localAdded,e.localRemoved);return t?[Px("loc",t)]:[]}function Xyr(e){let t=fye(e);return t?[t]:[]}function exr(e,t,r,n,o="full"){let i=`${Myr}${PC} ${Vyr(e,o==="full")} `,s=Yyr(t);o==="full"&&s!==null&&(i+=`${Pyr}${PC} ${s} `),i+=`${Uft}${OY}`;let a=o==="short"?[Lft(t),r&&r.openIssues&&r.openIssues>0?Px("iss",String(r.openIssues))+(r.cacheAgeS!==void 0?` (${DR(r.cacheAgeS)})`:""):null].filter(c=>c!==null):[Lft(t),...Jyr(t),...Kyr(r),...Zyr(r),...Xyr(n)].filter(c=>c!==null);return a.length&&(i+=` ${a.join(" ")}`),`${i}${Gft}`}function txr(e,t){return[e,t].filter(Boolean).join("\xB7")}function rxr(e,t){let r=Odt(e,t),n=[r.runner,r.model?Mft(r.model):void 0,r.effort].filter(s=>!!s).join(" "),o=Wyr.has(r.phase),i=o||r.origin!==void 0&&Hyr.has(r.origin);return{workerId:r.workerId,run:`run=${n}`,org:`org=${o?"landing":r.origin||"afk"}`,iss:r.issue===null?"":`iss=${String(r.issue)}`,phase:r.issue===null?"":txr(r.phase,r.activity),elapsed:r.elapsed,loc:i?"":`loc=${rM(r.added,r.removed)}`,tks:i?"":`tks=${zyr(r)}`,tls:i?"":`tls=${String(r.tools)}`,rsn:i?"":`rsn=${String(r.reasoning)}`,txt:i?"":`txt=${String(r.text)}`}}function nxr(e,t=QY){let r=Object.fromEntries(QY.map(n=>[n,0]));for(let n of e)for(let o of t)r[o]=Math.max(r[o],qft(n[o]));return r}function oxr(e,t){if(e==="workerId")return`${Wft}${t}${jft}`;let r=t.indexOf("=");return r>0?`${$ft}${t.slice(0,r+1)}${Hft}${t.slice(r+1)}${OY}`:t}function ixr(e,t,r=QY){let n=r.map(o=>oxr(o,Gyr(e[o],t[o])));return`${Uft}${OY}${n.join(Uyr)}${Gft}`}function sxr(e,t,r="full"){let n=e.map(s=>rxr(s,t)),o=r==="short"?$yr:QY,i=nxr(n,o);return n.map(s=>ixr(s,i,o))}function axr(e,t={}){let r=t.preset??"full",n=[exr(e.project,e.claude,e.repo,e.fleet,r)],o=t.now??0;return n.push(...sxr(t.workers??[],o,r)),n.join(`
827
827
  `)}function zft(e,t,r={}){let n=r.preset??"full";return t?axr(e,r):Fft(e,n)}Mo();_P();function dxr(e){return new Promise(t=>{if(e.isTTY){t("");return}let r="",n=!1,o=()=>{n||(n=!0,t(r))};e.setEncoding("utf8"),e.on("data",i=>{r+=i}),e.on("end",o),e.on("error",o),e.on("close",o)})}function fxr(e){if(!e.trim())return{};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null?t:{}}catch{return{}}}function pxr(e){try{return uxr(e).isDirectory()}catch{return!1}}function mxr(e,t,r){if(e&&pxr(e))return e;let n=t.workspace?.project_dir||t.workspace?.current_dir||t.cwd;return n||r}function hxr(e){let t=Vft(e,".red","config.yaml");if(!cxr(t))return!0;let r=Cr(t,{warn:()=>{}});return!(Pe(r,"statusline")==="false"||Pe(r,"afk.statusline")==="false")}function NY(e){return e==="full"||e==="short"?e:void 0}function gxr(e){return NY(Pe(e,"plugins.dev.statusline.preset"))??NY(Pe(e,"dev.statusline.preset"))??NY(Pe(e,"afk.statusline.preset"))??NY(Pe(e,"statusline.preset"))??"full"}async function Axr(e){let t={cwd:e},r=_Y("dev").version,n={basename:lxr(e),version:r},o=await fP(t);if(o)return{...n,branch:o};let i=await pg(t);return i?{...n,detachedSha:i}:n}function yxr(e){let t=e.model?.display_name,r=e.effort?.level,n=e.context_window?.total_input_tokens,o=e.context_window?.used_percentage,i=e.rate_limits?.five_hour?.used_percentage,s=e.rate_limits?.seven_day?.used_percentage;if(!(t===void 0&&n===void 0&&i===void 0&&s===void 0))return{model:t||void 0,effort:r||void 0,contextTokens:n,contextPercent:o,usage5h:i,usage7d:s}}async function Yft(e,t=process.cwd(),r=process.stdout,n=process.stdin){if(e.includes("--legend"))return r.write(`${CY()}
828
828
  `),0;let o=e[0],i=await dxr(n),s=fxr(i),a=mxr(o,s,t);if(!hxr(a))return 0;let c=await Axr(a),u=yxr(s),l={root:a,repo:fR(a),remote:"origin"},d=Cr(Vft(a,".red","config.yaml"),{warn:()=>{}}),f=gxr(d),p=_4(process.env,R=>Pe(d,R)),g=`origin/${await cf({issueBody:""},{readLockedBranch:()=>xg(vx(a)),configLockedBranch:Pe(d,"dev.lock.branch"),configTrunk:Pe(d,"dev.trunk"),fetchIssueBody:async()=>{}})}`,[A,E,y,b]=await Promise.all([Oat(l,p,g),Tat(l,p).then(R=>R??void 0),Dat(l),Qat(l)]),I=!process.env.NO_COLOR,w=Number.parseInt(process.env.COLUMNS??"",10),v=Math.floor(Date.now()/1e3),k=zft({project:c,claude:u,repo:A,fleet:y,afk:E},I,{columns:Number.isFinite(w)&&w>0?w:void 0,workers:b,now:v,preset:f});return r.write(`${k}
829
829
  `),0}async function Jft(e,t=process.cwd()){let r=e[0]??t,n="",o="";for(let i=1;i<e.length;i+=1){let s=e[i];s==="--repo"?n=e[++i]??"":s==="--lock"&&(o=e[++i]??"")}return await _at(r,n||fR(r),o||void 0),0}KC();import{spawn as dpt}from"node:child_process";import{existsSync as mye,openSync as ppt,closeSync as vxr,writeFileSync as mpt,writeSync as Rxr,rmSync as hye,renameSync as Bxr}from"node:fs";import{join as MC}from"node:path";import{existsSync as xxr,readdirSync as iM,readFileSync as PY,statSync as ept}from"node:fs";import{join as ls}from"node:path";ru();Vd();function Exr(e,t){return ls(e,`afk-supervisor-slot-${t}.log`)}function bxr(e){let t;try{t=PY(e,"utf8")}catch{return[]}let r=[],n=new Set;for(let o of t.split(`
@@ -6561,7 +6561,7 @@ Usage:
6561
6561
  ${n} archive --candidate <json> [--root <dir>] [--archive-dir <rel>]
6562
6562
  ${n} restore <name> [--root <dir>] [--archive-dir <rel>]`}function Fx(n){return AWn(typeof n.root=="string"?n.root:process.cwd())}function not(n){return typeof n["archive-dir"]=="string"?n["archive-dir"]:void 0}async function Yj(n){let a=await Co(n);return a?a.mode!=="graph"?{ok:!1,message:`curate: skill telemetry needs graph mode (this project is "${a.mode}") \u2014 run \`${iwe}\``}:sZ(a)?{ok:!0}:{ok:!1,message:`curate: skill telemetry is not enabled here \u2014 run \`${iwe}\``}:{ok:!1,message:`curate: memory is not initialized here \u2014 run \`${iwe}\``}}function xWn(){let n=kWn(LWn(import.meta.url));return n.includes("dist/curate-skill")||n.endsWith("dist/curate-skill")?eot(n,"..","cli.js"):eot(n,"..","cli.ts")}async function zWn(n,a){let i=["curate","skills","--json"];a!==void 0&&i.push("--stale-days",String(a));let d=xWn(),h=d.endsWith(".ts")?$st(process.execPath,["--import","tsx",d,...i,"--root",n],{encoding:"utf8"}):$st(process.execPath,[d,...i,"--root",n],{encoding:"utf8"}),y=h.status??1;if(y!==0)throw new Error(`memory curate skills exited ${y}`);return Kst(h.stdout??"")}function OWn(n){return typeof n.flags["stale-days"]=="string"?Number(n.flags["stale-days"]):void 0}async function Iot(n,a){return(a.loadCuratorReport??zWn)(Fx(n.flags),OWn(n))}async function UWn(n){let a=Fx(n.flags),i=await Yj(a);return i.ok?(console.log("curate: skill telemetry is enabled \u2014 ready to curate"),0):(console.error(i.message),2)}async function MWn(n,a){let i=Fx(n.flags),d=await Yj(i);if(!d.ok)return console.error(d.message),2;let b;try{b=await Iot(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{candidates:h,byCategory:y,filtered:w}=cwe(b);return console.log(JSON.stringify({candidates:h,byCategory:y,filtered:w,totals:{totalSkills:b.totalSkills,curatableSkills:b.curatableSkills,readOnlySkills:b.readOnlySkills}},null,2)),0}async function BWn(n,a){let i=Fx(n.flags),d=await Yj(i);if(!d.ok)return console.error(d.message),2;let b;try{b=await Iot(n,a)}catch(J){return console.error(`curate: ${J.message}`),1}let{byCategory:h}=cwe(b);if(rwe(h)===0)return console.error("curate: no candidates \u2014 no issue filed"),0;let y=typeof n.flags.label=="string"?n.flags.label:void 0,w=await qst({byCategory:h,totals:{totalSkills:b.totalSkills,curatableSkills:b.curatableSkills,readOnlySkills:b.readOnlySkills},generatedAt:b.generatedAt},{cwd:i,label:y});return console.log(`curate: filed background issue \u2014 ${w.output||w.title}`),0}async function SWn(n){let a=Fx(n.flags),i=await Yj(a);if(!i.ok)return console.error(i.message),2;let d=n.flags.candidate;if(typeof d!="string")return console.error("curate archive: --candidate <json> is required"),2;let b;try{b=JSON.parse(d)}catch(y){return console.error(`curate archive: invalid --candidate JSON: ${y.message}`),2}let h=await jst(b,{rootDir:a,archiveDir:not(n.flags)});return h.ok?(console.log(`curate: archived "${h.receipt.name}" \u2192 ${h.receipt.archiveRoot} (${h.receipt.files.length} file(s), manifest at ${h.receipt.manifestPath})`),0):(console.error(`curate archive: refused \u2014 ${h.rejection.reason}: ${h.rejection.detail}`),3)}async function TWn(n){let a=Fx(n.flags),i=await Yj(a);if(!i.ok)return console.error(i.message),2;let d=n.positional[0];if(!d)return console.error("curate restore: skill name is required"),2;let b=await Dst(d,{rootDir:a,archiveDir:not(n.flags)});return console.log(`curate: restored "${b.name}" \u2192 ${b.restoredRoot} (${b.files.length} file(s) hash-verified)`),0}async function lot(n,a={}){switch(n.command){case"check":return UWn(n);case"list":return MWn(n,a);case"background":return BWn(n,a);case"archive":return SWn(n);case"restore":return TWn(n);case void 0:case"--help":case"-h":return console.log(tot(a.usageCommand)),0;default:return console.error(`unknown curate subcommand: ${n.command}
6563
6563
 
6564
- ${tot(a.usageCommand)}`),2}}function aot(n){let a={app:n,version:jWn(Xx("__RED_BUILD_VERSION__",()=>"2.33.5")??"0.0.0-dev"),gitSha:Xx("__RED_BUILD_GIT_SHA__",()=>"6ef5daf4fc41cc2b6f117cbb366b92f53caa8594")??"unknown",buildTime:Xx("__RED_BUILD_TIME__",()=>"2026-07-12T15:21:43-03:00")??"unknown",bundleAsset:Xx("__RED_BUNDLE_ASSET__",()=>"memory.bundle.min.mjs")??"unknown"},i=Xx("__REDDB_SDK_VERSION__",()=>"1.23.1"),d=Xx("__REDDB_BINARY_TAG__",()=>"v1.23.1");return i&&(a.reddbSdkVersion=i),d&&(a.reddbBinaryTag=d),a}function jWn(n){return n.startsWith("v")?n.slice(1):n}function cot(n){return`${n.app} ${n.version} ${n.gitSha}`}function Xx(n,a){try{let i=a();return typeof i=="string"&&i.length>0?i:void 0}catch{return process.env[n.replace(/^__|__$/g,"")]}}var rot=`memory \u2014 governed operational memory for code agents
6564
+ ${tot(a.usageCommand)}`),2}}function aot(n){let a={app:n,version:jWn(Xx("__RED_BUILD_VERSION__",()=>"2.33.7")??"0.0.0-dev"),gitSha:Xx("__RED_BUILD_GIT_SHA__",()=>"1df8f1f70e01908504ddf08c07d85ae00a44090a")??"unknown",buildTime:Xx("__RED_BUILD_TIME__",()=>"2026-07-12T16:04:46-03:00")??"unknown",bundleAsset:Xx("__RED_BUNDLE_ASSET__",()=>"memory.bundle.min.mjs")??"unknown"},i=Xx("__REDDB_SDK_VERSION__",()=>"1.23.1"),d=Xx("__REDDB_BINARY_TAG__",()=>"v1.23.1");return i&&(a.reddbSdkVersion=i),d&&(a.reddbBinaryTag=d),a}function jWn(n){return n.startsWith("v")?n.slice(1):n}function cot(n){return`${n.app} ${n.version} ${n.gitSha}`}function Xx(n,a){try{let i=a();return typeof i=="string"&&i.length>0?i:void 0}catch{return process.env[n.replace(/^__|__$/g,"")]}}var rot=`memory \u2014 governed operational memory for code agents
6565
6565
 
6566
6566
  Common workflows:
6567
6567
  remember one fact memory store "Decision: ..."