@reddb-io/red-skills 4.0.10 → 4.0.12

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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
3
- var Adt=Object.create;var VW=Object.defineProperty;var Odt=Object.getOwnPropertyDescriptor;var $dt=Object.getOwnPropertyNames;var Mdt=Object.getPrototypeOf,Ddt=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vn=(e,t)=>{for(var r in t)VW(e,r,{get:t[r],enumerable:!0})},Ndt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $dt(t))!Ddt.call(e,o)&&o!==r&&VW(e,o,{get:()=>t[o],enumerable:!(n=Odt(t,o))||n.enumerable});return e};var Cp=(e,t,r)=>(r=e!=null?Adt(Mdt(e)):{},Ndt(t||!e||!e.__esModule?VW(r,"default",{value:e,enumerable:!0}):r,e));function KW(e){let t={app:e,version:zdt(fk("__RED_BUILD_VERSION__",()=>"4.0.10")??"0.0.0-dev"),gitSha:fk("__RED_BUILD_GIT_SHA__",()=>"3d81b7e98824d7f9b040f21f2a1097f97f84b90e")??"unknown",buildTime:fk("__RED_BUILD_TIME__",()=>"2026-08-20T10:19:53-03:00")??"unknown",bundleAsset:fk("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=fk("__REDDB_SDK_VERSION__",()=>""),n=fk("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function zdt(e){return e.startsWith("v")?e.slice(1):e}function rSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function fk(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ZW=p(()=>{});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function yo(e){return e&&Object.assign(jy,e),jy}var nSe,QW,YW,Hl,qm,jy,Uy=p(()=>{QW=Object.freeze({status:"aborted"});YW=Symbol("zod_brand"),Hl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},qm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(nSe=globalThis).__zod_globalConfig??(nSe.__zod_globalConfig={});jy=globalThis.__zod_globalConfig});var Re={};Vn(Re,{BIGINT_FORMAT_RANGES:()=>c4,Class:()=>e4,NUMBER_FORMAT_RANGES:()=>a4,aborted:()=>Vm,allowsEval:()=>n4,assert:()=>qdt,assertEqual:()=>Fdt,assertIs:()=>Udt,assertNever:()=>Hdt,assertNotEqual:()=>jdt,assignProp:()=>Bm,base64ToUint8Array:()=>iSe,base64urlToUint8Array:()=>spt,cached:()=>hk,captureStackTrace:()=>T$,cleanEnum:()=>ipt,cleanRegex:()=>C0,clone:()=>Cs,cloneDef:()=>Bdt,createTransparentProxy:()=>Qdt,defineLazy:()=>Jt,esc:()=>R$,escapeRegex:()=>$c,explicitlyAborted:()=>l4,extend:()=>ept,finalizeIssue:()=>Ps,floatSafeRemainder:()=>t4,getElementAtPath:()=>Wdt,getEnumValues:()=>T0,getLengthableOrigin:()=>A0,getParsedType:()=>Jdt,getSizableOrigin:()=>I0,hexToUint8Array:()=>cpt,isObject:()=>Hy,isPlainObject:()=>Wm,issue:()=>gk,joinValues:()=>ne,jsonStringifyReplacer:()=>mk,merge:()=>rpt,mergeDefs:()=>Pp,normalizeParams:()=>Ie,nullish:()=>Gm,numKeys:()=>Zdt,objectClone:()=>Gdt,omit:()=>Xdt,optionalKeys:()=>s4,parsedType:()=>Ee,partial:()=>npt,pick:()=>Ydt,prefixIssues:()=>ca,primitiveTypes:()=>i4,promiseAllObject:()=>Vdt,propertyKeyTypes:()=>P0,randomString:()=>Kdt,required:()=>opt,safeExtend:()=>tpt,shallowClone:()=>o4,slugify:()=>r4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>sSe,uint8ArrayToBase64url:()=>apt,uint8ArrayToHex:()=>lpt,unwrapMessage:()=>R0});function Fdt(e){return e}function jdt(e){return e}function Udt(e){}function Hdt(e){throw new Error("Unexpected value in exhaustive check")}function qdt(e){}function T0(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function mk(e,t){return typeof t=="bigint"?t.toString():t}function hk(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gm(e){return e==null}function C0(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function t4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Jt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==oSe)return n===void 0&&(n=oSe,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Gdt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Bm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Pp(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Bdt(e){return Pp(e._zod.def)}function Wdt(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Vdt(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function Kdt(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function R$(e){return JSON.stringify(e)}function r4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Hy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wm(e){if(Hy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Hy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function o4(e){return Wm(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Zdt(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function $c(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cs(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Qdt(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function s4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function Ydt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function Xdt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function ept(e,t){if(!Wm(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Pp(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Bm(this,"shape",i),i}});return Cs(e,o)}function tpt(e,t){if(!Wm(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Bm(this,"shape",n),n}});return Cs(e,r)}function rpt(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Bm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Cs(e,r)}function npt(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Pp(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Bm(this,"shape",c),c},checks:[]});return Cs(t,s)}function opt(e,t,r){let n=Pp(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Bm(this,"shape",i),i}});return Cs(t,n)}function Vm(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function l4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ca(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function R0(e){return typeof e=="string"?e:e?.message}function Ps(e,t,r){let n=e.message?e.message:R0(e.inst?._zod.def?.error?.(e))??R0(t?.error?.(e))??R0(r.customError?.(e))??R0(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function I0(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function A0(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function gk(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function ipt(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function iSe(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function sSe(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function spt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return iSe(t+r)}function apt(e){return sSe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function cpt(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function lpt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var oSe,T$,n4,Jdt,P0,i4,a4,c4,e4,ot=p(()=>{Uy();oSe=Symbol("evaluating");T$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};n4=hk(()=>{if(jy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});Jdt=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},P0=new Set(["string","number","symbol"]),i4=new Set(["string","number","bigint","boolean","symbol","undefined"]);a4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},c4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};e4=class{constructor(...t){}}});function $0(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function M0(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function u4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function cSe(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function d4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${cSe(n.path)}`);return t.join(`
3
+ var Adt=Object.create;var VW=Object.defineProperty;var Odt=Object.getOwnPropertyDescriptor;var $dt=Object.getOwnPropertyNames;var Mdt=Object.getPrototypeOf,Ddt=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vn=(e,t)=>{for(var r in t)VW(e,r,{get:t[r],enumerable:!0})},Ndt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $dt(t))!Ddt.call(e,o)&&o!==r&&VW(e,o,{get:()=>t[o],enumerable:!(n=Odt(t,o))||n.enumerable});return e};var Cp=(e,t,r)=>(r=e!=null?Adt(Mdt(e)):{},Ndt(t||!e||!e.__esModule?VW(r,"default",{value:e,enumerable:!0}):r,e));function KW(e){let t={app:e,version:zdt(fk("__RED_BUILD_VERSION__",()=>"4.0.12")??"0.0.0-dev"),gitSha:fk("__RED_BUILD_GIT_SHA__",()=>"9e845974d25837206f7bd441a924b4ce0928243b")??"unknown",buildTime:fk("__RED_BUILD_TIME__",()=>"2026-08-20T13:40:28-03:00")??"unknown",bundleAsset:fk("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=fk("__REDDB_SDK_VERSION__",()=>""),n=fk("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function zdt(e){return e.startsWith("v")?e.slice(1):e}function rSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function fk(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var ZW=p(()=>{});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function yo(e){return e&&Object.assign(jy,e),jy}var nSe,QW,YW,Hl,qm,jy,Uy=p(()=>{QW=Object.freeze({status:"aborted"});YW=Symbol("zod_brand"),Hl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},qm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(nSe=globalThis).__zod_globalConfig??(nSe.__zod_globalConfig={});jy=globalThis.__zod_globalConfig});var Re={};Vn(Re,{BIGINT_FORMAT_RANGES:()=>c4,Class:()=>e4,NUMBER_FORMAT_RANGES:()=>a4,aborted:()=>Vm,allowsEval:()=>n4,assert:()=>qdt,assertEqual:()=>Fdt,assertIs:()=>Udt,assertNever:()=>Hdt,assertNotEqual:()=>jdt,assignProp:()=>Bm,base64ToUint8Array:()=>iSe,base64urlToUint8Array:()=>spt,cached:()=>hk,captureStackTrace:()=>T$,cleanEnum:()=>ipt,cleanRegex:()=>C0,clone:()=>Cs,cloneDef:()=>Bdt,createTransparentProxy:()=>Qdt,defineLazy:()=>Jt,esc:()=>R$,escapeRegex:()=>$c,explicitlyAborted:()=>l4,extend:()=>ept,finalizeIssue:()=>Ps,floatSafeRemainder:()=>t4,getElementAtPath:()=>Wdt,getEnumValues:()=>T0,getLengthableOrigin:()=>A0,getParsedType:()=>Jdt,getSizableOrigin:()=>I0,hexToUint8Array:()=>cpt,isObject:()=>Hy,isPlainObject:()=>Wm,issue:()=>gk,joinValues:()=>ne,jsonStringifyReplacer:()=>mk,merge:()=>rpt,mergeDefs:()=>Pp,normalizeParams:()=>Ie,nullish:()=>Gm,numKeys:()=>Zdt,objectClone:()=>Gdt,omit:()=>Xdt,optionalKeys:()=>s4,parsedType:()=>Ee,partial:()=>npt,pick:()=>Ydt,prefixIssues:()=>ca,primitiveTypes:()=>i4,promiseAllObject:()=>Vdt,propertyKeyTypes:()=>P0,randomString:()=>Kdt,required:()=>opt,safeExtend:()=>tpt,shallowClone:()=>o4,slugify:()=>r4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>sSe,uint8ArrayToBase64url:()=>apt,uint8ArrayToHex:()=>lpt,unwrapMessage:()=>R0});function Fdt(e){return e}function jdt(e){return e}function Udt(e){}function Hdt(e){throw new Error("Unexpected value in exhaustive check")}function qdt(e){}function T0(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function mk(e,t){return typeof t=="bigint"?t.toString():t}function hk(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Gm(e){return e==null}function C0(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function t4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Jt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==oSe)return n===void 0&&(n=oSe,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Gdt(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Bm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Pp(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Bdt(e){return Pp(e._zod.def)}function Wdt(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function Vdt(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function Kdt(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function R$(e){return JSON.stringify(e)}function r4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Hy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wm(e){if(Hy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Hy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function o4(e){return Wm(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function Zdt(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function $c(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cs(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Qdt(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function s4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function Ydt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function Xdt(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Pp(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Bm(this,"shape",s),s},checks:[]});return Cs(e,i)}function ept(e,t){if(!Wm(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Pp(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Bm(this,"shape",i),i}});return Cs(e,o)}function tpt(e,t){if(!Wm(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Bm(this,"shape",n),n}});return Cs(e,r)}function rpt(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=Pp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Bm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Cs(e,r)}function npt(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=Pp(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Bm(this,"shape",c),c},checks:[]});return Cs(t,s)}function opt(e,t,r){let n=Pp(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Bm(this,"shape",i),i}});return Cs(t,n)}function Vm(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function l4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function ca(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function R0(e){return typeof e=="string"?e:e?.message}function Ps(e,t,r){let n=e.message?e.message:R0(e.inst?._zod.def?.error?.(e))??R0(t?.error?.(e))??R0(r.customError?.(e))??R0(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function I0(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function A0(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function gk(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function ipt(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function iSe(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function sSe(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function spt(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return iSe(t+r)}function apt(e){return sSe(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function cpt(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function lpt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var oSe,T$,n4,Jdt,P0,i4,a4,c4,e4,ot=p(()=>{Uy();oSe=Symbol("evaluating");T$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};n4=hk(()=>{if(jy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});Jdt=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},P0=new Set(["string","number","symbol"]),i4=new Set(["string","number","bigint","boolean","symbol","undefined"]);a4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},c4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};e4=class{constructor(...t){}}});function $0(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function M0(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function u4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function cSe(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function d4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${cSe(n.path)}`);return t.join(`
4
4
  `)}var aSe,O0,la,p4=p(()=>{Uy();ot();aSe=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,mk,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},O0=K("$ZodError",aSe),la=K("$ZodError",aSe,{Parent:Error})});var yk,C$,bk,P$,xk,f4,Sk,m4,I$,dpt,A$,ppt,O$,fpt,$$,mpt,M$,hpt,D$,gpt,N$,ypt,z$,bpt,h4=p(()=>{Uy();p4();ot();yk=e=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Hl;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ps(c,i,yo())));throw T$(a,o?.callee),a}return s.value},C$=yk(la),bk=e=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>Ps(c,i,yo())));throw T$(a,o?.callee),a}return s.value},P$=bk(la),xk=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Hl;return i.issues.length?{success:!1,error:new(e??O0)(i.issues.map(s=>Ps(s,o,yo())))}:{success:!0,data:i.value}},f4=xk(la),Sk=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>Ps(s,o,yo())))}:{success:!0,data:i.value}},m4=Sk(la),I$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return yk(e)(t,r,o)},dpt=I$(la),A$=e=>(t,r,n)=>yk(e)(t,r,n),ppt=A$(la),O$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return bk(e)(t,r,o)},fpt=O$(la),$$=e=>async(t,r,n)=>bk(e)(t,r,n),mpt=$$(la),M$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return xk(e)(t,r,o)},hpt=M$(la),D$=e=>(t,r,n)=>xk(e)(t,r,n),gpt=D$(la),N$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Sk(e)(t,r,o)},ypt=N$(la),z$=e=>async(t,r,n)=>Sk(e)(t,r,n),bpt=z$(la)});var Va={};Vn(Va,{base64:()=>A4,base64url:()=>L$,bigint:()=>L4,boolean:()=>j4,browserEmail:()=>Rpt,cidrv4:()=>P4,cidrv6:()=>I4,cuid:()=>g4,cuid2:()=>y4,date:()=>M4,datetime:()=>N4,domain:()=>Ppt,duration:()=>_4,e164:()=>$4,email:()=>v4,emoji:()=>E4,extendedDuration:()=>xpt,guid:()=>w4,hex:()=>Ipt,hostname:()=>Cpt,html5Email:()=>wpt,httpProtocol:()=>O4,idnEmail:()=>Ept,integer:()=>F4,ipv4:()=>R4,ipv6:()=>T4,ksuid:()=>S4,lowercase:()=>q4,mac:()=>C4,md5_base64:()=>Opt,md5_base64url:()=>$pt,md5_hex:()=>Apt,nanoid:()=>k4,null:()=>U4,number:()=>F$,rfc5322Email:()=>vpt,sha1_base64:()=>Dpt,sha1_base64url:()=>Npt,sha1_hex:()=>Mpt,sha256_base64:()=>Lpt,sha256_base64url:()=>Fpt,sha256_hex:()=>zpt,sha384_base64:()=>Upt,sha384_base64url:()=>Hpt,sha384_hex:()=>jpt,sha512_base64:()=>Gpt,sha512_base64url:()=>Bpt,sha512_hex:()=>qpt,string:()=>z4,time:()=>D4,ulid:()=>b4,undefined:()=>H4,unicodeEmail:()=>lSe,uppercase:()=>G4,uuid:()=>qy,uuid4:()=>Spt,uuid6:()=>kpt,uuid7:()=>_pt,xid:()=>x4});function E4(){return new RegExp(Tpt,"u")}function dSe(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function D4(e){return new RegExp(`^${dSe(e)}$`)}function N4(e){let t=dSe({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${uSe}T(?:${n})$`)}function D0(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function N0(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var g4,y4,b4,x4,S4,k4,_4,xpt,w4,qy,Spt,kpt,_pt,v4,wpt,vpt,lSe,Ept,Rpt,Tpt,R4,T4,C4,P4,I4,A4,L$,Cpt,Ppt,O4,$4,uSe,M4,z4,L4,F4,F$,j4,U4,H4,q4,G4,Ipt,Apt,Opt,$pt,Mpt,Dpt,Npt,zpt,Lpt,Fpt,jpt,Upt,Hpt,qpt,Gpt,Bpt,j$=p(()=>{ot();g4=/^[cC][0-9a-z]{6,}$/,y4=/^[0-9a-z]+$/,b4=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,x4=/^[0-9a-vA-V]{20}$/,S4=/^[A-Za-z0-9]{27}$/,k4=/^[a-zA-Z0-9_-]{21}$/,_4=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xpt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,w4=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qy=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Spt=qy(4),kpt=qy(6),_pt=qy(7),v4=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,wpt=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,vpt=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,lSe=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Ept=lSe,Rpt=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Tpt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";R4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,T4=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,C4=e=>{let t=$c(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},P4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,I4=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,A4=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,L$=/^[A-Za-z0-9_-]*$/,Cpt=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Ppt=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,O4=/^https?$/,$4=/^\+[1-9]\d{6,14}$/,uSe="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",M4=new RegExp(`^${uSe}$`);z4=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},L4=/^-?\d+n?$/,F4=/^-?\d+$/,F$=/^-?\d+(?:\.\d+)?$/,j4=/^(?:true|false)$/i,U4=/^null$/i,H4=/^undefined$/i,q4=/^[^A-Z]*$/,G4=/^[^a-z]*$/,Ipt=/^[0-9a-fA-F]*$/;Apt=/^[0-9a-fA-F]{32}$/,Opt=D0(22,"=="),$pt=N0(22),Mpt=/^[0-9a-fA-F]{40}$/,Dpt=D0(27,"="),Npt=N0(27),zpt=/^[0-9a-fA-F]{64}$/,Lpt=D0(43,"="),Fpt=N0(43),jpt=/^[0-9a-fA-F]{96}$/,Upt=D0(64,""),Hpt=N0(64),qpt=/^[0-9a-fA-F]{128}$/,Gpt=D0(86,"=="),Bpt=N0(86)});function pSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues))}var un,fSe,U$,H$,B4,W4,V4,K4,Z4,J4,Q4,Y4,X4,kk,eV,tV,rV,nV,oV,iV,sV,aV,cV,q$=p(()=>{Uy();j$();ot();un=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),fSe={number:"number",bigint:"bigint",object:"date"},U$=K("$ZodCheckLessThan",(e,t)=>{un.init(e,t);let r=fSe[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),H$=K("$ZodCheckGreaterThan",(e,t)=>{un.init(e,t);let r=fSe[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),B4=K("$ZodCheckMultipleOf",(e,t)=>{un.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):t4(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),W4=K("$ZodCheckNumberFormat",(e,t)=>{un.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=a4[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=F4)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),V4=K("$ZodCheckBigIntFormat",(e,t)=>{un.init(e,t);let[r,n]=c4[t.format];e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{let i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),K4=K("$ZodCheckMaxSize",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;o.size<=t.maximum||n.issues.push({origin:I0(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Z4=K("$ZodCheckMinSize",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:I0(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),J4=K("$ZodCheckSizeEquals",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,i=o.size;if(i===t.size)return;let s=i>t.size;n.issues.push({origin:I0(o),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Q4=K("$ZodCheckMaxLength",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=A0(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Y4=K("$ZodCheckMinLength",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=A0(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),X4=K("$ZodCheckLengthEquals",(e,t)=>{var r;un.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Gm(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=A0(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),kk=K("$ZodCheckStringFormat",(e,t)=>{var r,n;un.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),eV=K("$ZodCheckRegex",(e,t)=>{kk.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),tV=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=q4),kk.init(e,t)}),rV=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=G4),kk.init(e,t)}),nV=K("$ZodCheckIncludes",(e,t)=>{un.init(e,t);let r=$c(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),oV=K("$ZodCheckStartsWith",(e,t)=>{un.init(e,t);let r=new RegExp(`^${$c(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),iV=K("$ZodCheckEndsWith",(e,t)=>{un.init(e,t);let r=new RegExp(`.*${$c(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});sV=K("$ZodCheckProperty",(e,t)=>{un.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>pSe(o,r,t.property));pSe(n,r,t.property)}}),aV=K("$ZodCheckMimeType",(e,t)=>{un.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),cV=K("$ZodCheckOverwrite",(e,t)=>{un.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var z0,lV=p(()=>{z0=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
5
5
  `).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
6
6
  `))}}});var uV,dV=p(()=>{uV={major:4,minor:4,patch:3}});function $V(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function PSe(e){if(!L$.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return $V(r)}function ISe(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}function hSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues)),t.value[r]=e.value}function V$(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...ca(r,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function ASe(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=s4(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function OSe(e,t,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,l=c.def.type,u=c.optin==="optional",d=c.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(l==="never"){s.push(f);continue}let m=c.run({value:t[f],issues:[]},n);m instanceof Promise?e.push(m.then(b=>V$(b,r,f,t,u,d))):V$(m,r,f,t,u,d)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function gSe(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!Vm(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Ps(s,n,yo())))}),t)}function ySe(e,t,r,n){let o=e.filter(i=>i.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>Ps(s,n,yo())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function pV(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Wm(e)&&Wm(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=pV(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=pV(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function bSe(e,t,r){let n=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),Vm(e))return e;let s=pV(t.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}function xSe(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function SSe(e,t,r){e.issues.length&&t.issues.push(...ca(r,e.issues)),t.value[r]=e.value}function kSe(e,t,r,n,o){for(let i=0;i<r.length;i++){let s=e[i],a=i<n.length;if(s.issues.length){if(!a&&i>=o){t.value.length=i;break}t.issues.push(...ca(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=n.length&&(r[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}function _Se(e,t,r,n,o,i,s){e.issues.length&&(P0.has(typeof n)?r.issues.push(...ca(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map(a=>Ps(a,s,yo()))})),t.issues.length&&(P0.has(typeof n)?r.issues.push(...ca(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:t.issues.map(a=>Ps(a,s,yo()))})),r.value.set(e.value,t.value)}function wSe(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function vSe(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}function ESe(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function RSe(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function G$(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function B$(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(i=>W$(e,i,t.out,r)):W$(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(i=>W$(e,i,t.in,r)):W$(e,o,t.in,r)}}function W$(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}function TSe(e){return e.value=Object.freeze(e.value),e}function CSe(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(gk(o))}}var At,Gy,Qr,fV,mV,hV,gV,yV,bV,xV,SV,kV,_V,wV,vV,EV,RV,TV,CV,PV,IV,AV,OV,MV,DV,NV,zV,LV,K$,FV,L0,Z$,jV,UV,HV,qV,GV,BV,WV,VV,KV,ZV,$Se,JV,F0,QV,YV,XV,J$,e6,t6,r6,n6,o6,i6,s6,Q$,a6,c6,l6,u6,d6,p6,f6,m6,Y$,j0,h6,g6,y6,b6,x6,S6,k6,_6=p(()=>{q$();Uy();lV();h4();j$();ot();dV();ot();At=K("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=uV;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,a,c)=>{let l=Vm(s),u;for(let d of a){if(d._zod.def.when){if(l4(s)||!d._zod.def.when(s))continue}else if(l)continue;let f=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&c?.async===!1)throw new Hl;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==f&&(l||(l=Vm(s,f)))});else{if(s.issues.length===f)continue;l||(l=Vm(s,f))}}return u?u.then(()=>s):s},i=(s,a,c)=>{if(Vm(s))return s.aborted=!0,s;let l=o(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new Hl;return l.then(u=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>i(u,s,a)):i(l,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Hl;return c.then(l=>o(l,n,a))}return o(c,n,a)}}Jt(e,"~standard",()=>({validate:o=>{try{let i=f4(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return m4(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Gy=K("$ZodString",(e,t)=>{At.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??z4(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Qr=K("$ZodStringFormat",(e,t)=>{kk.init(e,t),Gy.init(e,t)}),fV=K("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=w4),Qr.init(e,t)}),mV=K("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=qy(n))}else t.pattern??(t.pattern=qy());Qr.init(e,t)}),hV=K("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=v4),Qr.init(e,t)}),gV=K("$ZodURL",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===O4.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),yV=K("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=E4()),Qr.init(e,t)}),bV=K("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=k4),Qr.init(e,t)}),xV=K("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=g4),Qr.init(e,t)}),SV=K("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=y4),Qr.init(e,t)}),kV=K("$ZodULID",(e,t)=>{t.pattern??(t.pattern=b4),Qr.init(e,t)}),_V=K("$ZodXID",(e,t)=>{t.pattern??(t.pattern=x4),Qr.init(e,t)}),wV=K("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=S4),Qr.init(e,t)}),vV=K("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=N4(t)),Qr.init(e,t)}),EV=K("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=M4),Qr.init(e,t)}),RV=K("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=D4(t)),Qr.init(e,t)}),TV=K("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=_4),Qr.init(e,t)}),CV=K("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=R4),Qr.init(e,t),e._zod.bag.format="ipv4"}),PV=K("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=T4),Qr.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),IV=K("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=C4(t.delimiter)),Qr.init(e,t),e._zod.bag.format="mac"}),AV=K("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=P4),Qr.init(e,t)}),OV=K("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=I4),Qr.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});MV=K("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=A4),Qr.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{$V(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});DV=K("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=L$),Qr.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{PSe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),NV=K("$ZodE164",(e,t)=>{t.pattern??(t.pattern=$4),Qr.init(e,t)});zV=K("$ZodJWT",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{ISe(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),LV=K("$ZodCustomStringFormat",(e,t)=>{Qr.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),K$=K("$ZodNumber",(e,t)=>{At.init(e,t),e._zod.pattern=e._zod.bag.pattern??F$,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),FV=K("$ZodNumberFormat",(e,t)=>{W4.init(e,t),K$.init(e,t)}),L0=K("$ZodBoolean",(e,t)=>{At.init(e,t),e._zod.pattern=j4,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),Z$=K("$ZodBigInt",(e,t)=>{At.init(e,t),e._zod.pattern=L4,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),jV=K("$ZodBigIntFormat",(e,t)=>{V4.init(e,t),Z$.init(e,t)}),UV=K("$ZodSymbol",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),HV=K("$ZodUndefined",(e,t)=>{At.init(e,t),e._zod.pattern=H4,e._zod.values=new Set([void 0]),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),qV=K("$ZodNull",(e,t)=>{At.init(e,t),e._zod.pattern=U4,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),GV=K("$ZodAny",(e,t)=>{At.init(e,t),e._zod.parse=r=>r}),BV=K("$ZodUnknown",(e,t)=>{At.init(e,t),e._zod.parse=r=>r}),WV=K("$ZodNever",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),VV=K("$ZodVoid",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),KV=K("$ZodDate",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});ZV=K("$ZodArray",(e,t)=>{At.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>hSe(l,r,s))):hSe(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});$Se=K("$ZodObject",(e,t)=>{if(At.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=hk(()=>ASe(t));Jt(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let o=Hy,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!o(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let m=d[f],b=m._zod.optin==="optional",S=m._zod.optout==="optional",_=m._zod.run({value:l[f],issues:[]},c);_ instanceof Promise?u.push(_.then(E=>V$(E,a,f,l,b,S))):V$(_,a,f,l,b,S)}return i?OSe(u,l,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}}),JV=K("$ZodObjectJIT",(e,t)=>{$Se.init(e,t);let r=e._zod.parse,n=hk(()=>ASe(t)),o=f=>{let m=new z0(["shape","payload","ctx"]),b=n.value,S=A=>{let $=R$(A);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};m.write("const input = payload.value;");let _=Object.create(null),E=0;for(let A of b.keys)_[A]=`key_${E++}`;m.write("const newResult = {};");for(let A of b.keys){let $=_[A],M=R$(A),L=f[A],F=L?._zod?.optin==="optional",H=L?._zod?.optout==="optional";m.write(`const ${$} = ${S(A)};`),F&&H?m.write(`
@@ -244,7 +244,7 @@ ${n instanceof Error?n.message:String(n)}`})}).pipe(j.flatMap(n=>n.exitCode!==0?
244
244
  ${n.stderr}`})):j.succeed(n))),Jit=(e,t)=>j.gen(function*(){let r=(yield*Fge("git rev-parse --abbrev-ref HEAD",e)).trim(),n=yield*j.tryPromise({try:()=>Err(Zit(Trr(),"sandcastle-bundle-")),catch:i=>new go({message:`Failed to create temp dir: ${i instanceof Error?i.message:String(i)}`})}),o=Zit(n,"repo.bundle");return yield*j.ensuring(j.gen(function*(){yield*Fge(`git bundle create "${o}" --all`,e);let s=(yield*CO(t,"mktemp -d -t sandcastle-XXXXXX")).stdout.trim(),a=`${s}/repo.bundle`;yield*j.tryPromise({try:()=>t.copyIn(o,a),catch:d=>new go({message:`Failed to copy bundle into sandbox: ${d instanceof Error?d.message:String(d)}`})});let c=t.worktreePath;yield*CO(t,`git clone "${a}" "${c}_clone"`),yield*CO(t,`rm -rf "${c}" && mv "${c}_clone" "${c}"`),yield*CO(t,`git checkout "${r}"`,{cwd:c}),yield*j.tryPromise({try:()=>t.exec(`rm -rf "${s}"`),catch:()=>new go({message:"Failed to clean up sandbox temp dir"})});let l=(yield*Fge("git rev-parse HEAD",e)).trim(),u=(yield*CO(t,"git rev-parse HEAD",{cwd:c})).stdout.trim();l!==u&&(yield*j.fail(new go({message:`HEAD mismatch after sync-in: host=${l} sandbox=${u}`})))}),j.promise(()=>Rrr(n,{recursive:!0,force:!0}))),{branch:r}})});import{tmpdir as Crr,homedir as q_n}from"node:os";import{isAbsolute as B_n,resolve as W_n,join as jge,dirname as V_n}from"node:path";import{mkdtemp as Prr,writeFile as Irr}from"node:fs/promises";var Yit,Xit,Arr,o0,i0=p(()=>{"use strict";Ac();Sy();Ha();Yit="/.red-castle-parent-git",Xit=(e,t,r,n=process.platform)=>{if(n!=="win32")return e;let o=t.replace(/\\/g,"/");return e.map(i=>{let s=i.hostPath.replace(/\\/g,"/"),a=i.sandboxPath;if(/^[A-Za-z]:[/\\]/.test(a)||a.includes("\\")){let c=a.replace(/\\/g,"/");if(c.startsWith(o+"/")){let l=c.slice(o.length);a=r+l}else c===o?a=r:a=c}return{...i,hostPath:s,sandboxPath:a}})},Arr=e=>{let r=e.replace(/\\/g,"/").replace(/\/+$/,"").split("/"),n=r.pop();r.pop();let o=r.join("/");return{worktreeName:n,parentGitDir:o}},o0=(e,t,r,n,o,i=process.platform)=>j.gen(function*(){if(i!=="win32")return e;let s=n??(async L=>{let{readFile:F}=await import("node:fs/promises");return F(L,"utf-8")}),a=o??(async L=>{let{stat:F}=await import("node:fs/promises");return(await F(L)).isDirectory()?"directory":"file"}),c=jge(t,".git"),l=yield*j.tryPromise({try:()=>a(c),catch:()=>null}).pipe(j.catchAll(()=>j.succeed(null)));if(l===null||l==="directory")return e;let u=yield*j.tryPromise({try:()=>s(c),catch:()=>null}).pipe(j.map(L=>L.trim()),j.catchAll(()=>j.succeed(null)));if(u===null)return e;let d=u.match(/^gitdir:\s*(.+)$/);if(!d)return e;let f=d[1],{parentGitDir:m,worktreeName:b}=Arr(f),S=`${Yit}/worktrees/${b}`,_=yield*j.tryPromise({try:()=>Prr(jge(Crr(),"sandcastle-git-")),catch:L=>new si({message:`Failed to create temp dir for git override: ${L instanceof Error?L.message:String(L)}`})}),E=jge(_,"git-override");yield*j.tryPromise({try:()=>Irr(E,`gitdir: ${S}
245
245
  `),catch:L=>new si({message:`Failed to write git override file: ${L instanceof Error?L.message:String(L)}`})});let R=m.replace(/\\/g,"/"),A=c.replace(/\\/g,"/"),$=[],M=!1;for(let L of e){let F=L.hostPath.replace(/\\/g,"/");F===R?$.push({...L,sandboxPath:Yit}):F===A?($.push({...L,hostPath:E,sandboxPath:`${r}/.git`}),M=!0):$.push(L)}return M||$.push({hostPath:E,sandboxPath:`${r}/.git`}),$})});import{existsSync as Orr}from"node:fs";import{join as $rr,posix as Mrr}from"node:path";var s0,Uge,Hge,zm,Drr,Nrr,zrr,PO=p(()=>{"use strict";Ac();Ha();Sy();Qit();i0();s0=12e4,Uge=12e4,Hge=12e4,zm=e=>e.provider.tag==="bind-mount"?Nrr(e):e.provider.tag==="none"?Drr(e):zrr(e),Drr=e=>j.tryPromise({try:()=>e.provider.create({worktreePath:e.worktreeOrRepoPath,env:e.env}),catch:t=>new si({message:`Provider '${e.provider.name}' create failed: ${t instanceof Error?t.message:String(t)}`})}).pipe(j.map(t=>({handle:t,sandbox:a0(t),worktreePath:t.worktreePath}))),Nrr=e=>j.tryPromise({try:()=>{let t=[{hostPath:e.worktreeOrRepoPath,sandboxPath:e.repoDir},...e.gitMounts],r=Xit(t,e.worktreeOrRepoPath,wp),n=process.platform==="win32"?e.worktreeOrRepoPath.replace(/\\/g,"/"):e.worktreeOrRepoPath;return e.provider.create({worktreePath:n,hostRepoPath:e.hostRepoDir,mounts:r,env:e.env})},catch:t=>new si({message:`Provider '${e.provider.name}' create failed: ${t instanceof Error?t.message:String(t)}`})}).pipe(j.map(t=>({handle:t,sandbox:a0(t),worktreePath:t.worktreePath})),Ll(s0,()=>new kO({message:`Sandbox container start timed out after ${s0}ms`,timeoutMs:s0}))),zrr=e=>j.gen(function*(){let t=yield*j.tryPromise({try:()=>e.provider.create({env:e.env}),catch:r=>new si({message:`Isolated provider '${e.provider.name}' setup failed: ${r instanceof Error?r.message:String(r)}`})}).pipe(Ll(s0,()=>new kO({message:`Isolated sandbox container start timed out after ${s0}ms`,timeoutMs:s0})));if(yield*Jit(e.hostRepoDir,t).pipe(Ll(Uge,()=>new $B({message:`Sync-in timed out after ${Uge}ms`,timeoutMs:Uge}))),e.copyPaths&&e.copyPaths.length>0){let r=e.copyPaths;yield*j.gen(function*(){for(let n of r){let o=$rr(e.hostRepoDir,n);if(!Orr(o))continue;let i=Mrr.join(t.worktreePath,n);yield*j.tryPromise({try:()=>t.copyIn(o,i),catch:s=>new si({message:`Failed to copy ${n} into sandbox: ${s instanceof Error?s.message:String(s)}`})})}}).pipe(Ll(Hge,()=>new ZE({message:`Copying paths to worktree timed out after ${Hge}ms`,timeoutMs:Hge,paths:r})))}return{handle:t,sandbox:a0(t),worktreePath:t.worktreePath}})});import{dirname as est,join as Bge,resolve as Lrr}from"node:path";var Frr,a0,wp,c0,jB,jrr,qge,Gge,Urr,IO,Hrr,Sy=p(()=>{"use strict";Ac();gge();Ha();tk();EO();Hu();n0();PO();r0();i0();Frr=e=>"copyIn"in e?(t,r)=>j.tryPromise({try:()=>e.copyIn(t,r),catch:n=>new xy({message:`copyIn failed: ${n instanceof Error?n.message:String(n)}`})}):"copyFileIn"in e?(t,r)=>j.tryPromise({try:()=>e.copyFileIn(t,r),catch:n=>new xy({message:`copyFileIn failed: ${n instanceof Error?n.message:String(n)}`})}):()=>j.fail(new xy({message:"copyIn is not supported for this sandbox provider"})),a0=e=>({exec:(t,r)=>j.tryPromise({try:n=>e.exec(t,{...r,signal:n}),catch:n=>new WE({command:t,message:`exec failed: ${n instanceof Error?n.message:String(n)}`})}),copyIn:Frr(e),copyFileOut:"copyFileOut"in e?(t,r)=>j.tryPromise({try:()=>e.copyFileOut(t,r),catch:n=>new xy({message:`copyFileOut failed: ${n instanceof Error?n.message:String(n)}`})}):()=>j.fail(new xy({message:"copyFileOut is not supported for this sandbox provider"}))}),wp="/home/agent/workspace",c0=class extends ar.Tag("SandboxFactory")(){},jB=class extends ar.Tag("SandboxConfig")(){},jrr=(e,t)=>{console.error(`
246
246
  ${t}`),console.error(` To review: cd ${e}`),console.error(` To clean up: git worktree remove --force ${e}`)},qge=(e,t,r)=>e0(e).pipe(j.catchAll(()=>j.succeed(!1)),j.flatMap(n=>n?(jrr(e,Zs.isSuccess(r)?`Run succeeded but worktree has uncommitted changes at ${e}`:`Worktree preserved at ${e}`),j.succeed(e)):(Zs.isSuccess(r)||console.error(`
247
- Worktree removed (no uncommitted changes)`),wO(e,t).pipe(j.map(()=>{}))))),Gge=(e,t)=>{if(e!==void 0){if(t instanceof KE)return new KE({message:t.message,timeoutMs:t.timeoutMs,preservedWorktreePath:e});if(t instanceof VE)return new VE({message:t.message,preservedWorktreePath:e})}return t},Urr=e=>j.gen(function*(){let t=yield*Tc.FileSystem,r=e;for(;;){let n=yield*t.stat(r).pipe(j.map(s=>({gitPath:r,stat:s})),j.catchSome(s=>s._tag==="SystemError"&&s.reason==="NotFound"?_t.some(j.succeed(void 0)):_t.none()));if(n!==void 0)return n;let o=est(r),i=est(o);if(i===o){let s=yield*t.stat(e);return{gitPath:e,stat:s}}r=Bge(i,".git")}}),IO=e=>j.gen(function*(){let t=yield*Tc.FileSystem,r=yield*Urr(e),{stat:n}=r;if(e=r.gitPath,n.type==="Directory")return[{hostPath:e,sandboxPath:e}];let i=(yield*t.readFileString(e)).trim().match(/^gitdir:\s*(.+)$/);if(!i)return[{hostPath:e,sandboxPath:e}];let s=i[1],a=Lrr(s,"..","..");return[{hostPath:e,sandboxPath:e},{hostPath:a,sandboxPath:a}]}),Hrr={layer:sp.effect(c0,j.gen(function*(){let{env:e,hostRepoDir:t,worktreePath:r,copyToWorktree:n,name:o,sandboxProvider:i,branchStrategy:s,hooks:a,signal:c,timeouts:l}=yield*jB,u=s.type==="head",d=s.type==="branch"?s.branch:void 0,f=s.type==="branch"?s.baseBranch:void 0,m=yield*Tc.FileSystem,b=yield*Ua,S=()=>vO(t).pipe(j.catchAll(_=>j.sync(()=>{console.error("[sandcastle] Warning: failed to prune stale worktrees:",_.message)})),j.andThen(d?XE(t,{branch:d,baseBranch:f,path:r}):XE(t,{name:o,path:r})),j.provideService(Tc.FileSystem,m));return{withSandbox:_=>{if(i.tag==="none"){let R;return u?(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,t,c):j.void).pipe(j.andThen(j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:t}),({sandbox:A,worktreePath:$})=>_({hostWorktreePath:t,sandboxRepoPath:$},A),({handle:A})=>j.tryPromise({try:()=>A.close(),catch:()=>{}}).pipe(j.orDie)).pipe(j.map(A=>({value:A,preservedWorktreePath:void 0}))))):j.acquireUseRelease(S(),A=>(n&&n.length>0?b.spinner("Copying to worktree",t0(n,t,A.path,l?.copyToWorktreeMs)):j.succeed(void 0)).pipe(j.andThen(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,A.path,c):j.void),j.andThen(j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:A.path}),({sandbox:$,worktreePath:M})=>_({hostWorktreePath:A.path,sandboxRepoPath:M},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)))),(A,$)=>qge(A.path,t,$).pipe(j.tap(M=>{R=M}),j.asVoid,j.orDie)).pipe(j.map(A=>({value:A,preservedWorktreePath:R})),j.mapError(A=>Gge(R,A)))}if(i.tag==="isolated"){let R;return j.acquireUseRelease(S(),A=>(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,A.path,c):j.void).pipe(j.andThen(j.acquireUseRelease(zm({provider:i,hostRepoDir:A.path,env:e,copyPaths:n}),({sandbox:$,worktreePath:M,handle:L})=>_({hostWorktreePath:A.path,sandboxRepoPath:M,applyToHost:()=>TO(A.path,L)},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)))),(A,$)=>qge(A.path,t,$).pipe(j.tap(M=>{R=M}),j.asVoid,j.orDie)).pipe(j.map(A=>({value:A,preservedWorktreePath:R})),j.mapError(A=>Gge(R,A)))}if(u){let R=Bge(t,".git");return(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,t,c):j.void).pipe(j.andThen(IO(R)),j.provideService(Tc.FileSystem,m),j.mapError(A=>new si({message:`Failed to resolve git mounts: ${A}`})),j.flatMap(A=>o0(A,t,wp)),j.flatMap(A=>j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:t,gitMounts:A,repoDir:wp}),({sandbox:$,worktreePath:M,handle:L})=>_({hostWorktreePath:t,sandboxRepoPath:M,bindMountHandle:L},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)).pipe(j.map($=>({value:$,preservedWorktreePath:void 0})))))}let E;return j.acquireUseRelease(S(),R=>(n&&n.length>0?b.spinner("Copying to worktree",t0(n,t,R.path,l?.copyToWorktreeMs)):j.succeed(void 0)).pipe(j.andThen(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,R.path,c):j.void),j.andThen(IO(Bge(t,".git")).pipe(j.provideService(Tc.FileSystem,m),j.mapError(A=>new si({message:`Failed to resolve git mounts: ${A}`})))),j.flatMap(A=>o0(A,R.path,wp)),j.flatMap(A=>j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:R.path,gitMounts:A,repoDir:wp}),({sandbox:$,worktreePath:M,handle:L})=>_({hostWorktreePath:R.path,sandboxRepoPath:M,bindMountHandle:L},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)))),(R,A)=>qge(R.path,t,A).pipe(j.tap($=>{E=$}),j.asVoid,j.orDie)).pipe(j.map(R=>({value:R,preservedWorktreePath:E})),j.mapError(R=>Gge(E,R)))}}}))}});var tst=p(()=>{"use strict"});var kwn,Wge=p(()=>{"use strict";kwn=Symbol.for("@ai-hero/sandcastle/run-abort-metadata")});var Dwn,UB=p(()=>{"use strict";bO();Hu();JE();Ha();Sy();n0();tst();Wge();Yre();Dwn=10*60});var AO=p(()=>{"use strict";Ha()});var OO=p(()=>{"use strict"});var rst=p(()=>{"use strict";Hu()});var $O=p(()=>{"use strict"});var MO=p(()=>{"use strict";Hu();Ha();JE()});var Zge,DO=p(()=>{"use strict";Zge={object:e=>({_tag:"object",tag:e.tag,schema:e.schema,maxRetries:e.maxRetries}),string:e=>({_tag:"string",tag:e.tag,maxRetries:e.maxRetries})}});var ost=p(()=>{"use strict";DO()});var NO=p(()=>{"use strict";ek();RB();Yt();Hu();UB();AO();Sy();OO();rst();bO();$O();tk();MO();DO();ost();Wge()});var ust=p(()=>{"use strict"});var oye=p(()=>{"use strict";ust()});var iye=p(()=>{"use strict"});var dst=p(()=>{"use strict";Tge();Hu();JE();AO();Sy();i0();n0();OO();$O();EO();PO();r0();tk();tk();MO();oye();iye();ek()});var pst=p(()=>{"use strict"});var sye=p(()=>{"use strict";Hu();OO();$O();UB();bO();MO();AO();JE();NO();n0();Sy();PO();r0();tk();EO();ek();i0();RB();pst()});var fst=p(()=>{"use strict";Hu();JE();AO();Sy();i0();n0();sye();NO();UB();bO();OO();$O();PO();r0();tk();zge();EO();ek();RB();MO();oye();iye()});var aye=p(()=>{"use strict"});var mst=p(()=>{cR();cR()});var hst,gst,Xrr,yst=p(()=>{"use strict";mst();DO();hst="agent-output",gst=ki.object({success:ki.boolean(),summary:ki.string(),key_changes_made:ki.array(ki.string()),key_learnings:ki.array(ki.string()),should_fully_stop:ki.boolean()}),Xrr=Zge.object({tag:hst,schema:gst})});var bst=p(()=>{"use strict";ek()});var cye,xst=p(()=>{"use strict";Yt();Vl();xC();cye=Cze.liveness});var Sst=p(()=>{"use strict";aye()});var kst=p(()=>{"use strict"});var HB=p(()=>{"use strict";NO();NO();dst();sye();fst();aye();DO();yst();bst();xst();Ure();Sst();kst();Bi()});var lye=p(()=>{"use strict"});var qB=p(()=>{"use strict";lye()});var Est=p(()=>{"use strict"});var V0n,K0n,ky=p(()=>{"use strict";V0n=Object.freeze({minWallTimeMs:20*6e4,sampleIntervalMs:3e4,idleCpuThresholdMs:5}),K0n=64*1024*1024});function anr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zO(){if(Rst)return _y;Rst=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function r(s){return Array.isArray(s)?s:e(s)?[]:[s]}function n(s,a){if(a){let c=Object.keys(a);for(let l=0,u=c.length;l<u;l+=1){let d=c[l];s[d]=a[d]}}return s}function o(s,a){let c="";for(let l=0;l<a;l+=1)c+=s;return c}function i(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return _y.isNothing=e,_y.isObject=t,_y.toArray=r,_y.repeat=o,_y.isNegativeZero=i,_y.extend=n,_y}function LO(){if(Tst)return uye;Tst=1;function e(r,n){let o="",i=r.reason||"(unknown reason)";return r.mark?(r.mark.name&&(o+='in "'+r.mark.name+'" '),o+="("+(r.mark.line+1)+":"+(r.mark.column+1)+")",!n&&r.mark.snippet&&(o+=`
247
+ Worktree removed (no uncommitted changes)`),wO(e,t).pipe(j.map(()=>{}))))),Gge=(e,t)=>{if(e!==void 0){if(t instanceof KE)return new KE({message:t.message,timeoutMs:t.timeoutMs,preservedWorktreePath:e});if(t instanceof VE)return new VE({message:t.message,preservedWorktreePath:e})}return t},Urr=e=>j.gen(function*(){let t=yield*Tc.FileSystem,r=e;for(;;){let n=yield*t.stat(r).pipe(j.map(s=>({gitPath:r,stat:s})),j.catchSome(s=>s._tag==="SystemError"&&s.reason==="NotFound"?_t.some(j.succeed(void 0)):_t.none()));if(n!==void 0)return n;let o=est(r),i=est(o);if(i===o){let s=yield*t.stat(e);return{gitPath:e,stat:s}}r=Bge(i,".git")}}),IO=e=>j.gen(function*(){let t=yield*Tc.FileSystem,r=yield*Urr(e),{stat:n}=r;if(e=r.gitPath,n.type==="Directory")return[{hostPath:e,sandboxPath:e}];let i=(yield*t.readFileString(e)).trim().match(/^gitdir:\s*(.+)$/);if(!i)return[{hostPath:e,sandboxPath:e}];let s=i[1],a=Lrr(s,"..","..");return[{hostPath:e,sandboxPath:e},{hostPath:a,sandboxPath:a}]}),Hrr={layer:sp.effect(c0,j.gen(function*(){let{env:e,hostRepoDir:t,worktreePath:r,copyToWorktree:n,name:o,sandboxProvider:i,branchStrategy:s,hooks:a,signal:c,timeouts:l}=yield*jB,u=s.type==="head",d=s.type==="branch"?s.branch:void 0,f=s.type==="branch"?s.baseBranch:void 0,m=yield*Tc.FileSystem,b=yield*Ua,S=()=>vO(t).pipe(j.catchAll(_=>j.sync(()=>{console.error("[sandcastle] Warning: failed to prune stale worktrees:",_.message)})),j.andThen(d?XE(t,{branch:d,baseBranch:f,path:r}):XE(t,{name:o,path:r})),j.provideService(Tc.FileSystem,m));return{withSandbox:_=>{if(i.tag==="none"){let R;return u?(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,t,c):j.void).pipe(j.andThen(j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:t}),({sandbox:A,worktreePath:$})=>_({hostWorktreePath:t,sandboxRepoPath:$},A),({handle:A})=>j.tryPromise({try:()=>A.close(),catch:()=>{}}).pipe(j.orDie)).pipe(j.map(A=>({value:A,preservedWorktreePath:void 0}))))):j.acquireUseRelease(S(),A=>(n&&n.length>0?b.spinner("Copying to worktree",t0(n,t,A.path,l?.copyToWorktreeMs)):j.succeed(void 0)).pipe(j.andThen(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,A.path,c):j.void),j.andThen(j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:A.path}),({sandbox:$,worktreePath:M})=>_({hostWorktreePath:A.path,sandboxRepoPath:M},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)))),(A,$)=>qge(A.path,t,$).pipe(j.tap(M=>{R=M}),j.asVoid,j.orDie)).pipe(j.map(A=>({value:A,preservedWorktreePath:R})),j.mapError(A=>Gge(R,A)))}if(i.tag==="isolated"){let R;return j.acquireUseRelease(S(),A=>(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,A.path,c):j.void).pipe(j.andThen(j.acquireUseRelease(zm({provider:i,hostRepoDir:A.path,env:e,copyPaths:n}),({sandbox:$,worktreePath:M,handle:L})=>_({hostWorktreePath:A.path,sandboxRepoPath:M,applyToHost:()=>TO(A.path,L)},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)))),(A,$)=>qge(A.path,t,$).pipe(j.tap(M=>{R=M}),j.asVoid,j.orDie)).pipe(j.map(A=>({value:A,preservedWorktreePath:R})),j.mapError(A=>Gge(R,A)))}if(u){let R=Bge(t,".git");return(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,t,c):j.void).pipe(j.andThen(IO(R)),j.provideService(Tc.FileSystem,m),j.mapError(A=>new si({message:`Failed to resolve git mounts: ${A}`})),j.flatMap(A=>o0(A,t,wp)),j.flatMap(A=>j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:t,gitMounts:A,repoDir:wp}),({sandbox:$,worktreePath:M,handle:L})=>_({hostWorktreePath:t,sandboxRepoPath:M,bindMountHandle:L},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)).pipe(j.map($=>({value:$,preservedWorktreePath:void 0})))))}let E;return j.acquireUseRelease(S(),R=>(n&&n.length>0?b.spinner("Copying to worktree",t0(n,t,R.path,l?.copyToWorktreeMs)):j.succeed(void 0)).pipe(j.andThen(a?.host?.onWorktreeReady?.length?Nm(a.host.onWorktreeReady,R.path,c):j.void),j.andThen(IO(Bge(t,".git")).pipe(j.provideService(Tc.FileSystem,m),j.mapError(A=>new si({message:`Failed to resolve git mounts: ${A}`})))),j.flatMap(A=>o0(A,R.path,wp)),j.flatMap(A=>j.acquireUseRelease(zm({provider:i,hostRepoDir:t,env:e,worktreeOrRepoPath:R.path,gitMounts:A,repoDir:wp}),({sandbox:$,worktreePath:M,handle:L})=>_({hostWorktreePath:R.path,sandboxRepoPath:M,bindMountHandle:L},$),({handle:$})=>j.tryPromise({try:()=>$.close(),catch:()=>{}}).pipe(j.orDie)))),(R,A)=>qge(R.path,t,A).pipe(j.tap($=>{E=$}),j.asVoid,j.orDie)).pipe(j.map(R=>({value:R,preservedWorktreePath:E})),j.mapError(R=>Gge(E,R)))}}}))}});var tst=p(()=>{"use strict"});var kwn,Wge=p(()=>{"use strict";kwn=Symbol.for("@ai-hero/sandcastle/run-abort-metadata")});var Mwn,UB=p(()=>{"use strict";bO();Hu();JE();Ha();Sy();n0();tst();Wge();Yre();Mwn=10*60});var AO=p(()=>{"use strict";Ha()});var OO=p(()=>{"use strict"});var rst=p(()=>{"use strict";Hu()});var $O=p(()=>{"use strict"});var MO=p(()=>{"use strict";Hu();Ha();JE()});var Zge,DO=p(()=>{"use strict";Zge={object:e=>({_tag:"object",tag:e.tag,schema:e.schema,maxRetries:e.maxRetries}),string:e=>({_tag:"string",tag:e.tag,maxRetries:e.maxRetries})}});var ost=p(()=>{"use strict";DO()});var NO=p(()=>{"use strict";ek();RB();Yt();Hu();UB();AO();Sy();OO();rst();bO();$O();tk();MO();DO();ost();Wge()});var ust=p(()=>{"use strict"});var oye=p(()=>{"use strict";ust()});var iye=p(()=>{"use strict"});var dst=p(()=>{"use strict";Tge();Hu();JE();AO();Sy();i0();n0();OO();$O();EO();PO();r0();tk();tk();MO();oye();iye();ek()});var pst=p(()=>{"use strict"});var sye=p(()=>{"use strict";Hu();OO();$O();UB();bO();MO();AO();JE();NO();n0();Sy();PO();r0();tk();EO();ek();i0();RB();pst()});var fst=p(()=>{"use strict";Hu();JE();AO();Sy();i0();n0();sye();NO();UB();bO();OO();$O();PO();r0();tk();zge();EO();ek();RB();MO();oye();iye()});var aye=p(()=>{"use strict"});var mst=p(()=>{cR();cR()});var hst,gst,Xrr,yst=p(()=>{"use strict";mst();DO();hst="agent-output",gst=ki.object({success:ki.boolean(),summary:ki.string(),key_changes_made:ki.array(ki.string()),key_learnings:ki.array(ki.string()),should_fully_stop:ki.boolean()}),Xrr=Zge.object({tag:hst,schema:gst})});var bst=p(()=>{"use strict";ek()});var cye,xst=p(()=>{"use strict";Yt();Vl();xC();cye=Cze.liveness});var Sst=p(()=>{"use strict";aye()});var kst=p(()=>{"use strict"});var HB=p(()=>{"use strict";NO();NO();dst();sye();fst();aye();DO();yst();bst();xst();Ure();Sst();kst();Bi()});var lye=p(()=>{"use strict"});var qB=p(()=>{"use strict";lye()});var Est=p(()=>{"use strict"});var W0n,V0n,ky=p(()=>{"use strict";W0n=Object.freeze({minWallTimeMs:20*6e4,sampleIntervalMs:3e4,idleCpuThresholdMs:5}),V0n=64*1024*1024});function anr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zO(){if(Rst)return _y;Rst=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function r(s){return Array.isArray(s)?s:e(s)?[]:[s]}function n(s,a){if(a){let c=Object.keys(a);for(let l=0,u=c.length;l<u;l+=1){let d=c[l];s[d]=a[d]}}return s}function o(s,a){let c="";for(let l=0;l<a;l+=1)c+=s;return c}function i(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return _y.isNothing=e,_y.isObject=t,_y.toArray=r,_y.repeat=o,_y.isNegativeZero=i,_y.extend=n,_y}function LO(){if(Tst)return uye;Tst=1;function e(r,n){let o="",i=r.reason||"(unknown reason)";return r.mark?(r.mark.name&&(o+='in "'+r.mark.name+'" '),o+="("+(r.mark.line+1)+":"+(r.mark.column+1)+")",!n&&r.mark.snippet&&(o+=`
248
248
 
249
249
  `+r.mark.snippet),i+" "+o):i}function t(r,n){Error.call(this),this.name="YAMLException",this.reason=r,this.mark=n,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(n){return this.name+": "+e(this,n)},uye=t,uye}function cnr(){if(Cst)return dye;Cst=1;let e=zO();function t(o,i,s,a,c){let l="",u="",d=Math.floor(c/2)-1;return a-i>d&&(l=" ... ",i=a-d+l.length),s-a>d&&(u=" ...",s=a+d-u.length),{str:l+o.slice(i,s).replace(/\t/g,"\u2192")+u,pos:a-i+l.length}}function r(o,i){return e.repeat(" ",i-o.length)+o}function n(o,i){if(i=Object.create(i||null),!o.buffer)return null;i.maxLength||(i.maxLength=79),typeof i.indent!="number"&&(i.indent=1),typeof i.linesBefore!="number"&&(i.linesBefore=3),typeof i.linesAfter!="number"&&(i.linesAfter=2);let s=/\r?\n|\r|\0/g,a=[0],c=[],l,u=-1;for(;l=s.exec(o.buffer);)c.push(l.index),a.push(l.index+l[0].length),o.position<=l.index&&u<0&&(u=a.length-2);u<0&&(u=a.length-1);let d="",f=Math.min(o.line+i.linesAfter,c.length).toString().length,m=i.maxLength-(i.indent+f+3);for(let S=1;S<=i.linesBefore&&!(u-S<0);S++){let _=t(o.buffer,a[u-S],c[u-S],o.position-(a[u]-a[u-S]),m);d=e.repeat(" ",i.indent)+r((o.line-S+1).toString(),f)+" | "+_.str+`
250
250
  `+d}let b=t(o.buffer,a[u],c[u],o.position,m);d+=e.repeat(" ",i.indent)+r((o.line+1).toString(),f)+" | "+b.str+`
@@ -275,7 +275,7 @@ Worktree removed (no uncommitted changes)`),wO(e,t).pipe(j.map(()=>{}))))),Gge=(
275
275
  `+v.slice(pe,xe),pe=xe+1),we=Be;return We+=`
276
276
  `,v.length-pe>q&&we>pe?We+=v.slice(pe,we)+`
277
277
  `+v.slice(we+1):We+=v.slice(pe),We.slice(1)}function aa(v){let q="",de=0;for(let ue=0;ue<v.length;de>=65536?ue+=2:ue++){de=Ul(v,ue);let pe=U[de];!pe&&_n(de)?(q+=v[ue],de>=65536&&(q+=v[ue+1])):q+=pe||ae(de)}return q}function Ly(v,q,de){let ue="",pe=v.tag;for(let xe=0,we=de.length;xe<we;xe+=1){let Be=de[xe];v.replacer&&(Be=v.replacer.call(de,String(xe),Be)),(P(v,q,Be,!1,!1)||typeof Be>"u"&&P(v,q,null,!1,!1))&&(ue!==""&&(ue+=","+(v.condenseFlow?"":" ")),ue+=v.dump)}v.tag=pe,v.dump="["+ue+"]"}function Fy(v,q,de,ue){let pe="",xe=v.tag;for(let we=0,Be=de.length;we<Be;we+=1){let We=de[we];v.replacer&&(We=v.replacer.call(de,String(we),We)),(P(v,q+1,We,!0,!0,!1,!0)||typeof We>"u"&&P(v,q+1,null,!0,!0,!1,!0))&&((!ue||pe!=="")&&(pe+=Bt(v,q)),v.dump&&a===v.dump.charCodeAt(0)?pe+="-":pe+="- ",pe+=v.dump)}v.tag=xe,v.dump=pe||"[]"}function w0(v,q,de){let ue="",pe=v.tag,xe=Object.keys(de);for(let we=0,Be=xe.length;we<Be;we+=1){let We="";ue!==""&&(We+=", "),v.condenseFlow&&(We+='"');let mt=xe[we],bt=de[mt];v.replacer&&(bt=v.replacer.call(de,mt,bt)),P(v,q,mt,!1,!1)&&(v.dump.length>1024&&(We+="? "),We+=v.dump+(v.condenseFlow?'"':"")+":"+(v.condenseFlow?"":" "),P(v,q,bt,!1,!1)&&(We+=v.dump,ue+=We))}v.tag=pe,v.dump="{"+ue+"}"}function h(v,q,de,ue){let pe="",xe=v.tag,we=Object.keys(de);if(v.sortKeys===!0)we.sort();else if(typeof v.sortKeys=="function")we.sort(v.sortKeys);else if(v.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Be=0,We=we.length;Be<We;Be+=1){let mt="";(!ue||pe!=="")&&(mt+=Bt(v,q));let bt=we[Be],pr=de[bt];if(v.replacer&&(pr=v.replacer.call(de,bt,pr)),!P(v,q+1,bt,!0,!0,!0))continue;let An=v.tag!==null&&v.tag!=="?"||v.dump&&v.dump.length>1024;An&&(v.dump&&a===v.dump.charCodeAt(0)?mt+="?":mt+="? "),mt+=v.dump,An&&(mt+=Bt(v,q)),P(v,q+1,pr,!0,An)&&(v.dump&&a===v.dump.charCodeAt(0)?mt+=":":mt+=": ",mt+=v.dump,pe+=mt)}v.tag=xe,v.dump=pe||"{}"}function D(v,q,de){let ue=de?v.explicitTypes:v.implicitTypes;for(let pe=0,xe=ue.length;pe<xe;pe+=1){let we=ue[pe];if((we.instanceOf||we.predicate)&&(!we.instanceOf||typeof q=="object"&&q instanceof we.instanceOf)&&(!we.predicate||we.predicate(q))){if(de?we.multi&&we.representName?v.tag=we.representName(q):v.tag=we.tag:v.tag="?",we.represent){let Be=v.styleMap[we.tag]||we.defaultStyle,We;if(n.call(we.represent)==="[object Function]")We=we.represent(q,Be);else if(o.call(we.represent,Be))We=we.represent[Be](q,Be);else throw new t("!<"+we.tag+'> tag resolver accepts not "'+Be+'" style');v.dump=We}return!0}}return!1}function P(v,q,de,ue,pe,xe,we){v.tag=null,v.dump=de,D(v,de,!1)||D(v,de,!0);let Be=n.call(v.dump),We=ue;ue&&(ue=v.flowLevel<0||v.flowLevel>q);let mt=Be==="[object Object]"||Be==="[object Array]",bt,pr;if(mt&&(bt=v.duplicates.indexOf(de),pr=bt!==-1),(v.tag!==null&&v.tag!=="?"||pr||v.indent!==2&&q>0)&&(pe=!1),pr&&v.usedDuplicates[bt])v.dump="*ref_"+bt;else{if(mt&&pr&&!v.usedDuplicates[bt]&&(v.usedDuplicates[bt]=!0),Be==="[object Object]")ue&&Object.keys(v.dump).length!==0?(h(v,q,v.dump,pe),pr&&(v.dump="&ref_"+bt+v.dump)):(w0(v,q,v.dump),pr&&(v.dump="&ref_"+bt+" "+v.dump));else if(Be==="[object Array]")ue&&v.dump.length!==0?(v.noArrayIndent&&!we&&q>0?Fy(v,q-1,v.dump,pe):Fy(v,q,v.dump,pe),pr&&(v.dump="&ref_"+bt+v.dump)):(Ly(v,q,v.dump),pr&&(v.dump="&ref_"+bt+" "+v.dump));else if(Be==="[object String]")v.tag!=="?"&&Dy(v,v.dump,q,xe,We);else{if(Be==="[object Undefined]")return!1;if(v.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Be)}if(v.tag!==null&&v.tag!=="?"){let An=encodeURI(v.tag[0]==="!"?v.tag.slice(1):v.tag).replace(/!/g,"%21");v.tag[0]==="!"?An="!"+An:An.slice(0,18)==="tag:yaml.org,2002:"?An="!!"+An.slice(18):An="!<"+An+">",v.dump=An+" "+v.dump}}return!0}function z(v,q){let de=[],ue=[];N(v,de,ue);let pe=ue.length;for(let xe=0;xe<pe;xe+=1)q.duplicates.push(de[ue[xe]]);q.usedDuplicates=new Array(pe)}function N(v,q,de){if(v!==null&&typeof v=="object"){let ue=q.indexOf(v);if(ue!==-1)de.indexOf(ue)===-1&&de.push(ue);else if(q.push(v),Array.isArray(v))for(let pe=0,xe=v.length;pe<xe;pe+=1)N(v[pe],q,de);else{let pe=Object.keys(v);for(let xe=0,we=pe.length;xe<we;xe+=1)N(v[pe[xe]],q,de)}}}function B(v,q){q=q||{};let de=new Qe(q);de.noRefs||z(v,de);let ue=v;return de.replacer&&(ue=de.replacer.call({"":ue},"",ue)),P(de,0,ue,!0,!0)?de.dump+`
278
- `:""}return Aye.dump=B,Aye}function dnr(){if(Jst)return Ts;Jst=1;let e=lnr(),t=unr();function r(n,o){return function(){throw new Error("Function yaml."+n+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return Ts.Type=sa(),Ts.Schema=Qst(),Ts.FAILSAFE_SCHEMA=tat(),Ts.JSON_SCHEMA=sat(),Ts.CORE_SCHEMA=aat(),Ts.DEFAULT_SCHEMA=Oye(),Ts.load=e.load,Ts.loadAll=e.loadAll,Ts.dump=t.dump,Ts.YAMLException=LO(),Ts.types={binary:uat(),float:iat(),map:eat(),null:rat(),pairs:pat(),set:fat(),timestamp:cat(),bool:nat(),int:oat(),merge:lat(),omap:dat(),seq:Xst(),str:Yst()},Ts.safeLoad=r("safeLoad","load"),Ts.safeLoadAll=r("safeLoadAll","loadAll"),Ts.safeDump=r("safeDump","dump"),Ts}var Ts,GB,_y,Rst,uye,Tst,dye,Cst,pye,Pst,fye,Ist,mye,Ast,hye,Ost,gye,$st,yye,Mst,bye,Dst,xye,Nst,Sye,zst,kye,Lst,_ye,Fst,wye,jst,vye,Ust,Eye,Hst,Rye,qst,Tye,Gst,Cye,Bst,Pye,Wst,Iye,Vst,Kst,Aye,Zst,Jst,pnr,$ye,J0n,Q0n,Y0n,X0n,eRn,tRn,rRn,nRn,oRn,iRn,sRn,aRn,cRn,lRn,Mye=p(()=>{Ts={},GB={},_y={};Aye={};pnr=dnr(),$ye=anr(pnr),{Type:J0n,Schema:Q0n,FAILSAFE_SCHEMA:Y0n,JSON_SCHEMA:X0n,CORE_SCHEMA:eRn,DEFAULT_SCHEMA:tRn,load:rRn,loadAll:nRn,dump:oRn,YAMLException:iRn,types:sRn,safeLoad:aRn,safeLoadAll:cRn,safeDump:lRn}=$ye});var mat=p(()=>{"use strict";Mye();wi();fw();wi()});var BB=p(()=>{"use strict";mat();wi()});var Dye=p(()=>{});var hat=p(()=>{"use strict";BB()});var CRn,PRn,IRn,ARn,FO=p(()=>{"use strict";Dye();hat();CRn=30*60*1e3,PRn=60*1e3,IRn=60*1e3,ARn=5*1e3});var yat=p(()=>{"use strict";wi();h_();ky();BB();FO()});var zye=p(()=>{"use strict";Dye();Bi();Bi()});var bat=p(()=>{"use strict"});var Lye=p(()=>{"use strict";bat()});var xat,YRn,hnr,XRn,Sat=p(()=>{"use strict";dC();xat="agent-output",YRn=`<${xat}>`,hnr=`</${xat}>`,XRn=w.object({success:w.boolean(),summary:w.string(),key_changes_made:w.array(w.string()),key_learnings:w.array(w.string()),should_fully_stop:w.boolean()})});var Fye=p(()=>{"use strict"});var jye=p(()=>{"use strict"});var Uye=p(()=>{"use strict";zye()});var vat=p(()=>{"use strict";HB();qB();Est();yat();zye();Lye();ine();Bi();Sat();Fye();jye();Uye();Uye()});var Eat=p(()=>{"use strict";Bi();ine();vat();Fye();jye()});var Rat=p(()=>{"use strict"});var Tat=p(()=>{"use strict"});var Lm=p(()=>{"use strict";Yt()});var vnr,Enr,Rnr,Cat=p(()=>{"use strict";dC();vnr=w.object({kind:w.string().default(""),value:w.string().default("")}),Enr=w.object({kind:w.string().default(""),number:w.union([w.number(),w.string()]).optional().default(""),title:w.string().default(""),slug:w.string().default(""),worktree:w.string().default(""),handoff:w.string().default(""),started_at:w.string().default(""),activity:w.string().default(""),phase:w.string().default(""),heartbeat_glyph:w.union([w.string(),w.number(),w.null()]).optional().default(""),heartbeat_pid:w.union([w.string(),w.number(),w.null()]).optional().default(""),runner:w.string().default(""),model:w.string().default(""),model_tier:w.string().default(""),effort:w.string().default(""),retries:w.number().default(0),last_stream_line:w.string().default(""),run_mode:w.string().default(""),last_commit_at:w.string().default(""),last_loc_progress_at:w.string().default(""),last_event_at:w.string().default(""),iteration:w.union([w.number(),w.string()]).optional().default(""),base:w.string().default(""),base_ref:w.string().default(""),base_sha:w.string().default(""),base_source:w.string().default(""),base_remote_reachable:w.boolean().default(!1),base_local_sha:w.string().default(""),base_local_ahead:w.number().default(0),base_local_behind:w.number().default(0),tools_called_count:w.number().default(0),text_chunk_count:w.number().default(0),reasoning_events:w.number().default(0),reasoning_tokens:w.number().default(0),waiting_count:w.number().default(0),loc_added:w.number().default(0),loc_removed:w.number().default(0),loc_peak_added:w.number().default(0),loc_peak_removed:w.number().default(0),input_tokens:w.number().default(0),output_tokens:w.number().default(0),cost_usd:w.number().default(0),context_tokens:w.number().default(0),output_shaping_variant:w.string().default(""),output_shaping_enabled:w.boolean().default(!1),reseed:w.object({version:w.literal(1).default(1),rounds:w.number().int().nonnegative().default(0),by_cause:w.object({gate:w.number().int().nonnegative().default(0),tier:w.number().int().nonnegative().default(0),review:w.number().int().nonnegative().default(0)}).default({gate:0,tier:0,review:0})}).default({version:1,rounds:0,by_cause:{gate:0,tier:0,review:0}}),blocked_on:w.string().default(""),blocked_detail:w.string().default(""),blocked_for_s:w.union([w.number(),w.string()]).optional().default(""),wait_kind:w.string().default(""),wait_subject:w.string().default(""),wait_pid:w.number().default(0),wait_started_at:w.string().default(""),wait_deadline:w.string().default(""),wait_escalation:w.string().default(""),implementer_runner_startup_before_ms:w.number().default(0),implementer_runner_startup_after_ms:w.number().default(0),implementer_skill_manifest_before_bytes:w.number().default(0),implementer_skill_manifest_after_bytes:w.number().default(0)}),Rnr=w.object({version:w.number().default(1),worker_id:w.string().default(""),pid:w.number().default(0),pid_start_time:w.string().default(""),log:w.string().default(""),started_at:w.string().default(""),origin:w.string().default(""),runner:w.string().default(""),session_artifact:w.string().default(""),filter:vnr.default({}),total:w.number().default(0),done:w.number().default(0),failed:w.number().default(0),blocked:w.number().default(0),completed:w.array(w.number()).default([]),queue:w.array(w.number()).default([]),current:Enr.default({}),durations_seconds:w.array(w.number()).default([]),envelope:w.object({posted:w.boolean().default(!1)}).default({posted:!1})})});var rk=p(()=>{"use strict";Lm();Cat()});var Pat=p(()=>{"use strict";Wb()});var UO=p(()=>{"use strict";Pat();rk();Wb()});var HO=p(()=>{"use strict";rk();UO();Wb();HB()});var Aat=p(()=>{"use strict"});var Tnr,$Cn,u0=p(()=>{"use strict";ky();Aat();FO();Tnr="red-trunk",$Cn=`refs/heads/${Tnr}`});var Oat=p(()=>{"use strict";Vl();Yt()});var Dat=p(()=>{"use strict";SL();Eat();Lye();Rat();Tat();HO();rk();HB();xL();u0();Oh();Oat()});var GO=p(()=>{"use strict";qD();E8();Lm()});var hPn,Bye=p(()=>{"use strict";GO();Lm();hPn=30*6e4});import{execFile as Inr}from"node:child_process";import{promisify as Anr}from"node:util";var wPn,vPn,Wye=p(()=>{"use strict";Vl();Yt();Bi();wPn=Qa["castle-history"].maxLines,vPn=Anr(Inr)});var zat=p(()=>{"use strict";Yt()});var Lat=p(()=>{"use strict";zat();Lm()});var Vye=p(()=>{"use strict";Bye();Lm();HO();Wye();Bi();UO();Lat();Oh()});var Tr=ee(ns=>{"use strict";var Kye=Symbol.for("yaml.alias"),Fat=Symbol.for("yaml.document"),WB=Symbol.for("yaml.map"),jat=Symbol.for("yaml.pair"),Zye=Symbol.for("yaml.scalar"),VB=Symbol.for("yaml.seq"),Fm=Symbol.for("yaml.node.type"),Nnr=e=>!!e&&typeof e=="object"&&e[Fm]===Kye,znr=e=>!!e&&typeof e=="object"&&e[Fm]===Fat,Lnr=e=>!!e&&typeof e=="object"&&e[Fm]===WB,Fnr=e=>!!e&&typeof e=="object"&&e[Fm]===jat,Uat=e=>!!e&&typeof e=="object"&&e[Fm]===Zye,jnr=e=>!!e&&typeof e=="object"&&e[Fm]===VB;function Hat(e){if(e&&typeof e=="object")switch(e[Fm]){case WB:case VB:return!0}return!1}function Unr(e){if(e&&typeof e=="object")switch(e[Fm]){case Kye:case WB:case Zye:case VB:return!0}return!1}var Hnr=e=>(Uat(e)||Hat(e))&&!!e.anchor;ns.ALIAS=Kye;ns.DOC=Fat;ns.MAP=WB;ns.NODE_TYPE=Fm;ns.PAIR=jat;ns.SCALAR=Zye;ns.SEQ=VB;ns.hasAnchor=Hnr;ns.isAlias=Nnr;ns.isCollection=Hat;ns.isDocument=znr;ns.isMap=Lnr;ns.isNode=Unr;ns.isPair=Fnr;ns.isScalar=Uat;ns.isSeq=jnr});var BO=ee(Jye=>{"use strict";var Si=Tr(),qa=Symbol("break visit"),qat=Symbol("skip children"),vp=Symbol("remove node");function KB(e,t){let r=Gat(t);Si.isDocument(e)?d0(null,e.contents,r,Object.freeze([e]))===vp&&(e.contents=null):d0(null,e,r,Object.freeze([]))}KB.BREAK=qa;KB.SKIP=qat;KB.REMOVE=vp;function d0(e,t,r,n){let o=Bat(e,t,r,n);if(Si.isNode(o)||Si.isPair(o))return Wat(e,n,o),d0(e,o,r,n);if(typeof o!="symbol"){if(Si.isCollection(t)){n=Object.freeze(n.concat(t));for(let i=0;i<t.items.length;++i){let s=d0(i,t.items[i],r,n);if(typeof s=="number")i=s-1;else{if(s===qa)return qa;s===vp&&(t.items.splice(i,1),i-=1)}}}else if(Si.isPair(t)){n=Object.freeze(n.concat(t));let i=d0("key",t.key,r,n);if(i===qa)return qa;i===vp&&(t.key=null);let s=d0("value",t.value,r,n);if(s===qa)return qa;s===vp&&(t.value=null)}}return o}async function ZB(e,t){let r=Gat(t);Si.isDocument(e)?await p0(null,e.contents,r,Object.freeze([e]))===vp&&(e.contents=null):await p0(null,e,r,Object.freeze([]))}ZB.BREAK=qa;ZB.SKIP=qat;ZB.REMOVE=vp;async function p0(e,t,r,n){let o=await Bat(e,t,r,n);if(Si.isNode(o)||Si.isPair(o))return Wat(e,n,o),p0(e,o,r,n);if(typeof o!="symbol"){if(Si.isCollection(t)){n=Object.freeze(n.concat(t));for(let i=0;i<t.items.length;++i){let s=await p0(i,t.items[i],r,n);if(typeof s=="number")i=s-1;else{if(s===qa)return qa;s===vp&&(t.items.splice(i,1),i-=1)}}}else if(Si.isPair(t)){n=Object.freeze(n.concat(t));let i=await p0("key",t.key,r,n);if(i===qa)return qa;i===vp&&(t.key=null);let s=await p0("value",t.value,r,n);if(s===qa)return qa;s===vp&&(t.value=null)}}return o}function Gat(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Bat(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Si.isMap(t))return r.Map?.(e,t,n);if(Si.isSeq(t))return r.Seq?.(e,t,n);if(Si.isPair(t))return r.Pair?.(e,t,n);if(Si.isScalar(t))return r.Scalar?.(e,t,n);if(Si.isAlias(t))return r.Alias?.(e,t,n)}function Wat(e,t,r){let n=t[t.length-1];if(Si.isCollection(n))n.items[e]=r;else if(Si.isPair(n))e==="key"?n.key=r:n.value=r;else if(Si.isDocument(n))n.contents=r;else{let o=Si.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}Jye.visit=KB;Jye.visitAsync=ZB});var Qye=ee(Kat=>{"use strict";var Vat=Tr(),qnr=BO(),Gnr={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bnr=e=>e.replace(/[!,[\]{}]/g,t=>Gnr[t]),WO=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),o=n.shift();switch(o){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,s]=n;return this.tags[i]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let s=/^\d+\.\d+$/.test(i);return r(6,`Unsupported YAML version ${i}`,s),!1}}default:return r(0,`Unknown directive ${o}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let s=t.slice(2,-1);return s==="!"||s==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),s)}let[,n,o]=t.match(/^(.*!)([^!]*)$/s);o||r(`The ${t} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(o)}catch(s){return r(String(s)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+Bnr(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),o;if(t&&n.length>0&&Vat.isNode(t.contents)){let i={};qnr.visit(t.contents,(s,a)=>{Vat.isNode(a)&&a.tag&&(i[a.tag]=!0)}),o=Object.keys(i)}else o=[];for(let[i,s]of n)i==="!!"&&s==="tag:yaml.org,2002:"||(!t||o.some(a=>a.startsWith(s)))&&r.push(`%TAG ${i} ${s}`);return r.join(`
278
+ `:""}return Aye.dump=B,Aye}function dnr(){if(Jst)return Ts;Jst=1;let e=lnr(),t=unr();function r(n,o){return function(){throw new Error("Function yaml."+n+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return Ts.Type=sa(),Ts.Schema=Qst(),Ts.FAILSAFE_SCHEMA=tat(),Ts.JSON_SCHEMA=sat(),Ts.CORE_SCHEMA=aat(),Ts.DEFAULT_SCHEMA=Oye(),Ts.load=e.load,Ts.loadAll=e.loadAll,Ts.dump=t.dump,Ts.YAMLException=LO(),Ts.types={binary:uat(),float:iat(),map:eat(),null:rat(),pairs:pat(),set:fat(),timestamp:cat(),bool:nat(),int:oat(),merge:lat(),omap:dat(),seq:Xst(),str:Yst()},Ts.safeLoad=r("safeLoad","load"),Ts.safeLoadAll=r("safeLoadAll","loadAll"),Ts.safeDump=r("safeDump","dump"),Ts}var Ts,GB,_y,Rst,uye,Tst,dye,Cst,pye,Pst,fye,Ist,mye,Ast,hye,Ost,gye,$st,yye,Mst,bye,Dst,xye,Nst,Sye,zst,kye,Lst,_ye,Fst,wye,jst,vye,Ust,Eye,Hst,Rye,qst,Tye,Gst,Cye,Bst,Pye,Wst,Iye,Vst,Kst,Aye,Zst,Jst,pnr,$ye,Z0n,J0n,Q0n,Y0n,X0n,eRn,tRn,rRn,nRn,oRn,iRn,sRn,aRn,cRn,Mye=p(()=>{Ts={},GB={},_y={};Aye={};pnr=dnr(),$ye=anr(pnr),{Type:Z0n,Schema:J0n,FAILSAFE_SCHEMA:Q0n,JSON_SCHEMA:Y0n,CORE_SCHEMA:X0n,DEFAULT_SCHEMA:eRn,load:tRn,loadAll:rRn,dump:nRn,YAMLException:oRn,types:iRn,safeLoad:sRn,safeLoadAll:aRn,safeDump:cRn}=$ye});var mat=p(()=>{"use strict";Mye();wi();fw();wi()});var BB=p(()=>{"use strict";mat();wi()});var Dye=p(()=>{});var hat=p(()=>{"use strict";BB()});var TRn,CRn,PRn,IRn,FO=p(()=>{"use strict";Dye();hat();TRn=30*60*1e3,CRn=60*1e3,PRn=60*1e3,IRn=5*1e3});var yat=p(()=>{"use strict";wi();h_();ky();BB();FO()});var zye=p(()=>{"use strict";Dye();Bi();Bi()});var bat=p(()=>{"use strict"});var Lye=p(()=>{"use strict";bat()});var xat,QRn,hnr,YRn,Sat=p(()=>{"use strict";dC();xat="agent-output",QRn=`<${xat}>`,hnr=`</${xat}>`,YRn=w.object({success:w.boolean(),summary:w.string(),key_changes_made:w.array(w.string()),key_learnings:w.array(w.string()),should_fully_stop:w.boolean()})});var Fye=p(()=>{"use strict"});var jye=p(()=>{"use strict"});var Uye=p(()=>{"use strict";zye()});var vat=p(()=>{"use strict";HB();qB();Est();yat();zye();Lye();ine();Bi();Sat();Fye();jye();Uye();Uye()});var Eat=p(()=>{"use strict";Bi();ine();vat();Fye();jye()});var Rat=p(()=>{"use strict"});var Tat=p(()=>{"use strict"});var Lm=p(()=>{"use strict";Yt()});var vnr,Enr,Rnr,Cat=p(()=>{"use strict";dC();vnr=w.object({kind:w.string().default(""),value:w.string().default("")}),Enr=w.object({kind:w.string().default(""),number:w.union([w.number(),w.string()]).optional().default(""),title:w.string().default(""),slug:w.string().default(""),worktree:w.string().default(""),handoff:w.string().default(""),started_at:w.string().default(""),activity:w.string().default(""),phase:w.string().default(""),heartbeat_glyph:w.union([w.string(),w.number(),w.null()]).optional().default(""),heartbeat_pid:w.union([w.string(),w.number(),w.null()]).optional().default(""),runner:w.string().default(""),model:w.string().default(""),model_tier:w.string().default(""),effort:w.string().default(""),retries:w.number().default(0),last_stream_line:w.string().default(""),run_mode:w.string().default(""),last_commit_at:w.string().default(""),last_loc_progress_at:w.string().default(""),last_event_at:w.string().default(""),iteration:w.union([w.number(),w.string()]).optional().default(""),base:w.string().default(""),base_ref:w.string().default(""),base_sha:w.string().default(""),base_source:w.string().default(""),base_remote_reachable:w.boolean().default(!1),base_local_sha:w.string().default(""),base_local_ahead:w.number().default(0),base_local_behind:w.number().default(0),tools_called_count:w.number().default(0),text_chunk_count:w.number().default(0),reasoning_events:w.number().default(0),reasoning_tokens:w.number().default(0),waiting_count:w.number().default(0),loc_added:w.number().default(0),loc_removed:w.number().default(0),loc_peak_added:w.number().default(0),loc_peak_removed:w.number().default(0),input_tokens:w.number().default(0),output_tokens:w.number().default(0),cost_usd:w.number().default(0),context_tokens:w.number().default(0),output_shaping_variant:w.string().default(""),output_shaping_enabled:w.boolean().default(!1),reseed:w.object({version:w.literal(1).default(1),rounds:w.number().int().nonnegative().default(0),by_cause:w.object({gate:w.number().int().nonnegative().default(0),tier:w.number().int().nonnegative().default(0),review:w.number().int().nonnegative().default(0)}).default({gate:0,tier:0,review:0})}).default({version:1,rounds:0,by_cause:{gate:0,tier:0,review:0}}),blocked_on:w.string().default(""),blocked_detail:w.string().default(""),blocked_for_s:w.union([w.number(),w.string()]).optional().default(""),wait_kind:w.string().default(""),wait_subject:w.string().default(""),wait_pid:w.number().default(0),wait_started_at:w.string().default(""),wait_deadline:w.string().default(""),wait_escalation:w.string().default(""),implementer_runner_startup_before_ms:w.number().default(0),implementer_runner_startup_after_ms:w.number().default(0),implementer_skill_manifest_before_bytes:w.number().default(0),implementer_skill_manifest_after_bytes:w.number().default(0)}),Rnr=w.object({version:w.number().default(1),worker_id:w.string().default(""),pid:w.number().default(0),pid_start_time:w.string().default(""),log:w.string().default(""),started_at:w.string().default(""),origin:w.string().default(""),runner:w.string().default(""),session_artifact:w.string().default(""),filter:vnr.default({}),total:w.number().default(0),done:w.number().default(0),failed:w.number().default(0),blocked:w.number().default(0),completed:w.array(w.number()).default([]),queue:w.array(w.number()).default([]),current:Enr.default({}),durations_seconds:w.array(w.number()).default([]),envelope:w.object({posted:w.boolean().default(!1)}).default({posted:!1})})});var rk=p(()=>{"use strict";Lm();Cat()});var Pat=p(()=>{"use strict";Wb()});var UO=p(()=>{"use strict";Pat();rk();Wb()});var HO=p(()=>{"use strict";rk();UO();Wb();HB()});var Aat=p(()=>{"use strict"});var Tnr,OCn,u0=p(()=>{"use strict";ky();Aat();FO();Tnr="red-trunk",OCn=`refs/heads/${Tnr}`});var Oat=p(()=>{"use strict";Vl();Yt()});var Dat=p(()=>{"use strict";SL();Eat();Lye();Rat();Tat();HO();rk();HB();xL();u0();Oh();Oat()});var GO=p(()=>{"use strict";qD();E8();Lm()});var mPn,Bye=p(()=>{"use strict";GO();Lm();mPn=30*6e4});import{execFile as Inr}from"node:child_process";import{promisify as Anr}from"node:util";var _Pn,wPn,Wye=p(()=>{"use strict";Vl();Yt();Bi();_Pn=Qa["castle-history"].maxLines,wPn=Anr(Inr)});var zat=p(()=>{"use strict";Yt()});var Lat=p(()=>{"use strict";zat();Lm()});var Vye=p(()=>{"use strict";Bye();Lm();HO();Wye();Bi();UO();Lat();Oh()});var Tr=ee(ns=>{"use strict";var Kye=Symbol.for("yaml.alias"),Fat=Symbol.for("yaml.document"),WB=Symbol.for("yaml.map"),jat=Symbol.for("yaml.pair"),Zye=Symbol.for("yaml.scalar"),VB=Symbol.for("yaml.seq"),Fm=Symbol.for("yaml.node.type"),Nnr=e=>!!e&&typeof e=="object"&&e[Fm]===Kye,znr=e=>!!e&&typeof e=="object"&&e[Fm]===Fat,Lnr=e=>!!e&&typeof e=="object"&&e[Fm]===WB,Fnr=e=>!!e&&typeof e=="object"&&e[Fm]===jat,Uat=e=>!!e&&typeof e=="object"&&e[Fm]===Zye,jnr=e=>!!e&&typeof e=="object"&&e[Fm]===VB;function Hat(e){if(e&&typeof e=="object")switch(e[Fm]){case WB:case VB:return!0}return!1}function Unr(e){if(e&&typeof e=="object")switch(e[Fm]){case Kye:case WB:case Zye:case VB:return!0}return!1}var Hnr=e=>(Uat(e)||Hat(e))&&!!e.anchor;ns.ALIAS=Kye;ns.DOC=Fat;ns.MAP=WB;ns.NODE_TYPE=Fm;ns.PAIR=jat;ns.SCALAR=Zye;ns.SEQ=VB;ns.hasAnchor=Hnr;ns.isAlias=Nnr;ns.isCollection=Hat;ns.isDocument=znr;ns.isMap=Lnr;ns.isNode=Unr;ns.isPair=Fnr;ns.isScalar=Uat;ns.isSeq=jnr});var BO=ee(Jye=>{"use strict";var Si=Tr(),qa=Symbol("break visit"),qat=Symbol("skip children"),vp=Symbol("remove node");function KB(e,t){let r=Gat(t);Si.isDocument(e)?d0(null,e.contents,r,Object.freeze([e]))===vp&&(e.contents=null):d0(null,e,r,Object.freeze([]))}KB.BREAK=qa;KB.SKIP=qat;KB.REMOVE=vp;function d0(e,t,r,n){let o=Bat(e,t,r,n);if(Si.isNode(o)||Si.isPair(o))return Wat(e,n,o),d0(e,o,r,n);if(typeof o!="symbol"){if(Si.isCollection(t)){n=Object.freeze(n.concat(t));for(let i=0;i<t.items.length;++i){let s=d0(i,t.items[i],r,n);if(typeof s=="number")i=s-1;else{if(s===qa)return qa;s===vp&&(t.items.splice(i,1),i-=1)}}}else if(Si.isPair(t)){n=Object.freeze(n.concat(t));let i=d0("key",t.key,r,n);if(i===qa)return qa;i===vp&&(t.key=null);let s=d0("value",t.value,r,n);if(s===qa)return qa;s===vp&&(t.value=null)}}return o}async function ZB(e,t){let r=Gat(t);Si.isDocument(e)?await p0(null,e.contents,r,Object.freeze([e]))===vp&&(e.contents=null):await p0(null,e,r,Object.freeze([]))}ZB.BREAK=qa;ZB.SKIP=qat;ZB.REMOVE=vp;async function p0(e,t,r,n){let o=await Bat(e,t,r,n);if(Si.isNode(o)||Si.isPair(o))return Wat(e,n,o),p0(e,o,r,n);if(typeof o!="symbol"){if(Si.isCollection(t)){n=Object.freeze(n.concat(t));for(let i=0;i<t.items.length;++i){let s=await p0(i,t.items[i],r,n);if(typeof s=="number")i=s-1;else{if(s===qa)return qa;s===vp&&(t.items.splice(i,1),i-=1)}}}else if(Si.isPair(t)){n=Object.freeze(n.concat(t));let i=await p0("key",t.key,r,n);if(i===qa)return qa;i===vp&&(t.key=null);let s=await p0("value",t.value,r,n);if(s===qa)return qa;s===vp&&(t.value=null)}}return o}function Gat(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Bat(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Si.isMap(t))return r.Map?.(e,t,n);if(Si.isSeq(t))return r.Seq?.(e,t,n);if(Si.isPair(t))return r.Pair?.(e,t,n);if(Si.isScalar(t))return r.Scalar?.(e,t,n);if(Si.isAlias(t))return r.Alias?.(e,t,n)}function Wat(e,t,r){let n=t[t.length-1];if(Si.isCollection(n))n.items[e]=r;else if(Si.isPair(n))e==="key"?n.key=r:n.value=r;else if(Si.isDocument(n))n.contents=r;else{let o=Si.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}Jye.visit=KB;Jye.visitAsync=ZB});var Qye=ee(Kat=>{"use strict";var Vat=Tr(),qnr=BO(),Gnr={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bnr=e=>e.replace(/[!,[\]{}]/g,t=>Gnr[t]),WO=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),o=n.shift();switch(o){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,s]=n;return this.tags[i]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let s=/^\d+\.\d+$/.test(i);return r(6,`Unsupported YAML version ${i}`,s),!1}}default:return r(0,`Unknown directive ${o}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let s=t.slice(2,-1);return s==="!"||s==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),s)}let[,n,o]=t.match(/^(.*!)([^!]*)$/s);o||r(`The ${t} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(o)}catch(s){return r(String(s)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+Bnr(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),o;if(t&&n.length>0&&Vat.isNode(t.contents)){let i={};qnr.visit(t.contents,(s,a)=>{Vat.isNode(a)&&a.tag&&(i[a.tag]=!0)}),o=Object.keys(i)}else o=[];for(let[i,s]of n)i==="!!"&&s==="tag:yaml.org,2002:"||(!t||o.some(a=>a.startsWith(s)))&&r.push(`%TAG ${i} ${s}`);return r.join(`
279
279
  `)}};WO.defaultYaml={explicit:!1,version:"1.2"};WO.defaultTags={"!!":"tag:yaml.org,2002:"};Kat.Directives=WO});var JB=ee(VO=>{"use strict";var Zat=Tr(),Wnr=BO();function Vnr(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Jat(e){let t=new Set;return Wnr.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function Qat(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function Knr(e,t){let r=[],n=new Map,o=null;return{onAnchor:i=>{r.push(i),o??(o=Jat(e));let s=Qat(t,o);return o.add(s),s},setAnchors:()=>{for(let i of r){let s=n.get(i);if(typeof s=="object"&&s.anchor&&(Zat.isScalar(s.node)||Zat.isCollection(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:n}}VO.anchorIsValid=Vnr;VO.anchorNames=Jat;VO.createNodeAnchors=Knr;VO.findNewAnchor=Qat});var Yye=ee(Yat=>{"use strict";function KO(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let o=0,i=n.length;o<i;++o){let s=n[o],a=KO(e,n,String(o),s);a===void 0?delete n[o]:a!==s&&(n[o]=a)}else if(n instanceof Map)for(let o of Array.from(n.keys())){let i=n.get(o),s=KO(e,n,o,i);s===void 0?n.delete(o):s!==i&&n.set(o,s)}else if(n instanceof Set)for(let o of Array.from(n)){let i=KO(e,n,o,o);i===void 0?n.delete(o):i!==o&&(n.delete(o),n.add(i))}else for(let[o,i]of Object.entries(n)){let s=KO(e,n,o,i);s===void 0?delete n[o]:s!==i&&(n[o]=s)}return e.call(t,r,n)}Yat.applyReviver=KO});var wy=ee(ect=>{"use strict";var Znr=Tr();function Xat(e,t,r){if(Array.isArray(e))return e.map((n,o)=>Xat(n,String(o),r));if(e&&typeof e.toJSON=="function"){if(!r||!Znr.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=i=>{n.res=i,delete r.onCreate};let o=e.toJSON(t,r);return r.onCreate&&r.onCreate(o),o}return typeof e=="bigint"&&!r?.keep?Number(e):e}ect.toJS=Xat});var QB=ee(rct=>{"use strict";var Jnr=Yye(),tct=Tr(),Qnr=wy(),Xye=class{constructor(t){Object.defineProperty(this,tct.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:n,onAnchor:o,reviver:i}={}){if(!tct.isDocument(t))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Qnr.toJS(this,"",s);if(typeof o=="function")for(let{count:c,res:l}of s.anchors.values())o(l,c);return typeof i=="function"?Jnr.applyReviver(i,{"":a},"",a):a}};rct.NodeBase=Xye});var ZO=ee(nct=>{"use strict";var Ynr=JB(),Xnr=BO(),f0=Tr(),eor=QB(),tor=wy(),ebe=class extends eor.NodeBase{constructor(t){super(f0.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],Xnr.visit(t,{Node:(i,s)=>{(f0.isAlias(s)||f0.hasAnchor(s))&&n.push(s)}}),r&&(r.aliasResolveCache=n));let o;for(let i of n){if(i===this)break;i.anchor===this.source&&(o=i)}return o}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:o,maxAliasCount:i}=r,s=this.resolve(o,r);if(!s){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(s);if(a||(tor.toJS(s,null,r),a=n.get(s)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=YB(o,s,n)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(t,r,n){let o=`*${this.source}`;if(t){if(Ynr.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(t.implicitKey)return`${o} `}return o}};function YB(e,t,r){if(f0.isAlias(t)){let n=t.resolve(e),o=r&&n&&r.get(n);return o?o.count*o.aliasCount:0}else if(f0.isCollection(t)){let n=0;for(let o of t.items){let i=YB(e,o,r);i>n&&(n=i)}return n}else if(f0.isPair(t)){let n=YB(e,t.key,r),o=YB(e,t.value,r);return Math.max(n,o)}return 1}nct.Alias=ebe});var ai=ee(tbe=>{"use strict";var ror=Tr(),nor=QB(),oor=wy(),ior=e=>!e||typeof e!="function"&&typeof e!="object",vy=class extends nor.NodeBase{constructor(t){super(ror.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:oor.toJS(this.value,t,r)}toString(){return String(this.value)}};vy.BLOCK_FOLDED="BLOCK_FOLDED";vy.BLOCK_LITERAL="BLOCK_LITERAL";vy.PLAIN="PLAIN";vy.QUOTE_DOUBLE="QUOTE_DOUBLE";vy.QUOTE_SINGLE="QUOTE_SINGLE";tbe.Scalar=vy;tbe.isScalarValue=ior});var JO=ee(ict=>{"use strict";var sor=ZO(),nk=Tr(),oct=ai(),aor="tag:yaml.org,2002:";function cor(e,t,r){if(t){let n=r.filter(i=>i.tag===t),o=n.find(i=>!i.format)??n[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return r.find(n=>n.identify?.(e)&&!n.format)}function lor(e,t,r){if(nk.isDocument(e)&&(e=e.contents),nk.isNode(e))return e;if(nk.isPair(e)){let d=r.schema[nk.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:o,onTagObj:i,schema:s,sourceObjects:a}=r,c;if(n&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=o(e)),new sor.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=aor+t.slice(2));let l=cor(e,t,s.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new oct.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?s[nk.MAP]:Symbol.iterator in Object(e)?s[nk.SEQ]:s[nk.MAP]}i&&(i(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new oct.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}ict.createNode=lor});var eW=ee(XB=>{"use strict";var uor=JO(),Ep=Tr(),dor=QB();function rbe(e,t,r){let n=r;for(let o=t.length-1;o>=0;--o){let i=t[o];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let s=[];s[i]=n,n=s}else n=new Map([[i,n]])}return uor.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var sct=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,nbe=class extends dor.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>Ep.isNode(n)||Ep.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(sct(t))this.add(r);else{let[n,...o]=t,i=this.get(n,!0);if(Ep.isCollection(i))i.addIn(o,r);else if(i===void 0&&this.schema)this.set(n,rbe(this.schema,o,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${o}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let o=this.get(r,!0);if(Ep.isCollection(o))return o.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...o]=t,i=this.get(n,!0);return o.length===0?!r&&Ep.isScalar(i)?i.value:i:Ep.isCollection(i)?i.getIn(o,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ep.isPair(r))return!1;let n=r.value;return n==null||t&&Ep.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let o=this.get(r,!0);return Ep.isCollection(o)?o.hasIn(n):!1}setIn(t,r){let[n,...o]=t;if(o.length===0)this.set(n,r);else{let i=this.get(n,!0);if(Ep.isCollection(i))i.setIn(o,r);else if(i===void 0&&this.schema)this.set(n,rbe(this.schema,o,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${o}`)}}};XB.Collection=nbe;XB.collectionFromPath=rbe;XB.isEmptyPath=sct});var QO=ee(tW=>{"use strict";var por=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function obe(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var mor=(e,t,r)=>e.endsWith(`
280
280
  `)?obe(r,t):r.includes(`
281
281
  `)?`
@@ -413,8 +413,8 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
413
413
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
414
414
  `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){HW(o,r.start),o.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,o=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",i=[];if(o&&r.sep&&!r.value){let s=[];for(let a=0;a<r.sep.length;++a){let c=r.sep[a];switch(c.type){case"newline":s.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(s.length=0);break;default:s.length=0}}s.length>=2&&(i=r.sep.splice(s[1]))}switch(this.type){case"anchor":case"tag":o||r.value?(i.push(this.sourceToken),t.items.push({start:i}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):o||r.value?(i.push(this.sourceToken),t.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ay(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(xut(r.key)&&!Ay(r.sep,"newline")){let s=k0(r.start),a=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:a,sep:c}]})}else i.length>0?r.sep=r.sep.concat(i,this.sourceToken):r.sep.push(this.sourceToken);else if(Ay(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let s=k0(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||o?t.items.push({start:i,key:null,sep:[this.sourceToken]}):Ay(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);o||r.value?(t.items.push({start:i,key:s,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(s):(Object.assign(r,{key:s,sep:[]}),this.onKeyLine=!0);return}default:{let s=this.startBlockValue(t);if(s){if(s.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Ay(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&t.items.push({start:i});this.stack.push(s);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let o=t.items[t.items.length-2]?.value?.end;if(Array.isArray(o)){HW(o,r.start),o.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Ay(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:o,sep:[]}):r.sep?this.stack.push(o):Object.assign(r,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let o=UW(n),i=k0(o);but(t);let s=t.end.splice(1,t.end.length);s.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
415
415
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
416
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=UW(t),n=k0(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=UW(t),n=k0(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Sut.Parser=Exe});var Eut=ee(S$=>{"use strict";var kut=pxe(),War=d$(),x$=m$(),Var=ube(),Kar=Tr(),Zar=vxe(),_ut=Rxe();function wut(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Zar.LineCounter||null,prettyErrors:t}}function Jar(e,t={}){let{lineCounter:r,prettyErrors:n}=wut(t),o=new _ut.Parser(r?.addNewLine),i=new kut.Composer(t),s=Array.from(i.compose(o.parse(e)));if(n&&r)for(let a of s)a.errors.forEach(x$.prettifyError(e,r)),a.warnings.forEach(x$.prettifyError(e,r));return s.length>0?s:Object.assign([],{empty:!0},i.streamInfo())}function vut(e,t={}){let{lineCounter:r,prettyErrors:n}=wut(t),o=new _ut.Parser(r?.addNewLine),i=new kut.Composer(t),s=null;for(let a of i.compose(o.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new x$.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(s.errors.forEach(x$.prettifyError(e,r)),s.warnings.forEach(x$.prettifyError(e,r))),s}function Qar(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let o=vut(e,r);if(!o)return null;if(o.warnings.forEach(i=>Var.warn(o.options.logLevel,i)),o.errors.length>0){if(o.options.logLevel!=="silent")throw o.errors[0];o.errors=[]}return o.toJS(Object.assign({reviver:n},r))}function Yar(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let o=Math.round(r);r=o<1?void 0:o>8?{indent:8}:{indent:o}}if(e===void 0){let{keepUndefined:o}=r??t??{};if(!o)return}return Kar.isDocument(e)&&!n?e.toString(r):new War.Document(e,n,r).toString(r)}S$.parse=Qar;S$.parseAllDocuments=Jar;S$.parseDocument=vut;S$.stringify=Yar});var Tut=ee(Wr=>{"use strict";var Xar=pxe(),ecr=d$(),tcr=Wbe(),Txe=m$(),rcr=ZO(),Oy=Tr(),ncr=Ty(),ocr=ai(),icr=Py(),scr=Iy(),acr=FW(),ccr=_xe(),lcr=vxe(),ucr=Rxe(),qW=Eut(),Rut=BO();Wr.Composer=Xar.Composer;Wr.Document=ecr.Document;Wr.Schema=tcr.Schema;Wr.YAMLError=Txe.YAMLError;Wr.YAMLParseError=Txe.YAMLParseError;Wr.YAMLWarning=Txe.YAMLWarning;Wr.Alias=rcr.Alias;Wr.isAlias=Oy.isAlias;Wr.isCollection=Oy.isCollection;Wr.isDocument=Oy.isDocument;Wr.isMap=Oy.isMap;Wr.isNode=Oy.isNode;Wr.isPair=Oy.isPair;Wr.isScalar=Oy.isScalar;Wr.isSeq=Oy.isSeq;Wr.Pair=ncr.Pair;Wr.Scalar=ocr.Scalar;Wr.YAMLMap=icr.YAMLMap;Wr.YAMLSeq=scr.YAMLSeq;Wr.CST=acr;Wr.Lexer=ccr.Lexer;Wr.LineCounter=lcr.LineCounter;Wr.Parser=ucr.Parser;Wr.parse=qW.parse;Wr.parseAllDocuments=qW.parseAllDocuments;Wr.parseDocument=qW.parseDocument;Wr.stringify=qW.stringify;Wr.visit=Rut.visit;Wr.visitAsync=Rut.visitAsync});var Cut=p(()=>{});var Cxe=p(()=>{});var Put=p(()=>{});var Pxe=p(()=>{"use strict";p1()});var Iut=p(()=>{"use strict";Pxe()});var Ixe=p(()=>{"use strict";Put();Pxe();Iut()});var dcr,pcr,qAn,Aut=p(()=>{"use strict";Yt();Cut();Cxe();Y9();Ixe();dcr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pcr=7,qAn=dcr.length**pcr});var fcr,Out=p(()=>{"use strict";Yt();Aut();fcr=30*24*60*60*1e3});var mcr,$ut=p(()=>{"use strict";mcr=Cp(Tut(),1);wi();YD();eb();Out()});var k$=p(()=>{"use strict";hw()});var GW=p(()=>{"use strict";k$();rk();Lm()});var Oxe=p(()=>{"use strict";k$();rk();GW();GW();GW()});var Mut=p(()=>{"use strict";$ut();Oxe();k$();Bi();HO();Wb();Oh();Vye()});var Dut=p(()=>{"use strict";Yt();Lm();ky();u0();Oh()});var Nut=p(()=>{"use strict"});var Bu=p(()=>{"use strict";Mye();wi();h_();fw();ky();FO()});var $xe=p(()=>{"use strict";wi();Nut();u0();UO();ky();Bu();Oh()});var Mxe=p(()=>{"use strict"});var BW=p(()=>{"use strict"});var zut=p(()=>{"use strict";Bu()});var w$=p(()=>{"use strict";wi();Bu()});var zxe=p(()=>{"use strict";Sd();Bu();w$()});var Fut=p(()=>{"use strict";Bu()});function Hut(e){let t=jut.blockedPrefix;return e.startsWith(t)?e.slice(t.length):null}var jut,Uut,k$n,Lxe=p(()=>{"use strict";Bi();Sd();Bi();jut={ready:su,running:rL,human:Ih,needsTriage:$1e,needsInfo:M1e,quarantine:Sre,dependencyBlocked:nL,blockedPrefix:"blocked:",reqPrefix:"req:"},Uut=[D1e,N1e,_re,z1e,L1e,wre,F1e,j1e,nL,U1e,H1e,q1e,G1e,vre,B1e,W1e,V1e,K1e,Z1e,J1e];k$n=Kre(jut)});var v$n,qut=p(()=>{v$n={id:"id",number:"number",title:"title",state:"state",labels:"labels(first: 100) { nodes { id name } }",body:"body",mergeable:"mergeable",checks:["commits(last: 1) {"," nodes { commit { statusCheckRollup {"," state"," contexts(first: 100) { nodes {"," __typename"," ... on CheckRun { name status conclusion detailsUrl }"," ... on StatusContext { context state targetUrl }"," } }"," } } }","}"].join(`
417
- `),subIssues:"subIssues(first: 100) { nodes { number } }"}});var Gut=p(()=>{"use strict";Sd();Lxe();qut();wi();qB();Bu();w$()});var Fxe=p(()=>{"use strict"});var But=p(()=>{"use strict";Fxe();Bu()});var Wut=p(()=>{"use strict";wi();ky();BB();FO()});var Kut=p(()=>{"use strict";Sd();zxe();Bu();Wut()});var Zut=p(()=>{"use strict";wi();Sd();Bu();w$()});var Jut=p(()=>{"use strict";Sd();Fxe();Bu()});var Qut=p(()=>{"use strict";w$()});var WW=p(()=>{"use strict";zut();zxe();Fut();Gut();But();Kut();Zut();Jut();Qut()});var tdt=p(()=>{"use strict";Mxe();SL();BW();WW();u0()});var rdt=p(()=>{"use strict";BW()});var jxe=p(()=>{"use strict";Bi()});var ndt=p(()=>{"use strict"});var Uxe=p(()=>{"use strict"});var bDn,Hxe=p(()=>{"use strict";GO();bDn=4*60*60*1e3});var odt=p(()=>{"use strict";Bi()});var qxe=p(()=>{"use strict";jxe();odt()});var Gxe=p(()=>{"use strict"});var Bxe=p(()=>{"use strict";GO();Lm()});var Wxe=p(()=>{"use strict"});var Vxe=p(()=>{"use strict";Cxe()});var Kxe=p(()=>{"use strict";hw();td();Ixe()});var r1n,n1n,o1n,idt=p(()=>{"use strict";hw();p1();Kxe();r1n=10*6e4,n1n=30*6e4,o1n=5*6e4});var g1n,Zxe=p(()=>{"use strict";kR();eb();idt();oT();M1();$1();Kxe();g1n=`Inspect the detection-only census with ${zp("red-skills-redskilled",["reap","--report"])}; the daemon reaps only stamped orphans, while unstamped suspects and dump files require operator review.`});var Jxe=p(()=>{"use strict"});var sdt=p(()=>{"use strict"});function adt(e){let t=elr.find(r=>r.kind===e);if(!t)throw new Error(`blocker-state: no cause rule for kind ${e}`);return t}var v1n,elr,E1n,cdt=p(()=>{"use strict";sdt();Lxe();v1n=new Set([...Uut.map(e=>Hut(e)),"claim-hygiene","decision","drift","push-failed","push-rejected","unclassified"]),elr=[{kind:"push-rejected",names:/\bnon-fast-forward\b|\bremote tip diverged\b|\bfetch first\b|\bstale info\b|\bupdates were rejected\b/i,next:"Reconcile the diverged remote tip \u2014 nothing is broken and no access was lost: the branch on origin is not an ancestor of the worker tip. Fetch it and re-push the attempt branch (the claim holder may force-with-lease on the observed tip), then requeue."},{kind:"push-failed",names:/\bpush (?:failed|did not run|was rejected)\b|\bfailed to push\b|the true cause is the push/i,next:"Restore push access to the worker branch's remote, then requeue \u2014 there is no merge conflict to resolve."}];E1n={"push-failed":adt("push-failed").next,"push-rejected":adt("push-rejected").next,unclassified:"Read the summary and classify the real cause before choosing a recovery route."}});var Qxe=p(()=>{"use strict";cdt();Sd()});var Yxe=p(()=>{"use strict";Vl();fw();eb()});var Xxe=p(()=>{"use strict"});var ldt=p(()=>{"use strict";Yt();Uxe();Hxe();qxe();Gxe();Bxe();Wxe();Vxe();Jxe();Qxe();Yxe();Zxe();Xxe()});var udt=p(()=>{"use strict";ndt();Uxe();Hxe();qxe();Gxe();Bxe();Wxe();Vxe();Zxe();Jxe();Qxe();Yxe();Xxe();ldt()});var ddt=p(()=>{"use strict"});var pdt=p(()=>{"use strict";Yt()});var fdt=p(()=>{"use strict";wi();qB();ddt();pdt()});var mdt=p(()=>{"use strict";ZW();h_();Bi();lye();SL();GO();Bye();rdt();BW();Sd();Wb();jxe();rk();udt();Wye();fdt();Mxe();HO();k$();ky();Oxe();WW();WW();u0();UO();Oh();$xe()});var hdt=p(()=>{"use strict";Oh();Dat();Vye();one();Mut();Dut();$xe();tdt();mdt()});import{readFileSync as nlr}from"node:fs";import{readdir as olr}from"node:fs/promises";import{dirname as ilr,join as v$}from"node:path";function ydt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function slr(e){let t=v$(af(e).tmpDir,cze()),r;try{r=(await olr(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{return[]}return r.map(n=>{let o=v$(t,n),i=null;try{let s=Number(nlr(v$(o,"worker.pid"),"utf8").trim());i=Number.isInteger(s)&&s>0?s:null}catch{i=null}return{worker:n,dir:o,pid:i,alive:i!==null&&ydt(i)}})}function alr(e){let t=e.trim();if(t==="")return{};try{return io(t)}catch{try{return JSON.parse(t)}catch{return{text:t}}}}function bdt(e){let t=ilr(e),r=e.slice(t.length+1);if(r.startsWith("redskilled-mcp"))return e;let n=r.match(/^dev-(.+)\.bundle\.min\.mjs$/);return n?v$(t,`redskilled-mcp-${n[1]}.bundle.min.mjs`):v$(t,"redskilled-mcp.bundle.min.mjs")}async function xdt(e=process.env){try{let{resolveRedskilledPaths:t}=await Promise.resolve().then(()=>(oT(),_7));return t({env:e}).socketPath}catch{return}}async function clr(e,t=process.env){try{let[{readRedskilledHostState:r},{resolveRedskilledPaths:n}]=await Promise.all([Promise.resolve().then(()=>(D8(),ACe)),Promise.resolve().then(()=>(oT(),_7))]),o=await r(n({env:t})),s=o.registrations?.find(a=>a.project_label===e)?.last_poll;return{reachable:!0,workers:o.workers.filter(a=>a.project_label===e).map(a=>({workerId:a.worker_id,pid:a.pid})),poll:s===void 0?null:{at:s.at,outcome:s.outcome,depth:s.depth,requestCount:s.request_count,detail:s.detail}}}catch(r){return{reachable:!1,workers:[],poll:null,detail:r instanceof Error?r.message:String(r)}}}async function Sdt(e){let t=new pL({command:e.command??process.execPath,args:[...e.args],cwd:e.cwd,env:e.env??process.env,stderr:"pipe"}),r=new uL({name:"mcp-lane-canary",version:"1"},{capabilities:{}}),n="";return await r.connect(t),t.stderr?.on("data",o=>{n=`${n}${o.toString("utf8")}`.slice(-8e3)}),{listTools:async()=>(await r.listTools()).tools.map(o=>o.name),callTool:async(o,i)=>{let s=await r.callTool({name:o,arguments:i},fd);if(s.isError===!0)throw new Error(`${o} returned an error result: ${gdt(s.content)}`);return alr(gdt(s.content))},observeWorkers:()=>slr(e.cwd),observeHost:o=>clr(o,e.env??process.env),isLive:ydt,sleep:o=>new Promise(i=>setTimeout(i,o)),now:()=>Date.now(),stderr:()=>n,close:async()=>{await r.close().catch(()=>{}),await t.close().catch(()=>{})}}}function gdt(e){return Array.isArray(e)?e.map(t=>{let r=t;return r.type==="text"?r.text??"":""}).join(""):""}var kdt=p(()=>{"use strict";yNe();aze();md();Yt();Wb();hdt()});var Rdt={};Vn(Rdt,{mcpLaneCanaryCommand:()=>llr,parseMcpLaneCanaryArgs:()=>vdt,runMcpLaneCanaryAgainstEntry:()=>Edt});import{resolve as _dt}from"node:path";function vdt(e,t=process.cwd()){let r={entry:bdt(process.argv[1]??""),root:t,runner:"claude",target:1,quietDeadlineMs:3e3,teardownDeadlineMs:2e4,demandDeadlineMs:6e4};for(let n=0;n<e.length;n+=1){let o=e[n],i=e[n+1],s=()=>{if(i===void 0)throw new Error(`${o} requires a value`);return n+=1,i};switch(o){case"--entry":r.entry=_dt(t,s());break;case"--root":r.root=_dt(t,s());break;case"--runner":r.runner=s();break;case"--quiet-deadline-ms":r.quietDeadlineMs=eSe(o,s());break;case"--teardown-deadline-ms":r.teardownDeadlineMs=eSe(o,s());break;case"--demand-deadline-ms":r.demandDeadlineMs=eSe(o,s());break;default:throw new Error(`unknown flag: ${String(o)}`)}}return r}function eSe(e,t){let r=Number(t);if(!Number.isInteger(r)||r<=0)throw new Error(`${String(e)} requires a positive integer, got ${t}`);return r}async function Edt(e){let t=await xdt(),r=await Sdt({args:[e.entry],cwd:e.root});try{return{result:await fNe(r,{runner:e.runner,target:e.target,quietDeadlineMs:e.quietDeadlineMs,teardownDeadlineMs:e.teardownDeadlineMs,demandDeadlineMs:e.demandDeadlineMs,...t!==void 0?{socketPath:t}:{}}),stderr:r.stderr()}}finally{await r.close()}}async function llr(e,t={stdout:process.stdout,stderr:process.stderr},r=process.cwd()){if(e.includes("--help")||e.includes("-h"))return t.stdout.write(wdt),0;let n;try{n=vdt(e,r)}catch(i){return t.stderr.write(`[mcp-canary] ${i instanceof Error?i.message:String(i)}
416
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=UW(t),n=k0(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=UW(t),n=k0(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Sut.Parser=Exe});var Eut=ee(S$=>{"use strict";var kut=pxe(),War=d$(),x$=m$(),Var=ube(),Kar=Tr(),Zar=vxe(),_ut=Rxe();function wut(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Zar.LineCounter||null,prettyErrors:t}}function Jar(e,t={}){let{lineCounter:r,prettyErrors:n}=wut(t),o=new _ut.Parser(r?.addNewLine),i=new kut.Composer(t),s=Array.from(i.compose(o.parse(e)));if(n&&r)for(let a of s)a.errors.forEach(x$.prettifyError(e,r)),a.warnings.forEach(x$.prettifyError(e,r));return s.length>0?s:Object.assign([],{empty:!0},i.streamInfo())}function vut(e,t={}){let{lineCounter:r,prettyErrors:n}=wut(t),o=new _ut.Parser(r?.addNewLine),i=new kut.Composer(t),s=null;for(let a of i.compose(o.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new x$.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(s.errors.forEach(x$.prettifyError(e,r)),s.warnings.forEach(x$.prettifyError(e,r))),s}function Qar(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let o=vut(e,r);if(!o)return null;if(o.warnings.forEach(i=>Var.warn(o.options.logLevel,i)),o.errors.length>0){if(o.options.logLevel!=="silent")throw o.errors[0];o.errors=[]}return o.toJS(Object.assign({reviver:n},r))}function Yar(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let o=Math.round(r);r=o<1?void 0:o>8?{indent:8}:{indent:o}}if(e===void 0){let{keepUndefined:o}=r??t??{};if(!o)return}return Kar.isDocument(e)&&!n?e.toString(r):new War.Document(e,n,r).toString(r)}S$.parse=Qar;S$.parseAllDocuments=Jar;S$.parseDocument=vut;S$.stringify=Yar});var Tut=ee(Wr=>{"use strict";var Xar=pxe(),ecr=d$(),tcr=Wbe(),Txe=m$(),rcr=ZO(),Oy=Tr(),ncr=Ty(),ocr=ai(),icr=Py(),scr=Iy(),acr=FW(),ccr=_xe(),lcr=vxe(),ucr=Rxe(),qW=Eut(),Rut=BO();Wr.Composer=Xar.Composer;Wr.Document=ecr.Document;Wr.Schema=tcr.Schema;Wr.YAMLError=Txe.YAMLError;Wr.YAMLParseError=Txe.YAMLParseError;Wr.YAMLWarning=Txe.YAMLWarning;Wr.Alias=rcr.Alias;Wr.isAlias=Oy.isAlias;Wr.isCollection=Oy.isCollection;Wr.isDocument=Oy.isDocument;Wr.isMap=Oy.isMap;Wr.isNode=Oy.isNode;Wr.isPair=Oy.isPair;Wr.isScalar=Oy.isScalar;Wr.isSeq=Oy.isSeq;Wr.Pair=ncr.Pair;Wr.Scalar=ocr.Scalar;Wr.YAMLMap=icr.YAMLMap;Wr.YAMLSeq=scr.YAMLSeq;Wr.CST=acr;Wr.Lexer=ccr.Lexer;Wr.LineCounter=lcr.LineCounter;Wr.Parser=ucr.Parser;Wr.parse=qW.parse;Wr.parseAllDocuments=qW.parseAllDocuments;Wr.parseDocument=qW.parseDocument;Wr.stringify=qW.stringify;Wr.visit=Rut.visit;Wr.visitAsync=Rut.visitAsync});var Cut=p(()=>{});var Cxe=p(()=>{});var Put=p(()=>{});var Pxe=p(()=>{"use strict";p1()});var Iut=p(()=>{"use strict";Pxe()});var Ixe=p(()=>{"use strict";Put();Pxe();Iut()});var dcr,pcr,HAn,Aut=p(()=>{"use strict";Yt();Cut();Cxe();Y9();Ixe();dcr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pcr=7,HAn=dcr.length**pcr});var fcr,Out=p(()=>{"use strict";Yt();Aut();fcr=30*24*60*60*1e3});var mcr,$ut=p(()=>{"use strict";mcr=Cp(Tut(),1);wi();YD();eb();Out()});var k$=p(()=>{"use strict";hw()});var GW=p(()=>{"use strict";k$();rk();Lm()});var Oxe=p(()=>{"use strict";k$();rk();GW();GW();GW()});var Mut=p(()=>{"use strict";$ut();Oxe();k$();Bi();HO();Wb();Oh();Vye()});var Dut=p(()=>{"use strict";Yt();Lm();ky();u0();Oh()});var Nut=p(()=>{"use strict"});var Bu=p(()=>{"use strict";Mye();wi();h_();fw();ky();FO()});var $xe=p(()=>{"use strict";wi();Nut();u0();UO();ky();Bu();Oh()});var Mxe=p(()=>{"use strict"});var BW=p(()=>{"use strict"});var zut=p(()=>{"use strict";Bu()});var w$=p(()=>{"use strict";wi();Bu()});var zxe=p(()=>{"use strict";Sd();Bu();w$()});var Fut=p(()=>{"use strict";Bu()});function Hut(e){let t=jut.blockedPrefix;return e.startsWith(t)?e.slice(t.length):null}var jut,Uut,S$n,Lxe=p(()=>{"use strict";Bi();Sd();Bi();jut={ready:su,running:rL,human:Ih,needsTriage:$1e,needsInfo:M1e,quarantine:Sre,dependencyBlocked:nL,blockedPrefix:"blocked:",reqPrefix:"req:"},Uut=[D1e,N1e,_re,z1e,L1e,wre,F1e,j1e,nL,U1e,H1e,q1e,G1e,vre,B1e,W1e,V1e,K1e,Z1e,J1e];S$n=Kre(jut)});var w$n,qut=p(()=>{w$n={id:"id",number:"number",title:"title",state:"state",labels:"labels(first: 100) { nodes { id name } }",body:"body",mergeable:"mergeable",checks:["commits(last: 1) {"," nodes { commit { statusCheckRollup {"," state"," contexts(first: 100) { nodes {"," __typename"," ... on CheckRun { name status conclusion detailsUrl }"," ... on StatusContext { context state targetUrl }"," } }"," } } }","}"].join(`
417
+ `),subIssues:"subIssues(first: 100) { nodes { number } }"}});var Gut=p(()=>{"use strict";Sd();Lxe();qut();wi();qB();Bu();w$()});var Fxe=p(()=>{"use strict"});var But=p(()=>{"use strict";Fxe();Bu()});var Wut=p(()=>{"use strict";wi();ky();BB();FO()});var Kut=p(()=>{"use strict";Sd();zxe();Bu();Wut()});var Zut=p(()=>{"use strict";wi();Sd();Bu();w$()});var Jut=p(()=>{"use strict";Sd();Fxe();Bu()});var Qut=p(()=>{"use strict";w$()});var WW=p(()=>{"use strict";zut();zxe();Fut();Gut();But();Kut();Zut();Jut();Qut()});var tdt=p(()=>{"use strict";Mxe();SL();BW();WW();u0()});var rdt=p(()=>{"use strict";BW()});var jxe=p(()=>{"use strict";Bi()});var ndt=p(()=>{"use strict"});var Uxe=p(()=>{"use strict"});var yDn,Hxe=p(()=>{"use strict";GO();yDn=4*60*60*1e3});var odt=p(()=>{"use strict";Bi()});var qxe=p(()=>{"use strict";jxe();odt()});var Gxe=p(()=>{"use strict"});var Bxe=p(()=>{"use strict";GO();Lm()});var Wxe=p(()=>{"use strict"});var Vxe=p(()=>{"use strict";Cxe()});var Kxe=p(()=>{"use strict";hw();td();Ixe()});var t1n,r1n,n1n,idt=p(()=>{"use strict";hw();p1();Kxe();t1n=10*6e4,r1n=30*6e4,n1n=5*6e4});var h1n,Zxe=p(()=>{"use strict";kR();eb();idt();oT();M1();$1();Kxe();h1n=`Inspect the detection-only census with ${zp("red-skills-redskilled",["reap","--report"])}; the daemon reaps only stamped orphans, while unstamped suspects and dump files require operator review.`});var Jxe=p(()=>{"use strict"});var sdt=p(()=>{"use strict"});function adt(e){let t=elr.find(r=>r.kind===e);if(!t)throw new Error(`blocker-state: no cause rule for kind ${e}`);return t}var w1n,elr,v1n,cdt=p(()=>{"use strict";sdt();Lxe();w1n=new Set([...Uut.map(e=>Hut(e)),"claim-hygiene","decision","drift","push-failed","push-rejected","unclassified"]),elr=[{kind:"push-rejected",names:/\bnon-fast-forward\b|\bremote tip diverged\b|\bfetch first\b|\bstale info\b|\bupdates were rejected\b/i,next:"Reconcile the diverged remote tip \u2014 nothing is broken and no access was lost: the branch on origin is not an ancestor of the worker tip. Fetch it and re-push the attempt branch (the claim holder may force-with-lease on the observed tip), then requeue."},{kind:"push-failed",names:/\bpush (?:failed|did not run|was rejected)\b|\bfailed to push\b|the true cause is the push/i,next:"Restore push access to the worker branch's remote, then requeue \u2014 there is no merge conflict to resolve."}];v1n={"push-failed":adt("push-failed").next,"push-rejected":adt("push-rejected").next,unclassified:"Read the summary and classify the real cause before choosing a recovery route."}});var Qxe=p(()=>{"use strict";cdt();Sd()});var Yxe=p(()=>{"use strict";Vl();fw();eb()});var Xxe=p(()=>{"use strict"});var ldt=p(()=>{"use strict";Yt();Uxe();Hxe();qxe();Gxe();Bxe();Wxe();Vxe();Jxe();Qxe();Yxe();Zxe();Xxe()});var udt=p(()=>{"use strict";ndt();Uxe();Hxe();qxe();Gxe();Bxe();Wxe();Vxe();Zxe();Jxe();Qxe();Yxe();Xxe();ldt()});var ddt=p(()=>{"use strict"});var pdt=p(()=>{"use strict";Yt()});var fdt=p(()=>{"use strict";wi();qB();ddt();pdt()});var mdt=p(()=>{"use strict";ZW();h_();Bi();lye();SL();GO();Bye();rdt();BW();Sd();Wb();jxe();rk();udt();Wye();fdt();Mxe();HO();k$();ky();Oxe();WW();WW();u0();UO();Oh();$xe()});var hdt=p(()=>{"use strict";Oh();Dat();Vye();one();Mut();Dut();$xe();tdt();mdt()});import{readFileSync as nlr}from"node:fs";import{readdir as olr}from"node:fs/promises";import{dirname as ilr,join as v$}from"node:path";function ydt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function slr(e){let t=v$(af(e).tmpDir,cze()),r;try{r=(await olr(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{return[]}return r.map(n=>{let o=v$(t,n),i=null;try{let s=Number(nlr(v$(o,"worker.pid"),"utf8").trim());i=Number.isInteger(s)&&s>0?s:null}catch{i=null}return{worker:n,dir:o,pid:i,alive:i!==null&&ydt(i)}})}function alr(e){let t=e.trim();if(t==="")return{};try{return io(t)}catch{try{return JSON.parse(t)}catch{return{text:t}}}}function bdt(e){let t=ilr(e),r=e.slice(t.length+1);if(r.startsWith("redskilled-mcp"))return e;let n=r.match(/^dev-(.+)\.bundle\.min\.mjs$/);return n?v$(t,`redskilled-mcp-${n[1]}.bundle.min.mjs`):v$(t,"redskilled-mcp.bundle.min.mjs")}async function xdt(e=process.env){try{let{resolveRedskilledPaths:t}=await Promise.resolve().then(()=>(oT(),_7));return t({env:e}).socketPath}catch{return}}async function clr(e,t=process.env){try{let[{readRedskilledHostState:r},{resolveRedskilledPaths:n}]=await Promise.all([Promise.resolve().then(()=>(D8(),ACe)),Promise.resolve().then(()=>(oT(),_7))]),o=await r(n({env:t})),s=o.registrations?.find(a=>a.project_label===e)?.last_poll;return{reachable:!0,workers:o.workers.filter(a=>a.project_label===e).map(a=>({workerId:a.worker_id,pid:a.pid})),poll:s===void 0?null:{at:s.at,outcome:s.outcome,depth:s.depth,requestCount:s.request_count,detail:s.detail}}}catch(r){return{reachable:!1,workers:[],poll:null,detail:r instanceof Error?r.message:String(r)}}}async function Sdt(e){let t=new pL({command:e.command??process.execPath,args:[...e.args],cwd:e.cwd,env:e.env??process.env,stderr:"pipe"}),r=new uL({name:"mcp-lane-canary",version:"1"},{capabilities:{}}),n="";return await r.connect(t),t.stderr?.on("data",o=>{n=`${n}${o.toString("utf8")}`.slice(-8e3)}),{listTools:async()=>(await r.listTools()).tools.map(o=>o.name),callTool:async(o,i)=>{let s=await r.callTool({name:o,arguments:i},fd);if(s.isError===!0)throw new Error(`${o} returned an error result: ${gdt(s.content)}`);return alr(gdt(s.content))},observeWorkers:()=>slr(e.cwd),observeHost:o=>clr(o,e.env??process.env),isLive:ydt,sleep:o=>new Promise(i=>setTimeout(i,o)),now:()=>Date.now(),stderr:()=>n,close:async()=>{await r.close().catch(()=>{}),await t.close().catch(()=>{})}}}function gdt(e){return Array.isArray(e)?e.map(t=>{let r=t;return r.type==="text"?r.text??"":""}).join(""):""}var kdt=p(()=>{"use strict";yNe();aze();md();Yt();Wb();hdt()});var Rdt={};Vn(Rdt,{mcpLaneCanaryCommand:()=>llr,parseMcpLaneCanaryArgs:()=>vdt,runMcpLaneCanaryAgainstEntry:()=>Edt});import{resolve as _dt}from"node:path";function vdt(e,t=process.cwd()){let r={entry:bdt(process.argv[1]??""),root:t,runner:"claude",target:1,quietDeadlineMs:3e3,teardownDeadlineMs:2e4,demandDeadlineMs:6e4};for(let n=0;n<e.length;n+=1){let o=e[n],i=e[n+1],s=()=>{if(i===void 0)throw new Error(`${o} requires a value`);return n+=1,i};switch(o){case"--entry":r.entry=_dt(t,s());break;case"--root":r.root=_dt(t,s());break;case"--runner":r.runner=s();break;case"--quiet-deadline-ms":r.quietDeadlineMs=eSe(o,s());break;case"--teardown-deadline-ms":r.teardownDeadlineMs=eSe(o,s());break;case"--demand-deadline-ms":r.demandDeadlineMs=eSe(o,s());break;default:throw new Error(`unknown flag: ${String(o)}`)}}return r}function eSe(e,t){let r=Number(t);if(!Number.isInteger(r)||r<=0)throw new Error(`${String(e)} requires a positive integer, got ${t}`);return r}async function Edt(e){let t=await xdt(),r=await Sdt({args:[e.entry],cwd:e.root});try{return{result:await fNe(r,{runner:e.runner,target:e.target,quietDeadlineMs:e.quietDeadlineMs,teardownDeadlineMs:e.teardownDeadlineMs,demandDeadlineMs:e.demandDeadlineMs,...t!==void 0?{socketPath:t}:{}}),stderr:r.stderr()}}finally{await r.close()}}async function llr(e,t={stdout:process.stdout,stderr:process.stderr},r=process.cwd()){if(e.includes("--help")||e.includes("-h"))return t.stdout.write(wdt),0;let n;try{n=vdt(e,r)}catch(i){return t.stderr.write(`[mcp-canary] ${i instanceof Error?i.message:String(i)}
418
418
  `),t.stderr.write(wdt),2}let o;try{o=await Edt(n)}catch(i){return t.stderr.write(`[mcp-canary] connect went inert: could not open an MCP session against ${n.entry}: ${i instanceof Error?i.message:String(i)}
419
419
  `),1}return t.stdout.write(`${mNe(o.result)}
420
420
  `),o.result.ok?0:(t.stderr.write(`[mcp-canary] ${o.result.summary}
@@ -437,7 +437,7 @@ naming the step that went inert.
437
437
  --demand-deadline-ms <n> how long the probe waits for the daemon's poll and
438
438
  the Worker it justifies (default: 60000)
439
439
  `});ZW();import{connect as $0t}from"node:net";import{Readable as M0t,Writable as D0t}from"node:stream";var Me={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},ir={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},JW={cancel_request:"$/cancel_request"};cR();cR();var Xwe=Symbol("skippedItem");function y(e,t){return e.catch(t)}function Kn(e,t){let r=e.catch(t);return ki.unknown().transform((n,o)=>n!==void 0?r.parse(n):(o.addIssue({code:"custom",message:"Required value is missing"}),ki.NEVER))}function eve(e,t){if(e===null||typeof e!="object"||Array.isArray(e))return;let r=e[t];return typeof r=="string"?r:void 0}function $n(e,t,r){return e.superRefine((n,o)=>{let i=eve(n,t);i!==void 0&&r.includes(i)&&o.addIssue({code:"custom",path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Mn(e,t,r){return ki.unknown().transform((n,o)=>{let i=e.safeParse(n);if(!i.success){for(let c of i.error.issues)o.addIssue({...c,input:n});return ki.NEVER}let s=i.data,a=eve(n,t);if(a!==void 0&&!r.includes(a)){let c=n;for(let[l,u]of Object.entries(c))l!=="__proto__"&&(Object.hasOwn(s,l)||(s[l]=u))}return s})}function Ve(e){return ki.array(e.catch(Xwe)).transform(t=>t.filter(r=>r!==Xwe))}var Xm=be([rt(),g()]).nullable(),Ar=g(),cZ=x({sessionId:Ar,path:g(),content:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),lZ=x({sessionId:Ar,path:g(),line:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),limit:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),uZ=g(),tve=be([O("read"),O("edit"),O("delete"),O("move"),O("search"),O("execute"),O("think"),O("fetch"),O("switch_mode"),O("other")]),rve=be([O("pending"),O("in_progress"),O("completed"),O("failed")]),Cmt=be([O("assistant"),O("user")]),lR=x({audience:y(Ve(Cmt).nullish(),()=>{}),lastModified:y(g().nullish(),()=>{}),priority:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Pmt=x({annotations:y(lR.nullish(),()=>{}),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Imt=x({annotations:y(lR.nullish(),()=>{}),data:g(),mimeType:g(),uri:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Amt=x({annotations:y(lR.nullish(),()=>{}),data:g(),mimeType:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Omt=x({annotations:y(lR.nullish(),()=>{}),description:y(g().nullish(),()=>{}),mimeType:y(g().nullish(),()=>{}),name:g(),size:y(rt().nullish(),()=>{}),title:y(g().nullish(),()=>{}),uri:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),$mt=x({mimeType:y(g().nullish(),()=>{}),text:g(),uri:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Mmt=x({blob:g(),mimeType:y(g().nullish(),()=>{}),uri:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Dmt=be([$mt,Mmt]),Nmt=x({annotations:y(lR.nullish(),()=>{}),resource:Dmt,_meta:y(C(g(),T()).nullish(),()=>{})}),dZ=be([Pmt.and(x({type:O("text")})),Imt.and(x({type:O("image")})),Amt.and(x({type:O("audio")})),Omt.and(x({type:O("resource_link")})),Nmt.and(x({type:O("resource")}))]),zmt=x({content:dZ,_meta:y(C(g(),T()).nullish(),()=>{})}),Lmt=x({path:g(),oldText:y(g().nullish(),()=>{}),newText:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Gk=g(),Fmt=x({terminalId:Gk,_meta:y(C(g(),T()).nullish(),()=>{})}),nve=be([zmt.and(x({type:O("content")})),Lmt.and(x({type:O("diff")})),Fmt.and(x({type:O("terminal")}))]),ove=x({path:g(),line:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),ive=x({toolCallId:uZ,kind:y(tve.nullish(),()=>{}),status:y(rve.nullish(),()=>{}),title:y(g().nullish(),()=>{}),name:y(g().nullish(),()=>{}),content:y(Ve(nve).nullish(),()=>{}),locations:y(Ve(ove).nullish(),()=>{}),rawInput:y(T().optional(),()=>{}),rawOutput:y(T().optional(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),sve=g(),jmt=be([O("allow_once"),O("allow_always"),O("reject_once"),O("reject_always")]),Umt=x({optionId:sve,name:g(),kind:jmt,_meta:y(C(g(),T()).nullish(),()=>{})}),pZ=x({sessionId:Ar,toolCall:ive,options:gt(Umt),_meta:y(C(g(),T()).nullish(),()=>{})}),ave=x({name:g(),value:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),fZ=x({sessionId:Ar,command:g(),args:y(Ve(g()).optional(),()=>[]),env:y(Ve(ave).optional(),()=>[]),cwd:y(g().nullish(),()=>{}),outputByteLimit:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),mZ=x({sessionId:Ar,terminalId:Gk,_meta:y(C(g(),T()).nullish(),()=>{})}),hZ=x({sessionId:Ar,terminalId:Gk,_meta:y(C(g(),T()).nullish(),()=>{})}),gZ=x({sessionId:Ar,terminalId:Gk,_meta:y(C(g(),T()).nullish(),()=>{})}),yZ=x({sessionId:Ar,terminalId:Gk,_meta:y(C(g(),T()).nullish(),()=>{})}),uR=x({sessionId:Ar,toolCallId:y(uZ.nullish(),()=>{})}),dR=x({requestId:Xm}),Hmt=O("object"),qmt=be([O("email"),O("uri"),O("date"),O("date-time")]),cve=x({const:g(),title:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),bZ=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minLength:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:g().nullish(),format:qmt.nullish(),default:y(g().nullish(),()=>{}),enum:gt(g()).nullish(),oneOf:gt(cve).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),xZ=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minimum:rt().nullish(),maximum:rt().nullish(),default:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),SZ=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minimum:rt().nullish(),maximum:rt().nullish(),default:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),kZ=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),default:y(mr().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),_Z=x({enum:gt(g()),_meta:y(C(g(),T()).nullish(),()=>{})}),lve=x({anyOf:gt(cve),_meta:y(C(g(),T()).nullish(),()=>{})}),Gmt=Mn(be([_Z.and(x({type:O("string")})),$n(x({type:g()}),"type",["string"]),lve]),"type",["string"]),wZ=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minItems:rt().nullish(),maxItems:rt().nullish(),items:Gmt,default:y(Ve(g()).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Bmt=Mn(be([bZ.and(x({type:O("string")})),xZ.and(x({type:O("number")})),SZ.and(x({type:O("integer")})),kZ.and(x({type:O("boolean")})),wZ.and(x({type:O("array")})),$n(x({type:g()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Wmt=x({type:y(Hmt.optional().default("object"),()=>"object"),title:y(g().nullish(),()=>{}),properties:C(g(),Bmt).optional().default({}),required:gt(g()).nullish(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),vZ=Ho(be([uR,dR]),x({requestedSchema:Wmt})),uve=g(),EZ=Ho(be([uR,dR]),x({elicitationId:uve,url:_r()})),RZ=Mn(Ho(be([vZ.and(x({mode:O("form")})),EZ.and(x({mode:O("url")})),$n(Ho(be([uR,dR]),x({mode:g()})),"mode",["form","url"])]),x({message:g(),_meta:y(C(g(),T()).nullish(),()=>{})})),"mode",["form","url"]),dve=g(),Vmt=x({serverId:dve,_meta:y(C(g(),T()).nullish(),()=>{})}),uD=g(),pve=x({connectionId:uD,method:g(),params:C(g(),T()).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),Kmt=x({connectionId:uD,_meta:y(C(g(),T()).nullish(),()=>{})}),fve=T(),gpr=x({id:Xm,method:g(),params:be([cZ,lZ,pZ,fZ,mZ,hZ,gZ,yZ,RZ,Vmt,pve,Kmt,fve]).nullish()}),mve=fr().gte(0).lte(65535),Zmt=x({image:y(mr().optional().default(!1),()=>!1),audio:y(mr().optional().default(!1),()=>!1),embeddedContext:y(mr().optional().default(!1),()=>!1),_meta:y(C(g(),T()).nullish(),()=>{})}),Jmt=x({http:y(mr().optional().default(!1),()=>!1),sse:y(mr().optional().default(!1),()=>!1),acp:y(mr().optional().default(!1),()=>!1),_meta:y(C(g(),T()).nullish(),()=>{})}),Qmt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Ymt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Xmt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),eht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),tht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),rht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),nht=x({list:y(Qmt.nullish(),()=>{}),delete:y(Ymt.nullish(),()=>{}),additionalDirectories:y(Xmt.nullish(),()=>{}),fork:y(eht.nullish(),()=>{}),resume:y(tht.nullish(),()=>{}),close:y(rht.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),oht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),iht=x({logout:y(oht.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),sht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),aht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),cht=be([O("full"),O("incremental")]),lht=x({syncKind:cht,_meta:y(C(g(),T()).nullish(),()=>{})}),uht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),dht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),pht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),fht=x({didOpen:y(aht.nullish(),()=>{}),didChange:y(lht.nullish(),()=>{}),didClose:y(uht.nullish(),()=>{}),didSave:y(dht.nullish(),()=>{}),didFocus:y(pht.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),mht=x({document:y(fht.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hht=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),ght=x({_meta:y(C(g(),T()).nullish(),()=>{})}),yht=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),bht=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),xht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Sht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),kht=x({recentFiles:y(hht.nullish(),()=>{}),relatedSnippets:y(ght.nullish(),()=>{}),editHistory:y(yht.nullish(),()=>{}),userActions:y(bht.nullish(),()=>{}),openFiles:y(xht.nullish(),()=>{}),diagnostics:y(Sht.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),_ht=x({events:y(mht.nullish(),()=>{}),context:y(kht.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hve=be([O("utf-16"),O("utf-32"),O("utf-8")]),wht=x({loadSession:y(mr().optional().default(!1),()=>!1),promptCapabilities:y(Zmt.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:y(Jmt.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:y(nht.optional().default({}),()=>({})),auth:y(iht.optional().default({}),()=>({})),providers:y(sht.nullish(),()=>{}),nes:y(_ht.nullish(),()=>{}),positionEncoding:y(hve.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),dD=g(),vht=x({name:g(),label:y(g().nullish(),()=>{}),secret:y(mr().optional().default(!0),()=>!0),optional:y(mr().optional().default(!1),()=>!1),_meta:y(C(g(),T()).nullish(),()=>{})}),Eht=x({id:dD,name:g(),description:y(g().nullish(),()=>{}),vars:Kn(Ve(vht),()=>[]),link:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Rht=x({id:dD,name:g(),description:y(g().nullish(),()=>{}),args:y(Ve(g()).optional(),()=>[]),env:y(C(g(),g()).optional(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Tht=x({id:dD,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Cht=be([Eht.and(x({type:O("env_var")})),Rht.and(x({type:O("terminal")})),Tht]),gve=x({name:g(),title:y(g().nullish(),()=>{}),version:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Pht=x({protocolVersion:mve,agentCapabilities:y(wht.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:y(Ve(Cht).optional().default([]),()=>[]),agentInfo:y(gve.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Iht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),TZ=g(),CZ=be([O("anthropic"),O("openai"),O("azure"),O("vertex"),O("bedrock"),g()]),Aht=x({apiType:CZ,baseUrl:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Oht=x({providerId:TZ,supported:Kn(Ve(CZ),()=>[]),required:mr(),current:Aht.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),$ht=x({providers:gt(Oht),_meta:y(C(g(),T()).nullish(),()=>{})}),Mht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Dht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Nht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),pD=g(),zht=x({id:pD,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),fD=x({currentModeId:pD,availableModes:Kn(Ve(zht),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),yve=g(),Lht=be([O("mode"),O("model"),O("model_config"),O("thought_level"),g()]),PZ=g(),bve=x({value:PZ,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Fht=g(),jht=x({group:Fht,name:g(),options:Kn(Ve(bve),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Uht=be([gt(bve),gt(jht)]),Hht=x({currentValue:PZ,options:Uht}),qht=x({currentValue:mr()}),Bk=Ho(be([Hht.and(x({type:O("select")})),qht.and(x({type:O("boolean")}))]),x({id:yve,name:g(),description:y(g().nullish(),()=>{}),category:y(Lht.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})})),Ght=x({sessionId:Ar,modes:y(fD.nullish(),()=>{}),configOptions:y(Ve(Bk).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Bht=x({modes:y(fD.nullish(),()=>{}),configOptions:y(Ve(Bk).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Wht=x({sessionId:Ar,cwd:g(),additionalDirectories:y(Ve(g()).optional(),()=>[]),title:y(g().nullish(),()=>{}),updatedAt:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Vht=x({sessions:Kn(Ve(Wht),()=>[]),nextCursor:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Kht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Zht=x({sessionId:Ar,modes:y(fD.nullish(),()=>{}),configOptions:y(Ve(Bk).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Jht=x({modes:y(fD.nullish(),()=>{}),configOptions:y(Ve(Bk).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Qht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Yht=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Xht=x({configOptions:Kn(Ve(Bk),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),egt=be([O("end_turn"),O("max_tokens"),O("max_turn_requests"),O("refusal"),O("cancelled")]),tgt=x({totalTokens:rt(),inputTokens:rt(),outputTokens:rt(),thoughtTokens:y(rt().nullish(),()=>{}),cachedReadTokens:y(rt().nullish(),()=>{}),cachedWriteTokens:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),rgt=x({stopReason:egt,usage:y(tgt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),ngt=x({sessionId:Ar,_meta:y(C(g(),T()).nullish(),()=>{})}),Wk=g(),eh=x({line:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:y(C(g(),T()).nullish(),()=>{})}),Vk=x({start:eh,end:eh,_meta:y(C(g(),T()).nullish(),()=>{})}),ogt=x({range:Vk,newText:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),igt=x({id:Wk,uri:g(),edits:gt(ogt),cursorPosition:y(eh.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),sgt=x({id:Wk,uri:g(),position:eh,_meta:y(C(g(),T()).nullish(),()=>{})}),agt=x({id:Wk,uri:g(),position:eh,newName:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),cgt=x({id:Wk,uri:g(),search:g(),replace:g(),isRegex:mr().nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),lgt=be([igt.and(x({kind:O("edit")})),sgt.and(x({kind:O("jump")})),agt.and(x({kind:O("rename")})),cgt.and(x({kind:O("searchAndReplace")}))]),ugt=x({suggestions:gt(lgt),_meta:y(C(g(),T()).nullish(),()=>{})}),dgt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),xve=T(),Sve=T(),pgt=be([O(-32700),O(-32600),O(-32601),O(-32602),O(-32603),O(-32800),O(-32e3),O(-32002),fr().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),kve=x({code:pgt,message:g(),data:y(T().optional(),()=>{})}),ypr=be([x({id:Xm,result:be([Pht,Iht,$ht,Mht,Dht,Nht,Ght,Bht,Vht,Kht,Zht,Jht,Qht,Yht,Xht,rgt,ngt,ugt,dgt,xve,Sve])}),x({id:Xm,error:kve})]),fgt=g(),sZ=x({content:dZ,messageId:y(fgt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),mgt=x({toolCallId:uZ,title:g(),name:y(g().nullish(),()=>{}),kind:y(tve.optional(),()=>{}),status:y(rve.optional(),()=>{}),content:y(Ve(nve).optional(),()=>[]),locations:y(Ve(ove).optional(),()=>[]),rawInput:y(T().optional(),()=>{}),rawOutput:y(T().optional(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hgt=be([O("high"),O("medium"),O("low")]),ggt=be([O("pending"),O("in_progress"),O("completed")]),_ve=x({content:g(),priority:hgt,status:ggt,_meta:y(C(g(),T()).nullish(),()=>{})}),ygt=x({entries:Kn(Ve(_ve),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),mD=g(),bgt=x({planId:mD,entries:Kn(Ve(_ve),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),xgt=x({planId:mD,uri:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Sgt=x({planId:mD,content:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),kgt=be([bgt.and(x({type:O("items")})),xgt.and(x({type:O("file")})),Sgt.and(x({type:O("markdown")}))]),_gt=x({plan:kgt,_meta:y(C(g(),T()).nullish(),()=>{})}),wgt=x({planId:mD,_meta:y(C(g(),T()).nullish(),()=>{})}),vgt=x({hint:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Egt=vgt,Rgt=x({name:g(),description:g(),input:y(Egt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Tgt=x({availableCommands:Kn(Ve(Rgt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Cgt=x({currentModeId:pD,_meta:y(C(g(),T()).nullish(),()=>{})}),Pgt=x({configOptions:Kn(Ve(Bk),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Igt=x({title:y(g().nullish(),()=>{}),updatedAt:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Agt=x({amount:rt(),currency:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Ogt=x({used:rt(),size:rt(),cost:y(Agt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),$gt=be([sZ.and(x({sessionUpdate:O("user_message_chunk")})),sZ.and(x({sessionUpdate:O("agent_message_chunk")})),sZ.and(x({sessionUpdate:O("agent_thought_chunk")})),mgt.and(x({sessionUpdate:O("tool_call")})),ive.and(x({sessionUpdate:O("tool_call_update")})),ygt.and(x({sessionUpdate:O("plan")})),_gt.and(x({sessionUpdate:O("plan_update")})),wgt.and(x({sessionUpdate:O("plan_removed")})),Tgt.and(x({sessionUpdate:O("available_commands_update")})),Cgt.and(x({sessionUpdate:O("current_mode_update")})),Pgt.and(x({sessionUpdate:O("config_option_update")})),Igt.and(x({sessionUpdate:O("session_info_update")})),Ogt.and(x({sessionUpdate:O("usage_update")}))]),hD=x({sessionId:Ar,update:$gt,_meta:y(C(g(),T()).nullish(),()=>{})}),IZ=x({elicitationId:uve,_meta:y(C(g(),T()).nullish(),()=>{})}),wve=x({connectionId:uD,method:g(),params:y(C(g(),T()).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),vve=T(),bpr=x({method:g(),params:be([hD,IZ,wve,vve]).nullish()}),Mgt=x({readTextFile:y(mr().optional().default(!1),()=>!1),writeTextFile:y(mr().optional().default(!1),()=>!1),_meta:y(C(g(),T()).nullish(),()=>{})}),Dgt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Ngt=x({boolean:y(Dgt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),zgt=x({configOptions:y(Ngt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Lgt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Fgt=x({terminal:y(mr().optional().default(!1),()=>!1),_meta:y(C(g(),T()).nullish(),()=>{})}),jgt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Ugt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Hgt=x({form:y(jgt.nullish(),()=>{}),url:y(Ugt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),qgt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Ggt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Bgt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Wgt=x({jump:y(qgt.nullish(),()=>{}),rename:y(Ggt.nullish(),()=>{}),searchAndReplace:y(Bgt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Vgt=x({fs:y(Mgt.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:y(mr().optional().default(!1),()=>!1),session:y(zgt.nullish(),()=>{}),plan:y(Lgt.nullish(),()=>{}),auth:y(Fgt.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:y(Hgt.nullish(),()=>{}),nes:y(Wgt.nullish(),()=>{}),positionEncodings:y(Ve(hve).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),gD=x({protocolVersion:mve,clientCapabilities:y(Vgt.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:y(gve.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),AZ=x({methodId:dD,_meta:y(C(g(),T()).nullish(),()=>{})}),OZ=x({_meta:y(C(g(),T()).nullish(),()=>{})}),$Z=x({providerId:TZ,apiType:CZ,baseUrl:g(),headers:C(g(),g()).optional(),_meta:y(C(g(),T()).nullish(),()=>{})}),MZ=x({providerId:TZ,_meta:y(C(g(),T()).nullish(),()=>{})}),DZ=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Eve=x({name:g(),value:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Kgt=x({name:g(),url:g(),headers:gt(Eve),_meta:y(C(g(),T()).nullish(),()=>{})}),Zgt=x({name:g(),url:g(),headers:gt(Eve),_meta:y(C(g(),T()).nullish(),()=>{})}),Jgt=x({name:g(),serverId:dve,_meta:y(C(g(),T()).nullish(),()=>{})}),Qgt=x({name:g(),command:g(),args:gt(g()),env:gt(ave),_meta:y(C(g(),T()).nullish(),()=>{})}),yD=be([Kgt.and(x({type:O("http")})),Zgt.and(x({type:O("sse")})),Jgt.and(x({type:O("acp")})),Qgt]),NZ=x({cwd:g(),additionalDirectories:y(Ve(g()).optional(),()=>[]),mcpServers:Kn(Ve(yD),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),zZ=x({mcpServers:Kn(Ve(yD),()=>[]),cwd:g(),additionalDirectories:y(Ve(g()).optional(),()=>[]),sessionId:Ar,_meta:y(C(g(),T()).nullish(),()=>{})}),LZ=x({cwd:g().nullish(),cursor:g().nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),FZ=x({sessionId:Ar,_meta:y(C(g(),T()).nullish(),()=>{})}),jZ=x({sessionId:Ar,cwd:g(),additionalDirectories:y(Ve(g()).optional(),()=>[]),mcpServers:y(Ve(yD).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),UZ=x({sessionId:Ar,cwd:g(),additionalDirectories:y(Ve(g()).optional(),()=>[]),mcpServers:y(Ve(yD).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),HZ=x({sessionId:Ar,_meta:y(C(g(),T()).nullish(),()=>{})}),qZ=x({sessionId:Ar,modeId:pD,_meta:y(C(g(),T()).nullish(),()=>{})}),GZ=Ho(be([x({value:mr(),type:O("boolean")}),x({value:PZ})]),x({sessionId:Ar,configId:yve,_meta:y(C(g(),T()).nullish(),()=>{})})),BZ=x({sessionId:Ar,prompt:gt(dZ),_meta:y(C(g(),T()).nullish(),()=>{})}),Ygt=x({uri:g(),name:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Xgt=x({name:g(),owner:g(),remoteUrl:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),WZ=x({workspaceUri:y(g().nullish(),()=>{}),workspaceFolders:gt(Ygt).nullish(),repository:y(Xgt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),eyt=be([O("automatic"),O("diagnostic"),O("manual")]),tyt=x({uri:g(),languageId:g(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),ryt=x({startLine:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),nyt=x({uri:g(),excerpts:gt(ryt),_meta:y(C(g(),T()).nullish(),()=>{})}),oyt=x({uri:g(),diff:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),iyt=x({action:g(),uri:g(),position:eh,timestampMs:rt(),_meta:y(C(g(),T()).nullish(),()=>{})}),syt=x({uri:g(),languageId:g(),visibleRange:y(Vk.nullish(),()=>{}),lastFocusedMs:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),ayt=be([O("error"),O("warning"),O("information"),O("hint")]),cyt=x({uri:g(),range:Vk,severity:ayt,message:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),lyt=x({recentFiles:gt(tyt).nullish(),relatedSnippets:gt(nyt).nullish(),editHistory:gt(oyt).nullish(),userActions:gt(iyt).nullish(),openFiles:gt(syt).nullish(),diagnostics:gt(cyt).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),VZ=x({sessionId:Ar,uri:g(),version:rt(),position:eh,selection:Vk.nullish(),triggerKind:eyt,context:lyt.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),KZ=x({sessionId:Ar,_meta:y(C(g(),T()).nullish(),()=>{})}),xpr=x({id:Xm,method:g(),params:be([gD,AZ,OZ,$Z,MZ,DZ,NZ,zZ,LZ,FZ,jZ,UZ,HZ,qZ,GZ,BZ,WZ,VZ,KZ,pve,fve]).nullish()}),uyt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),dyt=x({content:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),pyt=x({optionId:sve,_meta:y(C(g(),T()).nullish(),()=>{})}),fyt=be([x({outcome:O("cancelled")}),pyt.and(x({outcome:O("selected")}))]),myt=x({outcome:fyt,_meta:y(C(g(),T()).nullish(),()=>{})}),hyt=x({terminalId:Gk,_meta:y(C(g(),T()).nullish(),()=>{})}),gyt=x({exitCode:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),yyt=x({output:g(),truncated:mr(),exitStatus:y(gyt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),byt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),xyt=x({exitCode:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Syt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),kyt=be([g(),rt(),rt(),mr(),gt(g())]),ZZ=x({content:C(g(),kyt).nullish()}),_yt=Mn(Ho(be([ZZ.and(x({action:O("accept")})),x({action:O("decline")}),x({action:O("cancel")}),$n(x({action:g()}),"action",["accept","cancel","decline"])]),x({_meta:y(C(g(),T()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),wyt=x({connectionId:uD,_meta:y(C(g(),T()).nullish(),()=>{})}),vyt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Spr=be([x({id:Xm,result:be([uyt,dyt,myt,hyt,yyt,byt,xyt,Syt,_yt,wyt,vyt,Sve,xve])}),x({id:Xm,error:kve})]),JZ=x({sessionId:Ar,_meta:y(C(g(),T()).nullish(),()=>{})}),QZ=x({sessionId:Ar,uri:g(),languageId:g(),version:rt(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Eyt=x({range:Vk.nullish(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),YZ=x({sessionId:Ar,uri:g(),version:rt(),contentChanges:Kn(Ve(Eyt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),XZ=x({sessionId:Ar,uri:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),e9=x({sessionId:Ar,uri:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),t9=x({sessionId:Ar,uri:g(),version:rt(),position:eh,visibleRange:Vk,_meta:y(C(g(),T()).nullish(),()=>{})}),r9=x({sessionId:Ar,id:Wk,_meta:y(C(g(),T()).nullish(),()=>{})}),Ryt=be([O("rejected"),O("ignored"),O("replaced"),O("cancelled")]),n9=x({sessionId:Ar,id:Wk,reason:y(Ryt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),kpr=x({method:g(),params:be([JZ,QZ,YZ,XZ,e9,t9,r9,n9,wve,vve]).nullish()}),_pr=x({requestId:Xm,_meta:y(C(g(),T()).nullish(),()=>{})});var Tve="$/cancel_request";function bD(e){return c9(e)&&"id"in e&&typeof e.method=="string"&&l9(e.id)}function a9(e){if(!c9(e)||"method"in e||!("id"in e)||!l9(e.id))return!1;let t=Object.hasOwn(e,"result"),r=Object.hasOwn(e,"error");return t===r?!1:!r||Cyt(e.error)}function Kk(e){return c9(e)&&!("id"in e)&&typeof e.method=="string"}function Op(e){return typeof e=="object"&&e!==null}function c9(e){return Op(e)&&e.jsonrpc==="2.0"}function l9(e){return e===null||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function Cve(e){return Op(e)&&!("method"in e)&&("id"in e||"result"in e||"error"in e)}function Pve(e){let t=!1,r=!1,n=!1,o=!1;for(let i of e)t||=bD(i)||Kk(i),r||=a9(i),Op(i)&&(n||="method"in i,o||="result"in i||"error"in i);return t?!1:r?!0:o&&!n}function Tyt(e){if(!(!Op(e)||!l9(e.requestId)))return e.requestId}function Cyt(e){return Op(e)&&typeof e.code=="number"&&Number.isInteger(e.code)&&typeof e.message=="string"}var Mc={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Zy(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Pyt(e){if(e instanceof Error||typeof e=="object"&&e!=null&&"message"in e&&typeof e.message=="string")return e.message}function Iyt(e){return typeof e=="object"&&e!==null&&"name"in e&&e.name==="ZodError"&&"issues"in e&&Array.isArray(e.issues)&&"format"in e&&typeof e.format=="function"}function Ive(e){if(e instanceof Xr)return e.toResult();if(Iyt(e))return Xr.invalidParams(e.format()).toResult();let t=Pyt(e);try{return Xr.internalError(t?JSON.parse(t):{}).toResult()}catch{return Xr.internalError({details:t}).toResult()}}function Ayt(e){return e instanceof Xr&&e.code===-32800?e:Xr.requestCancelled(e)}function Oyt(e,t){let r=$yt(e,t);return r?r.toResult():Ive(e)}function $yt(e,t){if(!(!t.aborted||!Myt(e)))return Ayt(t.reason)}function Myt(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.name==="AbortError"||t.code==="ABORT_ERR"}var o9=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(t,r,n=new AbortController().signal,o){this.id=t,this.sendResult=r,this.signal=n,this.finishRequest=o}get responded(){return this.didRespond}respond(t){return this.respondWithResult({result:t??null})}respondWithError(t){let r=t instanceof Xr?t.toErrorResponse():t;return this.respondWithResult({error:r})}respondWithResult(t){return this.didRespond?Zy(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(t).finally(()=>{this.finishRequest?.()}))}},$p=class{disposeHandler;active=!0;constructor(t){this.disposeHandler=t}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},i9=class{connection;constructor(t){this.connection=t}sendRequest(t,r,n,o){return this.connection.sendRequest(t,r,n,o)}sendNotification(t,r){return this.connection.sendNotification(t,r)}sendBatch(t){return this.connection.sendBatch(t)}sendCancelRequest(t){return this.connection.sendCancelRequest(t)}addDynamicHandler(t){return this.connection.addDynamicHandler(t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},Mp=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new i9(this);receiveReader;allowBatches=!0;constructor(t,r,n,o){if(typeof t=="function"){let c=t,l=r,u=n;this.initialize(u,[...o?.handlers??[],this.legacyHandler(c,l)],o);return}let i=t,s=r,a=n;this.initialize(i,[...a?.handlers??[],...s],a)}static builder(){return new s9}runUntil(t){let r=!1,n=Promise.resolve().then(()=>t(this.context)).finally(()=>{r=!0}),o=this.closed.then(()=>{if(r)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,o]).finally(()=>{r=!0,this.close()})}addDynamicHandler(t){if(this.dynamicHandlers.add(t),this.retryQueue.length>0)for(let r of this.retryQueue.splice(0))this.processIncomingMessage(r).catch(n=>this.close(n));return new $p(()=>{this.dynamicHandlers.delete(t)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(t,r,n,o={}){if(this.abortController.signal.aborted)return Zy(this.closedReason());let i=this.prepareRequest(t,r,n,o);return this.sendWireMessage(i.message).catch(()=>{}),o.cancellationSignal?.aborted&&i.cancel(),i.response}sendBatch(t){if(this.abortController.signal.aborted)return Zy(this.closedReason());if(!this.allowBatches)return Zy(new TypeError("JSON-RPC batches are not supported on this connection"));if(t.length===0)return Zy(new TypeError("JSON-RPC batch must contain at least one entry"));let r=[],n=[],o=[];for(let c of t){if(c.kind==="notification"){r.push({jsonrpc:"2.0",method:c.method,params:c.params}),o.push(Promise.resolve(void 0));continue}let l=this.prepareRequest(c.method,c.params,c.mapResponse,c.options);r.push(l.message),o.push(l.response),n.push({signal:c.options?.cancellationSignal,cancel:l.cancel})}let i=r,s=this.sendWireMessage(i);for(let c of n)c.signal?.aborted&&c.cancel();let a=Promise.all([s,...o]).then(([,...c])=>c);return a.catch(()=>{}),a}sendCancelRequest(t){return this.sendNotification(Tve,{requestId:t})}sendNotification(t,r){return this.abortController.signal.aborted?Zy(this.closedReason()):this.sendWireMessage({jsonrpc:"2.0",method:t,params:r})}prepareRequest(t,r,n,o={}){let i=this.nextRequestId++,s=()=>{},a=new Promise((c,l)=>{let u={resolve:d=>{try{c(n?n(d):d)}catch(f){l(f)}},reject:l};s=()=>{u.cancellationSent||(u.cancellationSent=!0,u.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},o.cancellationSignal?.addEventListener("abort",s,{once:!0}),u.cleanup=()=>{o.cancellationSignal?.removeEventListener("abort",s)},this.pendingResponses.set(i,u)});return a.catch(()=>{}),{message:{jsonrpc:"2.0",id:i,method:t,params:r},response:a,cancel:()=>s()}}close(t){if(this.abortController.signal.aborted)return;let r=t??new Error("ACP connection closed");this.abortController.abort(r);for(let n of this.pendingResponses.values())n.cleanup?.(),n.reject(r);this.pendingResponses.clear();for(let n of this.incomingRequests.values())n.abort(r);this.incomingRequests.clear(),this.receiveReader?.cancel(r).catch(()=>{})}initialize(t,r,n){this.stream=t,this.staticHandlers=r,this.allowBatches=n?.allowBatches??!0,this.closedPromise=new Promise(o=>{this.abortController.signal.addEventListener("abort",()=>o())}),this.receive()}legacyHandler(t,r){return{handleMessage:async(n,o)=>{if(n.kind==="request"){let i=await t(n.method,n.params,o);await n.responder.respond(i)}else await r(n.method,n.params,o);return Mc.yes()}}}async receive(){let t;try{let r=this.stream.readable.getReader();this.receiveReader=r;try{for(;!this.abortController.signal.aborted;){let{value:n,done:o}=await r.read();if(this.abortController.signal.aborted||o)break;n&&this.receiveWireMessage(n)}}finally{this.receiveReader===r&&(this.receiveReader=void 0),r.releaseLock()}}catch(r){t=r}finally{this.close(t)}}receiveWireMessage(t){if(Array.isArray(t)){if(!this.allowBatches){this.close(new TypeError("JSON-RPC batches are not supported on this connection"));return}this.receiveBatch(t);return}if(!Op(t)){console.error("Invalid message",{message:t});return}this.receiveMessage(t)}receiveBatch(t){if(t.length===0){this.sendWireMessage({jsonrpc:"2.0",id:null,error:Xr.invalidRequest(t).toErrorResponse()}).catch(()=>{});return}let r=Pve(t),o=r?0:t.reduce((u,d)=>u+(Kk(d)?0:1),0),i=t.reduce((u,d)=>u+(Kk(d)?1:0),0),s=!1,a=[],c=async()=>{s||o!==0||i!==0||a.length===0||(s=!0,await this.sendWireMessage(a))},l=async u=>{a.push(u),o-=1,await c()};for(let u of t){if(r){Cve(u)&&this.receiveMessage(u);continue}if(!bD(u)&&!Kk(u)){l({jsonrpc:"2.0",id:null,error:Xr.invalidRequest(u).toErrorResponse()}).catch(()=>{});continue}let d=this.receiveMessage(u,bD(u)?l:void 0);Kk(u)&&d.finally(()=>{i-=1,c().catch(f=>this.close(f))})}}receiveMessage(t,r){return this.abortController.signal.aborted?Promise.resolve():Op(t)?"method"in t?("id"in t||this.handleProtocolNotification(t),this.processIncomingMessage(this.toIncomingMessage(t,r)).catch(n=>this.close(n))):("id"in t?this.handleResponse(t):console.error("Invalid message",{message:t}),Promise.resolve()):(console.error("Invalid message",{message:t}),Promise.resolve())}async processIncomingMessage(t){if(this.abortController.signal.aborted)return;let r=t,n=!1;try{for(let o of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let i=await o.handleMessage(r,this.context)??{handled:!0};if(i.handled)return;r=i.message??r,n=n||!!i.retry}n?this.retryQueue.push(r):r.kind==="request"&&await r.responder.respondWithError(Xr.methodNotFound(r.method))}catch(o){if(this.abortController.signal.aborted)return;if(r.kind==="request"&&!r.responder.responded)await r.responder.respondWithResult(Oyt(o,r.responder.signal));else{let i=Ive(o);"error"in i&&console.error("Error handling notification",t.raw,i.error)}}}toIncomingMessage(t,r){if("id"in t){let n=new AbortController;this.incomingRequests.set(t.id,n);let o=()=>{this.incomingRequests.get(t.id)===n&&this.incomingRequests.delete(t.id)};return{kind:"request",method:t.method,params:t.params,raw:t,signal:n.signal,responder:new o9(t.id,i=>{let s={jsonrpc:"2.0",id:t.id,...i};return r?r(s):this.sendWireMessage(s)},n.signal,o)}}return{kind:"notification",method:t.method,params:t.params,raw:t}}handleResponse(t){let r=this.pendingResponses.get(t.id);if(r)if(this.pendingResponses.delete(t.id),r.cleanup?.(),!a9(t))r.reject(Xr.invalidRequest(t));else if("result"in t)r.resolve(t.result);else{let{code:n,message:o,data:i}=t.error;r.reject(new Xr(n,o,i))}else console.error("Got response to unknown request",t.id)}handleProtocolNotification(t){if(t.method!==Tve)return;let r=Tyt(t.params);if(r===void 0)return;let n=this.incomingRequests.get(r);!n||n.signal.aborted||n.abort(Xr.requestCancelled({requestId:r}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendWireMessage(t){return this.abortController.signal.aborted?Zy(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let r=this.stream.writable.getWriter();try{await r.write(t)}finally{r.releaseLock()}}).catch(r=>{throw this.close(r),r}),this.writeQueue)}},s9=class{handlers=[];connectionName;name(t){return this.connectionName=t,this}withHandler(t){return this.handlers.push(t),this}onReceiveMessage(t){return this.withHandler({handleMessage:async(r,n)=>await t(r,n)??Mc.no(r),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(t,r,n){return this.withHandler({handleMessage:async(o,i)=>{if(o.kind!=="request"||o.method!==t)return Mc.no(o);let s=r(o.params);return await n(s,o.responder,i)??Mc.yes()},describe:()=>`${this.connectionName??"request"}:${t}`})}onReceiveNotification(t,r,n){return this.withHandler({handleMessage:async(o,i)=>{if(o.kind!=="notification"||o.method!==t)return Mc.no(o);let s=r(o.params);return await n(s,i)??Mc.yes()},describe:()=>`${this.connectionName??"notification"}:${t}`})}connect(t,r){return new Mp(t,this.handlers,r)}connectWith(t,r,n){return this.connect(t,n).runUntil(r)}},Xr=class e extends Error{code;data;constructor(t,r,n){super(r),this.code=t,this.name="RequestError",this.data=n}static parseError(t,r){return new e(-32700,`Parse error${r?`: ${r}`:""}`,t)}static invalidRequest(t,r){return new e(-32600,`Invalid request${r?`: ${r}`:""}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,r){return new e(-32602,`Invalid params${r?`: ${r}`:""}`,t)}static internalError(t,r){return new e(-32603,`Internal error${r?`: ${r}`:""}`,t)}static requestCancelled(t,r){return new e(-32800,`Request cancelled${r?`: ${r}`:""}`,t)}static authRequired(t,r){return new e(-32e3,`Authentication required${r?`: ${r}`:""}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:""}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};var xD=class{#e=[];push(t){let r=[],n=0,o=t.indexOf(10,n);for(;o!==-1;)r.push(this.#t(t.subarray(n,o))),n=o+1,o=t.indexOf(10,n);return n<t.byteLength&&this.#e.push(n===0?t:new Uint8Array(t.subarray(n))),r}flush(){if(this.#e.length!==0)return this.#t(new Uint8Array(0))}#t(t){if(this.#e.length===0)return t;let r=t.byteLength;for(let i of this.#e)r+=i.byteLength;let n=new Uint8Array(r),o=0;for(let i of this.#e)n.set(i,o),o+=i.byteLength;return n.set(t,o),this.#e=[],n}};function u9(e,t){let r=new TextEncoder,n=new TextDecoder,o=!1,i,s=new ReadableStream({async start(c){let l=new xD,u=f=>{let m=n.decode(f).trim();if(m)try{let b=JSON.parse(m);Op(b)||Array.isArray(b)?c.enqueue(b):console.warn("Skipping JSON line that is not an object:",m)}catch(b){console.error("Failed to parse JSON message:",m,b)}},d=t.getReader();i=d;try{for(;;){let{value:m,done:b}=await d.read();if(o)return;if(b)break;if(m){for(let S of l.push(m))if(u(S),o)return}}if(o)return;let f=l.flush();f&&u(f)}catch(f){if(o)return;c.error(f);return}finally{i===d&&(i=void 0),d.releaseLock()}o||c.close()},cancel(c){return o=!0,i?.cancel(c)}}),a=new WritableStream({async write(c){let l=JSON.stringify(c)+`
440
- `,u=e.getWriter();try{await u.write(r.encode(l))}finally{u.releaseLock()}}});return{readable:s,writable:a}}var Cpr=vZ.and(x({mode:O("form")})).and(x({message:g()})),Ppr=EZ.and(x({mode:O("url")})).and(x({message:g()})),Ipr=be([uR,dR]).and(x({message:g()})),Apr=bZ.and(x({type:O("string")})),Opr=xZ.and(x({type:O("number")})),$pr=SZ.and(x({type:O("integer")})),Mpr=kZ.and(x({type:O("boolean")})),Dpr=wZ.and(x({type:O("array")})),Npr=_Z.and(x({type:O("string")}));var zpr=ZZ.and(x({action:O("accept")})),Lpr=x({action:O("decline")}),Fpr=x({action:O("cancel")});function y9(e,t){return u9(e,t)}function Dc(e){return e??{}}function Mve(e){return typeof e=="object"&&e!==null&&"readable"in e&&"writable"in e}function Dve(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}var th={agent:{initialize:Me.initialize,authenticate:Me.authenticate,logout:Me.logout,providers:{list:Me.providers_list,set:Me.providers_set,disable:Me.providers_disable},session:{new:Me.session_new,load:Me.session_load,list:Me.session_list,delete:Me.session_delete,fork:Me.session_fork,resume:Me.session_resume,close:Me.session_close,setMode:Me.session_set_mode,setConfigOption:Me.session_set_config_option,prompt:Me.session_prompt,cancel:Me.session_cancel},nes:{start:Me.nes_start,suggest:Me.nes_suggest,accept:Me.nes_accept,reject:Me.nes_reject,close:Me.nes_close},document:{didOpen:Me.document_did_open,didChange:Me.document_did_change,didClose:Me.document_did_close,didSave:Me.document_did_save,didFocus:Me.document_did_focus}},client:{session:{requestPermission:ir.session_request_permission,update:ir.session_update},fs:{writeTextFile:ir.fs_write_text_file,readTextFile:ir.fs_read_text_file},terminal:{create:ir.terminal_create,output:ir.terminal_output,release:ir.terminal_release,waitForExit:ir.terminal_wait_for_exit,kill:ir.terminal_kill},elicitation:{create:ir.elicitation_create,complete:ir.elicitation_complete}},protocol:{cancelRequest:JW.cancel_request}},Nve=Symbol("startActiveSession"),_D=class{cx;currentRequestId;constructor(t,r){this.cx=t,this.currentRequestId=r}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(t,r,n,o){return this.cx.sendRequest(t,r,n,o)}sendNotification(t,r){return this.cx.sendNotification(t,r)}addDynamicHandler(t){return this.cx.addDynamicHandler(t)}},pR=class e extends _D{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}request(t,r,n){let o=qve[t];return this.sendRequest(t,r,o?.mapResponse,n)}notify(t,r){return this.sendNotification(t,r)}},fR=class e extends _D{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}[Nve](t,r){return this.sendRequest(Me.session_new,t,n=>this.attachSession(n),r)}buildSession(t){return typeof t=="string"?vD.create(this,{cwd:t,mcpServers:[]}):vD.create(this,t)}attachSession(t){let r=new f9,n=this.connectionContext.signal,o=()=>{r.fail(n.reason??new Error("ACP connection closed"))};n.aborted?o():n.addEventListener("abort",o);let i=Gve(this.connectionContext).attach(t,r),s=new $p(()=>{n.removeEventListener("abort",o)});return m9.create(this,t,r,[i,s])}request(t,r,n){let o=Hve[t];return this.sendRequest(t,r,o?.mapResponse,n)}notify(t,r){return this.sendNotification(t,r)}},wD=class{connection;constructor(t){this.connection=t}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(t){this.connection.close(t)}},d9=class extends wD{connectHandlers;client;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.client=pR.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,CD(this,this.connectHandlers))}},p9=class extends wD{connectHandlers;agent;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.agent=fR.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,CD(this,this.connectHandlers))}};function zve(e,t=[]){return new d9(e,t)}function Lve(e,t=[]){return new p9(e,t)}var f9=class{values=[];waiters=[];failed=!1;failure;enqueue(t){if(this.failed)return;let r=this.waiters.shift();r?r.resolve(t):this.values.push({kind:"value",value:t})}reject(t){if(!this.failed){if(this.waiters.length>0){for(let r of this.waiters.splice(0))r.reject(t);return}this.values.push({kind:"error",error:t})}}clearErrors(){this.values=this.values.filter(t=>t.kind==="value")}fail(t){if(!this.failed){this.failed=!0,this.failure=t;for(let r of this.waiters.splice(0))r.reject(t)}}next(){if(this.values.length>0){let t=this.values.shift();return t.kind==="error"?Promise.reject(t.error):Promise.resolve(t.value)}return this.failed?Promise.reject(this.failure):new Promise((t,r)=>{this.waiters.push({resolve:t,reject:r})})}};function Ave(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}var vD=class e{cx;request;constructor(t,r){this.cx=t,this.request=Ave(r)}static create(t,r){return new e(t,r)}toRequest(){return Ave(this.request)}withAdditionalDirectories(t){return this.request={...this.request,additionalDirectories:[...t]},this}withMcpServer(t){return this.request={...this.request,mcpServers:[...this.request.mcpServers,t]},this}async start(t){return this.cx[Nve](this.toRequest(),t)}async withSession(t){let r=await this.start();try{return await t(r)}finally{r.dispose()}}},m9=class e{cx;sessionResponse;updates;registrations;constructor(t,r,n,o){this.cx=t,this.sessionResponse=r,this.updates=n,this.registrations=o}static create(t,r,n,o){return new e(t,r,n,o)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(t,r){this.updates.clearErrors();let n=this.cx.request(Me.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(t)},r);return n.then(o=>{this.updates.enqueue({kind:"stop",response:o,stopReason:o.stopReason})},o=>{this.updates.reject(o)}),n}nextUpdate(){return this.updates.next()}async readText(){let t="";for(;;){let r=await this.nextUpdate();if(r.kind==="stop")return t;let{update:n}=r;n.sessionUpdate==="agent_message_chunk"&&n.content.type==="text"&&(t+=n.content.text)}}dispose(){for(let t of this.registrations.splice(0))t.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t:[t]}};function Fve(e,t){return e?typeof e=="function"?e(t):e.parse(t):t}function en(e,t,r){return{method:e,params:t,mapResponse:r}}function Qu(e,t){return{method:e,params:t}}function jve(e,t,r,n){e.onReceiveRequest(t.method,o=>Fve(t.params,o),async(o,i,s)=>{let a=await n(r(o,s,i.signal,i.id));await i.respond(t.mapResponse?t.mapResponse(a):a)})}function Uve(e,t,r,n){e.onReceiveNotification(t.method,o=>Fve(t.params,o),(o,i)=>n(r(o,i,i.signal)))}function TD(e){let t={};for(let r of Object.values(e))t[r.method]=r;return t}var Dyt={initialize:en(Me.initialize,gD),newSession:en(Me.session_new,NZ),loadSession:en(Me.session_load,zZ,Dc),unstable_forkSession:en(Me.session_fork,jZ),listSessions:en(Me.session_list,LZ),deleteSession:en(Me.session_delete,FZ,Dc),resumeSession:en(Me.session_resume,UZ),closeSession:en(Me.session_close,HZ,Dc),setSessionMode:en(Me.session_set_mode,qZ,Dc),setSessionConfigOption:en(Me.session_set_config_option,GZ),authenticate:en(Me.authenticate,AZ,Dc),unstable_listProviders:en(Me.providers_list,OZ),unstable_setProvider:en(Me.providers_set,$Z,Dc),unstable_disableProvider:en(Me.providers_disable,MZ,Dc),logout:en(Me.logout,DZ,Dc),prompt:en(Me.session_prompt,BZ),unstable_startNes:en(Me.nes_start,WZ),unstable_suggestNes:en(Me.nes_suggest,VZ),unstable_closeNes:en(Me.nes_close,KZ,Dc)},Nyt={cancel:Qu(Me.session_cancel,JZ),unstable_didOpenDocument:Qu(Me.document_did_open,QZ),unstable_didChangeDocument:Qu(Me.document_did_change,YZ),unstable_didCloseDocument:Qu(Me.document_did_close,XZ),unstable_didSaveDocument:Qu(Me.document_did_save,e9),unstable_didFocusDocument:Qu(Me.document_did_focus,t9),unstable_acceptNes:Qu(Me.nes_accept,r9),unstable_rejectNes:Qu(Me.nes_reject,n9)},zyt={requestPermission:en(ir.session_request_permission,pZ),writeTextFile:en(ir.fs_write_text_file,cZ,Dc),readTextFile:en(ir.fs_read_text_file,lZ),createTerminal:en(ir.terminal_create,fZ),terminalOutput:en(ir.terminal_output,mZ),releaseTerminal:en(ir.terminal_release,hZ,Dc),waitForTerminalExit:en(ir.terminal_wait_for_exit,gZ),killTerminal:en(ir.terminal_kill,yZ,Dc),unstable_createElicitation:en(ir.elicitation_create,RZ)},Lyt={sessionUpdate:Qu(ir.session_update,hD),unstable_completeElicitation:Qu(ir.elicitation_complete,IZ)},Hve=TD(Dyt),Fyt=TD(Nyt),qve=TD(zyt),jyt=TD(Lyt);function Uyt(e,t,r,n){return{params:e,requestId:n,signal:r,client:t}}function Hyt(e,t,r){return{params:e,signal:r,client:t}}function qyt(e,t,r,n){return{params:e,requestId:n,signal:r,agent:t}}function Gyt(e,t,r){return{params:e,signal:r,agent:t}}var h9=class{activeSessions=new Map;handleMessage(t){if(t.kind!=="notification"||t.method!==ir.session_update)return Mc.no(t);let r=hD.parse(t.params),n={kind:"session_update",notification:r,update:r.update},o=this.activeSessions.get(r.sessionId);if(o&&o.size>0)for(let i of o)i.enqueue(n);return Mc.no(t)}attach(t,r){let n=this.activeSessions.get(t.sessionId)??new Set;return n.add(r),this.activeSessions.set(t.sessionId,n),new $p(()=>{n.delete(r),n.size===0&&this.activeSessions.delete(t.sessionId)})}},Ove=new WeakMap;function Gve(e){let t=Ove.get(e);return t||(t=new h9,Ove.set(e,t)),t}function CD(e,t){for(let r of t){let n;try{n=r(e)}catch(o){throw e.close(o),o}Promise.resolve(n).catch(o=>{e.close(o)})}}var ED=Symbol("appBuilder"),SD=Symbol("runAgentConnectHandlers"),kD=Symbol("runClientConnectHandlers"),RD={allowBatches:!1};var $ve=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name)}[ED](){return this.builder}[SD](t){CD(t,this.connectHandlers)}connect(t,r={}){return this.connectConnection(t,r).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.client))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return this.request({method:t,params:r},n);let o=Hve[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return this.notification({method:t,params:r},n);let o=Fyt[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return jve(this.builder,t,(n,o,i,s)=>Uyt(n,pR.create(o,s),i,s),r),this}notification(t,r){return Uve(this.builder,t,(n,o,i)=>Hyt(n,pR.create(o),i),r),this}connectConnection(t,r={}){if(Mve(t)){let c=this.openStreamConnection(t);return r.deferConnectHandlers||this[SD](c.connection),c}let[n,o]=Dve(),i=t[ED]().connect(o,RD),s=Lve(i),a=this.openStreamConnection(n);a.rawConnection.closed.then(()=>s.close()),i.closed.then(()=>a.connection.close());try{t[kD](s),this[SD](a.connection)}catch(c){throw s.close(c),a.connection.close(c),c}return a}openStreamConnection(t){let r=this.builder.connect(t,RD);return{rawConnection:r,connection:zve(r,this.connectHandlers)}}};function Bve(e){return new g9(e)}var g9=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name),this.builder.withHandler({handleMessage:(r,n)=>Gve(n).handleMessage(r),describe:()=>"client-session-update-router"})}[ED](){return this.builder}[kD](t){CD(t,this.connectHandlers)}connect(t){return this.connectConnection(t).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.agent))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return this.request({method:t,params:r},n);let o=qve[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return this.notification({method:t,params:r},n);let o=jyt[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return jve(this.builder,t,(n,o,i,s)=>qyt(n,fR.create(o,s),i,s),r),this}notification(t,r){return Uve(this.builder,t,(n,o,i)=>Gyt(n,fR.create(o),i),r),this}connectConnection(t){if(Mve(t)){let a=this.openStreamConnection(t);return this[kD](a.connection),a}let[r,n]=Dve(),o=t[ED]().connect(n,RD),i=zve(o),s=this.openStreamConnection(r);s.rawConnection.closed.then(()=>i.close()),o.closed.then(()=>s.connection.close());try{t[SD](i),this[kD](s.connection)}catch(a){throw i.close(a),s.connection.close(a),a}return s}openStreamConnection(t){let r=this.builder.connect(t,RD);return{rawConnection:r,connection:Lve(r,this.connectHandlers)}}},Kpr=new Set([Me.initialize,Me.authenticate,Me.providers_list,Me.providers_set,Me.providers_disable,Me.session_new,Me.session_load,Me.session_set_mode,Me.session_set_config_option,Me.session_prompt,Me.session_list,Me.session_delete,Me.session_fork,Me.session_resume,Me.session_close,Me.logout,Me.nes_start,Me.nes_suggest,Me.nes_close]),Zpr=new Set([Me.session_cancel,Me.nes_accept,Me.nes_reject,Me.document_did_open,Me.document_did_change,Me.document_did_close,Me.document_did_save,Me.document_did_focus]),Jpr=new Set([ir.session_request_permission,ir.fs_write_text_file,ir.fs_read_text_file,ir.terminal_create,ir.terminal_output,ir.terminal_release,ir.terminal_wait_for_exit,ir.terminal_kill,ir.elicitation_create]),Qpr=new Set([ir.session_update,ir.elicitation_complete]);D8();T8();var ct={initialize:"initialize",auth_login:"auth/login",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",auth_logout:"auth/logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},vi={session_request_permission:"session/request_permission",session_update:"session/update",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},N1={cancel_request:"$/cancel_request"},Hp=2;var lh=be([rt(),g()]).nullable(),dn=g(),z1=g(),_wt=be([O("read"),O("edit"),O("delete"),O("move"),O("search"),O("execute"),O("think"),O("fetch"),O("switch_mode"),O("other"),g()]),wwt=be([O("pending"),O("in_progress"),O("completed"),O("failed"),O("cancelled"),g()]),vwt=be([O("assistant"),O("user"),g()]),WR=x({audience:y(Ve(vwt).nullish(),()=>{}),lastModified:y(Zu.datetime({offset:!0}).nullish(),()=>{}),priority:y(rt().gte(0).lte(1).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),N8=x({text:g(),annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),cb=g(),z8=x({data:g(),mimeType:cb,uri:y(_r().nullish(),()=>{}),annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),L8=x({data:g(),mimeType:cb,annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Ewt=be([O("light"),O("dark"),g()]),Rwt=x({src:_r(),mimeType:y(cb.nullish(),()=>{}),sizes:y(Ve(g()).nullish(),()=>{}),theme:y(Ewt.nullish(),()=>{})}),F8=x({name:g(),uri:_r(),title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),icons:y(Ve(Rwt).nullish(),()=>{}),mimeType:y(cb.nullish(),()=>{}),size:y(rt().nullish(),()=>{}),annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Twt=x({text:g(),uri:_r(),mimeType:y(cb.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Cwt=x({blob:g(),uri:_r(),mimeType:y(cb.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Pwt=be([Twt,Cwt]),j8=x({resource:Pwt,annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),b_=Mn(be([N8.and(x({type:O("text")})),z8.and(x({type:O("image")})),L8.and(x({type:O("audio")})),F8.and(x({type:O("resource_link")})),j8.and(x({type:O("resource")})),$n(x({type:g()}),"type",["audio","image","resource","resource_link","text"])]),"type",["audio","image","resource","resource_link","text"]),U8=x({content:b_,_meta:y(C(g(),T()).nullish(),()=>{})}),Iwt=be([O("text"),O("binary"),O("directory"),O("symlink"),g()]),ss=g(),sb=x({path:ss}),BR=x({oldPath:ss,path:ss}),Awt=Mn(Ho(be([sb.and(x({operation:O("add")})),sb.and(x({operation:O("delete")})),sb.and(x({operation:O("modify")})),BR.and(x({operation:O("move")})),BR.and(x({operation:O("copy")})),$n(x({operation:g()}),"operation",["add","copy","delete","modify","move"])]),x({fileType:y(Iwt.nullish(),()=>{}),mimeType:y(cb.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})})),"operation",["add","copy","delete","modify","move"]),Owt=be([O("git_patch"),g()]),$wt=x({format:Owt,text:g()}),H8=x({changes:Ve(Awt),patch:y($wt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),L1=g(),q8=x({terminalId:L1,_meta:y(C(g(),T()).nullish(),()=>{})}),OCe=Mn(be([U8.and(x({type:O("content")})),H8.and(x({type:O("diff")})),q8.and(x({type:O("terminal")})),$n(x({type:g()}),"type",["content","diff","terminal"])]),"type",["content","diff","terminal"]),Mwt=x({path:ss,line:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),F1=x({toolCallId:z1,name:y(g().nullish(),()=>{}),title:y(g().nullish(),()=>{}),kind:y(_wt.nullish(),()=>{}),status:y(wwt.nullish(),()=>{}),content:y(Ve(OCe).nullish(),()=>{}),locations:y(Ve(Mwt).nullish(),()=>{}),rawInput:y(T().optional(),()=>{}),rawOutput:y(T().optional(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),G8=x({toolCall:F1}),B8=x({command:g(),cwd:ss,toolCallId:y(z1.nullish(),()=>{}),terminalId:y(L1.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Dwt=Mn(be([G8.and(x({type:O("tool_call")})),B8.and(x({type:O("command")})),$n(x({type:g()}),"type",["command","tool_call"])]),"type",["command","tool_call"]),$Ce=g(),Nwt=be([O("allow_once"),O("allow_always"),O("reject_once"),O("reject_always"),g()]),zwt=x({optionId:$Ce,name:g(),kind:Nwt,_meta:y(C(g(),T()).nullish(),()=>{})}),W8=x({sessionId:dn,title:g(),description:y(g().nullish(),()=>{}),subject:Dwt.nullish(),options:gt(zwt).min(1),_meta:y(C(g(),T()).nullish(),()=>{})}),VR=x({sessionId:dn,toolCallId:y(z1.nullish(),()=>{})}),KR=x({requestId:lh}),Lwt=O("object"),Fwt=be([O("email"),O("uri"),O("date"),O("date-time"),g()]),MCe=x({const:g(),title:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),V8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minLength:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:g().nullish(),format:Fwt.nullish(),default:y(g().nullish(),()=>{}),enum:gt(g()).min(1).nullish(),oneOf:gt(MCe).min(1).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),K8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minimum:rt().nullish(),maximum:rt().nullish(),default:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Z8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minimum:rt().nullish(),maximum:rt().nullish(),default:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),J8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),default:y(mr().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Q8=x({enum:gt(g()).min(1),_meta:y(C(g(),T()).nullish(),()=>{})}),DCe=x({anyOf:gt(MCe).min(1),_meta:y(C(g(),T()).nullish(),()=>{})}),jwt=Mn(be([Q8.and(x({type:O("string")})),$n(x({type:g()}),"type",["string"]),DCe]),"type",["string"]),Y8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minItems:rt().nullish(),maxItems:rt().nullish(),items:jwt,default:y(Ve(g()).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Uwt=Mn(be([V8.and(x({type:O("string")})),K8.and(x({type:O("number")})),Z8.and(x({type:O("integer")})),J8.and(x({type:O("boolean")})),Y8.and(x({type:O("array")})),$n(x({type:g()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Hwt=x({type:y(Lwt.optional().default("object"),()=>"object"),title:y(g().nullish(),()=>{}),properties:C(g(),Uwt).optional().default({}),required:gt(g()).nullish(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),X8=Ho(be([VR,KR]),x({requestedSchema:Hwt})),NCe=g(),e5=Ho(be([VR,KR]),x({elicitationId:NCe,url:_r()})),t5=Mn(Ho(be([X8.and(x({mode:O("form")})),e5.and(x({mode:O("url")})),$n(Ho(be([VR,KR]),x({mode:g()})),"mode",["form","url"])]),x({message:g(),_meta:y(C(g(),T()).nullish(),()=>{})})),"mode",["form","url"]),zCe=g(),r5=x({serverId:zCe,_meta:y(C(g(),T()).nullish(),()=>{})}),j1=g(),ZR=x({connectionId:j1,method:g(),params:C(g(),T()).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),n5=x({connectionId:j1,_meta:y(C(g(),T()).nullish(),()=>{})}),LCe=T(),uwr=x({id:lh,method:g(),params:be([W8,t5,r5,ZR,n5,LCe]).nullish()}),FCe=fr().gte(0).lte(65535),jCe=x({name:g(),title:y(g().nullish(),()=>{}),version:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),qwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Gwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Bwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Wwt=x({image:y(qwt.nullish(),()=>{}),audio:y(Gwt.nullish(),()=>{}),embeddedContext:y(Bwt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Vwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Kwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Zwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Jwt=x({stdio:y(Vwt.nullish(),()=>{}),http:y(Kwt.nullish(),()=>{}),acp:y(Zwt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Qwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Ywt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Xwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),evt=x({prompt:y(Wwt.nullish(),()=>{}),mcp:y(Jwt.nullish(),()=>{}),delete:y(Qwt.nullish(),()=>{}),additionalDirectories:y(Ywt.nullish(),()=>{}),fork:y(Xwt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),tvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),rvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),nvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),ovt=be([O("full"),O("incremental")]),ivt=x({syncKind:ovt,_meta:y(C(g(),T()).nullish(),()=>{})}),svt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),avt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),cvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),lvt=x({didOpen:y(nvt.nullish(),()=>{}),didChange:y(ivt.nullish(),()=>{}),didClose:y(svt.nullish(),()=>{}),didSave:y(avt.nullish(),()=>{}),didFocus:y(cvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),uvt=x({document:y(lvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),dvt=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),pvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),fvt=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),mvt=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),gvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),yvt=x({recentFiles:y(dvt.nullish(),()=>{}),relatedSnippets:y(pvt.nullish(),()=>{}),editHistory:y(fvt.nullish(),()=>{}),userActions:y(mvt.nullish(),()=>{}),openFiles:y(hvt.nullish(),()=>{}),diagnostics:y(gvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),bvt=x({events:y(uvt.nullish(),()=>{}),context:y(yvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),UCe=be([O("utf-16"),O("utf-32"),O("utf-8")]),xvt=x({session:y(evt.nullish(),()=>{}),auth:y(tvt.nullish(),()=>{}),providers:y(rvt.nullish(),()=>{}),nes:y(bvt.nullish(),()=>{}),positionEncoding:y(UCe.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),lb=g(),Svt=x({name:g(),label:y(g().nullish(),()=>{}),secret:y(mr().optional().default(!0),()=>!0),optional:y(mr().optional().default(!1),()=>!1),_meta:y(C(g(),T()).nullish(),()=>{})}),o5=x({methodId:lb,name:g(),description:y(g().nullish(),()=>{}),vars:Kn(Ve(Svt),()=>[]),link:y(_r().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),HCe=x({name:g(),value:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),i5=x({methodId:lb,name:g(),description:y(g().nullish(),()=>{}),args:y(Ve(g()).optional(),()=>[]),env:y(Ve(HCe).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),s5=x({methodId:lb,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),kvt=Mn(be([o5.and(x({type:O("env_var")})),i5.and(x({type:O("terminal")})),s5.and(x({type:O("agent")})),$n(x({type:g(),methodId:lb,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),"type",["agent","env_var","terminal"])]),"type",["agent","env_var","terminal"]),a5=x({protocolVersion:FCe,info:jCe,capabilities:y(xvt.optional().default({}),()=>({})),authMethods:y(Ve(kvt).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),_vt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),c5=g(),l5=be([O("anthropic"),O("openai"),O("azure"),O("vertex"),O("bedrock"),g()]),wvt=x({apiType:l5,baseUrl:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),vvt=x({providerId:c5,supported:Kn(Ve(l5),()=>[]),required:mr(),current:wvt.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),Evt=x({providers:gt(vvt),_meta:y(C(g(),T()).nullish(),()=>{})}),Rvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Tvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Cvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),qp=g(),Pvt=be([O("mode"),O("model"),O("model_config"),O("thought_level"),g()]),JR=g(),qCe=x({value:JR,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Ivt=g(),Avt=x({groupId:Ivt,name:g(),options:Kn(Ve(qCe),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Ovt=be([gt(qCe),gt(Avt)]),u5=x({currentValue:JR,options:Ovt}),d5=x({currentValue:mr()}),QR=Mn(Ho(be([u5.and(x({type:O("select")})),d5.and(x({type:O("boolean")})),$n(x({type:g()}),"type",["boolean","select"])]),x({configId:qp,name:g(),description:y(g().nullish(),()=>{}),category:y(Pvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})})),"type",["boolean","select"]),$vt=x({sessionId:dn,configOptions:y(Ve(QR).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Mvt=x({sessionId:dn,cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),title:y(g().nullish(),()=>{}),updatedAt:y(Zu.datetime({offset:!0}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),GCe=g(),Dvt=x({sessions:Kn(Ve(Mvt),()=>[]),nextCursor:y(GCe.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Nvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),zvt=x({sessionId:dn,configOptions:y(Ve(QR).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Lvt=x({configOptions:y(Ve(QR).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Fvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),jvt=x({configOptions:Kn(Ve(QR),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Uvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Hvt=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),Gp=g(),uh=x({line:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:y(C(g(),T()).nullish(),()=>{})}),x_=x({start:uh,end:uh,_meta:y(C(g(),T()).nullish(),()=>{})}),qvt=x({range:x_,newText:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),p5=x({suggestionId:Gp,uri:_r(),edits:gt(qvt).min(1),cursorPosition:y(uh.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),f5=x({suggestionId:Gp,uri:_r(),position:uh,_meta:y(C(g(),T()).nullish(),()=>{})}),m5=x({suggestionId:Gp,uri:_r(),position:uh,newName:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),h5=x({suggestionId:Gp,uri:_r(),search:g(),replace:g(),isRegex:mr().nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),Gvt=Mn(be([p5.and(x({kind:O("edit")})),f5.and(x({kind:O("jump")})),m5.and(x({kind:O("rename")})),h5.and(x({kind:O("searchAndReplace")})),$n(x({kind:g(),suggestionId:Gp}),"kind",["edit","jump","rename","searchAndReplace"])]),"kind",["edit","jump","rename","searchAndReplace"]),Bvt=x({suggestions:gt(Gvt),_meta:y(C(g(),T()).nullish(),()=>{})}),Wvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),BCe=T(),WCe=T(),Vvt=be([O(-32700),O(-32600),O(-32601),O(-32602),O(-32603),O(-32800),O(-32e3),O(-32002),fr().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),VCe=x({code:Vvt,message:g(),data:y(T().optional(),()=>{})}),dwr=be([x({id:lh,result:be([a5,_vt,Evt,Rvt,Tvt,Cvt,$vt,Dvt,Nvt,zvt,Lvt,Fvt,jvt,Uvt,Hvt,Bvt,Wvt,BCe,WCe])}),x({id:lh,error:VCe})]),U1=g(),ab=x({messageId:U1,content:b_,_meta:y(C(g(),T()).nullish(),()=>{})}),g5=x({messageId:U1,content:y(Ve(b_).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),y5=x({messageId:U1,content:y(Ve(b_).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),b5=x({messageId:U1,content:y(Ve(b_).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),x5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Kvt=be([O("end_turn"),O("max_tokens"),O("max_turn_requests"),O("refusal"),O("cancelled"),g()]),Zvt=x({totalTokens:rt(),inputTokens:rt(),outputTokens:rt(),thoughtTokens:y(rt().nullish(),()=>{}),cachedReadTokens:y(rt().nullish(),()=>{}),cachedWriteTokens:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),S5=x({stopReason:y(Kvt.nullish(),()=>{}),usage:y(Zvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),k5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),_5=Mn(be([x5.and(x({state:O("running")})),S5.and(x({state:O("idle")})),k5.and(x({state:O("requires_action")})),$n(x({state:g()}),"state",["idle","requires_action","running"])]),"state",["idle","requires_action","running"]),w5=x({toolCallId:z1,content:OCe,_meta:y(C(g(),T()).nullish(),()=>{})}),Jvt=x({data:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Qvt=x({exitCode:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),v5=x({terminalId:L1,command:y(g().nullish(),()=>{}),cwd:y(ss.nullish(),()=>{}),output:y(Jvt.nullish(),()=>{}),exitStatus:y(Qvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),E5=x({terminalId:L1,data:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),ub=g(),Yvt=be([O("high"),O("medium"),O("low"),g()]),Xvt=be([O("pending"),O("in_progress"),O("completed"),O("cancelled"),g()]),eEt=x({content:g(),priority:Yvt,status:Xvt,_meta:y(C(g(),T()).nullish(),()=>{})}),R5=x({planId:ub,entries:Kn(Ve(eEt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),T5=x({planId:ub,uri:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),C5=x({planId:ub,content:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),tEt=Mn(be([R5.and(x({type:O("items")})),T5.and(x({type:O("file")})),C5.and(x({type:O("markdown")})),$n(x({type:g(),planId:ub}),"type",["file","items","markdown"])]),"type",["file","items","markdown"]),P5=x({plan:tEt,_meta:y(C(g(),T()).nullish(),()=>{})}),I5=x({planId:ub,_meta:y(C(g(),T()).nullish(),()=>{})}),A5=x({hint:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),rEt=Mn(be([A5.and(x({type:O("text")})),$n(x({type:g()}),"type",["text"])]),"type",["text"]),nEt=x({name:g(),description:g(),input:y(rEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),O5=x({availableCommands:Kn(Ve(nEt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),$5=x({configOptions:Kn(Ve(QR),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),M5=x({title:y(g().nullish(),()=>{}),updatedAt:y(Zu.datetime({offset:!0}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),oEt=x({amount:rt(),currency:g().regex(/^[A-Z]{3}$/),_meta:y(C(g(),T()).nullish(),()=>{})}),D5=x({used:rt(),size:rt(),cost:y(oEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),iEt=Mn(be([ab.and(x({sessionUpdate:O("user_message_chunk")})),g5.and(x({sessionUpdate:O("user_message")})),ab.and(x({sessionUpdate:O("agent_message_chunk")})),y5.and(x({sessionUpdate:O("agent_message")})),ab.and(x({sessionUpdate:O("agent_thought_chunk")})),b5.and(x({sessionUpdate:O("agent_thought")})),_5.and(x({sessionUpdate:O("state_update")})),w5.and(x({sessionUpdate:O("tool_call_content_chunk")})),F1.and(x({sessionUpdate:O("tool_call_update")})),v5.and(x({sessionUpdate:O("terminal_update")})),E5.and(x({sessionUpdate:O("terminal_output_chunk")})),P5.and(x({sessionUpdate:O("plan_update")})),I5.and(x({sessionUpdate:O("plan_removed")})),O5.and(x({sessionUpdate:O("available_commands_update")})),$5.and(x({sessionUpdate:O("config_option_update")})),M5.and(x({sessionUpdate:O("session_info_update")})),D5.and(x({sessionUpdate:O("usage_update")})),$n(x({sessionUpdate:g()}),"sessionUpdate",["agent_message","agent_message_chunk","agent_thought","agent_thought_chunk","available_commands_update","config_option_update","plan_removed","plan_update","session_info_update","state_update","terminal_output_chunk","terminal_update","tool_call_content_chunk","tool_call_update","usage_update","user_message","user_message_chunk"])]),"sessionUpdate",["agent_message","agent_message_chunk","agent_thought","agent_thought_chunk","available_commands_update","config_option_update","plan_removed","plan_update","session_info_update","state_update","terminal_output_chunk","terminal_update","tool_call_content_chunk","tool_call_update","usage_update","user_message","user_message_chunk"]),H1=x({sessionId:dn,update:iEt,_meta:y(C(g(),T()).nullish(),()=>{})}),N5=x({elicitationId:NCe,_meta:y(C(g(),T()).nullish(),()=>{})}),YR=x({connectionId:j1,method:g(),params:y(C(g(),T()).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),KCe=T(),pwr=x({method:g(),params:be([H1,N5,YR,KCe]).nullish()}),sEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),aEt=x({terminal:y(sEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),cEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),lEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),uEt=x({form:y(cEt.nullish(),()=>{}),url:y(lEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),dEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),pEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),fEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),mEt=x({jump:y(dEt.nullish(),()=>{}),rename:y(pEt.nullish(),()=>{}),searchAndReplace:y(fEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hEt=x({auth:y(aEt.nullish(),()=>{}),elicitation:y(uEt.nullish(),()=>{}),nes:y(mEt.nullish(),()=>{}),positionEncodings:y(Ve(UCe).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),q1=x({protocolVersion:FCe,info:jCe,capabilities:y(hEt.optional().default({}),()=>({})),_meta:y(C(g(),T()).nullish(),()=>{})}),z5=x({methodId:lb,_meta:y(C(g(),T()).nullish(),()=>{})}),L5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),F5=x({providerId:c5,apiType:l5,baseUrl:_r(),headers:C(g(),g()).optional(),_meta:y(C(g(),T()).nullish(),()=>{})}),j5=x({providerId:c5,_meta:y(C(g(),T()).nullish(),()=>{})}),U5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),gEt=x({name:g(),value:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),H5=x({name:g(),url:_r(),headers:gt(gEt).optional(),_meta:y(C(g(),T()).nullish(),()=>{})}),q5=x({name:g(),serverId:zCe,_meta:y(C(g(),T()).nullish(),()=>{})}),G5=x({name:g(),command:ss,args:gt(g()).optional(),env:gt(HCe).optional(),_meta:y(C(g(),T()).nullish(),()=>{})}),B5=Mn(be([H5.and(x({type:O("http")})),q5.and(x({type:O("acp")})),G5.and(x({type:O("stdio")})),$n(x({type:g()}),"type",["acp","http","stdio"])]),"type",["acp","http","stdio"]),W5=x({cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),mcpServers:y(Ve(B5).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),V5=x({cwd:ss.nullish(),cursor:GCe.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),K5=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),Z5=x({sessionId:dn,cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),mcpServers:y(Ve(B5).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),J5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),yEt=Mn(be([J5.and(x({type:O("start")})),$n(x({type:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),"type",["start"])]),"type",["start"]),Q5=x({sessionId:dn,cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),mcpServers:y(Ve(B5).optional(),()=>[]),replayFrom:y(yEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Y5=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),X5=Mn(Ho(be([x({value:JR,type:O("id")}),x({value:mr(),type:O("boolean")}),$n(x({type:g(),value:T()}),"type",["boolean","id"])]),x({sessionId:dn,configId:qp,_meta:y(C(g(),T()).nullish(),()=>{})})),"type",["boolean","id"]),e7=x({sessionId:dn,prompt:gt(b_),_meta:y(C(g(),T()).nullish(),()=>{})}),bEt=x({uri:_r(),name:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),xEt=x({name:g(),owner:g(),remoteUrl:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),t7=x({workspaceUri:y(_r().nullish(),()=>{}),workspaceFolders:gt(bEt).nullish(),repository:y(xEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),SEt=be([O("automatic"),O("diagnostic"),O("manual"),g()]),kEt=x({uri:_r(),languageId:g(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),_Et=x({startLine:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),wEt=x({uri:_r(),excerpts:gt(_Et),_meta:y(C(g(),T()).nullish(),()=>{})}),vEt=x({uri:_r(),diff:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),EEt=x({action:g(),uri:_r(),position:uh,timestampMs:rt(),_meta:y(C(g(),T()).nullish(),()=>{})}),REt=x({uri:_r(),languageId:g(),visibleRange:y(x_.nullish(),()=>{}),lastFocusedMs:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),TEt=be([O("error"),O("warning"),O("information"),O("hint"),g()]),CEt=x({uri:_r(),range:x_,severity:TEt,message:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),PEt=x({recentFiles:gt(kEt).nullish(),relatedSnippets:gt(wEt).nullish(),editHistory:gt(vEt).nullish(),userActions:gt(EEt).nullish(),openFiles:gt(REt).nullish(),diagnostics:gt(CEt).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),r7=x({sessionId:dn,uri:_r(),version:rt(),position:uh,selection:x_.nullish(),triggerKind:SEt,context:PEt.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),n7=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),fwr=x({id:lh,method:g(),params:be([q1,z5,L5,F5,j5,U5,W5,V5,K5,Z5,Q5,Y5,X5,e7,t7,r7,n7,ZR,LCe]).nullish()}),o7=x({optionId:$Ce,_meta:y(C(g(),T()).nullish(),()=>{})}),IEt=Mn(be([x({outcome:O("cancelled")}),o7.and(x({outcome:O("selected")})),$n(x({outcome:g()}),"outcome",["cancelled","selected"])]),"outcome",["cancelled","selected"]),AEt=x({outcome:IEt,_meta:y(C(g(),T()).nullish(),()=>{})}),OEt=be([g(),rt(),rt(),mr(),gt(g())]),i7=x({content:C(g(),OEt).nullish()}),$Et=Mn(Ho(be([i7.and(x({action:O("accept")})),x({action:O("decline")}),x({action:O("cancel")}),$n(x({action:g()}),"action",["accept","cancel","decline"])]),x({_meta:y(C(g(),T()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),MEt=x({connectionId:j1,_meta:y(C(g(),T()).nullish(),()=>{})}),DEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),mwr=be([x({id:lh,result:be([AEt,$Et,MEt,DEt,WCe,BCe])}),x({id:lh,error:VCe})]),s7=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),a7=x({sessionId:dn,uri:_r(),languageId:g(),version:rt(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),NEt=x({range:x_.nullish(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),c7=x({sessionId:dn,uri:_r(),version:rt(),contentChanges:Kn(Ve(NEt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),l7=x({sessionId:dn,uri:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),u7=x({sessionId:dn,uri:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),d7=x({sessionId:dn,uri:_r(),version:rt(),position:uh,visibleRange:x_,_meta:y(C(g(),T()).nullish(),()=>{})}),p7=x({sessionId:dn,suggestionId:Gp,_meta:y(C(g(),T()).nullish(),()=>{})}),zEt=be([O("rejected"),O("ignored"),O("replaced"),O("cancelled"),g()]),f7=x({sessionId:dn,suggestionId:Gp,reason:y(zEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hwr=x({method:g(),params:be([s7,a7,c7,l7,u7,d7,p7,f7,YR,KCe]).nullish()}),LEt=x({requestId:lh,_meta:y(C(g(),T()).nullish(),()=>{})}),gwr=x({method:g(),params:LEt.nullish()});function rn(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}var ywr=G8.and(x({type:O("tool_call")})),bwr=B8.and(x({type:O("command")})),xwr=U8.and(x({type:O("content")})),Swr=H8.and(x({type:O("diff")})),kwr=q8.and(x({type:O("terminal")})),FEt=N8.and(x({type:O("text")})),jEt=z8.and(x({type:O("image")})),UEt=L8.and(x({type:O("audio")})),HEt=F8.and(x({type:O("resource_link")})),qEt=j8.and(x({type:O("resource")})),_wr=sb.and(x({operation:O("add")})),wwr=sb.and(x({operation:O("delete")})),vwr=sb.and(x({operation:O("modify")})),Ewr=BR.and(x({operation:O("move")})),Rwr=BR.and(x({operation:O("copy")})),Twr=X8.and(x({mode:O("form")})).and(x({message:g()})),Cwr=e5.and(x({mode:O("url")})).and(x({message:g()})),Pwr=be([VR,KR]).and(x({message:g()})),Iwr=V8.and(x({type:O("string")})),Awr=K8.and(x({type:O("number")})),Owr=Z8.and(x({type:O("integer")})),$wr=J8.and(x({type:O("boolean")})),Mwr=Y8.and(x({type:O("array")})),Dwr=Q8.and(x({type:O("string")}));var Nwr=o5.and(x({type:O("env_var")})),zwr=i5.and(x({type:O("terminal")})),Lwr=s5.and(x({type:O("agent")})),Fwr=x({methodId:lb,name:g()}),jwr=u5.and(x({type:O("select")})).and(x({configId:qp,name:g()})),Uwr=d5.and(x({type:O("boolean")})).and(x({configId:qp,name:g()})),Hwr=x({configId:qp,name:g()}),qwr=p5.and(x({kind:O("edit")})),Gwr=f5.and(x({kind:O("jump")})),Bwr=m5.and(x({kind:O("rename")})),Wwr=h5.and(x({kind:O("searchAndReplace")})),Vwr=x({suggestionId:Gp}),GEt=ab.and(x({sessionUpdate:O("user_message_chunk")})),BEt=g5.and(x({sessionUpdate:O("user_message")})),WEt=ab.and(x({sessionUpdate:O("agent_message_chunk")})),VEt=y5.and(x({sessionUpdate:O("agent_message")})),KEt=ab.and(x({sessionUpdate:O("agent_thought_chunk")})),ZEt=b5.and(x({sessionUpdate:O("agent_thought")})),JEt=_5.and(x({sessionUpdate:O("state_update")})),QEt=w5.and(x({sessionUpdate:O("tool_call_content_chunk")})),YEt=F1.and(x({sessionUpdate:O("tool_call_update")})),XEt=v5.and(x({sessionUpdate:O("terminal_update")})),e0t=E5.and(x({sessionUpdate:O("terminal_output_chunk")})),t0t=P5.and(x({sessionUpdate:O("plan_update")})),r0t=I5.and(x({sessionUpdate:O("plan_removed")})),n0t=O5.and(x({sessionUpdate:O("available_commands_update")})),o0t=$5.and(x({sessionUpdate:O("config_option_update")})),i0t=M5.and(x({sessionUpdate:O("session_info_update")})),s0t=D5.and(x({sessionUpdate:O("usage_update")})),a0t=x5.and(x({state:O("running")})),c0t=S5.and(x({state:O("idle")})),l0t=k5.and(x({state:O("requires_action")})),Kwr=R5.and(x({type:O("items")})),Zwr=T5.and(x({type:O("file")})),Jwr=C5.and(x({type:O("markdown")})),Qwr=x({planId:ub}),Ywr=A5.and(x({type:O("text")})),Xwr=H5.and(x({type:O("http")})),evr=q5.and(x({type:O("acp")})),tvr=G5.and(x({type:O("stdio")})),rvr=J5.and(x({type:O("start")})),nvr=x({type:O("id")}).and(x({value:JR})).and(x({sessionId:dn,configId:qp})),ovr=x({type:O("boolean")}).and(x({value:mr()})).and(x({sessionId:dn,configId:qp})),ivr=x({value:T()}).and(x({sessionId:dn,configId:qp})),svr=x({outcome:O("cancelled")}),avr=o7.and(x({outcome:O("selected")})),cvr=i7.and(x({action:O("accept")})),lvr=x({action:O("decline")}),uvr=x({action:O("cancel")});var m7={isText(e){return rn(e,"type")==="text"&&FEt.safeParse(e).success},isImage(e){return rn(e,"type")==="image"&&jEt.safeParse(e).success},isAudio(e){return rn(e,"type")==="audio"&&UEt.safeParse(e).success},isResourceLink(e){return rn(e,"type")==="resource_link"&&HEt.safeParse(e).success},isResource(e){return rn(e,"type")==="resource"&&qEt.safeParse(e).success},isCustom(e){let t=rn(e,"type");return typeof t=="string"&&!["audio","image","resource","resource_link","text"].includes(t)}};var XR={isUserMessageChunk(e){return rn(e,"sessionUpdate")==="user_message_chunk"&&GEt.safeParse(e).success},isUserMessage(e){return rn(e,"sessionUpdate")==="user_message"&&BEt.safeParse(e).success},isAgentMessageChunk(e){return rn(e,"sessionUpdate")==="agent_message_chunk"&&WEt.safeParse(e).success},isAgentMessage(e){return rn(e,"sessionUpdate")==="agent_message"&&VEt.safeParse(e).success},isAgentThoughtChunk(e){return rn(e,"sessionUpdate")==="agent_thought_chunk"&&KEt.safeParse(e).success},isAgentThought(e){return rn(e,"sessionUpdate")==="agent_thought"&&ZEt.safeParse(e).success},isStateUpdate(e){return rn(e,"sessionUpdate")==="state_update"&&JEt.safeParse(e).success},isToolCallContentChunk(e){return rn(e,"sessionUpdate")==="tool_call_content_chunk"&&QEt.safeParse(e).success},isToolCallUpdate(e){return rn(e,"sessionUpdate")==="tool_call_update"&&YEt.safeParse(e).success},isTerminalUpdate(e){return rn(e,"sessionUpdate")==="terminal_update"&&XEt.safeParse(e).success},isTerminalOutputChunk(e){return rn(e,"sessionUpdate")==="terminal_output_chunk"&&e0t.safeParse(e).success},isPlanUpdate(e){return rn(e,"sessionUpdate")==="plan_update"&&t0t.safeParse(e).success},isPlanRemoved(e){return rn(e,"sessionUpdate")==="plan_removed"&&r0t.safeParse(e).success},isAvailableCommandsUpdate(e){return rn(e,"sessionUpdate")==="available_commands_update"&&n0t.safeParse(e).success},isConfigOptionUpdate(e){return rn(e,"sessionUpdate")==="config_option_update"&&o0t.safeParse(e).success},isSessionInfoUpdate(e){return rn(e,"sessionUpdate")==="session_info_update"&&i0t.safeParse(e).success},isUsageUpdate(e){return rn(e,"sessionUpdate")==="usage_update"&&s0t.safeParse(e).success},isCustom(e){let t=rn(e,"sessionUpdate");return typeof t=="string"&&!["agent_message","agent_message_chunk","agent_thought","agent_thought_chunk","available_commands_update","config_option_update","plan_removed","plan_update","session_info_update","state_update","terminal_output_chunk","terminal_update","tool_call_content_chunk","tool_call_update","usage_update","user_message","user_message_chunk"].includes(t)}},h7={isRunning(e){return rn(e,"state")==="running"&&a0t.safeParse(e).success},isIdle(e){return rn(e,"state")==="idle"&&c0t.safeParse(e).success},isRequiresAction(e){return rn(e,"state")==="requires_action"&&l0t.safeParse(e).success},isCustom(e){let t=rn(e,"state");return typeof t=="string"&&!["idle","requires_action","running"].includes(t)}};function Bp(e){return e??{}}function Wp(e,t,r,n=!1){if(!(Object.hasOwn(t,e)||n&&e===N1.cancel_request)&&!e.startsWith("_"))throw new TypeError(`Custom ACP v2 ${r} method '${e}' must start with '_'`)}function ePe(e,t,r){for(let n of e)Wp(n.method,n.kind==="request"?t:r,n.kind,n.kind==="notification")}function tPe(e){let t=q1.parse(e);if(t.protocolVersion!==Hp)throw Xr.invalidParams({expectedProtocolVersion:Hp,receivedProtocolVersion:t.protocolVersion},`The v2 API only supports protocol version ${Hp}`);return t}function rPe(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{};return tPe({...t,protocolVersion:Hp})}function nPe(e){let t=a5.parse(e);if(t.protocolVersion!==Hp)throw Xr.invalidRequest({expectedProtocolVersion:Hp,receivedProtocolVersion:t.protocolVersion},`The v2 API only supports protocol version ${Hp}`);return t}function d0t(e){return e.map(t=>{if(t.kind!=="request"||t.method!==ct.initialize)return t;let r=t.mapResponse;return{...t,params:rPe(t.params),mapResponse:n=>{let o=nPe(n);return r?r(o):o}}})}function oPe(e){return typeof e=="object"&&e!==null&&"readable"in e&&"writable"in e}function iPe(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}var zvr={agent:{initialize:ct.initialize,auth:{login:ct.auth_login,logout:ct.auth_logout},providers:{list:ct.providers_list,set:ct.providers_set,disable:ct.providers_disable},session:{new:ct.session_new,list:ct.session_list,delete:ct.session_delete,fork:ct.session_fork,resume:ct.session_resume,close:ct.session_close,setConfigOption:ct.session_set_config_option,prompt:ct.session_prompt,cancel:ct.session_cancel},mcp:{message:ct.mcp_message},nes:{start:ct.nes_start,suggest:ct.nes_suggest,accept:ct.nes_accept,reject:ct.nes_reject,close:ct.nes_close},document:{didOpen:ct.document_did_open,didChange:ct.document_did_change,didClose:ct.document_did_close,didSave:ct.document_did_save,didFocus:ct.document_did_focus}},client:{session:{requestPermission:vi.session_request_permission,update:vi.session_update},mcp:{connect:vi.mcp_connect,message:vi.mcp_message,disconnect:vi.mcp_disconnect},elicitation:{create:vi.elicitation_create,complete:vi.elicitation_complete}},protocol:{cancelRequest:N1.cancel_request}},sPe=Symbol("startActiveSession"),W1=class{cx;currentRequestId;constructor(t,r){this.cx=t,this.currentRequestId=r}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(t,r,n,o){return this.cx.sendRequest(t,r,n,o)}sendNotification(t,r){return this.cx.sendNotification(t,r)}sendBatch(t){return this.cx.sendBatch(t)}addDynamicHandler(t){return this.cx.addDynamicHandler(t)}},rT=class e extends W1{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}request(t,r,n){Wp(t,tT,"request");let o=tT[t];return this.sendRequest(t,r,o?.mapResponse,n)}notify(t,r){return Wp(t,J1,"notification",!0),this.sendNotification(t,r)}batch(t){return ePe(t,tT,J1),this.sendBatch(t)}},nT=class e extends W1{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}[sPe](t,r){return this.sendRequest(ct.session_new,t,n=>this.attachSession(n),r)}buildSession(t){return typeof t=="string"?K1.create(this,{cwd:t,mcpServers:[]}):K1.create(this,t)}attachSession(t){let r=new b7,n=new Set,o={enqueue:l=>r.enqueue(l),reject:l=>r.reject(l),clearErrors:()=>r.clearErrors(),fail:l=>r.fail(l),next:()=>r.next(),nextAfter:(l,u)=>r.nextAfter(l,u),beginPrompt:()=>{let l={updateCursor:r.cursor(),overlapController:new AbortController};if(n.size>0){let u=new Error("readText() cannot attribute updates across overlapping prompts; use nextUpdate() instead");for(let d of n)d.overlapController.abort(u);l.overlapController.abort(u)}return n.add(l),l},cancelPrompt:l=>n.delete(l),isAwaitingPromptCompletion:()=>n.size>0,completePrompt:()=>{n.clear()}},i=this.connectionContext.signal,s=()=>{r.fail(i.reason??new Error("ACP connection closed"))};i.aborted?s():i.addEventListener("abort",s);let a=pPe(this.connectionContext).attach(t,o),c=new $p(()=>{i.removeEventListener("abort",s)});return x7.create(this,t,o,[a,c])}request(t,r,n){Wp(t,eT,"request");let o=eT[t],i=t===ct.initialize?rPe(r):r;return this.sendRequest(t,i,o?.mapResponse,n)}notify(t,r){return Wp(t,Z1,"notification",!0),this.sendNotification(t,r)}batch(t){return ePe(t,eT,Z1),this.sendBatch(d0t(t))}},V1=class{connection;constructor(t){this.connection=t}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(t){this.connection.close(t)}},g7=class extends V1{connectHandlers;client;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.client=rT.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,X1(this,this.connectHandlers))}},y7=class extends V1{connectHandlers;agent;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.agent=nT.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,X1(this,this.connectHandlers))}};function aPe(e,t=[]){return new g7(e,t)}function cPe(e,t=[]){return new y7(e,t)}var b7=class{values=[];waiters=[];failed=!1;failure;nextSequence=0;enqueue(t){if(this.failed)return;let r=this.nextSequence++,n=this.waiters.shift();n?n.resolve(t):this.values.push({kind:"value",value:t,sequence:r})}reject(t){if(this.failed)return;let r=this.nextSequence++;if(this.waiters.length>0){for(let n of this.waiters.splice(0))n.reject(t);return}this.values.push({kind:"error",error:t,sequence:r})}clearErrors(){this.values=this.values.filter(t=>t.kind==="value")}cursor(){return this.nextSequence}nextAfter(t,r){if(r?.aborted)return Promise.reject(r.reason);for(;this.values[0]&&this.values[0].sequence<t;)this.values.shift();return this.next(r)}fail(t){if(!this.failed){this.failed=!0,this.failure=t;for(let r of this.waiters.splice(0))r.reject(t)}}next(t){if(t?.aborted)return Promise.reject(t.reason);if(this.values.length>0){let r=this.values.shift();return r.kind==="error"?Promise.reject(r.error):Promise.resolve(r.value)}return this.failed?Promise.reject(this.failure):new Promise((r,n)=>{let o=()=>{t?.removeEventListener("abort",s)},i={resolve:a=>{o(),r(a)},reject:a=>{o(),n(a)}},s=()=>{let a=this.waiters.indexOf(i);a>=0&&this.waiters.splice(a,1),i.reject(t?.reason)};this.waiters.push(i),t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s()})}};function JCe(e){return structuredClone(e)}var K1=class e{cx;request;constructor(t,r){this.cx=t,this.request=JCe(r)}static create(t,r){return new e(t,r)}toRequest(){return JCe(this.request)}withAdditionalDirectories(t){return this.request={...this.request,additionalDirectories:[...t]},this}withMcpServer(t){return this.request={...this.request,mcpServers:[...this.request.mcpServers??[],structuredClone(t)]},this}async start(t){return this.cx[sPe](this.toRequest(),t)}async withSession(t){let r=await this.start();try{return await t(r)}finally{r.dispose()}}},x7=class e{cx;sessionResponse;updates;registrations;latestPrompt;constructor(t,r,n,o){this.cx=t,this.sessionResponse=r,this.updates=n,this.registrations=o}static create(t,r,n,o){return new e(t,r,n,o)}get sessionId(){return this.sessionResponse.sessionId}get configOptions(){return this.sessionResponse.configOptions}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(t,r){this.updates.clearErrors();let n=this.updates.beginPrompt();this.latestPrompt=n;let o=this.cx.request(ct.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(t)},r);return o.catch(i=>{this.updates.cancelPrompt(n)&&this.updates.reject(i)}),o}nextUpdate(){return this.updates.next()}async readText(){let t=this.latestPrompt,r=t?.updateCursor,n=[],o=new Map,i=s=>{let a=o.get(s);return a||(a=[],n.push(s),o.set(s,a)),a};for(;;){let s=r===void 0?await this.nextUpdate():await this.updates.nextAfter(r,t?.overlapController.signal);if(s.kind==="stop")return n.flatMap(c=>o.get(c)??[]).filter(m7.isText).map(c=>c.text).join("");let{update:a}=s;XR.isAgentMessage(a)?(i(a.messageId),a.content!==void 0&&o.set(a.messageId,a.content??[])):XR.isAgentMessageChunk(a)&&i(a.messageId).push(a.content)}}dispose(){for(let t of this.registrations.splice(0))t.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t:[t]}};function lPe(e,t){return e?typeof e=="function"?e(t):e.parse(t):t}function so(e,t,r){return{method:e,params:t,mapResponse:r}}function qc(e,t){return{method:e,params:t}}function uPe(e,t,r,n){e.onReceiveRequest(t.method,o=>lPe(t.params,o),async(o,i,s)=>{let a=await n(r(o,s,i.signal,i.id));await i.respond(t.mapResponse?t.mapResponse(a):a)})}function dPe(e,t,r,n){e.onReceiveNotification(t.method,o=>lPe(t.params,o),(o,i)=>n(r(o,i,i.signal)))}function Y1(e){let t=Object.create(null);for(let r of Object.values(e))t[r.method]=r;return t}var p0t={initialize:so(ct.initialize,tPe,nPe),loginAuth:so(ct.auth_login,z5,Bp),unstable_listProviders:so(ct.providers_list,L5),unstable_setProvider:so(ct.providers_set,F5,Bp),unstable_disableProvider:so(ct.providers_disable,j5,Bp),newSession:so(ct.session_new,W5),setSessionConfigOption:so(ct.session_set_config_option,X5),prompt:so(ct.session_prompt,e7,Bp),unstable_messageMcp:so(ct.mcp_message,ZR),listSessions:so(ct.session_list,V5),deleteSession:so(ct.session_delete,K5,Bp),unstable_forkSession:so(ct.session_fork,Z5),resumeSession:so(ct.session_resume,Q5),closeSession:so(ct.session_close,Y5,Bp),logoutAuth:so(ct.auth_logout,U5,Bp),unstable_startNes:so(ct.nes_start,t7),unstable_suggestNes:so(ct.nes_suggest,r7),unstable_closeNes:so(ct.nes_close,n7,Bp)},f0t={cancelSession:qc(ct.session_cancel,s7),unstable_messageMcp:qc(ct.mcp_message,YR),unstable_didOpenDocument:qc(ct.document_did_open,a7),unstable_didChangeDocument:qc(ct.document_did_change,c7),unstable_didCloseDocument:qc(ct.document_did_close,l7),unstable_didSaveDocument:qc(ct.document_did_save,u7),unstable_didFocusDocument:qc(ct.document_did_focus,d7),unstable_acceptNes:qc(ct.nes_accept,p7),unstable_rejectNes:qc(ct.nes_reject,f7)},m0t={requestPermission:so(vi.session_request_permission,W8),unstable_connectMcp:so(vi.mcp_connect,r5),unstable_messageMcp:so(vi.mcp_message,ZR),unstable_disconnectMcp:so(vi.mcp_disconnect,n5,Bp),unstable_createElicitation:so(vi.elicitation_create,t5)},h0t={sessionUpdate:qc(vi.session_update,H1),unstable_messageMcp:qc(vi.mcp_message,YR),unstable_completeElicitation:qc(vi.elicitation_complete,N5)},eT=Y1(p0t),Z1=Y1(f0t),tT=Y1(m0t),J1=Y1(h0t);function g0t(e,t,r,n){return{params:e,requestId:n,signal:r,client:t}}function y0t(e,t,r){return{params:e,signal:r,client:t}}function b0t(e,t,r,n){return{params:e,requestId:n,signal:r,agent:t}}function x0t(e,t,r){return{params:e,signal:r,agent:t}}var S7=class{activeSessions=new Map;handleMessage(t){if(t.kind!=="notification"||t.method!==vi.session_update)return Mc.no(t);let r=H1.parse(t.params),{update:n}=r,o=XR.isStateUpdate(n)&&h7.isIdle(n),i=this.activeSessions.get(r.sessionId);if(i&&i.size>0)for(let s of i)o&&s.isAwaitingPromptCompletion()?(s.completePrompt(),s.enqueue({kind:"stop",notification:r,update:n,stopReason:n.stopReason})):s.enqueue({kind:"session_update",notification:r,update:n});return Mc.no(t)}attach(t,r){let n=this.activeSessions.get(t.sessionId)??new Set;return n.add(r),this.activeSessions.set(t.sessionId,n),new $p(()=>{n.delete(r),n.size===0&&this.activeSessions.delete(t.sessionId)})}},QCe=new WeakMap;function pPe(e){let t=QCe.get(e);return t||(t=new S7,QCe.set(e,t)),t}function X1(e,t){for(let r of t){let n;try{n=r(e)}catch(o){throw e.close(o),o}Promise.resolve(n).catch(o=>{e.close(o)})}}var Q1=Symbol("appBuilder"),G1=Symbol("runAgentConnectHandlers"),B1=Symbol("runClientConnectHandlers");var YCe=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name)}[Q1](){return this.builder}[G1](t){X1(t,this.connectHandlers)}connect(t,r={}){return this.connectConnection(t,r).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.client))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return Wp(t,eT,"request"),this.request({method:t,params:r},n);let o=eT[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return Wp(t,Z1,"notification",!0),this.notification({method:t,params:r},n);let o=Z1[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return uPe(this.builder,t,(n,o,i,s)=>g0t(n,rT.create(o,s),i,s),r),this}notification(t,r){return dPe(this.builder,t,(n,o,i)=>y0t(n,rT.create(o),i),r),this}connectConnection(t,r={}){if(oPe(t)){let c=this.openStreamConnection(t);return r.deferConnectHandlers||this[G1](c.connection),c}let[n,o]=iPe(),i=t[Q1]().connect(o),s=cPe(i),a=this.openStreamConnection(n);a.rawConnection.closed.then(()=>s.close()),i.closed.then(()=>a.connection.close());try{t[B1](s),this[G1](a.connection)}catch(c){throw s.close(c),a.connection.close(c),c}return a}openStreamConnection(t){let r=this.builder.connect(t);return{rawConnection:r,connection:aPe(r,this.connectHandlers)}}};var XCe=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name),this.builder.withHandler({handleMessage:(r,n)=>pPe(n).handleMessage(r),describe:()=>"client-session-update-router"})}[Q1](){return this.builder}[B1](t){X1(t,this.connectHandlers)}connect(t){return this.connectConnection(t).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.agent))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return Wp(t,tT,"request"),this.request({method:t,params:r},n);let o=tT[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return Wp(t,J1,"notification",!0),this.notification({method:t,params:r},n);let o=J1[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return uPe(this.builder,t,(n,o,i,s)=>b0t(n,nT.create(o,s),i,s),r),this}notification(t,r){return dPe(this.builder,t,(n,o,i)=>x0t(n,nT.create(o),i),r),this}connectConnection(t){if(oPe(t)){let a=this.openStreamConnection(t);return this[B1](a.connection),a}let[r,n]=iPe(),o=t[Q1]().connect(n),i=aPe(o),s=this.openStreamConnection(r);s.rawConnection.closed.then(()=>i.close()),o.closed.then(()=>s.connection.close());try{t[G1](i),this[B1](s.connection)}catch(a){throw i.close(a),s.connection.close(a),a}return s}openStreamConnection(t){let r=this.builder.connect(t);return{rawConnection:r,connection:cPe(r,this.connectHandlers)}}};var fPe=1;var mPe=["GET","HEAD","POST","PATCH","PUT","DELETE"];var Ms={hostState:"_redskills/host_state",hostBudgets:"_redskills/host_budgets",projectDrain:"_redskills/project_drain",projectStop:"_redskills/project_stop",projectStatus:"_redskills/project_status",projectBudget:"_redskills/project_budget",githubRead:"_redskills/github_read",githubRequest:"_redskills/github_request",githubWrite:"_redskills/github_write",githubUpdate:"_redskills/github_update",githubCustodyHandoff:"_redskills/github_custody_handoff",publish:"_redskills/publish",land:"_redskills/land",workerBudgetGrace:"_redskills/worker_budget_grace",goDispatch:"_redskills/go_dispatch",worktreeAdd:"_redskills/worktree_add",worktreeList:"_redskills/worktree_list",metrics:"_redskills/metrics",brainCall:"_redskills/brain_call",memoryCall:"_redskills/memory_call"},Vvr=Object.values(Ms);var k0t=16e3,_0t={type:"object",additionalProperties:!1,required:["demand"],properties:{demand:{type:"string",minLength:1,maxLength:k0t,description:"The one-off demand this dispatch exists to satisfy."}}},w0t={type:"object",additionalProperties:!1,required:["version","worker_id","ticket","lane"],properties:{version:{const:1},worker_id:{type:"string",minLength:1},ticket:{type:"integer",minimum:1},lane:{type:"string",minLength:1},session_id:{type:"string",minLength:1}}},Qvr={version:1,method:Ms.goDispatch,params:_0t,answer:w0t};var v0t=64,hPe=200,E0t=/^[a-z0-9][a-z0-9._-]*$/;var R0t={type:"object",additionalProperties:!1,required:["slug"],properties:{slug:{type:"string",minLength:1,maxLength:v0t,pattern:E0t.source,description:"What the human is about to work on; becomes the worktree directory name."},branch:{type:"string",minLength:1,maxLength:hPe,description:"Branch to create; defaults to the daemon's convention for the slug."},base:{type:"string",minLength:1,maxLength:hPe,description:"Trunk BRANCH to fork from; the remote is the Project's registered trunk remote."}}},T0t={type:"object",additionalProperties:!1,required:["version","kind","path","branch","base","lane","project_label"],properties:{version:{const:1},kind:{const:"interactive"},path:{type:"string",minLength:1},branch:{type:"string",minLength:1},base:{type:"string",minLength:1},lane:{type:"string",minLength:1},project_label:{type:"string",minLength:1}}},C0t={type:"object",additionalProperties:!1,required:["version","project_label","worktrees"],properties:{version:{const:1},project_label:{type:"string",minLength:1},worktrees:{type:"array",items:{type:"object",additionalProperties:!1,required:["kind","path","branch"],properties:{kind:{enum:["checkout","interactive","worker","unregistered"]},path:{type:"string",minLength:1},branch:{type:["string","null"]},lane:{type:"string",minLength:1},worker_id:{type:"string",minLength:1}}}}}},dEr={version:1,methods:{add:Ms.worktreeAdd,list:Ms.worktreeList},add:{params:R0t,answer:T0t},list:{answer:C0t}};oT();var N0t={drain:Ms.projectDrain,stop:Ms.projectStop,status:Ms.projectStatus};async function w7(e={}){let t=e.cwd??process.cwd(),r=e.name??"RedSkills Project client",n=e.version??"1",o=e.paths??eN();await GR(o);let i=(await ib(o)).paths,s=await j0t(i.acpSocketPath),a=[],c="",l=Bve({name:r}).onNotification(th.client.session.update,async({params:f})=>{f.sessionId===c&&(a.push(f.update),await e.onUpdate?.(f.update))});e.requestPermission!=null&&(l=l.onRequest(th.client.session.requestPermission,({params:f})=>e.requestPermission(f)));let u=l.connect(y9(D0t.toWeb(s),M0t.toWeb(s)));return await u.agent.request(th.agent.initialize,{protocolVersion:1,clientCapabilities:{},clientInfo:{name:r,version:n},_meta:{redskills:{wireMajor:fPe}}}),c=(await u.agent.request(th.agent.session.new,{cwd:t,mcpServers:[]})).sessionId,{control:async(f,m={})=>{let b=await u.agent.request(N0t[f],{...m.target==null?{}:{target:m.target},...m.runner==null?{}:{runner:m.runner},...m.registration==null?{}:{registration:m.registration}});if(!_Pe(b))throw new Error("redskilled returned an invalid Project control outcome");if(f==="status"&&!L0t(b))throw new Error("redskilled returned Project status without a valid RedSkills context");return b},github(f){return u.agent.request(Ms.githubRequest,{request:f})},brain(f){return u.agent.request(Ms.brainCall,{tool:f.tool,arguments:f.arguments})},memory(f){return u.agent.request(Ms.memoryCall,{tool:f.tool,arguments:f.arguments,...f.mode==null?{}:{mode:f.mode}})},async prompt(f){let m=a.length,b=await u.agent.request(th.agent.session.prompt,{sessionId:c,prompt:[{type:"text",text:f}]});return{stopReason:b.stopReason,...z0t(b._meta),updates:a.slice(m)}},cancel(){return u.agent.notify(th.agent.session.cancel,{sessionId:c})},async permission(f){return e.requestPermission==null?{outcome:{outcome:"cancelled"},_meta:{redskills:{permissionResolution:"hitl-required"}}}:await e.requestPermission(f)},close(){u.close(),s.destroy()}}}function z0t(e){let r=Kp(Kp(e)?.redskills)?.projectControl;return _Pe(r)?{projectControl:r}:{}}function _Pe(e){let t=Kp(e);return t?.version===1&&typeof t.project_id=="string"&&typeof t.revision=="number"&&Array.isArray(t.updates)}function L0t(e){let t=Kp(Kp(e)?.context),r=Kp(t?.queue),n=Kp(t?.workers),o=Kp(t?.adapter_health);return t?.version===1&&typeof t.observed_at=="string"&&typeof r?.posture=="string"&&(r.depth===null||typeof r.depth=="number")&&(r.target===null||typeof r.target=="number")&&typeof r.live=="number"&&(r.wanted===null||typeof r.wanted=="number")&&(r.observed_at===null||typeof r.observed_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&(r.freshness==="fresh"||r.freshness==="stale"||r.freshness==="unknown")&&typeof r.detail=="string"&&n?.freshness==="fresh"&&typeof n.observed_at=="string"&&typeof n.total=="number"&&Array.isArray(n.items)&&n.items.every(F0t)&&(o?.status==="healthy"||o?.status==="degraded"||o?.status==="unknown")&&(o.checked_at===null||typeof o.checked_at=="string")&&(o.last_success_at===null||typeof o.last_success_at=="string")&&(o.last_failure_at===null||typeof o.last_failure_at=="string")&&typeof o.detail=="string"}function F0t(e){let t=Kp(e);return typeof t?.worker_id=="string"&&t.state==="running"&&typeof t.started_at=="string"&&typeof t.isolated=="boolean"&&Array.isArray(t.warnings)&&t.warnings.every(r=>typeof r=="string")&&(t.base_commits_ahead===null||typeof t.base_commits_ahead=="number")}function Kp(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async function j0t(e){return await new Promise((t,r)=>{let n=$0t(e);n.once("connect",()=>t(n)),n.once("error",r)})}aee();md();tre();$_();md();var qz=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(s){if(i.some(u=>u.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 u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Mb,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},bh,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};rre();var Wz=class extends F_{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map($T.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 ow,this.setRequestHandler(XY,n=>this._oninitialize(n)),this.setNotificationHandler(tX,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(xX,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=$T.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new qz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=cz(this._capabilities,t)}setRequestHandler(t,r){let o=pd(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(ba(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 u=Ns(L_,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new ze(qe.InvalidParams,`Invalid tools/call request: ${b}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let b=Ns(tf,f);if(!b.success){let S=b.error instanceof Error?b.error.message:String(b.error);throw new ze(qe.InvalidParams,`Invalid task creation result: ${S}`)}return b.data}let m=Ns(fd,f);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new ze(qe.InvalidParams,`Invalid tools/call result: ${b}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Bz(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Gz(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:DN.includes(r)?r:vT,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"},ef)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(l=>l.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(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(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},MT,r):this.request({method:"sampling/createMessage",params:t},Mb,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},bh,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},bh,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new ze(qe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof ze?s:new ze(qe.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},wX,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};$_();see();md();var $De=Symbol.for("mcp.completable");function nre(e){return!!e&&typeof e=="object"&&$De in e}function MDe(e){return e[$De]?.complete}var ODe;(function(e){e.Completable="McpCompletable"})(ODe||(ODe={}));var O1t=/^[A-Za-z0-9._-]{1,128}$/;function $1t(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!O1t.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function M1t(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ore(e){let t=$1t(e);return M1t(e,t.warnings),t.isValid}var Vz=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};dC();var iw=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Wz(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Vz(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Ph(JN)),this.server.assertCanSetRequestHandler(Ph(L_)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(JN,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=O_(r.inputSchema);return o?nee(o,{strictUnions:!0,pipeStrategy:"input"}):D1t})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=O_(r.outputSchema);o&&(n.outputSchema=nee(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(L_,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new ze(qe.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new ze(qe.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new ze(qe.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new ze(qe.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof ze&&n.code===qe.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=O_(t.inputSchema)??t.inputSchema,s=await PN(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=IN(a);throw new ze(qe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new ze(qe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=O_(t.outputSchema),i=await PN(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=IN(s);throw new ze(qe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let d=await n.taskStore.getTask(c);if(!d)throw new ze(qe.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Ph(QN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(QN,async t=>{switch(t.params.ref.type){case"ref/prompt":return rOe(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return nOe(t),this.handleResourceCompletion(t,t.params.ref);default:throw new ze(qe.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new ze(qe.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ze(qe.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return pC;let i=pd(n.argsSchema)?.[t.params.argument.name];if(!nre(i))return pC;let s=MDe(i);if(!s)return pC;let a=await s(t.params.argument.value,t.params.context);return NDe(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return pC;throw new ze(qe.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return pC;let i=await o(t.params.argument.value,t.params.context);return NDe(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Ph(N_)),this.server.assertCanSetRequestHandler(Ph(VN)),this.server.assertCanSetRequestHandler(Ph(z_)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(N_,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(VN,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(z_,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new ze(qe.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 ze(qe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Ph(KN)),this.server.assertCanSetRequestHandler(Ph(ZN)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(KN,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?N1t(r.argsSchema):void 0}))})),this.server.setRequestHandler(ZN,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new ze(qe.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new ze(qe.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=O_(n.argsSchema),i=await PN(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=IN(c);throw new ze(qe.InvalidParams,`Invalid arguments for prompt ${t.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(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==t&&(delete this._registeredResourceTemplates[t],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[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:$b(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=$b(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let l=c instanceof ga?c._def?.innerType:c;return nre(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,l){ore(t);let u={title:r,description:n,inputSchema:DDe(o),outputSchema:DDe(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&ore(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=$b(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=$b(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(ire(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ire(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 ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var D1t={type:"object",properties:{}};function zDe(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function LDe(e){return"_def"in e||"_zod"in e||zDe(e)}function ire(e){return typeof e!="object"||e===null||LDe(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(zDe)}function DDe(e){if(e){if(ire(e))return $b(e);if(!LDe(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function N1t(e){let t=pd(e);return t?Object.entries(t).map(([r,n])=>{let o=dAe(n),i=pAe(n);return{name:r,description:o,required:!i}}):[]}function Ph(e){let r=pd(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=AN(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function NDe(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var pC={completion:{values:[],hasMore:!1}};sre();import FDe from"node:process";var fC=class{constructor(t=FDe.stdin,r=FDe.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new sw,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Kz(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{resolve as E$}from"node:path";import{fileURLToPath as Cdt}from"node:url";ao();function jDe(e){return[{name:"claim_status",title:"Read AFK claim",description:"Return the parsed claim marker records and current holder for one issue (`issue`) or a batch (`issues`), keyed per issue.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimStatus(t)},{name:"claim_release",title:"Release AFK claim",description:"MUTATING: post a concede marker for every un-conceded claim holder so the issue (`issue`) or each issue in a batch (`issues`) becomes claimable again.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimRelease(t)}]}f_();function are(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function cre(e){return typeof e=="string"&&e.trim()!==""?e:null}function L1t(e){let t=are(e);if(t===null)return null;let r=are(t.demand);return cre(r?.refusal)??cre(t.latest_refusal)}function UDe(e){return{tool:"status",args:{scope:"project"},why:e}}function F1t(){return{tool:"status",args:{scope:"host"},why:"diagnose why the host daemon does not answer before changing registration"}}function j1t(e,t){let r=e.registration;return r.daemon_reachable?!r.held&&r.repair!==void 0&&r.repair!=="none"?p_():e.live_workers.length>0&&t===null?{tool:"status",args:{scope:"worker"},why:"observe the Workers already draining this project's queue"}:UDe(t!==null?"observe when the daemon's refusal clears and capacity begins draining again":"observe the next socket-local queue poll and Worker birth"):F1t()}function U1t(e){let t=e.registration;if(!t.daemon_reachable)return"daemon unreachable: this project cannot read or change its host registration";if(!t.held)return"unregistered: the daemon is reachable but holds no registration for this project";let r=t.last_poll?.depth,n=r==null?"an unknown queue":`${r} queued`;return`draining: ${e.slots.busy} of ${e.slots.total} Worker slots are busy with ${n}`}function H1t(e){return[{intent:"choose the capability that matches your intent",tools:e.filter(t=>!t.description.startsWith("DEPRECATED:")).map(({name:t,title:r})=>({name:t,title:r}))}]}function HDe(e,t){return[{name:"help",title:"Find the next redskilled action",description:"Read live daemon, registration, queue, Worker, and refusal state; return the pasteable next call and a generated intent map. Makes no GitHub request.",inputSchema:{},invoke:async()=>{let[r,n]=await Promise.all([e.projectStatus(),e.hostState().catch(()=>null)]),o=U1t(r),i=L1t(n),s=j1t(r,i),a=ma({state:`you are ${o}`,repair:s});if(a.repair==="none")throw new Error("help produced no callable next action");return{here:o,state:{daemon:{reachable:r.registration.daemon_reachable,version:cre(are(n)?.daemon_version)??""},registration:{held:r.registration.held,project:r.registration.project,renewal:r.registration.renewal,target:r.registration.target},queue:r.registration.last_poll==null?null:{at:r.registration.last_poll.at,outcome:r.registration.last_poll.outcome,depth:r.registration.last_poll.depth,detail:r.registration.last_poll.detail},workers:{busy:r.slots.busy,free:r.slots.free,live:r.live_workers.length,target:r.slots.total},validation_schedule:r.validation_schedule,last_refusal:i,warnings:r.warnings??[]},guidance:a.prose,next:a.repair,intent_map:H1t(t())}}}]}ao();function qDe(e){return[{name:"merge_arm",title:"Arm PR for the merge driver",description:"MUTATING: hand one open PR to a live project merge-driver process \u2014 it owns the PR to a terminal state (update-branch when BEHIND, merge-commit once green at head, bounded retries, needs-medic/needs-human classification) without GitHub native auto-merge. Refuses when the merge-driver process is missing so custody cannot become orphaned.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeArm({pr:t})},{name:"merge_status",title:"Read merge driver state",description:"Return whether the merge-driver process is ticking plus durable per-PR records: armed records labeled driver-ticking or orphaned, attempts, last observed state, and terminal classifications.",inputSchema:{},invoke:()=>e.mergeStatus()},{name:"merge_release",title:"Release PR from the merge driver",description:"MUTATING: stop driver ownership of one PR. The record is kept as released for observability.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeRelease({pr:t})}]}ao();var q1t=["requeue","retake","park","close"];function GDe(e){return[{name:"hitl_resolve",title:"Resolve parked issue with a human decision",description:"MUTATING: encode one human decision on a parked issue atomically \u2014 requeue (concede dangling claims, strip park labels, ready-for-agent), retake (route to the no-agent landing lane), park (keep ready-for-human, record why), or close. The rationale is posted as an issue comment for the audit trail.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(q1t),rationale:w.string().min(1)},invoke:t=>e.hitlResolve(t)}]}ao();var Zz="2.0.0";function Jz(e,t){return{version:Zz,schema:e,projection:t}}var ZAr=w.object({age_s:w.number(),stale:w.boolean(),stale_after_s:w.number(),reason:w.enum(["fresh","aged-out","never-observed","orphaned"])}),G1t=w.object({version:w.string(),source:w.enum(["registry","recorded","installed-plugin","bundle-cache","unresolved"]),age_ms:w.number(),stale_after_ms:w.number(),stale:w.boolean(),reason:w.enum(["fresh","aged-out","installed-only","cache-only","never-observed"])}),B1t=w.object({tool:w.string().min(1),args:w.record(w.string(),w.unknown()),why:w.string().min(1)}),W1t=w.union([B1t,w.literal("none")]),V1t=w.object({held:w.boolean(),daemon_reachable:w.boolean(),project:w.string(),socket:w.string(),selector:w.string(),target:w.number(),renewal:w.enum(["renewing","self-renewing","running-on","unknown"]),renew_by:w.string(),renewals:w.number(),lapsed_at:w.string(),reason:w.string(),repair:W1t.optional(),repair_reason:w.string().min(1).optional(),launch_revision:w.number(),bundle_version:w.string(),plugin_cache_version:w.string(),last_poll:w.object({at:w.string(),outcome:w.string(),depth:w.number().nullable(),request_count:w.number(),detail:w.string()}).optional(),published_version:G1t.optional()}).superRefine((e,t)=>{!e.held&&e.repair===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair"],message:"an absent registration must carry a repair or an argued none"}),e.repair==="none"&&e.repair_reason===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair_reason"],message:"repair none must state why no callable cure is safe"})}),K1t=w.object({name:w.literal("project-birth-breaker"),project_label:w.string(),state:w.enum(["open","half-open"]),opened_at:w.string(),reason:w.string(),closes:w.string(),probe_worker_id:w.string().nullable(),repair:w.object({tool:w.literal("project_reset"),args:w.object({latch:w.literal("project-birth-breaker")}),why:w.string()})}),Z1t=w.object({narration:w.string(),moments:w.array(w.object({moment:w.enum(["iteration","post_done","landing"]),state:w.enum(["declared","skip"]),declared:w.boolean(),commands:w.array(w.string())})).length(3)}),mC=w.object({registration:V1t,validation_schedule:Z1t,birth_latch:K1t.nullable(),slots:w.object({busy:w.number(),free:w.number(),parked:w.number(),total:w.number(),interactive_reservation:w.number()}),live_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),unattributed_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),warnings:w.array(w.string()).optional()}),J1t=w.object({number:w.union([w.number(),w.string()]),runner:w.string(),retries:w.number(),phase:w.string(),iteration:w.union([w.number(),w.string()]),activity:w.string(),loc_added:w.number(),loc_removed:w.number(),last_commit_at:w.string(),tools_called_count:w.number(),text_chunk_count:w.number(),reasoning_events:w.number(),reasoning_tokens:w.number(),last_event_at:w.string(),waiting_count:w.number(),input_tokens:w.number(),output_tokens:w.number(),cost_usd:w.number()}),Q1t=w.object({status:w.enum(["alive","stalled","capped","unknown"]),laneFresh:w.boolean(),laneAgeMs:w.number().optional(),crossCheckArmed:w.boolean(),liveDescendants:w.boolean().optional(),reason:w.string()}),Y1t=w.object({verdict:w.enum(["alive","dead","unknown"]),anchor:w.enum(["daemon","none"]),project_label:w.string().nullable(),pid:w.number().nullable(),staleness:w.object({stale:w.boolean(),age_ms:w.number().nullable(),threshold_ms:w.number().nullable(),reason:w.string()})}),WDe=w.object({worker:w.object({id:w.string(),pid:w.number(),runner:w.string(),origin:w.string(),started_at:w.string(),done:w.number(),total:w.number(),blocked:w.number(),failed:w.number(),current:J1t}),live:w.boolean(),active:w.boolean(),renderable_live:w.boolean(),liveness:w.enum(["active","quiet-but-live","dead"]),liveness_verdict:Q1t,daemon_liveness:Y1t.optional()}),Qz=w.array(WDe),Yz=w.array(WDe.partial()),X1t=w.object({state:w.object({worker_id:w.string(),pid:w.number(),runner:w.string(),started_at:w.string(),total:w.number(),done:w.number(),blocked:w.number(),failed:w.number(),current:w.object({number:w.union([w.number(),w.string()]),title:w.string(),activity:w.string(),started_at:w.string()})}),live:w.boolean()}),hC=w.object({workers:w.array(X1t),events:w.array(w.object({event:w.string(),epoch:w.number()})),fleet:w.object({ts:w.string(),epoch:w.number(),runner:w.string(),readyForAgent:w.number(),slotsBusy:w.number(),slotsFree:w.number(),slotsTotal:w.number(),slotsParked:w.number(),interactiveReservation:w.number(),spawnsThisTick:w.number()}).nullable(),remoteQueue:w.number().optional(),remoteHuman:w.number().optional(),remoteCacheAgeS:w.number().optional()}),BDe=w.object({number:w.number(),title:w.string(),labels:w.array(w.string())}),VDe=w.object({ready_for_agent:w.object({eligible:w.array(BDe),held_for_summon:w.array(BDe)}),ready_for_human:w.array(w.object({number:w.number(),title:w.string(),labels:w.array(w.string()),body:w.string().optional(),createdAt:w.string().nullable().optional()})),counts:w.object({ready_for_agent_eligible:w.number(),ready_for_agent_held:w.number(),ready_for_human:w.number()}),degraded:w.boolean(),errors:w.array(w.object({kind:w.literal("trust-read"),number:w.number(),message:w.string()}))}),KDe=Jz(mC),JAr=Jz(Qz,{input:"fields",schema:Yz}),QAr=Jz(hC),ZDe=Jz(VDe);function eNt(e,t){let{projection:r}=e;if(!r)return e.schema;let n=t[r.input];return Array.isArray(n)&&n.length>0?r.schema:e.schema}function JDe(e){return e.map(t=>{let r=t.outputContract;if(!r)return t;let n=t.invoke.bind(t);return{...t,invoke:async o=>{let i=await n(o),s=eNt(r,o).safeParse(i);if(!s.success)throw new Error(`${t.name} output violates contract ${r.version}: ${s.error.issues.map(a=>`${a.path.join(".")||"<root>"}: ${a.message}`).join("; ")}`);return i}}})}ao();var QDe="named fleets were removed (ADR 0130): the host daemon owns the budget and each project has exactly one demand producer, so a fleet name addresses nothing. Drop the name \u2014 the work scope, the runner and the base branch now ride with the project's producer: pass `selector` / `runner` / `base` to the rs_dev `project_start` tool (status: `project_status`, resize: `project_resize`, stop: `project_stop`).",lre=class extends Error{constructor(t){super(t===void 0||t===""?QDe:`fleet ${JSON.stringify(t)}: ${QDe}`),this.name="FleetNamingRemovedError"}};function aw(e){if(!(e==null||e===""))throw new lre(typeof e=="string"?e:String(e))}ao();var tNt=w.object({tool:w.literal("status"),args:w.object({scope:w.enum(["worker","project","host"])})});function YDe(e){return w.object({deprecated:w.literal(!0),message:w.string().min(1),replacement:tNt,result:e})}function e1e(e){return{version:e.version,schema:YDe(e.schema),...e.projection===void 0?{}:{projection:{input:e.projection.input,schema:YDe(e.projection.schema)}}}}var rNt=w.object({status:w.unknown(),vitals:Qz,monitor:hC}),nNt=w.object({status:w.unknown(),vitals:Yz,monitor:hC}),XDe=w.object({state:w.unknown(),dashboard:w.unknown(),provision_check:w.unknown(),unit_status:w.unknown()}),oNt={version:Zz,schema:w.union([mC,rNt,XDe]),projection:{input:"fields",schema:w.union([mC,nNt,XDe])}};function t1e(e,t,r){return{deprecated:!0,message:`${e} is deprecated; use status { scope: ${t} }`,replacement:{tool:"status",args:{scope:t}},result:r}}async function iNt(e,t){if(t.scope==="project")return e.projectStatus();if(t.scope==="host"){let[s,a,c,l]=await Promise.all([e.hostState(),e.hostDashboard(),e.hostProvisionCheck(),e.hostUnitStatus()]);return{state:s,dashboard:a,provision_check:c,unit_status:l}}let r={worker:t.worker,live_only:t.live_only??!0,fields:t.fields},[n,o,i]=await Promise.all([e.workerStatus(r),e.workerVitals({live_only:r.live_only,fields:r.fields}),e.monitor()]);return{status:n,vitals:o,monitor:i}}function r1e(e){return[{name:"status",title:"Read redskilled status",description:"Answer the current worker, project, or host status through one intent-scoped read.",inputSchema:{scope:w.enum(["worker","project","host"]),worker:w.string().min(1).optional(),live_only:w.boolean().default(!0),fields:w.array(w.string().min(1)).optional()},outputContract:oNt,invoke:t=>iNt(e,t)}]}Xz();var eL={spec:w.number().int().positive().optional(),lane:w.string().min(1).optional(),label:w.string().min(1).optional(),issues:w.array(w.number().int().positive()).optional(),tags:w.array(w.string().min(1)).optional(),user:w.string().min(1).optional()};var i1e=w.record(w.string(),w.union([w.string(),w.number(),w.boolean()])),gC=w.string().optional().describe("REMOVED: naming a fleet is refused; a project has one producer.");function s1e(e){return[{name:"project_activation",title:"Preview this project's redskilled activation",description:"READ-ONLY: report whether this project opted into RedSkills and the canonical runner and target a no-argument drain would register.",inputSchema:{},invoke:()=>e.projectActivation()},{name:"project_status",title:"Deprecated project status alias",description:"DEPRECATED: use status { scope: project }. Returns the project answer and names its replacement.",inputSchema:{fleet:gC},outputContract:e1e(KDe),invoke:async({fleet:t})=>(aw(t),t1e("project_status","project",await e.projectStatus()))},{name:"drain",title:"Make this project drain",description:"MUTATING: ensure the daemon is reachable and this project is registered. Omitted runner and target resolve from this project's canonical RedSkills configuration; repeated calls report what was kept.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional()},invoke:async t=>e.drain(t)},{name:"project_start",title:"Start this project's workers",description:"MUTATING: register this project with the host daemon \u2014 a runner, a target width, and its work policy. Registers rather than launches: the project contributes a record, never a process of its own.",inputSchema:{runner:w.string().min(1),target:w.number().int().min(0).default(1),selector:w.object(eL).optional(),config:i1e.optional(),base:w.string().min(1).optional(),fleet:gC},invoke:async t=>(aw(t.fleet),e.projectStart(t))},{name:"project_resize",title:"Re-aim this project's workers",description:"MUTATING: change this project's target width, runner, or work policy and send the live directive.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional(),selector:w.object(eL).optional(),config:i1e.optional(),base:w.string().min(1).optional(),fleet:gC},invoke:async t=>(aw(t.fleet),e.projectResize(t))},{name:"project_reset",title:"Reset project execution latch",description:"MUTATING: clear a named in-memory latch for this project so autonomous demand may retry immediately.",inputSchema:{latch:w.literal("project-birth-breaker"),fleet:gC},invoke:async({latch:t,fleet:r})=>(aw(r),e.projectReset({latch:t}))},{name:"project_stop",title:"Stop this project's workers",description:"MUTATING: stop this project's work and give its registration back; force hard teardown explicitly.",inputSchema:{force:w.boolean().optional(),fleet:gC},invoke:async({force:t,fleet:r})=>(aw(r),e.projectStop({force:t}))}]}ao();function a1e(e){return[{name:"gate_run",title:"Run the AFK gate",description:"MUTATING: materialize the branch's feedback worktree and run the package-scoped validation gate against it.",dangerClass:"mutating",inputSchema:{branch:w.string().min(1),base:w.string().min(1).optional()},invoke:t=>e.gateRun(t)}]}function c1e(e){return[{name:"deadend_audit",title:"Audit AFK deadends",description:"Return the read-only deadend audit: dangling claims, red PRs with dead owners, superseded PRs, executable Tickets carrying an active Current blocker, dependency blocks whose req targets all closed, human-queue age outliers, and stale worktrees \u2014 each class paired with its recommended cure. Cache-backed: repeated calls within the refresh window cost zero GitHub quota.",inputSchema:{},invoke:()=>e.deadendAudit()}]}ao();function l1e(e){return[{name:"requeue",title:"Requeue AFK issue",description:"MUTATING: apply the complete parked-issue requeue transition and record human guidance.",inputSchema:{issue:w.number().int().positive(),guidance:w.string().min(1),repo:w.string().min(1).optional(),dryRun:w.boolean().optional(),adoptBranch:w.string().min(1).optional()},invoke:t=>e.requeue(t)},{name:"retake",title:"Recommend AFK retake",description:"Return the structured issue, PR, branch, worktree, worker-state, and recommended-next-action report.",inputSchema:{issue:w.number().int().positive(),repo:w.string().min(1).optional(),prLimit:w.number().int().positive().max(1e3).optional()},invoke:t=>e.retake(t)},{name:"reap",title:"Reap AFK branches",description:"MUTATING: classify and delete stale local and remote AFK branches.",inputSchema:{},invoke:()=>e.reap()},{name:"unblock_sweep",title:"Sweep dependency blocks",description:"MUTATING: promote dependency-blocked issues whose requirements are all closed.",inputSchema:{},invoke:()=>e.unblockSweep()}]}ao();function u1e(e){return[{name:"land_branch",title:"Land AFK branch",description:"MUTATING: land one validated worker branch into its base through the complete landing sequence.",dangerClass:"mutating",inputSchema:{issue:w.number().int().positive(),branch:w.string().min(1),base:w.string().min(1).optional(),title:w.string().min(1).optional(),openPr:w.boolean().optional()},invoke:t=>e.landBranch(t)},{name:"cascade_status",title:"Read close cascade",description:"Return the dependents of one issue and which of them the close cascade would promote.",inputSchema:{issue:w.number().int().positive()},invoke:({issue:t})=>e.cascadeStatus({issue:t})}]}ao();function d1e(e){return[{name:"logs",title:"Read redskilled logs",description:"Return the newest CastleLaneRecord entries from one structured lane; bounded by `limit` (default 200, max 10 000). Pass `kind` to filter before the limit.",inputSchema:{lane:w.enum(["worker","supervisor","monitor","liveness"]),id:w.string().min(1),limit:w.number().int().positive().max(1e4).default(200),kind:w.string().optional()},invoke:t=>e.logs(t)},{name:"dashboard",title:"Build AFK dashboard",description:"Build the structured operational dashboard from GitHub and local state.",inputSchema:{periodDays:w.number().int().positive().default(30)},invoke:({periodDays:t})=>e.dashboard({periodDays:t})},{name:"history",title:"Read redskilled history",description:"Return structured AFK history records, newest records last.",inputSchema:{limit:w.number().int().positive().max(1e4).optional()},invoke:({limit:t})=>e.history({limit:t})},{name:"queue_status",title:"Read AFK queues",description:"Return ready-for-agent and ready-for-human queue candidates, retaining successful candidates and naming partial trust-read failures as a degraded result. Pass `selector` to preview the producer's scoped view of the ready queue (same facets as its work selector, e.g. tags/user).",inputSchema:{selector:w.object(eL).optional()},outputContract:ZDe,invoke:t=>e.queueStatus({selector:t.selector})},{name:"events_since",title:"Poll events since cursor",description:"Return AFK history events and Worker lane records after an opaque cursor, plus the next cursor. Omit cursor to get a fresh baseline cursor with no events. Unknown or expired cursors are refused with a re-baseline prompt.",inputSchema:{cursor:w.string().min(1).optional()},invoke:t=>e.eventsSince({cursor:t.cursor})}]}ao();function p1e(e){return[{name:"manager",title:"Route work through the Manager",description:"MUTATING: take one operator intent into the Manager \u2014 intake, route an effort to a skill, attach an artifact, read effort status, or export/import the checkpoint \u2014 and return the effort record it acted on.",inputSchema:{intent:w.string().min(1).optional(),action:w.enum(["intake","route","artifact","status","checkpoint"]).optional(),effort:w.string().min(1).optional(),skill:w.string().min(1).optional(),artifact:w.string().min(1).optional(),checkpoint:w.enum(["export","import"]).optional(),path:w.string().min(1).optional()},invoke:t=>e.manager(t)},{name:"red_doctor",title:"Diagnose this repository's RedSkills setup",description:"READ-ONLY: return every doctor finding for this repository \u2014 operational probes, host toolchain, lane and process census, executable acceptance, HUMAN-ONLY type declarations and disposable-lane hygiene \u2014 each paired with the route that repairs it. Applying a repair is the `/red-doctor` skill's own fix lane, never a side effect of the read.",inputSchema:{checks:w.array(w.string().min(1)).optional()},invoke:t=>e.redDoctor(t)},{name:"audit_skills",title:"Audit the shipped skills",description:"Return the ranked skill-audit scores for this repository's skill tree. Pass `mechanical_only` to score without the judge, which makes the read deterministic and free of agent cost.",inputSchema:{mechanical_only:w.boolean().optional(),runner:w.string().min(1).optional()},invoke:t=>e.auditSkills(t)},{name:"install_type_labels",title:"Install Wayfinder type labels",description:"MUTATING: create the Wayfinder ticket type labels on the tracker AND declare the HUMAN-ONLY ones in this project's configuration, in one act \u2014 the two are one protection with two halves, and installing only the labels leaves the repository looking protected while unblocked decision Tickets enter the autonomous queue (#3013).",inputSchema:{labels:w.array(w.string().min(1)).optional(),repo:w.string().min(1).optional(),dry_run:w.boolean().optional()},invoke:t=>e.installTypeLabels(t)},{name:"codex_statusline",title:"Inspect the Codex footer preference",description:"READ-ONLY: return the active Codex configuration's status-line inspection \u2014 the file read, the current preference, and the problem that keeps the RedSkills footer from rendering.",inputSchema:{config:w.string().min(1).optional()},invoke:t=>e.codexStatusline(t)},{name:"codex_monitor_agent",title:"Build the Codex monitor agent brief",description:"Return the read-only monitor brief a Codex sub-agent is spawned with: what to poll, how often, and the conditions under which it closes itself. It spawns nothing \u2014 the host's own spawn primitive does.",inputSchema:{project_root:w.string().min(1).optional(),mode:w.string().min(1).optional(),interval_seconds:w.number().int().positive().optional()},invoke:t=>e.codexMonitorAgent(t)},{name:"reconcile_engine",title:"Reconcile this project's engine delivery",description:"MUTATING: warm the published engine bundle into the stable cache path and re-point a standing registration at it in one operation, then return the version, the bundle path, and what happened to the registration.",inputSchema:{version:w.string().min(1).optional()},invoke:t=>e.reconcileEngine(t)}]}ao();function f1e(e){return[{name:"daily_review",title:"Build daily activity review",description:"Return the structured daily activity review report for the local window.",inputSchema:{},invoke:()=>e.dailyReview({})},{name:"weekly_review",title:"Build weekly activity review",description:"Return the structured weekly activity review report for the local window.",inputSchema:{},invoke:()=>e.weeklyReview({})},{name:"triage",title:"Apply triage decision",description:"MUTATING: apply the decided triage transition to one issue, gated by the per-repo trust policy.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(["ready-for-agent","needs-info","ready-for-human","wontfix"]),summon:w.boolean().optional(),repo:w.string().min(1).optional()},invoke:t=>e.triage(t)},{name:"respond",title:"Handle comment event",description:"MUTATING: parse a /dev comment summon, authorize the commenter, and route the advisory or mutation verb.",inputSchema:{body:w.string(),number:w.number().int().positive(),author:w.string().min(1).optional(),is_pr:w.boolean().optional(),runner:w.string().min(1).optional(),repo:w.string().min(1).optional()},invoke:t=>e.respond(t)}]}ao();ao();f_();function dre(e){let t=ma({state:e instanceof Error?e.message:String(e),repair:ob("the caller must choose one dispatch intent before retrying")});if(t.repair!=="none")throw new Error("invalid worker refusal repair");return{refused:!0,reason:t.prose,repair:t.repair,repair_reason:t.repair_reason}}var pre={issue:w.number().int().positive().optional(),demand:w.string().min(1).optional(),runner:w.string().min(1).optional(),mode:w.enum(["no-mistakes","direct-PR","local-only","scout"]).optional()};function fre(e){let t=e;if(t.issue===void 0==(t.demand===void 0))throw new Error("exactly one of issue or demand is required");if(t.mode==="scout"&&t.issue!==void 0)throw new Error("mode: scout is demand-only \u2014 combine scout with demand, not issue");if(t.issue!==void 0&&t.mode!==void 0)throw new Error("mode is only valid for demand dispatches");return t}function m1e(e){return[{name:"worker_dispatch",title:"Dispatch AFK worker",description:"MUTATING: run one tracked issue or mint and run one disposable demand through the AFK worker lifecycle.",inputSchema:pre,invoke:t=>{let r;try{r=fre(t)}catch(n){return Promise.resolve(dre(n))}return e.workerDispatch(r)}},{name:"worker_stop",title:"Stop AFK worker",description:"MUTATING: terminate one worker process tree.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!1})},{name:"worker_recycle",title:"Recycle AFK worker",description:"MUTATING: terminate one fleet worker so its supervisor can replace the slot.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!0})}]}function h1e(e){return[{name:"runner_list",title:"List AFK runners",description:"Return the canonical runner specification registry.",inputSchema:{},invoke:()=>e.runnerList()},{name:"runner_detect",title:"Detect AFK runner",description:"Resolve the runner selected by an explicit override or the current host environment.",inputSchema:{runner:w.string().min(1).optional()},invoke:({runner:t})=>e.runnerDetect({runner:t})},{name:"runner_steer",title:"Steer live AFK worker",description:"MUTATING: write a live-steer request into a running worker's next iteration.",inputSchema:{worker:w.string().min(1),text:w.string().min(1)},invoke:t=>e.runnerSteer(t)},{name:"steer_status",title:"Read steer status",description:"Return the live-steer status for a worker: none (no steer ever written), pending (written, not yet consumed), or consumed (consumed at a specific iteration).",inputSchema:{worker:w.string().min(1)},invoke:t=>e.steerStatus(t)},{name:"worker_request",title:"Dispatch worker with request",description:"MUTATING: dispatch a new worker and inject a special request into its spawn-time handoff.",inputSchema:{...pre,text:w.string().min(1)},invoke:t=>{let r;try{r=fre(t)}catch(n){return Promise.resolve(dre(n))}return e.workerRequest({...r,text:t.text})}}]}function g1e(e){return[{name:"statusline_aggregate",title:"Read statusline aggregate",description:"Return the project-side statusline aggregate (project, repo counters, docs drift, drain, Worker rows, aggregated AFK block, queue) as structured data, using the same collector cores and cache discipline as the command-backed statusLine. Host-side fields (session model/effort, context %, usage quotas) are out of scope.",inputSchema:{},invoke:()=>e.statuslineAggregate()}]}ao();f_();function y1e(e,t,r={}){let n=e==="confirm"?ma({state:"dangerous tool requires explicit confirmation",repair:{tool:t,args:{...r,confirmation:!0},why:"retry the same operation with explicit confirmation"}}):ma({state:"dangerous tool is denied by the configured posture",repair:ob("the configured posture deliberately forbids this tool")});return{refused:!0,posture:e,action:t,reason:n.prose,repair:n.repair,...n.repair==="none"?{repair_reason:n.repair_reason}:{}}}function b1e(e,t){return t==="allow"?e:e.map(r=>{if(!r.dangerClass)return r;if(t==="deny")return{...r,invoke:async i=>y1e("deny",r.name)};let n={...r.inputSchema,confirmation:w.boolean().optional()},o=r.invoke.bind(r);return{...r,inputSchema:n,invoke:async i=>{if(i.confirmation!==!0)return y1e("confirm",r.name,i);let{confirmation:s,...a}=i;return o(a)}}})}ao();function x1e(e){return[{name:"wait_start",title:"Start rsp wait",description:"MUTATING: spawn a detached rsp wait (pr | run | release | cmd) and return its registry id.",inputSchema:{kind:w.enum(["pr","run","release","cmd"]),target:w.string().min(1),timeout_ms:w.number().int().positive().optional(),reason:w.string().optional()},invoke:t=>e.waitStart(t)},{name:"wait_list",title:"List active rsp waits",description:"Return the active-wait registry from .red/tmp/waits.",inputSchema:{},invoke:()=>e.waitList()},{name:"wait_status",title:"Read rsp wait status",description:"Return the registry entry for a running wait or the sealed result envelope for a finished one.",inputSchema:{id:w.string().min(1)},invoke:({id:t})=>e.waitStatus({id:t})}]}ao();function S1e(e){return[{name:"worktree_list",title:"List disposable worktrees",description:"Enumerate every checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{},invoke:()=>e.worktreeList()},{name:"worktree_remove",title:"Remove disposable worktree",description:"MUTATING: remove one checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{path:w.string().min(1)},invoke:({path:t})=>e.worktreeRemove({path:t})}]}var tL="Call the redskilled MCP's `help` tool.\nFollow its guidance and invoke the returned `next` call.",mre=[{name:"drain",title:"Drain this project's queue",description:"Find the next action for starting or continuing a project drain.",body:tL},{name:"diagnose",title:"Diagnose redskilled",description:"Find the next action for understanding a redskilled problem.",body:tL},{name:"configure",title:"Configure redskilled",description:"Find the next action for changing project execution configuration.",body:tL},{name:"stop",title:"Stop project work",description:"Find the next action for stopping project work safely.",body:tL}];var k1e="rs_dev";function _1e(e,t="allow"){let r=[],n=[...HDe(e,()=>r),...r1e(e),...s1e(e),...d1e(e),...c1e(e),...m1e(e),...h1e(e),...l1e(e),...a1e(e),...u1e(e),...jDe(e),...qDe(e),...GDe(e),...S1e(e),...x1e(e),...f1e(e),...g1e(e),...p1e(e)];return r=b1e(JDe(n),t),r}Yt();function cw(e){return tn(JSON.parse(JSON.stringify(e??null)),{objectArrayColumns:!0,primitiveArrayColumns:!0})}var sNt=new Map([["drain","drain"],["project_drain","drain"],["project_stop","stop"],["project_status","status"],["status","status"]]),aNt=new Set(["target","runner","scope","registration","live_only","fields","worker"]);async function w1e(e,t,r){let n=sNt.get(t);if(n!=null){let o=Object.keys(r).filter(i=>!aNt.has(i));if(o.length>0)throw new Error(`the Project control surface cannot express ${JSON.stringify(o.sort())} for ${JSON.stringify(t)}`);return n==="status"?await e.control("status"):await e.control(n,cNt(r))}if(!uNt(t))throw new Error(`unsupported ACP Project capability ${JSON.stringify(t)}`);return await e.prompt(lNt(t,r))}function cNt(e){let t=e.target,r=e.runner,n=e.registration;return{...typeof t=="number"&&Number.isInteger(t)&&t>=0?{target:t}:{},...typeof r=="string"&&r.length>0?{runner:r}:{},...n!=null&&typeof n=="object"&&!Array.isArray(n)?{registration:n}:{}}}function lNt(e,t){return`/${e} ${JSON.stringify(t)}`}function uNt(e){return/^[a-z][a-z0-9_]*$/.test(e)&&!e.startsWith("private_")&&!e.includes("worker_birth")&&!e.includes("daemon_protocol")&&!e.includes("github_client")}xre();Xz();import{execFileSync as INt}from"node:child_process";kR();Sd();function Q1e(e){let t=X1e(e.repo).join("/"),r=e.selector??{},n=[`repo:${t}`,"is:issue","is:open",oL(e.readyLabel??su)];r.lane!=null&&r.lane!==""&&n.push(oL(`lane:${r.lane}`)),r.label!=null&&r.label!==""&&n.push(oL(r.label));for(let o of r.tags??[])o!==""&&n.push(oL(`${kre}${o}`));return r.user!=null&&r.user!==""&&r.user!=="@me"&&n.push(`author:${r.user}`),n.join(" ")}function Y1e(e){let[t,r]=X1e(e.repo),n=e.selector??{},o=e.readyLabel??su,i=[o];n.lane!=null&&n.lane!==""&&i.push(`lane:${n.lane}`),n.label!=null&&n.label!==""&&i.push(n.label);for(let a of n.tags??[])a!==""&&i.push(`${kre}${a}`);let s=n.user!=null&&n.user!==""&&n.user!=="@me"?n.user:void 0;return{owner:t,repo:r,labels:i,...s===void 0?{}:{creator:s},counter_labels:{ready:o,human:Ih}}}function oL(e){return`label:${JSON.stringify(e)}`}function X1e(e){let t=e.trim().split("/");if(t.length!==2||t[0]===""||t[1]==="")throw new Error("a registration needs the repository its queue lives in: the daemon polls the string it is handed and cannot work out which tracker a checkout belongs to");return[t[0],t[1]]}var PNt="Work issue #{{work_item}} in this repository to a merged pull request, following the /afk skill: claim it, implement it in this workspace, run the gate, open the PR, and land it. If you cannot claim it or the work is blocked, say so plainly and stop.";function eNe(e){let t={repo:e.repo,...e.selector==null?{}:{selector:e.selector},...e.readyLabel==null?{}:{readyLabel:e.readyLabel}};return{selector:Q1e(t),queue_poll:Y1e(t),argv:zp("red-skills-redskilled",["acp-worker",...e.runner==null?[]:["--child-agent",e.runner]],e.version).split(" "),workspace_path:e.workspacePath,trunk:{remote:"origin",branch:e.trunkBranch??"main"},prompt:PNt,target:e.target}}function rNe(e,t,r={},n=bre){let o=ANt(e,n);if(o==null)return;let i=typeof r.target=="number"&&Number.isInteger(r.target)&&r.target>=0?r.target:1,s=typeof r.runner=="string"&&r.runner.length>0?r.runner:void 0;return eNe({repo:o,workspacePath:e,target:i,version:t,...s==null?{}:{runner:s},...tNe(e)==null?{}:{trunkBranch:tNe(e)}})}function tNe(e){try{let r=INt("git",["-C",e,"symbolic-ref","refs/remotes/origin/HEAD"],{encoding:"utf8",timeout:5e3}).trim().split("/").pop();return r==null||r===""?void 0:r}catch{return}}function ANt(e,t=bre){let r;try{r=t(e).name}catch{return}return/^[^/\s]+\/[^/\s]+$/.test(r)?r:void 0}md();var lw="redskilled://lanes/events",ONt=1e3;function nNe(e,t,r={}){let n=r.bufferLimit??ONt,o=[],i=0,s,a=c=>{o.push(c.record),o.length>n&&o.splice(0,o.length-n),e.sendResourceUpdated({uri:lw})};return e.registerCapabilities({resources:{subscribe:!0}}),e.setRequestHandler(N_,()=>({resources:[{uri:lw,name:"Redskilled lane events",description:"Subscribe to receive AFK lane records (Worker landings, deaths, lost claims, supervisor halts) appended after subscription. Payloads are byte-compatible with the `logs` tool's CastleLaneRecord shape.",mimeType:"application/toon"}]})),e.setRequestHandler(z_,c=>{let l=Ere(c);if(l!==lw)throw new Error(`unknown resource ${JSON.stringify(l)}`);let u=o.splice(0,o.length);return{contents:[{uri:lw,mimeType:"application/toon",text:cw({events:u})}]}}),e.setRequestHandler(cX,async c=>Ere(c)!==lw?{}:(i+=1,i===1&&(s=await t.subscribe(a),t.start(r.intervalMs)),{})),e.setRequestHandler(lX,c=>Ere(c)!==lw?{}:(i>0&&(i-=1),i===0&&(s?.(),s=void 0,t.stop()),{})),{poll:()=>t.poll(),stop:()=>{s?.(),s=void 0,t.stop()}}}function Ere(e){let t=e?.params;return typeof t?.uri=="string"?t.uri:""}function iNe(e){let t=new Set,r,n,o=async()=>{let s=await e("events_since",r===void 0?{}:{cursor:r});if(!oNe(s)||typeof s.cursor!="string")throw new Error("redskilled ACP returned an invalid events_since envelope");let a=Array.isArray(s.lane_records)?s.lane_records.filter(oNe):[];return{cursor:s.cursor,lane_records:a}},i={async subscribe(s){return r===void 0&&(r=(await o()).cursor),t.add(s),()=>t.delete(s)},async poll(){if(t.size===0)return 0;let s=await o();r=s.cursor;for(let a of s.lane_records)for(let c of t)c({path:"redskilled-acp",record:a});return s.lane_records.length},start(s=1e3){n===void 0&&(n=setInterval(()=>void i.poll().catch(()=>{}),s),n.unref())},stop(){n!==void 0&&clearInterval(n),n=void 0,t.clear()}};return i}function oNe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}ao();var Rre="rs_github",sNe="github_request",iL=Ms.githubRequest;function Tre(){return[{name:sNe,title:"Request the Project's forge",description:"MUTATING: forward one REST request to the Project's GitHub gateway. An observing method (GET, HEAD) is served from the daemon's Project cache and carries the age of what it served; concurrent identical reads share one upstream call. A mutating method is scheduled through the daemon's durable outbox and answers with its publication receipt. Paths are repository-relative \u2014 `issues/17` \u2014 or the full `repos/<owner>/<repo>/\u2026` form of this Project's own repository; another repository is refused.",method:iL,inputSchema:{method:w.enum(mPe),path:w.string().min(1),body:w.record(w.unknown()).optional(),headers:w.record(w.string()).optional()}}]}function aNe(e){return{request:{method:e.method,path:e.path,...e.body===void 0?{}:{body:e.body},...e.headers===void 0?{}:{headers:e.headers}}}}function Cre(e){let t=new iw({name:Rre,version:e.version}),r=t.registerTool.bind(t);for(let n of e.tools??Tre())r(n.name,{title:n.title,description:n.description,inputSchema:n.inputSchema},async o=>({content:[{type:"text",text:cw(await e.invoke(n.method,aNe(o)))}]}));return t}var lk=KW("redskilled-mcp");function ulr(e=process.cwd(),t){let r=new iw({name:k1e,version:lk.version}),n=r.registerTool.bind(r),o=t??(async()=>{throw new Error("REDSKILLED_ACP_UNAVAILABLE: the stdio adapter has no ACP client")}),i={},s=(a,c)=>a==="drain"&&c.registration==null?{...c,registration:rNe(e,lk.version,c)}:c;for(let a of _1e(i))n(a.name,{title:a.title,description:a.description,inputSchema:a.inputSchema},async c=>({content:[{type:"text",text:cw(await o(a.name,s(a.name,c)))}]}));for(let a of mre)r.registerPrompt(a.name,{title:a.title,description:a.description},async()=>({messages:[{role:"user",content:{type:"text",text:a.body}}]}));return nNe(r.server,iNe(o)),r}async function Pdt(e,t=process.env,r=process.cwd()){let n=(t.RED_SKILLS_PROJECT_ROOT??t.CLAUDE_PROJECT_DIR??t.CODEX_PROJECT_DIR??t.OPENCODE_PROJECT_DIR??"").trim();if(n!=="")return E$(n);if(e.getClientCapabilities()?.roots!==void 0)try{let o=await e.listRoots();for(let i of o.roots)if(i.uri.startsWith("file:"))return E$(Cdt(i.uri))}catch{}return E$(r)}async function Idt(e){let t,r=new Promise(n=>{t=n});e.server.server.onclose=t,await e.server.connect(e.transport),await r}async function dlr(){let e=process.cwd(),t,r,n=()=>(t??=Pdt(r.server,process.env,e).then(i=>w7({cwd:i,name:"RedSkills GitHub MCP adapter",version:lk.version})),t);r=Cre({version:lk.version,invoke:async(i,s)=>{if(i!==iL)throw new Error(`rs_github: no daemon method ${JSON.stringify(i)}`);return(await n()).github(s.request)}});let o=()=>{r.close()};process.once("SIGINT",o),process.once("SIGTERM",o);try{await Idt({server:r,transport:new fC})}finally{if(t!==void 0)try{(await t).close()}catch{}process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o)}}async function plr(){let e=process.cwd(),t,r,n=()=>(t??=Pdt(r.server,process.env,e).then(i=>w7({cwd:i,name:"RedSkills MCP adapter",version:lk.version})),t);r=ulr(e,async(i,s)=>w1e(await n(),i,s));let o=()=>{r.close()};process.once("SIGINT",o),process.once("SIGTERM",o);try{await Idt({server:r,transport:new fC})}finally{if(t!==void 0)try{(await t).close()}catch{}process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o)}}var flr=`Usage: red-skills-redskilled-mcp [command]
440
+ `,u=e.getWriter();try{await u.write(r.encode(l))}finally{u.releaseLock()}}});return{readable:s,writable:a}}var Cpr=vZ.and(x({mode:O("form")})).and(x({message:g()})),Ppr=EZ.and(x({mode:O("url")})).and(x({message:g()})),Ipr=be([uR,dR]).and(x({message:g()})),Apr=bZ.and(x({type:O("string")})),Opr=xZ.and(x({type:O("number")})),$pr=SZ.and(x({type:O("integer")})),Mpr=kZ.and(x({type:O("boolean")})),Dpr=wZ.and(x({type:O("array")})),Npr=_Z.and(x({type:O("string")}));var zpr=ZZ.and(x({action:O("accept")})),Lpr=x({action:O("decline")}),Fpr=x({action:O("cancel")});function y9(e,t){return u9(e,t)}function Dc(e){return e??{}}function Mve(e){return typeof e=="object"&&e!==null&&"readable"in e&&"writable"in e}function Dve(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}var th={agent:{initialize:Me.initialize,authenticate:Me.authenticate,logout:Me.logout,providers:{list:Me.providers_list,set:Me.providers_set,disable:Me.providers_disable},session:{new:Me.session_new,load:Me.session_load,list:Me.session_list,delete:Me.session_delete,fork:Me.session_fork,resume:Me.session_resume,close:Me.session_close,setMode:Me.session_set_mode,setConfigOption:Me.session_set_config_option,prompt:Me.session_prompt,cancel:Me.session_cancel},nes:{start:Me.nes_start,suggest:Me.nes_suggest,accept:Me.nes_accept,reject:Me.nes_reject,close:Me.nes_close},document:{didOpen:Me.document_did_open,didChange:Me.document_did_change,didClose:Me.document_did_close,didSave:Me.document_did_save,didFocus:Me.document_did_focus}},client:{session:{requestPermission:ir.session_request_permission,update:ir.session_update},fs:{writeTextFile:ir.fs_write_text_file,readTextFile:ir.fs_read_text_file},terminal:{create:ir.terminal_create,output:ir.terminal_output,release:ir.terminal_release,waitForExit:ir.terminal_wait_for_exit,kill:ir.terminal_kill},elicitation:{create:ir.elicitation_create,complete:ir.elicitation_complete}},protocol:{cancelRequest:JW.cancel_request}},Nve=Symbol("startActiveSession"),_D=class{cx;currentRequestId;constructor(t,r){this.cx=t,this.currentRequestId=r}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(t,r,n,o){return this.cx.sendRequest(t,r,n,o)}sendNotification(t,r){return this.cx.sendNotification(t,r)}addDynamicHandler(t){return this.cx.addDynamicHandler(t)}},pR=class e extends _D{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}request(t,r,n){let o=qve[t];return this.sendRequest(t,r,o?.mapResponse,n)}notify(t,r){return this.sendNotification(t,r)}},fR=class e extends _D{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}[Nve](t,r){return this.sendRequest(Me.session_new,t,n=>this.attachSession(n),r)}buildSession(t){return typeof t=="string"?vD.create(this,{cwd:t,mcpServers:[]}):vD.create(this,t)}attachSession(t){let r=new f9,n=this.connectionContext.signal,o=()=>{r.fail(n.reason??new Error("ACP connection closed"))};n.aborted?o():n.addEventListener("abort",o);let i=Gve(this.connectionContext).attach(t,r),s=new $p(()=>{n.removeEventListener("abort",o)});return m9.create(this,t,r,[i,s])}request(t,r,n){let o=Hve[t];return this.sendRequest(t,r,o?.mapResponse,n)}notify(t,r){return this.sendNotification(t,r)}},wD=class{connection;constructor(t){this.connection=t}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(t){this.connection.close(t)}},d9=class extends wD{connectHandlers;client;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.client=pR.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,CD(this,this.connectHandlers))}},p9=class extends wD{connectHandlers;agent;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.agent=fR.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,CD(this,this.connectHandlers))}};function zve(e,t=[]){return new d9(e,t)}function Lve(e,t=[]){return new p9(e,t)}var f9=class{values=[];waiters=[];failed=!1;failure;enqueue(t){if(this.failed)return;let r=this.waiters.shift();r?r.resolve(t):this.values.push({kind:"value",value:t})}reject(t){if(!this.failed){if(this.waiters.length>0){for(let r of this.waiters.splice(0))r.reject(t);return}this.values.push({kind:"error",error:t})}}clearErrors(){this.values=this.values.filter(t=>t.kind==="value")}fail(t){if(!this.failed){this.failed=!0,this.failure=t;for(let r of this.waiters.splice(0))r.reject(t)}}next(){if(this.values.length>0){let t=this.values.shift();return t.kind==="error"?Promise.reject(t.error):Promise.resolve(t.value)}return this.failed?Promise.reject(this.failure):new Promise((t,r)=>{this.waiters.push({resolve:t,reject:r})})}};function Ave(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}var vD=class e{cx;request;constructor(t,r){this.cx=t,this.request=Ave(r)}static create(t,r){return new e(t,r)}toRequest(){return Ave(this.request)}withAdditionalDirectories(t){return this.request={...this.request,additionalDirectories:[...t]},this}withMcpServer(t){return this.request={...this.request,mcpServers:[...this.request.mcpServers,t]},this}async start(t){return this.cx[Nve](this.toRequest(),t)}async withSession(t){let r=await this.start();try{return await t(r)}finally{r.dispose()}}},m9=class e{cx;sessionResponse;updates;registrations;constructor(t,r,n,o){this.cx=t,this.sessionResponse=r,this.updates=n,this.registrations=o}static create(t,r,n,o){return new e(t,r,n,o)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(t,r){this.updates.clearErrors();let n=this.cx.request(Me.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(t)},r);return n.then(o=>{this.updates.enqueue({kind:"stop",response:o,stopReason:o.stopReason})},o=>{this.updates.reject(o)}),n}nextUpdate(){return this.updates.next()}async readText(){let t="";for(;;){let r=await this.nextUpdate();if(r.kind==="stop")return t;let{update:n}=r;n.sessionUpdate==="agent_message_chunk"&&n.content.type==="text"&&(t+=n.content.text)}}dispose(){for(let t of this.registrations.splice(0))t.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t:[t]}};function Fve(e,t){return e?typeof e=="function"?e(t):e.parse(t):t}function en(e,t,r){return{method:e,params:t,mapResponse:r}}function Qu(e,t){return{method:e,params:t}}function jve(e,t,r,n){e.onReceiveRequest(t.method,o=>Fve(t.params,o),async(o,i,s)=>{let a=await n(r(o,s,i.signal,i.id));await i.respond(t.mapResponse?t.mapResponse(a):a)})}function Uve(e,t,r,n){e.onReceiveNotification(t.method,o=>Fve(t.params,o),(o,i)=>n(r(o,i,i.signal)))}function TD(e){let t={};for(let r of Object.values(e))t[r.method]=r;return t}var Dyt={initialize:en(Me.initialize,gD),newSession:en(Me.session_new,NZ),loadSession:en(Me.session_load,zZ,Dc),unstable_forkSession:en(Me.session_fork,jZ),listSessions:en(Me.session_list,LZ),deleteSession:en(Me.session_delete,FZ,Dc),resumeSession:en(Me.session_resume,UZ),closeSession:en(Me.session_close,HZ,Dc),setSessionMode:en(Me.session_set_mode,qZ,Dc),setSessionConfigOption:en(Me.session_set_config_option,GZ),authenticate:en(Me.authenticate,AZ,Dc),unstable_listProviders:en(Me.providers_list,OZ),unstable_setProvider:en(Me.providers_set,$Z,Dc),unstable_disableProvider:en(Me.providers_disable,MZ,Dc),logout:en(Me.logout,DZ,Dc),prompt:en(Me.session_prompt,BZ),unstable_startNes:en(Me.nes_start,WZ),unstable_suggestNes:en(Me.nes_suggest,VZ),unstable_closeNes:en(Me.nes_close,KZ,Dc)},Nyt={cancel:Qu(Me.session_cancel,JZ),unstable_didOpenDocument:Qu(Me.document_did_open,QZ),unstable_didChangeDocument:Qu(Me.document_did_change,YZ),unstable_didCloseDocument:Qu(Me.document_did_close,XZ),unstable_didSaveDocument:Qu(Me.document_did_save,e9),unstable_didFocusDocument:Qu(Me.document_did_focus,t9),unstable_acceptNes:Qu(Me.nes_accept,r9),unstable_rejectNes:Qu(Me.nes_reject,n9)},zyt={requestPermission:en(ir.session_request_permission,pZ),writeTextFile:en(ir.fs_write_text_file,cZ,Dc),readTextFile:en(ir.fs_read_text_file,lZ),createTerminal:en(ir.terminal_create,fZ),terminalOutput:en(ir.terminal_output,mZ),releaseTerminal:en(ir.terminal_release,hZ,Dc),waitForTerminalExit:en(ir.terminal_wait_for_exit,gZ),killTerminal:en(ir.terminal_kill,yZ,Dc),unstable_createElicitation:en(ir.elicitation_create,RZ)},Lyt={sessionUpdate:Qu(ir.session_update,hD),unstable_completeElicitation:Qu(ir.elicitation_complete,IZ)},Hve=TD(Dyt),Fyt=TD(Nyt),qve=TD(zyt),jyt=TD(Lyt);function Uyt(e,t,r,n){return{params:e,requestId:n,signal:r,client:t}}function Hyt(e,t,r){return{params:e,signal:r,client:t}}function qyt(e,t,r,n){return{params:e,requestId:n,signal:r,agent:t}}function Gyt(e,t,r){return{params:e,signal:r,agent:t}}var h9=class{activeSessions=new Map;handleMessage(t){if(t.kind!=="notification"||t.method!==ir.session_update)return Mc.no(t);let r=hD.parse(t.params),n={kind:"session_update",notification:r,update:r.update},o=this.activeSessions.get(r.sessionId);if(o&&o.size>0)for(let i of o)i.enqueue(n);return Mc.no(t)}attach(t,r){let n=this.activeSessions.get(t.sessionId)??new Set;return n.add(r),this.activeSessions.set(t.sessionId,n),new $p(()=>{n.delete(r),n.size===0&&this.activeSessions.delete(t.sessionId)})}},Ove=new WeakMap;function Gve(e){let t=Ove.get(e);return t||(t=new h9,Ove.set(e,t)),t}function CD(e,t){for(let r of t){let n;try{n=r(e)}catch(o){throw e.close(o),o}Promise.resolve(n).catch(o=>{e.close(o)})}}var ED=Symbol("appBuilder"),SD=Symbol("runAgentConnectHandlers"),kD=Symbol("runClientConnectHandlers"),RD={allowBatches:!1};var $ve=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name)}[ED](){return this.builder}[SD](t){CD(t,this.connectHandlers)}connect(t,r={}){return this.connectConnection(t,r).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.client))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return this.request({method:t,params:r},n);let o=Hve[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return this.notification({method:t,params:r},n);let o=Fyt[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return jve(this.builder,t,(n,o,i,s)=>Uyt(n,pR.create(o,s),i,s),r),this}notification(t,r){return Uve(this.builder,t,(n,o,i)=>Hyt(n,pR.create(o),i),r),this}connectConnection(t,r={}){if(Mve(t)){let c=this.openStreamConnection(t);return r.deferConnectHandlers||this[SD](c.connection),c}let[n,o]=Dve(),i=t[ED]().connect(o,RD),s=Lve(i),a=this.openStreamConnection(n);a.rawConnection.closed.then(()=>s.close()),i.closed.then(()=>a.connection.close());try{t[kD](s),this[SD](a.connection)}catch(c){throw s.close(c),a.connection.close(c),c}return a}openStreamConnection(t){let r=this.builder.connect(t,RD);return{rawConnection:r,connection:zve(r,this.connectHandlers)}}};function Bve(e){return new g9(e)}var g9=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name),this.builder.withHandler({handleMessage:(r,n)=>Gve(n).handleMessage(r),describe:()=>"client-session-update-router"})}[ED](){return this.builder}[kD](t){CD(t,this.connectHandlers)}connect(t){return this.connectConnection(t).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.agent))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return this.request({method:t,params:r},n);let o=qve[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return this.notification({method:t,params:r},n);let o=jyt[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return jve(this.builder,t,(n,o,i,s)=>qyt(n,fR.create(o,s),i,s),r),this}notification(t,r){return Uve(this.builder,t,(n,o,i)=>Gyt(n,fR.create(o),i),r),this}connectConnection(t){if(Mve(t)){let a=this.openStreamConnection(t);return this[kD](a.connection),a}let[r,n]=Dve(),o=t[ED]().connect(n,RD),i=zve(o),s=this.openStreamConnection(r);s.rawConnection.closed.then(()=>i.close()),o.closed.then(()=>s.connection.close());try{t[SD](i),this[kD](s.connection)}catch(a){throw i.close(a),s.connection.close(a),a}return s}openStreamConnection(t){let r=this.builder.connect(t,RD);return{rawConnection:r,connection:Lve(r,this.connectHandlers)}}},Kpr=new Set([Me.initialize,Me.authenticate,Me.providers_list,Me.providers_set,Me.providers_disable,Me.session_new,Me.session_load,Me.session_set_mode,Me.session_set_config_option,Me.session_prompt,Me.session_list,Me.session_delete,Me.session_fork,Me.session_resume,Me.session_close,Me.logout,Me.nes_start,Me.nes_suggest,Me.nes_close]),Zpr=new Set([Me.session_cancel,Me.nes_accept,Me.nes_reject,Me.document_did_open,Me.document_did_change,Me.document_did_close,Me.document_did_save,Me.document_did_focus]),Jpr=new Set([ir.session_request_permission,ir.fs_write_text_file,ir.fs_read_text_file,ir.terminal_create,ir.terminal_output,ir.terminal_release,ir.terminal_wait_for_exit,ir.terminal_kill,ir.elicitation_create]),Qpr=new Set([ir.session_update,ir.elicitation_complete]);D8();T8();var ct={initialize:"initialize",auth_login:"auth/login",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",auth_logout:"auth/logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},vi={session_request_permission:"session/request_permission",session_update:"session/update",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},N1={cancel_request:"$/cancel_request"},Hp=2;var lh=be([rt(),g()]).nullable(),dn=g(),z1=g(),_wt=be([O("read"),O("edit"),O("delete"),O("move"),O("search"),O("execute"),O("think"),O("fetch"),O("switch_mode"),O("other"),g()]),wwt=be([O("pending"),O("in_progress"),O("completed"),O("failed"),O("cancelled"),g()]),vwt=be([O("assistant"),O("user"),g()]),WR=x({audience:y(Ve(vwt).nullish(),()=>{}),lastModified:y(Zu.datetime({offset:!0}).nullish(),()=>{}),priority:y(rt().gte(0).lte(1).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),N8=x({text:g(),annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),cb=g(),z8=x({data:g(),mimeType:cb,uri:y(_r().nullish(),()=>{}),annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),L8=x({data:g(),mimeType:cb,annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Ewt=be([O("light"),O("dark"),g()]),Rwt=x({src:_r(),mimeType:y(cb.nullish(),()=>{}),sizes:y(Ve(g()).nullish(),()=>{}),theme:y(Ewt.nullish(),()=>{})}),F8=x({name:g(),uri:_r(),title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),icons:y(Ve(Rwt).nullish(),()=>{}),mimeType:y(cb.nullish(),()=>{}),size:y(rt().nullish(),()=>{}),annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Twt=x({text:g(),uri:_r(),mimeType:y(cb.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Cwt=x({blob:g(),uri:_r(),mimeType:y(cb.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Pwt=be([Twt,Cwt]),j8=x({resource:Pwt,annotations:y(WR.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),b_=Mn(be([N8.and(x({type:O("text")})),z8.and(x({type:O("image")})),L8.and(x({type:O("audio")})),F8.and(x({type:O("resource_link")})),j8.and(x({type:O("resource")})),$n(x({type:g()}),"type",["audio","image","resource","resource_link","text"])]),"type",["audio","image","resource","resource_link","text"]),U8=x({content:b_,_meta:y(C(g(),T()).nullish(),()=>{})}),Iwt=be([O("text"),O("binary"),O("directory"),O("symlink"),g()]),ss=g(),sb=x({path:ss}),BR=x({oldPath:ss,path:ss}),Awt=Mn(Ho(be([sb.and(x({operation:O("add")})),sb.and(x({operation:O("delete")})),sb.and(x({operation:O("modify")})),BR.and(x({operation:O("move")})),BR.and(x({operation:O("copy")})),$n(x({operation:g()}),"operation",["add","copy","delete","modify","move"])]),x({fileType:y(Iwt.nullish(),()=>{}),mimeType:y(cb.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})})),"operation",["add","copy","delete","modify","move"]),Owt=be([O("git_patch"),g()]),$wt=x({format:Owt,text:g()}),H8=x({changes:Ve(Awt),patch:y($wt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),L1=g(),q8=x({terminalId:L1,_meta:y(C(g(),T()).nullish(),()=>{})}),OCe=Mn(be([U8.and(x({type:O("content")})),H8.and(x({type:O("diff")})),q8.and(x({type:O("terminal")})),$n(x({type:g()}),"type",["content","diff","terminal"])]),"type",["content","diff","terminal"]),Mwt=x({path:ss,line:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),F1=x({toolCallId:z1,name:y(g().nullish(),()=>{}),title:y(g().nullish(),()=>{}),kind:y(_wt.nullish(),()=>{}),status:y(wwt.nullish(),()=>{}),content:y(Ve(OCe).nullish(),()=>{}),locations:y(Ve(Mwt).nullish(),()=>{}),rawInput:y(T().optional(),()=>{}),rawOutput:y(T().optional(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),G8=x({toolCall:F1}),B8=x({command:g(),cwd:ss,toolCallId:y(z1.nullish(),()=>{}),terminalId:y(L1.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Dwt=Mn(be([G8.and(x({type:O("tool_call")})),B8.and(x({type:O("command")})),$n(x({type:g()}),"type",["command","tool_call"])]),"type",["command","tool_call"]),$Ce=g(),Nwt=be([O("allow_once"),O("allow_always"),O("reject_once"),O("reject_always"),g()]),zwt=x({optionId:$Ce,name:g(),kind:Nwt,_meta:y(C(g(),T()).nullish(),()=>{})}),W8=x({sessionId:dn,title:g(),description:y(g().nullish(),()=>{}),subject:Dwt.nullish(),options:gt(zwt).min(1),_meta:y(C(g(),T()).nullish(),()=>{})}),VR=x({sessionId:dn,toolCallId:y(z1.nullish(),()=>{})}),KR=x({requestId:lh}),Lwt=O("object"),Fwt=be([O("email"),O("uri"),O("date"),O("date-time"),g()]),MCe=x({const:g(),title:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),V8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minLength:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:g().nullish(),format:Fwt.nullish(),default:y(g().nullish(),()=>{}),enum:gt(g()).min(1).nullish(),oneOf:gt(MCe).min(1).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),K8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minimum:rt().nullish(),maximum:rt().nullish(),default:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Z8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minimum:rt().nullish(),maximum:rt().nullish(),default:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),J8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),default:y(mr().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Q8=x({enum:gt(g()).min(1),_meta:y(C(g(),T()).nullish(),()=>{})}),DCe=x({anyOf:gt(MCe).min(1),_meta:y(C(g(),T()).nullish(),()=>{})}),jwt=Mn(be([Q8.and(x({type:O("string")})),$n(x({type:g()}),"type",["string"]),DCe]),"type",["string"]),Y8=x({title:y(g().nullish(),()=>{}),description:y(g().nullish(),()=>{}),minItems:rt().nullish(),maxItems:rt().nullish(),items:jwt,default:y(Ve(g()).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Uwt=Mn(be([V8.and(x({type:O("string")})),K8.and(x({type:O("number")})),Z8.and(x({type:O("integer")})),J8.and(x({type:O("boolean")})),Y8.and(x({type:O("array")})),$n(x({type:g()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Hwt=x({type:y(Lwt.optional().default("object"),()=>"object"),title:y(g().nullish(),()=>{}),properties:C(g(),Uwt).optional().default({}),required:gt(g()).nullish(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),X8=Ho(be([VR,KR]),x({requestedSchema:Hwt})),NCe=g(),e5=Ho(be([VR,KR]),x({elicitationId:NCe,url:_r()})),t5=Mn(Ho(be([X8.and(x({mode:O("form")})),e5.and(x({mode:O("url")})),$n(Ho(be([VR,KR]),x({mode:g()})),"mode",["form","url"])]),x({message:g(),_meta:y(C(g(),T()).nullish(),()=>{})})),"mode",["form","url"]),zCe=g(),r5=x({serverId:zCe,_meta:y(C(g(),T()).nullish(),()=>{})}),j1=g(),ZR=x({connectionId:j1,method:g(),params:C(g(),T()).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),n5=x({connectionId:j1,_meta:y(C(g(),T()).nullish(),()=>{})}),LCe=T(),uwr=x({id:lh,method:g(),params:be([W8,t5,r5,ZR,n5,LCe]).nullish()}),FCe=fr().gte(0).lte(65535),jCe=x({name:g(),title:y(g().nullish(),()=>{}),version:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),qwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Gwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Bwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Wwt=x({image:y(qwt.nullish(),()=>{}),audio:y(Gwt.nullish(),()=>{}),embeddedContext:y(Bwt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Vwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Kwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Zwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Jwt=x({stdio:y(Vwt.nullish(),()=>{}),http:y(Kwt.nullish(),()=>{}),acp:y(Zwt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Qwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Ywt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Xwt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),evt=x({prompt:y(Wwt.nullish(),()=>{}),mcp:y(Jwt.nullish(),()=>{}),delete:y(Qwt.nullish(),()=>{}),additionalDirectories:y(Ywt.nullish(),()=>{}),fork:y(Xwt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),tvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),rvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),nvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),ovt=be([O("full"),O("incremental")]),ivt=x({syncKind:ovt,_meta:y(C(g(),T()).nullish(),()=>{})}),svt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),avt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),cvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),lvt=x({didOpen:y(nvt.nullish(),()=>{}),didChange:y(ivt.nullish(),()=>{}),didClose:y(svt.nullish(),()=>{}),didSave:y(avt.nullish(),()=>{}),didFocus:y(cvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),uvt=x({document:y(lvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),dvt=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),pvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),fvt=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),mvt=x({maxCount:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),gvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),yvt=x({recentFiles:y(dvt.nullish(),()=>{}),relatedSnippets:y(pvt.nullish(),()=>{}),editHistory:y(fvt.nullish(),()=>{}),userActions:y(mvt.nullish(),()=>{}),openFiles:y(hvt.nullish(),()=>{}),diagnostics:y(gvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),bvt=x({events:y(uvt.nullish(),()=>{}),context:y(yvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),UCe=be([O("utf-16"),O("utf-32"),O("utf-8")]),xvt=x({session:y(evt.nullish(),()=>{}),auth:y(tvt.nullish(),()=>{}),providers:y(rvt.nullish(),()=>{}),nes:y(bvt.nullish(),()=>{}),positionEncoding:y(UCe.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),lb=g(),Svt=x({name:g(),label:y(g().nullish(),()=>{}),secret:y(mr().optional().default(!0),()=>!0),optional:y(mr().optional().default(!1),()=>!1),_meta:y(C(g(),T()).nullish(),()=>{})}),o5=x({methodId:lb,name:g(),description:y(g().nullish(),()=>{}),vars:Kn(Ve(Svt),()=>[]),link:y(_r().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),HCe=x({name:g(),value:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),i5=x({methodId:lb,name:g(),description:y(g().nullish(),()=>{}),args:y(Ve(g()).optional(),()=>[]),env:y(Ve(HCe).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),s5=x({methodId:lb,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),kvt=Mn(be([o5.and(x({type:O("env_var")})),i5.and(x({type:O("terminal")})),s5.and(x({type:O("agent")})),$n(x({type:g(),methodId:lb,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),"type",["agent","env_var","terminal"])]),"type",["agent","env_var","terminal"]),a5=x({protocolVersion:FCe,info:jCe,capabilities:y(xvt.optional().default({}),()=>({})),authMethods:y(Ve(kvt).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),_vt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),c5=g(),l5=be([O("anthropic"),O("openai"),O("azure"),O("vertex"),O("bedrock"),g()]),wvt=x({apiType:l5,baseUrl:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),vvt=x({providerId:c5,supported:Kn(Ve(l5),()=>[]),required:mr(),current:wvt.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),Evt=x({providers:gt(vvt),_meta:y(C(g(),T()).nullish(),()=>{})}),Rvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Tvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Cvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),qp=g(),Pvt=be([O("mode"),O("model"),O("model_config"),O("thought_level"),g()]),JR=g(),qCe=x({value:JR,name:g(),description:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Ivt=g(),Avt=x({groupId:Ivt,name:g(),options:Kn(Ve(qCe),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Ovt=be([gt(qCe),gt(Avt)]),u5=x({currentValue:JR,options:Ovt}),d5=x({currentValue:mr()}),QR=Mn(Ho(be([u5.and(x({type:O("select")})),d5.and(x({type:O("boolean")})),$n(x({type:g()}),"type",["boolean","select"])]),x({configId:qp,name:g(),description:y(g().nullish(),()=>{}),category:y(Pvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})})),"type",["boolean","select"]),$vt=x({sessionId:dn,configOptions:y(Ve(QR).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Mvt=x({sessionId:dn,cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),title:y(g().nullish(),()=>{}),updatedAt:y(Zu.datetime({offset:!0}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),GCe=g(),Dvt=x({sessions:Kn(Ve(Mvt),()=>[]),nextCursor:y(GCe.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Nvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),zvt=x({sessionId:dn,configOptions:y(Ve(QR).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Lvt=x({configOptions:y(Ve(QR).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Fvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),jvt=x({configOptions:Kn(Ve(QR),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),Uvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Hvt=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),Gp=g(),uh=x({line:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:y(C(g(),T()).nullish(),()=>{})}),x_=x({start:uh,end:uh,_meta:y(C(g(),T()).nullish(),()=>{})}),qvt=x({range:x_,newText:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),p5=x({suggestionId:Gp,uri:_r(),edits:gt(qvt).min(1),cursorPosition:y(uh.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),f5=x({suggestionId:Gp,uri:_r(),position:uh,_meta:y(C(g(),T()).nullish(),()=>{})}),m5=x({suggestionId:Gp,uri:_r(),position:uh,newName:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),h5=x({suggestionId:Gp,uri:_r(),search:g(),replace:g(),isRegex:mr().nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),Gvt=Mn(be([p5.and(x({kind:O("edit")})),f5.and(x({kind:O("jump")})),m5.and(x({kind:O("rename")})),h5.and(x({kind:O("searchAndReplace")})),$n(x({kind:g(),suggestionId:Gp}),"kind",["edit","jump","rename","searchAndReplace"])]),"kind",["edit","jump","rename","searchAndReplace"]),Bvt=x({suggestions:gt(Gvt),_meta:y(C(g(),T()).nullish(),()=>{})}),Wvt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),BCe=T(),WCe=T(),Vvt=be([O(-32700),O(-32600),O(-32601),O(-32602),O(-32603),O(-32800),O(-32e3),O(-32002),fr().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),VCe=x({code:Vvt,message:g(),data:y(T().optional(),()=>{})}),dwr=be([x({id:lh,result:be([a5,_vt,Evt,Rvt,Tvt,Cvt,$vt,Dvt,Nvt,zvt,Lvt,Fvt,jvt,Uvt,Hvt,Bvt,Wvt,BCe,WCe])}),x({id:lh,error:VCe})]),U1=g(),ab=x({messageId:U1,content:b_,_meta:y(C(g(),T()).nullish(),()=>{})}),g5=x({messageId:U1,content:y(Ve(b_).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),y5=x({messageId:U1,content:y(Ve(b_).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),b5=x({messageId:U1,content:y(Ve(b_).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),x5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),Kvt=be([O("end_turn"),O("max_tokens"),O("max_turn_requests"),O("refusal"),O("cancelled"),g()]),Zvt=x({totalTokens:rt(),inputTokens:rt(),outputTokens:rt(),thoughtTokens:y(rt().nullish(),()=>{}),cachedReadTokens:y(rt().nullish(),()=>{}),cachedWriteTokens:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),S5=x({stopReason:y(Kvt.nullish(),()=>{}),usage:y(Zvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),k5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),_5=Mn(be([x5.and(x({state:O("running")})),S5.and(x({state:O("idle")})),k5.and(x({state:O("requires_action")})),$n(x({state:g()}),"state",["idle","requires_action","running"])]),"state",["idle","requires_action","running"]),w5=x({toolCallId:z1,content:OCe,_meta:y(C(g(),T()).nullish(),()=>{})}),Jvt=x({data:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),Qvt=x({exitCode:y(fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:y(g().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),v5=x({terminalId:L1,command:y(g().nullish(),()=>{}),cwd:y(ss.nullish(),()=>{}),output:y(Jvt.nullish(),()=>{}),exitStatus:y(Qvt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),E5=x({terminalId:L1,data:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),ub=g(),Yvt=be([O("high"),O("medium"),O("low"),g()]),Xvt=be([O("pending"),O("in_progress"),O("completed"),O("cancelled"),g()]),eEt=x({content:g(),priority:Yvt,status:Xvt,_meta:y(C(g(),T()).nullish(),()=>{})}),R5=x({planId:ub,entries:Kn(Ve(eEt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),T5=x({planId:ub,uri:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),C5=x({planId:ub,content:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),tEt=Mn(be([R5.and(x({type:O("items")})),T5.and(x({type:O("file")})),C5.and(x({type:O("markdown")})),$n(x({type:g(),planId:ub}),"type",["file","items","markdown"])]),"type",["file","items","markdown"]),P5=x({plan:tEt,_meta:y(C(g(),T()).nullish(),()=>{})}),I5=x({planId:ub,_meta:y(C(g(),T()).nullish(),()=>{})}),A5=x({hint:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),rEt=Mn(be([A5.and(x({type:O("text")})),$n(x({type:g()}),"type",["text"])]),"type",["text"]),nEt=x({name:g(),description:g(),input:y(rEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),O5=x({availableCommands:Kn(Ve(nEt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),$5=x({configOptions:Kn(Ve(QR),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),M5=x({title:y(g().nullish(),()=>{}),updatedAt:y(Zu.datetime({offset:!0}).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),oEt=x({amount:rt(),currency:g().regex(/^[A-Z]{3}$/),_meta:y(C(g(),T()).nullish(),()=>{})}),D5=x({used:rt(),size:rt(),cost:y(oEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),iEt=Mn(be([ab.and(x({sessionUpdate:O("user_message_chunk")})),g5.and(x({sessionUpdate:O("user_message")})),ab.and(x({sessionUpdate:O("agent_message_chunk")})),y5.and(x({sessionUpdate:O("agent_message")})),ab.and(x({sessionUpdate:O("agent_thought_chunk")})),b5.and(x({sessionUpdate:O("agent_thought")})),_5.and(x({sessionUpdate:O("state_update")})),w5.and(x({sessionUpdate:O("tool_call_content_chunk")})),F1.and(x({sessionUpdate:O("tool_call_update")})),v5.and(x({sessionUpdate:O("terminal_update")})),E5.and(x({sessionUpdate:O("terminal_output_chunk")})),P5.and(x({sessionUpdate:O("plan_update")})),I5.and(x({sessionUpdate:O("plan_removed")})),O5.and(x({sessionUpdate:O("available_commands_update")})),$5.and(x({sessionUpdate:O("config_option_update")})),M5.and(x({sessionUpdate:O("session_info_update")})),D5.and(x({sessionUpdate:O("usage_update")})),$n(x({sessionUpdate:g()}),"sessionUpdate",["agent_message","agent_message_chunk","agent_thought","agent_thought_chunk","available_commands_update","config_option_update","plan_removed","plan_update","session_info_update","state_update","terminal_output_chunk","terminal_update","tool_call_content_chunk","tool_call_update","usage_update","user_message","user_message_chunk"])]),"sessionUpdate",["agent_message","agent_message_chunk","agent_thought","agent_thought_chunk","available_commands_update","config_option_update","plan_removed","plan_update","session_info_update","state_update","terminal_output_chunk","terminal_update","tool_call_content_chunk","tool_call_update","usage_update","user_message","user_message_chunk"]),H1=x({sessionId:dn,update:iEt,_meta:y(C(g(),T()).nullish(),()=>{})}),N5=x({elicitationId:NCe,_meta:y(C(g(),T()).nullish(),()=>{})}),YR=x({connectionId:j1,method:g(),params:y(C(g(),T()).nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),KCe=T(),pwr=x({method:g(),params:be([H1,N5,YR,KCe]).nullish()}),sEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),aEt=x({terminal:y(sEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),cEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),lEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),uEt=x({form:y(cEt.nullish(),()=>{}),url:y(lEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),dEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),pEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),fEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),mEt=x({jump:y(dEt.nullish(),()=>{}),rename:y(pEt.nullish(),()=>{}),searchAndReplace:y(fEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hEt=x({auth:y(aEt.nullish(),()=>{}),elicitation:y(uEt.nullish(),()=>{}),nes:y(mEt.nullish(),()=>{}),positionEncodings:y(Ve(UCe).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),q1=x({protocolVersion:FCe,info:jCe,capabilities:y(hEt.optional().default({}),()=>({})),_meta:y(C(g(),T()).nullish(),()=>{})}),z5=x({methodId:lb,_meta:y(C(g(),T()).nullish(),()=>{})}),L5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),F5=x({providerId:c5,apiType:l5,baseUrl:_r(),headers:C(g(),g()).optional(),_meta:y(C(g(),T()).nullish(),()=>{})}),j5=x({providerId:c5,_meta:y(C(g(),T()).nullish(),()=>{})}),U5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),gEt=x({name:g(),value:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),H5=x({name:g(),url:_r(),headers:gt(gEt).optional(),_meta:y(C(g(),T()).nullish(),()=>{})}),q5=x({name:g(),serverId:zCe,_meta:y(C(g(),T()).nullish(),()=>{})}),G5=x({name:g(),command:ss,args:gt(g()).optional(),env:gt(HCe).optional(),_meta:y(C(g(),T()).nullish(),()=>{})}),B5=Mn(be([H5.and(x({type:O("http")})),q5.and(x({type:O("acp")})),G5.and(x({type:O("stdio")})),$n(x({type:g()}),"type",["acp","http","stdio"])]),"type",["acp","http","stdio"]),W5=x({cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),mcpServers:y(Ve(B5).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),V5=x({cwd:ss.nullish(),cursor:GCe.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),K5=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),Z5=x({sessionId:dn,cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),mcpServers:y(Ve(B5).optional(),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),J5=x({_meta:y(C(g(),T()).nullish(),()=>{})}),yEt=Mn(be([J5.and(x({type:O("start")})),$n(x({type:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),"type",["start"])]),"type",["start"]),Q5=x({sessionId:dn,cwd:ss,additionalDirectories:y(Ve(ss).optional(),()=>[]),mcpServers:y(Ve(B5).optional(),()=>[]),replayFrom:y(yEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),Y5=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),X5=Mn(Ho(be([x({value:JR,type:O("id")}),x({value:mr(),type:O("boolean")}),$n(x({type:g(),value:T()}),"type",["boolean","id"])]),x({sessionId:dn,configId:qp,_meta:y(C(g(),T()).nullish(),()=>{})})),"type",["boolean","id"]),e7=x({sessionId:dn,prompt:gt(b_),_meta:y(C(g(),T()).nullish(),()=>{})}),bEt=x({uri:_r(),name:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),xEt=x({name:g(),owner:g(),remoteUrl:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),t7=x({workspaceUri:y(_r().nullish(),()=>{}),workspaceFolders:gt(bEt).nullish(),repository:y(xEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),SEt=be([O("automatic"),O("diagnostic"),O("manual"),g()]),kEt=x({uri:_r(),languageId:g(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),_Et=x({startLine:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:fr().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),wEt=x({uri:_r(),excerpts:gt(_Et),_meta:y(C(g(),T()).nullish(),()=>{})}),vEt=x({uri:_r(),diff:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),EEt=x({action:g(),uri:_r(),position:uh,timestampMs:rt(),_meta:y(C(g(),T()).nullish(),()=>{})}),REt=x({uri:_r(),languageId:g(),visibleRange:y(x_.nullish(),()=>{}),lastFocusedMs:y(rt().nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),TEt=be([O("error"),O("warning"),O("information"),O("hint"),g()]),CEt=x({uri:_r(),range:x_,severity:TEt,message:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),PEt=x({recentFiles:gt(kEt).nullish(),relatedSnippets:gt(wEt).nullish(),editHistory:gt(vEt).nullish(),userActions:gt(EEt).nullish(),openFiles:gt(REt).nullish(),diagnostics:gt(CEt).nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),r7=x({sessionId:dn,uri:_r(),version:rt(),position:uh,selection:x_.nullish(),triggerKind:SEt,context:PEt.nullish(),_meta:y(C(g(),T()).nullish(),()=>{})}),n7=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),fwr=x({id:lh,method:g(),params:be([q1,z5,L5,F5,j5,U5,W5,V5,K5,Z5,Q5,Y5,X5,e7,t7,r7,n7,ZR,LCe]).nullish()}),o7=x({optionId:$Ce,_meta:y(C(g(),T()).nullish(),()=>{})}),IEt=Mn(be([x({outcome:O("cancelled")}),o7.and(x({outcome:O("selected")})),$n(x({outcome:g()}),"outcome",["cancelled","selected"])]),"outcome",["cancelled","selected"]),AEt=x({outcome:IEt,_meta:y(C(g(),T()).nullish(),()=>{})}),OEt=be([g(),rt(),rt(),mr(),gt(g())]),i7=x({content:C(g(),OEt).nullish()}),$Et=Mn(Ho(be([i7.and(x({action:O("accept")})),x({action:O("decline")}),x({action:O("cancel")}),$n(x({action:g()}),"action",["accept","cancel","decline"])]),x({_meta:y(C(g(),T()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),MEt=x({connectionId:j1,_meta:y(C(g(),T()).nullish(),()=>{})}),DEt=x({_meta:y(C(g(),T()).nullish(),()=>{})}),mwr=be([x({id:lh,result:be([AEt,$Et,MEt,DEt,WCe,BCe])}),x({id:lh,error:VCe})]),s7=x({sessionId:dn,_meta:y(C(g(),T()).nullish(),()=>{})}),a7=x({sessionId:dn,uri:_r(),languageId:g(),version:rt(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),NEt=x({range:x_.nullish(),text:g(),_meta:y(C(g(),T()).nullish(),()=>{})}),c7=x({sessionId:dn,uri:_r(),version:rt(),contentChanges:Kn(Ve(NEt),()=>[]),_meta:y(C(g(),T()).nullish(),()=>{})}),l7=x({sessionId:dn,uri:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),u7=x({sessionId:dn,uri:_r(),_meta:y(C(g(),T()).nullish(),()=>{})}),d7=x({sessionId:dn,uri:_r(),version:rt(),position:uh,visibleRange:x_,_meta:y(C(g(),T()).nullish(),()=>{})}),p7=x({sessionId:dn,suggestionId:Gp,_meta:y(C(g(),T()).nullish(),()=>{})}),zEt=be([O("rejected"),O("ignored"),O("replaced"),O("cancelled"),g()]),f7=x({sessionId:dn,suggestionId:Gp,reason:y(zEt.nullish(),()=>{}),_meta:y(C(g(),T()).nullish(),()=>{})}),hwr=x({method:g(),params:be([s7,a7,c7,l7,u7,d7,p7,f7,YR,KCe]).nullish()}),LEt=x({requestId:lh,_meta:y(C(g(),T()).nullish(),()=>{})}),gwr=x({method:g(),params:LEt.nullish()});function rn(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}var ywr=G8.and(x({type:O("tool_call")})),bwr=B8.and(x({type:O("command")})),xwr=U8.and(x({type:O("content")})),Swr=H8.and(x({type:O("diff")})),kwr=q8.and(x({type:O("terminal")})),FEt=N8.and(x({type:O("text")})),jEt=z8.and(x({type:O("image")})),UEt=L8.and(x({type:O("audio")})),HEt=F8.and(x({type:O("resource_link")})),qEt=j8.and(x({type:O("resource")})),_wr=sb.and(x({operation:O("add")})),wwr=sb.and(x({operation:O("delete")})),vwr=sb.and(x({operation:O("modify")})),Ewr=BR.and(x({operation:O("move")})),Rwr=BR.and(x({operation:O("copy")})),Twr=X8.and(x({mode:O("form")})).and(x({message:g()})),Cwr=e5.and(x({mode:O("url")})).and(x({message:g()})),Pwr=be([VR,KR]).and(x({message:g()})),Iwr=V8.and(x({type:O("string")})),Awr=K8.and(x({type:O("number")})),Owr=Z8.and(x({type:O("integer")})),$wr=J8.and(x({type:O("boolean")})),Mwr=Y8.and(x({type:O("array")})),Dwr=Q8.and(x({type:O("string")}));var Nwr=o5.and(x({type:O("env_var")})),zwr=i5.and(x({type:O("terminal")})),Lwr=s5.and(x({type:O("agent")})),Fwr=x({methodId:lb,name:g()}),jwr=u5.and(x({type:O("select")})).and(x({configId:qp,name:g()})),Uwr=d5.and(x({type:O("boolean")})).and(x({configId:qp,name:g()})),Hwr=x({configId:qp,name:g()}),qwr=p5.and(x({kind:O("edit")})),Gwr=f5.and(x({kind:O("jump")})),Bwr=m5.and(x({kind:O("rename")})),Wwr=h5.and(x({kind:O("searchAndReplace")})),Vwr=x({suggestionId:Gp}),GEt=ab.and(x({sessionUpdate:O("user_message_chunk")})),BEt=g5.and(x({sessionUpdate:O("user_message")})),WEt=ab.and(x({sessionUpdate:O("agent_message_chunk")})),VEt=y5.and(x({sessionUpdate:O("agent_message")})),KEt=ab.and(x({sessionUpdate:O("agent_thought_chunk")})),ZEt=b5.and(x({sessionUpdate:O("agent_thought")})),JEt=_5.and(x({sessionUpdate:O("state_update")})),QEt=w5.and(x({sessionUpdate:O("tool_call_content_chunk")})),YEt=F1.and(x({sessionUpdate:O("tool_call_update")})),XEt=v5.and(x({sessionUpdate:O("terminal_update")})),e0t=E5.and(x({sessionUpdate:O("terminal_output_chunk")})),t0t=P5.and(x({sessionUpdate:O("plan_update")})),r0t=I5.and(x({sessionUpdate:O("plan_removed")})),n0t=O5.and(x({sessionUpdate:O("available_commands_update")})),o0t=$5.and(x({sessionUpdate:O("config_option_update")})),i0t=M5.and(x({sessionUpdate:O("session_info_update")})),s0t=D5.and(x({sessionUpdate:O("usage_update")})),a0t=x5.and(x({state:O("running")})),c0t=S5.and(x({state:O("idle")})),l0t=k5.and(x({state:O("requires_action")})),Kwr=R5.and(x({type:O("items")})),Zwr=T5.and(x({type:O("file")})),Jwr=C5.and(x({type:O("markdown")})),Qwr=x({planId:ub}),Ywr=A5.and(x({type:O("text")})),Xwr=H5.and(x({type:O("http")})),evr=q5.and(x({type:O("acp")})),tvr=G5.and(x({type:O("stdio")})),rvr=J5.and(x({type:O("start")})),nvr=x({type:O("id")}).and(x({value:JR})).and(x({sessionId:dn,configId:qp})),ovr=x({type:O("boolean")}).and(x({value:mr()})).and(x({sessionId:dn,configId:qp})),ivr=x({value:T()}).and(x({sessionId:dn,configId:qp})),svr=x({outcome:O("cancelled")}),avr=o7.and(x({outcome:O("selected")})),cvr=i7.and(x({action:O("accept")})),lvr=x({action:O("decline")}),uvr=x({action:O("cancel")});var m7={isText(e){return rn(e,"type")==="text"&&FEt.safeParse(e).success},isImage(e){return rn(e,"type")==="image"&&jEt.safeParse(e).success},isAudio(e){return rn(e,"type")==="audio"&&UEt.safeParse(e).success},isResourceLink(e){return rn(e,"type")==="resource_link"&&HEt.safeParse(e).success},isResource(e){return rn(e,"type")==="resource"&&qEt.safeParse(e).success},isCustom(e){let t=rn(e,"type");return typeof t=="string"&&!["audio","image","resource","resource_link","text"].includes(t)}};var XR={isUserMessageChunk(e){return rn(e,"sessionUpdate")==="user_message_chunk"&&GEt.safeParse(e).success},isUserMessage(e){return rn(e,"sessionUpdate")==="user_message"&&BEt.safeParse(e).success},isAgentMessageChunk(e){return rn(e,"sessionUpdate")==="agent_message_chunk"&&WEt.safeParse(e).success},isAgentMessage(e){return rn(e,"sessionUpdate")==="agent_message"&&VEt.safeParse(e).success},isAgentThoughtChunk(e){return rn(e,"sessionUpdate")==="agent_thought_chunk"&&KEt.safeParse(e).success},isAgentThought(e){return rn(e,"sessionUpdate")==="agent_thought"&&ZEt.safeParse(e).success},isStateUpdate(e){return rn(e,"sessionUpdate")==="state_update"&&JEt.safeParse(e).success},isToolCallContentChunk(e){return rn(e,"sessionUpdate")==="tool_call_content_chunk"&&QEt.safeParse(e).success},isToolCallUpdate(e){return rn(e,"sessionUpdate")==="tool_call_update"&&YEt.safeParse(e).success},isTerminalUpdate(e){return rn(e,"sessionUpdate")==="terminal_update"&&XEt.safeParse(e).success},isTerminalOutputChunk(e){return rn(e,"sessionUpdate")==="terminal_output_chunk"&&e0t.safeParse(e).success},isPlanUpdate(e){return rn(e,"sessionUpdate")==="plan_update"&&t0t.safeParse(e).success},isPlanRemoved(e){return rn(e,"sessionUpdate")==="plan_removed"&&r0t.safeParse(e).success},isAvailableCommandsUpdate(e){return rn(e,"sessionUpdate")==="available_commands_update"&&n0t.safeParse(e).success},isConfigOptionUpdate(e){return rn(e,"sessionUpdate")==="config_option_update"&&o0t.safeParse(e).success},isSessionInfoUpdate(e){return rn(e,"sessionUpdate")==="session_info_update"&&i0t.safeParse(e).success},isUsageUpdate(e){return rn(e,"sessionUpdate")==="usage_update"&&s0t.safeParse(e).success},isCustom(e){let t=rn(e,"sessionUpdate");return typeof t=="string"&&!["agent_message","agent_message_chunk","agent_thought","agent_thought_chunk","available_commands_update","config_option_update","plan_removed","plan_update","session_info_update","state_update","terminal_output_chunk","terminal_update","tool_call_content_chunk","tool_call_update","usage_update","user_message","user_message_chunk"].includes(t)}},h7={isRunning(e){return rn(e,"state")==="running"&&a0t.safeParse(e).success},isIdle(e){return rn(e,"state")==="idle"&&c0t.safeParse(e).success},isRequiresAction(e){return rn(e,"state")==="requires_action"&&l0t.safeParse(e).success},isCustom(e){let t=rn(e,"state");return typeof t=="string"&&!["idle","requires_action","running"].includes(t)}};function Bp(e){return e??{}}function Wp(e,t,r,n=!1){if(!(Object.hasOwn(t,e)||n&&e===N1.cancel_request)&&!e.startsWith("_"))throw new TypeError(`Custom ACP v2 ${r} method '${e}' must start with '_'`)}function ePe(e,t,r){for(let n of e)Wp(n.method,n.kind==="request"?t:r,n.kind,n.kind==="notification")}function tPe(e){let t=q1.parse(e);if(t.protocolVersion!==Hp)throw Xr.invalidParams({expectedProtocolVersion:Hp,receivedProtocolVersion:t.protocolVersion},`The v2 API only supports protocol version ${Hp}`);return t}function rPe(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{};return tPe({...t,protocolVersion:Hp})}function nPe(e){let t=a5.parse(e);if(t.protocolVersion!==Hp)throw Xr.invalidRequest({expectedProtocolVersion:Hp,receivedProtocolVersion:t.protocolVersion},`The v2 API only supports protocol version ${Hp}`);return t}function d0t(e){return e.map(t=>{if(t.kind!=="request"||t.method!==ct.initialize)return t;let r=t.mapResponse;return{...t,params:rPe(t.params),mapResponse:n=>{let o=nPe(n);return r?r(o):o}}})}function oPe(e){return typeof e=="object"&&e!==null&&"readable"in e&&"writable"in e}function iPe(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}var zvr={agent:{initialize:ct.initialize,auth:{login:ct.auth_login,logout:ct.auth_logout},providers:{list:ct.providers_list,set:ct.providers_set,disable:ct.providers_disable},session:{new:ct.session_new,list:ct.session_list,delete:ct.session_delete,fork:ct.session_fork,resume:ct.session_resume,close:ct.session_close,setConfigOption:ct.session_set_config_option,prompt:ct.session_prompt,cancel:ct.session_cancel},mcp:{message:ct.mcp_message},nes:{start:ct.nes_start,suggest:ct.nes_suggest,accept:ct.nes_accept,reject:ct.nes_reject,close:ct.nes_close},document:{didOpen:ct.document_did_open,didChange:ct.document_did_change,didClose:ct.document_did_close,didSave:ct.document_did_save,didFocus:ct.document_did_focus}},client:{session:{requestPermission:vi.session_request_permission,update:vi.session_update},mcp:{connect:vi.mcp_connect,message:vi.mcp_message,disconnect:vi.mcp_disconnect},elicitation:{create:vi.elicitation_create,complete:vi.elicitation_complete}},protocol:{cancelRequest:N1.cancel_request}},sPe=Symbol("startActiveSession"),W1=class{cx;currentRequestId;constructor(t,r){this.cx=t,this.currentRequestId=r}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(t,r,n,o){return this.cx.sendRequest(t,r,n,o)}sendNotification(t,r){return this.cx.sendNotification(t,r)}sendBatch(t){return this.cx.sendBatch(t)}addDynamicHandler(t){return this.cx.addDynamicHandler(t)}},rT=class e extends W1{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}request(t,r,n){Wp(t,tT,"request");let o=tT[t];return this.sendRequest(t,r,o?.mapResponse,n)}notify(t,r){return Wp(t,J1,"notification",!0),this.sendNotification(t,r)}batch(t){return ePe(t,tT,J1),this.sendBatch(t)}},nT=class e extends W1{constructor(t,r){super(t,r)}static create(t,r){return new e(t,r)}[sPe](t,r){return this.sendRequest(ct.session_new,t,n=>this.attachSession(n),r)}buildSession(t){return typeof t=="string"?K1.create(this,{cwd:t,mcpServers:[]}):K1.create(this,t)}attachSession(t){let r=new b7,n=new Set,o={enqueue:l=>r.enqueue(l),reject:l=>r.reject(l),clearErrors:()=>r.clearErrors(),fail:l=>r.fail(l),next:()=>r.next(),nextAfter:(l,u)=>r.nextAfter(l,u),beginPrompt:()=>{let l={updateCursor:r.cursor(),overlapController:new AbortController};if(n.size>0){let u=new Error("readText() cannot attribute updates across overlapping prompts; use nextUpdate() instead");for(let d of n)d.overlapController.abort(u);l.overlapController.abort(u)}return n.add(l),l},cancelPrompt:l=>n.delete(l),isAwaitingPromptCompletion:()=>n.size>0,completePrompt:()=>{n.clear()}},i=this.connectionContext.signal,s=()=>{r.fail(i.reason??new Error("ACP connection closed"))};i.aborted?s():i.addEventListener("abort",s);let a=pPe(this.connectionContext).attach(t,o),c=new $p(()=>{i.removeEventListener("abort",s)});return x7.create(this,t,o,[a,c])}request(t,r,n){Wp(t,eT,"request");let o=eT[t],i=t===ct.initialize?rPe(r):r;return this.sendRequest(t,i,o?.mapResponse,n)}notify(t,r){return Wp(t,Z1,"notification",!0),this.sendNotification(t,r)}batch(t){return ePe(t,eT,Z1),this.sendBatch(d0t(t))}},V1=class{connection;constructor(t){this.connection=t}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(t){this.connection.close(t)}},g7=class extends V1{connectHandlers;client;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.client=rT.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,X1(this,this.connectHandlers))}},y7=class extends V1{connectHandlers;agent;didStartConnectHandlers=!1;constructor(t,r=[]){super(t),this.connectHandlers=r,this.agent=nT.create(t.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,X1(this,this.connectHandlers))}};function aPe(e,t=[]){return new g7(e,t)}function cPe(e,t=[]){return new y7(e,t)}var b7=class{values=[];waiters=[];failed=!1;failure;nextSequence=0;enqueue(t){if(this.failed)return;let r=this.nextSequence++,n=this.waiters.shift();n?n.resolve(t):this.values.push({kind:"value",value:t,sequence:r})}reject(t){if(this.failed)return;let r=this.nextSequence++;if(this.waiters.length>0){for(let n of this.waiters.splice(0))n.reject(t);return}this.values.push({kind:"error",error:t,sequence:r})}clearErrors(){this.values=this.values.filter(t=>t.kind==="value")}cursor(){return this.nextSequence}nextAfter(t,r){if(r?.aborted)return Promise.reject(r.reason);for(;this.values[0]&&this.values[0].sequence<t;)this.values.shift();return this.next(r)}fail(t){if(!this.failed){this.failed=!0,this.failure=t;for(let r of this.waiters.splice(0))r.reject(t)}}next(t){if(t?.aborted)return Promise.reject(t.reason);if(this.values.length>0){let r=this.values.shift();return r.kind==="error"?Promise.reject(r.error):Promise.resolve(r.value)}return this.failed?Promise.reject(this.failure):new Promise((r,n)=>{let o=()=>{t?.removeEventListener("abort",s)},i={resolve:a=>{o(),r(a)},reject:a=>{o(),n(a)}},s=()=>{let a=this.waiters.indexOf(i);a>=0&&this.waiters.splice(a,1),i.reject(t?.reason)};this.waiters.push(i),t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s()})}};function JCe(e){return structuredClone(e)}var K1=class e{cx;request;constructor(t,r){this.cx=t,this.request=JCe(r)}static create(t,r){return new e(t,r)}toRequest(){return JCe(this.request)}withAdditionalDirectories(t){return this.request={...this.request,additionalDirectories:[...t]},this}withMcpServer(t){return this.request={...this.request,mcpServers:[...this.request.mcpServers??[],structuredClone(t)]},this}async start(t){return this.cx[sPe](this.toRequest(),t)}async withSession(t){let r=await this.start();try{return await t(r)}finally{r.dispose()}}},x7=class e{cx;sessionResponse;updates;registrations;latestPrompt;constructor(t,r,n,o){this.cx=t,this.sessionResponse=r,this.updates=n,this.registrations=o}static create(t,r,n,o){return new e(t,r,n,o)}get sessionId(){return this.sessionResponse.sessionId}get configOptions(){return this.sessionResponse.configOptions}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(t,r){this.updates.clearErrors();let n=this.updates.beginPrompt();this.latestPrompt=n;let o=this.cx.request(ct.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(t)},r);return o.catch(i=>{this.updates.cancelPrompt(n)&&this.updates.reject(i)}),o}nextUpdate(){return this.updates.next()}async readText(){let t=this.latestPrompt,r=t?.updateCursor,n=[],o=new Map,i=s=>{let a=o.get(s);return a||(a=[],n.push(s),o.set(s,a)),a};for(;;){let s=r===void 0?await this.nextUpdate():await this.updates.nextAfter(r,t?.overlapController.signal);if(s.kind==="stop")return n.flatMap(c=>o.get(c)??[]).filter(m7.isText).map(c=>c.text).join("");let{update:a}=s;XR.isAgentMessage(a)?(i(a.messageId),a.content!==void 0&&o.set(a.messageId,a.content??[])):XR.isAgentMessageChunk(a)&&i(a.messageId).push(a.content)}}dispose(){for(let t of this.registrations.splice(0))t.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t:[t]}};function lPe(e,t){return e?typeof e=="function"?e(t):e.parse(t):t}function so(e,t,r){return{method:e,params:t,mapResponse:r}}function qc(e,t){return{method:e,params:t}}function uPe(e,t,r,n){e.onReceiveRequest(t.method,o=>lPe(t.params,o),async(o,i,s)=>{let a=await n(r(o,s,i.signal,i.id));await i.respond(t.mapResponse?t.mapResponse(a):a)})}function dPe(e,t,r,n){e.onReceiveNotification(t.method,o=>lPe(t.params,o),(o,i)=>n(r(o,i,i.signal)))}function Y1(e){let t=Object.create(null);for(let r of Object.values(e))t[r.method]=r;return t}var p0t={initialize:so(ct.initialize,tPe,nPe),loginAuth:so(ct.auth_login,z5,Bp),unstable_listProviders:so(ct.providers_list,L5),unstable_setProvider:so(ct.providers_set,F5,Bp),unstable_disableProvider:so(ct.providers_disable,j5,Bp),newSession:so(ct.session_new,W5),setSessionConfigOption:so(ct.session_set_config_option,X5),prompt:so(ct.session_prompt,e7,Bp),unstable_messageMcp:so(ct.mcp_message,ZR),listSessions:so(ct.session_list,V5),deleteSession:so(ct.session_delete,K5,Bp),unstable_forkSession:so(ct.session_fork,Z5),resumeSession:so(ct.session_resume,Q5),closeSession:so(ct.session_close,Y5,Bp),logoutAuth:so(ct.auth_logout,U5,Bp),unstable_startNes:so(ct.nes_start,t7),unstable_suggestNes:so(ct.nes_suggest,r7),unstable_closeNes:so(ct.nes_close,n7,Bp)},f0t={cancelSession:qc(ct.session_cancel,s7),unstable_messageMcp:qc(ct.mcp_message,YR),unstable_didOpenDocument:qc(ct.document_did_open,a7),unstable_didChangeDocument:qc(ct.document_did_change,c7),unstable_didCloseDocument:qc(ct.document_did_close,l7),unstable_didSaveDocument:qc(ct.document_did_save,u7),unstable_didFocusDocument:qc(ct.document_did_focus,d7),unstable_acceptNes:qc(ct.nes_accept,p7),unstable_rejectNes:qc(ct.nes_reject,f7)},m0t={requestPermission:so(vi.session_request_permission,W8),unstable_connectMcp:so(vi.mcp_connect,r5),unstable_messageMcp:so(vi.mcp_message,ZR),unstable_disconnectMcp:so(vi.mcp_disconnect,n5,Bp),unstable_createElicitation:so(vi.elicitation_create,t5)},h0t={sessionUpdate:qc(vi.session_update,H1),unstable_messageMcp:qc(vi.mcp_message,YR),unstable_completeElicitation:qc(vi.elicitation_complete,N5)},eT=Y1(p0t),Z1=Y1(f0t),tT=Y1(m0t),J1=Y1(h0t);function g0t(e,t,r,n){return{params:e,requestId:n,signal:r,client:t}}function y0t(e,t,r){return{params:e,signal:r,client:t}}function b0t(e,t,r,n){return{params:e,requestId:n,signal:r,agent:t}}function x0t(e,t,r){return{params:e,signal:r,agent:t}}var S7=class{activeSessions=new Map;handleMessage(t){if(t.kind!=="notification"||t.method!==vi.session_update)return Mc.no(t);let r=H1.parse(t.params),{update:n}=r,o=XR.isStateUpdate(n)&&h7.isIdle(n),i=this.activeSessions.get(r.sessionId);if(i&&i.size>0)for(let s of i)o&&s.isAwaitingPromptCompletion()?(s.completePrompt(),s.enqueue({kind:"stop",notification:r,update:n,stopReason:n.stopReason})):s.enqueue({kind:"session_update",notification:r,update:n});return Mc.no(t)}attach(t,r){let n=this.activeSessions.get(t.sessionId)??new Set;return n.add(r),this.activeSessions.set(t.sessionId,n),new $p(()=>{n.delete(r),n.size===0&&this.activeSessions.delete(t.sessionId)})}},QCe=new WeakMap;function pPe(e){let t=QCe.get(e);return t||(t=new S7,QCe.set(e,t)),t}function X1(e,t){for(let r of t){let n;try{n=r(e)}catch(o){throw e.close(o),o}Promise.resolve(n).catch(o=>{e.close(o)})}}var Q1=Symbol("appBuilder"),G1=Symbol("runAgentConnectHandlers"),B1=Symbol("runClientConnectHandlers");var YCe=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name)}[Q1](){return this.builder}[G1](t){X1(t,this.connectHandlers)}connect(t,r={}){return this.connectConnection(t,r).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.client))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return Wp(t,eT,"request"),this.request({method:t,params:r},n);let o=eT[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return Wp(t,Z1,"notification",!0),this.notification({method:t,params:r},n);let o=Z1[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return uPe(this.builder,t,(n,o,i,s)=>g0t(n,rT.create(o,s),i,s),r),this}notification(t,r){return dPe(this.builder,t,(n,o,i)=>y0t(n,rT.create(o),i),r),this}connectConnection(t,r={}){if(oPe(t)){let c=this.openStreamConnection(t);return r.deferConnectHandlers||this[G1](c.connection),c}let[n,o]=iPe(),i=t[Q1]().connect(o),s=cPe(i),a=this.openStreamConnection(n);a.rawConnection.closed.then(()=>s.close()),i.closed.then(()=>a.connection.close());try{t[B1](s),this[G1](a.connection)}catch(c){throw s.close(c),a.connection.close(c),c}return a}openStreamConnection(t){let r=this.builder.connect(t);return{rawConnection:r,connection:aPe(r,this.connectHandlers)}}};var XCe=class{builder=Mp.builder();connectHandlers=[];constructor(t={}){t.name&&this.builder.name(t.name),this.builder.withHandler({handleMessage:(r,n)=>pPe(n).handleMessage(r),describe:()=>"client-session-update-router"})}[Q1](){return this.builder}[B1](t){X1(t,this.connectHandlers)}connect(t){return this.connectConnection(t).connection}connectWith(t,r){let{rawConnection:n,connection:o}=this.connectConnection(t);return n.runUntil(()=>r(o.agent))}onConnect(t){return this.connectHandlers.push(t),this}onRequest(t,r,n){if(n)return Wp(t,tT,"request"),this.request({method:t,params:r},n);let o=tT[t];if(!o)throw new Error(`Unknown ACP request method '${t}'. Pass a params parser for custom methods.`);return this.request(o,r)}onNotification(t,r,n){if(n)return Wp(t,J1,"notification",!0),this.notification({method:t,params:r},n);let o=J1[t];if(!o)throw new Error(`Unknown ACP notification method '${t}'. Pass a params parser for custom methods.`);return this.notification(o,r)}request(t,r){return uPe(this.builder,t,(n,o,i,s)=>b0t(n,nT.create(o,s),i,s),r),this}notification(t,r){return dPe(this.builder,t,(n,o,i)=>x0t(n,nT.create(o),i),r),this}connectConnection(t){if(oPe(t)){let a=this.openStreamConnection(t);return this[B1](a.connection),a}let[r,n]=iPe(),o=t[Q1]().connect(n),i=aPe(o),s=this.openStreamConnection(r);s.rawConnection.closed.then(()=>i.close()),o.closed.then(()=>s.connection.close());try{t[G1](i),this[B1](s.connection)}catch(a){throw i.close(a),s.connection.close(a),a}return s}openStreamConnection(t){let r=this.builder.connect(t);return{rawConnection:r,connection:cPe(r,this.connectHandlers)}}};var fPe=1;var mPe=["GET","HEAD","POST","PATCH","PUT","DELETE"];var Ms={hostState:"_redskills/host_state",hostBudgets:"_redskills/host_budgets",projectDrain:"_redskills/project_drain",projectStop:"_redskills/project_stop",projectStatus:"_redskills/project_status",projectBudget:"_redskills/project_budget",githubRead:"_redskills/github_read",githubRequest:"_redskills/github_request",githubWrite:"_redskills/github_write",githubUpdate:"_redskills/github_update",githubCustodyHandoff:"_redskills/github_custody_handoff",publish:"_redskills/publish",land:"_redskills/land",workerBudgetGrace:"_redskills/worker_budget_grace",goDispatch:"_redskills/go_dispatch",worktreeAdd:"_redskills/worktree_add",worktreeList:"_redskills/worktree_list",metrics:"_redskills/metrics",brainCall:"_redskills/brain_call",memoryCall:"_redskills/memory_call"},Vvr=Object.values(Ms);var k0t=16e3,_0t={type:"object",additionalProperties:!1,required:["demand"],properties:{demand:{type:"string",minLength:1,maxLength:k0t,description:"The one-off demand this dispatch exists to satisfy."}}},w0t={type:"object",additionalProperties:!1,required:["version","worker_id","ticket","lane"],properties:{version:{const:1},worker_id:{type:"string",minLength:1},ticket:{type:"integer",minimum:1},lane:{type:"string",minLength:1},session_id:{type:"string",minLength:1}}},Qvr={version:1,method:Ms.goDispatch,params:_0t,answer:w0t};var v0t=64,hPe=200,E0t=/^[a-z0-9][a-z0-9._-]*$/;var R0t={type:"object",additionalProperties:!1,required:["slug"],properties:{slug:{type:"string",minLength:1,maxLength:v0t,pattern:E0t.source,description:"What the human is about to work on; becomes the worktree directory name."},branch:{type:"string",minLength:1,maxLength:hPe,description:"Branch to create; defaults to the daemon's convention for the slug."},base:{type:"string",minLength:1,maxLength:hPe,description:"Trunk BRANCH to fork from; the remote is the Project's registered trunk remote."}}},T0t={type:"object",additionalProperties:!1,required:["version","kind","path","branch","base","lane","project_label"],properties:{version:{const:1},kind:{const:"interactive"},path:{type:"string",minLength:1},branch:{type:"string",minLength:1},base:{type:"string",minLength:1},lane:{type:"string",minLength:1},project_label:{type:"string",minLength:1}}},C0t={type:"object",additionalProperties:!1,required:["version","project_label","worktrees"],properties:{version:{const:1},project_label:{type:"string",minLength:1},worktrees:{type:"array",items:{type:"object",additionalProperties:!1,required:["kind","path","branch"],properties:{kind:{enum:["checkout","interactive","worker","unregistered"]},path:{type:"string",minLength:1},branch:{type:["string","null"]},lane:{type:"string",minLength:1},worker_id:{type:"string",minLength:1}}}}}},dEr={version:1,methods:{add:Ms.worktreeAdd,list:Ms.worktreeList},add:{params:R0t,answer:T0t},list:{answer:C0t}};oT();var N0t={drain:Ms.projectDrain,stop:Ms.projectStop,status:Ms.projectStatus};async function w7(e={}){let t=e.cwd??process.cwd(),r=e.name??"RedSkills Project client",n=e.version??"1",o=e.paths??eN();await GR(o);let i=(await ib(o)).paths,s=await j0t(i.acpSocketPath),a=[],c="",l=Bve({name:r}).onNotification(th.client.session.update,async({params:f})=>{f.sessionId===c&&(a.push(f.update),await e.onUpdate?.(f.update))});e.requestPermission!=null&&(l=l.onRequest(th.client.session.requestPermission,({params:f})=>e.requestPermission(f)));let u=l.connect(y9(D0t.toWeb(s),M0t.toWeb(s)));return await u.agent.request(th.agent.initialize,{protocolVersion:1,clientCapabilities:{},clientInfo:{name:r,version:n},_meta:{redskills:{wireMajor:fPe}}}),c=(await u.agent.request(th.agent.session.new,{cwd:t,mcpServers:[]})).sessionId,{control:async(f,m={})=>{let b=await u.agent.request(N0t[f],{...m.target==null?{}:{target:m.target},...m.runner==null?{}:{runner:m.runner},...m.registration==null?{}:{registration:m.registration}});if(!_Pe(b))throw new Error("redskilled returned an invalid Project control outcome");if(f==="status"&&!L0t(b))throw new Error("redskilled returned Project status without a valid RedSkills context");return b},github(f){return u.agent.request(Ms.githubRequest,{request:f})},brain(f){return u.agent.request(Ms.brainCall,{tool:f.tool,arguments:f.arguments})},memory(f){return u.agent.request(Ms.memoryCall,{tool:f.tool,arguments:f.arguments,...f.mode==null?{}:{mode:f.mode}})},async prompt(f){let m=a.length,b=await u.agent.request(th.agent.session.prompt,{sessionId:c,prompt:[{type:"text",text:f}]});return{stopReason:b.stopReason,...z0t(b._meta),updates:a.slice(m)}},cancel(){return u.agent.notify(th.agent.session.cancel,{sessionId:c})},async permission(f){return e.requestPermission==null?{outcome:{outcome:"cancelled"},_meta:{redskills:{permissionResolution:"hitl-required"}}}:await e.requestPermission(f)},close(){u.close(),s.destroy()}}}function z0t(e){let r=Kp(Kp(e)?.redskills)?.projectControl;return _Pe(r)?{projectControl:r}:{}}function _Pe(e){let t=Kp(e);return t?.version===1&&typeof t.project_id=="string"&&typeof t.revision=="number"&&Array.isArray(t.updates)}function L0t(e){let t=Kp(Kp(e)?.context),r=Kp(t?.queue),n=Kp(t?.workers),o=Kp(t?.adapter_health);return t?.version===1&&typeof t.observed_at=="string"&&typeof r?.posture=="string"&&(r.depth===null||typeof r.depth=="number")&&(r.target===null||typeof r.target=="number")&&typeof r.live=="number"&&(r.wanted===null||typeof r.wanted=="number")&&(r.observed_at===null||typeof r.observed_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&(r.freshness==="fresh"||r.freshness==="stale"||r.freshness==="unknown")&&typeof r.detail=="string"&&n?.freshness==="fresh"&&typeof n.observed_at=="string"&&typeof n.total=="number"&&Array.isArray(n.items)&&n.items.every(F0t)&&(o?.status==="healthy"||o?.status==="degraded"||o?.status==="unknown")&&(o.checked_at===null||typeof o.checked_at=="string")&&(o.last_success_at===null||typeof o.last_success_at=="string")&&(o.last_failure_at===null||typeof o.last_failure_at=="string")&&typeof o.detail=="string"}function F0t(e){let t=Kp(e);return typeof t?.worker_id=="string"&&t.state==="running"&&typeof t.started_at=="string"&&typeof t.isolated=="boolean"&&Array.isArray(t.warnings)&&t.warnings.every(r=>typeof r=="string")&&(t.base_commits_ahead===null||typeof t.base_commits_ahead=="number")}function Kp(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async function j0t(e){return await new Promise((t,r)=>{let n=$0t(e);n.once("connect",()=>t(n)),n.once("error",r)})}aee();md();tre();$_();md();var qz=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(s){if(i.some(u=>u.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 u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Mb,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},bh,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};rre();var Wz=class extends F_{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map($T.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 ow,this.setRequestHandler(XY,n=>this._oninitialize(n)),this.setNotificationHandler(tX,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(xX,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=$T.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new qz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=cz(this._capabilities,t)}setRequestHandler(t,r){let o=pd(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(ba(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 u=Ns(L_,c);if(!u.success){let b=u.error instanceof Error?u.error.message:String(u.error);throw new ze(qe.InvalidParams,`Invalid tools/call request: ${b}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let b=Ns(tf,f);if(!b.success){let S=b.error instanceof Error?b.error.message:String(b.error);throw new ze(qe.InvalidParams,`Invalid task creation result: ${S}`)}return b.data}let m=Ns(fd,f);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new ze(qe.InvalidParams,`Invalid tools/call result: ${b}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Bz(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Gz(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:DN.includes(r)?r:vT,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"},ef)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(l=>l.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(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(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},MT,r):this.request({method:"sampling/createMessage",params:t},Mb,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},bh,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},bh,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new ze(qe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof ze?s:new ze(qe.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},wX,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};$_();see();md();var $De=Symbol.for("mcp.completable");function nre(e){return!!e&&typeof e=="object"&&$De in e}function MDe(e){return e[$De]?.complete}var ODe;(function(e){e.Completable="McpCompletable"})(ODe||(ODe={}));var O1t=/^[A-Za-z0-9._-]{1,128}$/;function $1t(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!O1t.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function M1t(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ore(e){let t=$1t(e);return M1t(e,t.warnings),t.isValid}var Vz=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};dC();var iw=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Wz(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Vz(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Ph(JN)),this.server.assertCanSetRequestHandler(Ph(L_)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(JN,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=O_(r.inputSchema);return o?nee(o,{strictUnions:!0,pipeStrategy:"input"}):D1t})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=O_(r.outputSchema);o&&(n.outputSchema=nee(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(L_,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new ze(qe.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new ze(qe.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new ze(qe.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new ze(qe.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof ze&&n.code===qe.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=O_(t.inputSchema)??t.inputSchema,s=await PN(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=IN(a);throw new ze(qe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new ze(qe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=O_(t.outputSchema),i=await PN(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=IN(s);throw new ze(qe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let d=await n.taskStore.getTask(c);if(!d)throw new ze(qe.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Ph(QN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(QN,async t=>{switch(t.params.ref.type){case"ref/prompt":return rOe(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return nOe(t),this.handleResourceCompletion(t,t.params.ref);default:throw new ze(qe.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new ze(qe.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ze(qe.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return pC;let i=pd(n.argsSchema)?.[t.params.argument.name];if(!nre(i))return pC;let s=MDe(i);if(!s)return pC;let a=await s(t.params.argument.value,t.params.context);return NDe(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return pC;throw new ze(qe.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return pC;let i=await o(t.params.argument.value,t.params.context);return NDe(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Ph(N_)),this.server.assertCanSetRequestHandler(Ph(VN)),this.server.assertCanSetRequestHandler(Ph(z_)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(N_,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(VN,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(z_,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new ze(qe.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 ze(qe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Ph(KN)),this.server.assertCanSetRequestHandler(Ph(ZN)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(KN,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?N1t(r.argsSchema):void 0}))})),this.server.setRequestHandler(ZN,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new ze(qe.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new ze(qe.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=O_(n.argsSchema),i=await PN(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=IN(c);throw new ze(qe.InvalidParams,`Invalid arguments for prompt ${t.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(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==t&&(delete this._registeredResourceTemplates[t],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[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:$b(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=$b(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let l=c instanceof ga?c._def?.innerType:c;return nre(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,l){ore(t);let u={title:r,description:n,inputSchema:DDe(o),outputSchema:DDe(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&ore(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=$b(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=$b(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(ire(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!ire(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 ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var D1t={type:"object",properties:{}};function zDe(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function LDe(e){return"_def"in e||"_zod"in e||zDe(e)}function ire(e){return typeof e!="object"||e===null||LDe(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(zDe)}function DDe(e){if(e){if(ire(e))return $b(e);if(!LDe(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function N1t(e){let t=pd(e);return t?Object.entries(t).map(([r,n])=>{let o=dAe(n),i=pAe(n);return{name:r,description:o,required:!i}}):[]}function Ph(e){let r=pd(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=AN(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function NDe(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var pC={completion:{values:[],hasMore:!1}};sre();import FDe from"node:process";var fC=class{constructor(t=FDe.stdin,r=FDe.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new sw,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Kz(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{resolve as E$}from"node:path";import{fileURLToPath as Cdt}from"node:url";ao();function jDe(e){return[{name:"claim_status",title:"Read AFK claim",description:"Return the parsed claim marker records and current holder for one issue (`issue`) or a batch (`issues`), keyed per issue.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimStatus(t)},{name:"claim_release",title:"Release AFK claim",description:"MUTATING: post a concede marker for every un-conceded claim holder so the issue (`issue`) or each issue in a batch (`issues`) becomes claimable again.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimRelease(t)}]}f_();function are(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function cre(e){return typeof e=="string"&&e.trim()!==""?e:null}function L1t(e){let t=are(e);if(t===null)return null;let r=are(t.demand);return cre(r?.refusal)??cre(t.latest_refusal)}function UDe(e){return{tool:"status",args:{scope:"project"},why:e}}function F1t(){return{tool:"status",args:{scope:"host"},why:"diagnose why the host daemon does not answer before changing registration"}}function j1t(e,t){let r=e.registration;return r.daemon_reachable?!r.held&&r.repair!==void 0&&r.repair!=="none"?p_():e.live_workers.length>0&&t===null?{tool:"status",args:{scope:"worker"},why:"observe the Workers already draining this project's queue"}:UDe(t!==null?"observe when the daemon's refusal clears and capacity begins draining again":"observe the next socket-local queue poll and Worker birth"):F1t()}function U1t(e){let t=e.registration;if(!t.daemon_reachable)return"daemon unreachable: this project cannot read or change its host registration";if(!t.held)return"unregistered: the daemon is reachable but holds no registration for this project";let r=t.last_poll?.depth,n=r==null?"an unknown queue":`${r} queued`;return`draining: ${e.slots.busy} of ${e.slots.total} Worker slots are busy with ${n}`}function H1t(e){return[{intent:"choose the capability that matches your intent",tools:e.filter(t=>!t.description.startsWith("DEPRECATED:")).map(({name:t,title:r})=>({name:t,title:r}))}]}function HDe(e,t){return[{name:"help",title:"Find the next redskilled action",description:"Read live daemon, registration, queue, Worker, and refusal state; return the pasteable next call and a generated intent map. Makes no GitHub request.",inputSchema:{},invoke:async()=>{let[r,n]=await Promise.all([e.projectStatus(),e.hostState().catch(()=>null)]),o=U1t(r),i=L1t(n),s=j1t(r,i),a=ma({state:`you are ${o}`,repair:s});if(a.repair==="none")throw new Error("help produced no callable next action");return{here:o,state:{daemon:{reachable:r.registration.daemon_reachable,version:cre(are(n)?.daemon_version)??""},registration:{held:r.registration.held,project:r.registration.project,renewal:r.registration.renewal,target:r.registration.target},queue:r.registration.last_poll==null?null:{at:r.registration.last_poll.at,outcome:r.registration.last_poll.outcome,depth:r.registration.last_poll.depth,detail:r.registration.last_poll.detail},workers:{busy:r.slots.busy,free:r.slots.free,live:r.live_workers.length,target:r.slots.total},validation_schedule:r.validation_schedule,last_refusal:i,warnings:r.warnings??[]},guidance:a.prose,next:a.repair,intent_map:H1t(t())}}}]}ao();function qDe(e){return[{name:"merge_arm",title:"Arm PR for the merge driver",description:"MUTATING: hand one open PR to a live project merge-driver process \u2014 it owns the PR to a terminal state (update-branch when BEHIND, merge-commit once green at head, bounded retries, needs-medic/needs-human classification) without GitHub native auto-merge. Refuses when the merge-driver process is missing so custody cannot become orphaned.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeArm({pr:t})},{name:"merge_status",title:"Read merge driver state",description:"Return whether the merge-driver process is ticking plus durable per-PR records: armed records labeled driver-ticking or orphaned, attempts, last observed state, and terminal classifications.",inputSchema:{},invoke:()=>e.mergeStatus()},{name:"merge_release",title:"Release PR from the merge driver",description:"MUTATING: stop driver ownership of one PR. The record is kept as released for observability.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeRelease({pr:t})}]}ao();var q1t=["requeue","retake","park","close"];function GDe(e){return[{name:"hitl_resolve",title:"Resolve parked issue with a human decision",description:"MUTATING: encode one human decision on a parked issue atomically \u2014 requeue (concede dangling claims, strip park labels, ready-for-agent), retake (route to the no-agent landing lane), park (keep ready-for-human, record why), or close. The rationale is posted as an issue comment for the audit trail.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(q1t),rationale:w.string().min(1)},invoke:t=>e.hitlResolve(t)}]}ao();var Zz="2.0.0";function Jz(e,t){return{version:Zz,schema:e,projection:t}}var ZAr=w.object({age_s:w.number(),stale:w.boolean(),stale_after_s:w.number(),reason:w.enum(["fresh","aged-out","never-observed","orphaned"])}),G1t=w.object({version:w.string(),source:w.enum(["registry","recorded","installed-plugin","bundle-cache","unresolved"]),age_ms:w.number(),stale_after_ms:w.number(),stale:w.boolean(),reason:w.enum(["fresh","aged-out","installed-only","cache-only","never-observed"])}),B1t=w.object({tool:w.string().min(1),args:w.record(w.string(),w.unknown()),why:w.string().min(1)}),W1t=w.union([B1t,w.literal("none")]),V1t=w.object({held:w.boolean(),daemon_reachable:w.boolean(),project:w.string(),socket:w.string(),selector:w.string(),target:w.number(),renewal:w.enum(["renewing","self-renewing","running-on","unknown"]),renew_by:w.string(),renewals:w.number(),lapsed_at:w.string(),reason:w.string(),repair:W1t.optional(),repair_reason:w.string().min(1).optional(),launch_revision:w.number(),bundle_version:w.string(),plugin_cache_version:w.string(),last_poll:w.object({at:w.string(),outcome:w.string(),depth:w.number().nullable(),request_count:w.number(),detail:w.string()}).optional(),published_version:G1t.optional()}).superRefine((e,t)=>{!e.held&&e.repair===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair"],message:"an absent registration must carry a repair or an argued none"}),e.repair==="none"&&e.repair_reason===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair_reason"],message:"repair none must state why no callable cure is safe"})}),K1t=w.object({name:w.literal("project-birth-breaker"),project_label:w.string(),state:w.enum(["open","half-open"]),opened_at:w.string(),reason:w.string(),closes:w.string(),probe_worker_id:w.string().nullable(),repair:w.object({tool:w.literal("project_reset"),args:w.object({latch:w.literal("project-birth-breaker")}),why:w.string()})}),Z1t=w.object({narration:w.string(),moments:w.array(w.object({moment:w.enum(["iteration","post_done","landing"]),state:w.enum(["declared","skip"]),declared:w.boolean(),commands:w.array(w.string())})).length(3)}),mC=w.object({registration:V1t,validation_schedule:Z1t,birth_latch:K1t.nullable(),slots:w.object({busy:w.number(),free:w.number(),parked:w.number(),total:w.number(),interactive_reservation:w.number()}),live_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),unattributed_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),warnings:w.array(w.string()).optional()}),J1t=w.object({number:w.union([w.number(),w.string()]),runner:w.string(),retries:w.number(),phase:w.string(),iteration:w.union([w.number(),w.string()]),activity:w.string(),loc_added:w.number(),loc_removed:w.number(),last_commit_at:w.string(),tools_called_count:w.number(),text_chunk_count:w.number(),reasoning_events:w.number(),reasoning_tokens:w.number(),last_event_at:w.string(),waiting_count:w.number(),input_tokens:w.number(),output_tokens:w.number(),cost_usd:w.number()}),Q1t=w.object({status:w.enum(["alive","stalled","capped","unknown"]),laneFresh:w.boolean(),laneAgeMs:w.number().optional(),crossCheckArmed:w.boolean(),liveDescendants:w.boolean().optional(),reason:w.string()}),Y1t=w.object({verdict:w.enum(["alive","dead","unknown"]),anchor:w.enum(["daemon","none"]),project_label:w.string().nullable(),pid:w.number().nullable(),staleness:w.object({stale:w.boolean(),age_ms:w.number().nullable(),threshold_ms:w.number().nullable(),reason:w.string()})}),WDe=w.object({worker:w.object({id:w.string(),pid:w.number(),runner:w.string(),origin:w.string(),started_at:w.string(),done:w.number(),total:w.number(),blocked:w.number(),failed:w.number(),current:J1t}),live:w.boolean(),active:w.boolean(),renderable_live:w.boolean(),liveness:w.enum(["active","quiet-but-live","dead"]),liveness_verdict:Q1t,daemon_liveness:Y1t.optional()}),Qz=w.array(WDe),Yz=w.array(WDe.partial()),X1t=w.object({state:w.object({worker_id:w.string(),pid:w.number(),runner:w.string(),started_at:w.string(),total:w.number(),done:w.number(),blocked:w.number(),failed:w.number(),current:w.object({number:w.union([w.number(),w.string()]),title:w.string(),activity:w.string(),started_at:w.string()})}),live:w.boolean()}),hC=w.object({workers:w.array(X1t),events:w.array(w.object({event:w.string(),epoch:w.number()})),fleet:w.object({ts:w.string(),epoch:w.number(),runner:w.string(),readyForAgent:w.number(),slotsBusy:w.number(),slotsFree:w.number(),slotsTotal:w.number(),slotsParked:w.number(),interactiveReservation:w.number(),spawnsThisTick:w.number()}).nullable(),remoteQueue:w.number().optional(),remoteHuman:w.number().optional(),remoteCacheAgeS:w.number().optional()}),BDe=w.object({number:w.number(),title:w.string(),labels:w.array(w.string())}),VDe=w.object({ready_for_agent:w.object({eligible:w.array(BDe),held_for_summon:w.array(BDe)}),ready_for_human:w.array(w.object({number:w.number(),title:w.string(),labels:w.array(w.string()),body:w.string().optional(),createdAt:w.string().nullable().optional()})),counts:w.object({ready_for_agent_eligible:w.number(),ready_for_agent_held:w.number(),ready_for_human:w.number()}),degraded:w.boolean(),errors:w.array(w.object({kind:w.literal("trust-read"),number:w.number(),message:w.string()}))}),KDe=Jz(mC),JAr=Jz(Qz,{input:"fields",schema:Yz}),QAr=Jz(hC),ZDe=Jz(VDe);function eNt(e,t){let{projection:r}=e;if(!r)return e.schema;let n=t[r.input];return Array.isArray(n)&&n.length>0?r.schema:e.schema}function JDe(e){return e.map(t=>{let r=t.outputContract;if(!r)return t;let n=t.invoke.bind(t);return{...t,invoke:async o=>{let i=await n(o),s=eNt(r,o).safeParse(i);if(!s.success)throw new Error(`${t.name} output violates contract ${r.version}: ${s.error.issues.map(a=>`${a.path.join(".")||"<root>"}: ${a.message}`).join("; ")}`);return i}}})}ao();var QDe="named fleets were removed (ADR 0130): the host daemon owns the budget and each project has exactly one demand producer, so a fleet name addresses nothing. Drop the name \u2014 the work scope, the runner and the base branch now ride with the project's producer: pass `selector` / `runner` / `base` to the rs_dev `project_start` tool (status: `project_status`, resize: `project_resize`, stop: `project_stop`).",lre=class extends Error{constructor(t){super(t===void 0||t===""?QDe:`fleet ${JSON.stringify(t)}: ${QDe}`),this.name="FleetNamingRemovedError"}};function aw(e){if(!(e==null||e===""))throw new lre(typeof e=="string"?e:String(e))}ao();var tNt=w.object({tool:w.literal("status"),args:w.object({scope:w.enum(["worker","project","host"])})});function YDe(e){return w.object({deprecated:w.literal(!0),message:w.string().min(1),replacement:tNt,result:e})}function e1e(e){return{version:e.version,schema:YDe(e.schema),...e.projection===void 0?{}:{projection:{input:e.projection.input,schema:YDe(e.projection.schema)}}}}var rNt=w.object({status:w.unknown(),vitals:Qz,monitor:hC}),nNt=w.object({status:w.unknown(),vitals:Yz,monitor:hC}),XDe=w.object({state:w.unknown(),dashboard:w.unknown(),provision_check:w.unknown(),unit_status:w.unknown()}),oNt={version:Zz,schema:w.union([mC,rNt,XDe]),projection:{input:"fields",schema:w.union([mC,nNt,XDe])}};function t1e(e,t,r){return{deprecated:!0,message:`${e} is deprecated; use status { scope: ${t} }`,replacement:{tool:"status",args:{scope:t}},result:r}}async function iNt(e,t){if(t.scope==="project")return e.projectStatus();if(t.scope==="host"){let[s,a,c,l]=await Promise.all([e.hostState(),e.hostDashboard(),e.hostProvisionCheck(),e.hostUnitStatus()]);return{state:s,dashboard:a,provision_check:c,unit_status:l}}let r={worker:t.worker,live_only:t.live_only??!0,fields:t.fields},[n,o,i]=await Promise.all([e.workerStatus(r),e.workerVitals({live_only:r.live_only,fields:r.fields}),e.monitor()]);return{status:n,vitals:o,monitor:i}}function r1e(e){return[{name:"status",title:"Read redskilled status",description:"Answer the current worker, project, or host status through one intent-scoped read.",inputSchema:{scope:w.enum(["worker","project","host"]),worker:w.string().min(1).optional(),live_only:w.boolean().default(!0),fields:w.array(w.string().min(1)).optional()},outputContract:oNt,invoke:t=>iNt(e,t)}]}Xz();var eL={spec:w.number().int().positive().optional(),lane:w.string().min(1).optional(),label:w.string().min(1).optional(),issues:w.array(w.number().int().positive()).optional(),tags:w.array(w.string().min(1)).optional(),user:w.string().min(1).optional()};var i1e=w.record(w.string(),w.union([w.string(),w.number(),w.boolean()])),gC=w.string().optional().describe("REMOVED: naming a fleet is refused; a project has one producer.");function s1e(e){return[{name:"project_activation",title:"Preview this project's redskilled activation",description:"READ-ONLY: report whether this project opted into RedSkills and the canonical runner and target a no-argument drain would register.",inputSchema:{},invoke:()=>e.projectActivation()},{name:"project_status",title:"Deprecated project status alias",description:"DEPRECATED: use status { scope: project }. Returns the project answer and names its replacement.",inputSchema:{fleet:gC},outputContract:e1e(KDe),invoke:async({fleet:t})=>(aw(t),t1e("project_status","project",await e.projectStatus()))},{name:"drain",title:"Make this project drain",description:"MUTATING: ensure the daemon is reachable and this project is registered. Omitted runner and target resolve from this project's canonical RedSkills configuration; repeated calls report what was kept.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional()},invoke:async t=>e.drain(t)},{name:"project_start",title:"Start this project's workers",description:"MUTATING: register this project with the host daemon \u2014 a runner, a target width, and its work policy. Registers rather than launches: the project contributes a record, never a process of its own.",inputSchema:{runner:w.string().min(1),target:w.number().int().min(0).default(1),selector:w.object(eL).optional(),config:i1e.optional(),base:w.string().min(1).optional(),fleet:gC},invoke:async t=>(aw(t.fleet),e.projectStart(t))},{name:"project_resize",title:"Re-aim this project's workers",description:"MUTATING: change this project's target width, runner, or work policy and send the live directive.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional(),selector:w.object(eL).optional(),config:i1e.optional(),base:w.string().min(1).optional(),fleet:gC},invoke:async t=>(aw(t.fleet),e.projectResize(t))},{name:"project_reset",title:"Reset project execution latch",description:"MUTATING: clear a named in-memory latch for this project so autonomous demand may retry immediately.",inputSchema:{latch:w.literal("project-birth-breaker"),fleet:gC},invoke:async({latch:t,fleet:r})=>(aw(r),e.projectReset({latch:t}))},{name:"project_stop",title:"Stop this project's workers",description:"MUTATING: stop this project's work and give its registration back; force hard teardown explicitly.",inputSchema:{force:w.boolean().optional(),fleet:gC},invoke:async({force:t,fleet:r})=>(aw(r),e.projectStop({force:t}))}]}ao();function a1e(e){return[{name:"gate_run",title:"Run the AFK gate",description:"MUTATING: materialize the branch's feedback worktree and run the package-scoped validation gate against it.",dangerClass:"mutating",inputSchema:{branch:w.string().min(1),base:w.string().min(1).optional()},invoke:t=>e.gateRun(t)}]}function c1e(e){return[{name:"deadend_audit",title:"Audit AFK deadends",description:"Return the read-only deadend audit: dangling claims, red PRs with dead owners, superseded PRs, executable Tickets carrying an active Current blocker, dependency blocks whose req targets all closed, human-queue age outliers, and stale worktrees \u2014 each class paired with its recommended cure. Cache-backed: repeated calls within the refresh window cost zero GitHub quota.",inputSchema:{},invoke:()=>e.deadendAudit()}]}ao();function l1e(e){return[{name:"requeue",title:"Requeue AFK issue",description:"MUTATING: apply the complete parked-issue requeue transition and record human guidance.",inputSchema:{issue:w.number().int().positive(),guidance:w.string().min(1),repo:w.string().min(1).optional(),dryRun:w.boolean().optional(),adoptBranch:w.string().min(1).optional()},invoke:t=>e.requeue(t)},{name:"retake",title:"Recommend AFK retake",description:"Return the structured issue, PR, branch, worktree, worker-state, and recommended-next-action report.",inputSchema:{issue:w.number().int().positive(),repo:w.string().min(1).optional(),prLimit:w.number().int().positive().max(1e3).optional()},invoke:t=>e.retake(t)},{name:"reap",title:"Reap AFK branches",description:"MUTATING: classify and delete stale local and remote AFK branches.",inputSchema:{},invoke:()=>e.reap()},{name:"unblock_sweep",title:"Sweep dependency blocks",description:"MUTATING: promote dependency-blocked issues whose requirements are all closed.",inputSchema:{},invoke:()=>e.unblockSweep()}]}ao();function u1e(e){return[{name:"land_branch",title:"Land AFK branch",description:"MUTATING: land one validated worker branch into its base through the complete landing sequence.",dangerClass:"mutating",inputSchema:{issue:w.number().int().positive(),branch:w.string().min(1),base:w.string().min(1).optional(),title:w.string().min(1).optional(),openPr:w.boolean().optional()},invoke:t=>e.landBranch(t)},{name:"cascade_status",title:"Read close cascade",description:"Return the dependents of one issue and which of them the close cascade would promote.",inputSchema:{issue:w.number().int().positive()},invoke:({issue:t})=>e.cascadeStatus({issue:t})}]}ao();function d1e(e){return[{name:"logs",title:"Read redskilled logs",description:"Return the newest CastleLaneRecord entries from one structured lane; bounded by `limit` (default 200, max 10 000). Pass `kind` to filter before the limit.",inputSchema:{lane:w.enum(["worker","supervisor","monitor","liveness"]),id:w.string().min(1),limit:w.number().int().positive().max(1e4).default(200),kind:w.string().optional()},invoke:t=>e.logs(t)},{name:"dashboard",title:"Build AFK dashboard",description:"Build the structured operational dashboard from GitHub and local state.",inputSchema:{periodDays:w.number().int().positive().default(30)},invoke:({periodDays:t})=>e.dashboard({periodDays:t})},{name:"history",title:"Read redskilled history",description:"Return structured AFK history records, newest records last.",inputSchema:{limit:w.number().int().positive().max(1e4).optional()},invoke:({limit:t})=>e.history({limit:t})},{name:"queue_status",title:"Read AFK queues",description:"Return ready-for-agent and ready-for-human queue candidates, retaining successful candidates and naming partial trust-read failures as a degraded result. Pass `selector` to preview the producer's scoped view of the ready queue (same facets as its work selector, e.g. tags/user).",inputSchema:{selector:w.object(eL).optional()},outputContract:ZDe,invoke:t=>e.queueStatus({selector:t.selector})},{name:"events_since",title:"Poll events since cursor",description:"Return AFK history events and Worker lane records after an opaque cursor, plus the next cursor. Omit cursor to get a fresh baseline cursor with no events. Unknown or expired cursors are refused with a re-baseline prompt.",inputSchema:{cursor:w.string().min(1).optional()},invoke:t=>e.eventsSince({cursor:t.cursor})}]}ao();function p1e(e){return[{name:"manager",title:"Route work through the Manager",description:"MUTATING: take one operator intent into the Manager \u2014 intake, route an effort to a skill, attach an artifact, read effort status, or export/import the checkpoint \u2014 and return the effort record it acted on.",inputSchema:{intent:w.string().min(1).optional(),action:w.enum(["intake","route","artifact","status","checkpoint"]).optional(),effort:w.string().min(1).optional(),skill:w.string().min(1).optional(),artifact:w.string().min(1).optional(),checkpoint:w.enum(["export","import"]).optional(),path:w.string().min(1).optional()},invoke:t=>e.manager(t)},{name:"red_doctor",title:"Diagnose this repository's RedSkills setup",description:"READ-ONLY: return every doctor finding for this repository \u2014 operational probes, host toolchain, lane and process census, executable acceptance, HUMAN-ONLY type declarations and disposable-lane hygiene \u2014 each paired with the route that repairs it. Applying a repair is the `/red-doctor` skill's own fix lane, never a side effect of the read.",inputSchema:{checks:w.array(w.string().min(1)).optional()},invoke:t=>e.redDoctor(t)},{name:"audit_skills",title:"Audit the shipped skills",description:"Return the ranked skill-audit scores for this repository's skill tree. Pass `mechanical_only` to score without the judge, which makes the read deterministic and free of agent cost.",inputSchema:{mechanical_only:w.boolean().optional(),runner:w.string().min(1).optional()},invoke:t=>e.auditSkills(t)},{name:"install_type_labels",title:"Install Wayfinder type labels",description:"MUTATING: create the Wayfinder ticket type labels on the tracker AND declare the HUMAN-ONLY ones in this project's configuration, in one act \u2014 the two are one protection with two halves, and installing only the labels leaves the repository looking protected while unblocked decision Tickets enter the autonomous queue (#3013).",inputSchema:{labels:w.array(w.string().min(1)).optional(),repo:w.string().min(1).optional(),dry_run:w.boolean().optional()},invoke:t=>e.installTypeLabels(t)},{name:"codex_statusline",title:"Inspect the Codex footer preference",description:"READ-ONLY: return the active Codex configuration's status-line inspection \u2014 the file read, the current preference, and the problem that keeps the RedSkills footer from rendering.",inputSchema:{config:w.string().min(1).optional()},invoke:t=>e.codexStatusline(t)},{name:"codex_monitor_agent",title:"Build the Codex monitor agent brief",description:"Return the read-only monitor brief a Codex sub-agent is spawned with: what to poll, how often, and the conditions under which it closes itself. It spawns nothing \u2014 the host's own spawn primitive does.",inputSchema:{project_root:w.string().min(1).optional(),mode:w.string().min(1).optional(),interval_seconds:w.number().int().positive().optional()},invoke:t=>e.codexMonitorAgent(t)},{name:"reconcile_engine",title:"Reconcile this project's engine delivery",description:"MUTATING: warm the published engine bundle into the stable cache path and re-point a standing registration at it in one operation, then return the version, the bundle path, and what happened to the registration.",inputSchema:{version:w.string().min(1).optional()},invoke:t=>e.reconcileEngine(t)}]}ao();function f1e(e){return[{name:"daily_review",title:"Build daily activity review",description:"Return the structured daily activity review report for the local window.",inputSchema:{},invoke:()=>e.dailyReview({})},{name:"weekly_review",title:"Build weekly activity review",description:"Return the structured weekly activity review report for the local window.",inputSchema:{},invoke:()=>e.weeklyReview({})},{name:"triage",title:"Apply triage decision",description:"MUTATING: apply the decided triage transition to one issue, gated by the per-repo trust policy.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(["ready-for-agent","needs-info","ready-for-human","wontfix"]),summon:w.boolean().optional(),repo:w.string().min(1).optional()},invoke:t=>e.triage(t)},{name:"respond",title:"Handle comment event",description:"MUTATING: parse a /dev comment summon, authorize the commenter, and route the advisory or mutation verb.",inputSchema:{body:w.string(),number:w.number().int().positive(),author:w.string().min(1).optional(),is_pr:w.boolean().optional(),runner:w.string().min(1).optional(),repo:w.string().min(1).optional()},invoke:t=>e.respond(t)}]}ao();ao();f_();function dre(e){let t=ma({state:e instanceof Error?e.message:String(e),repair:ob("the caller must choose one dispatch intent before retrying")});if(t.repair!=="none")throw new Error("invalid worker refusal repair");return{refused:!0,reason:t.prose,repair:t.repair,repair_reason:t.repair_reason}}var pre={issue:w.number().int().positive().optional(),demand:w.string().min(1).optional(),runner:w.string().min(1).optional(),mode:w.enum(["no-mistakes","direct-PR","local-only","scout"]).optional()};function fre(e){let t=e;if(t.issue===void 0==(t.demand===void 0))throw new Error("exactly one of issue or demand is required");if(t.mode==="scout"&&t.issue!==void 0)throw new Error("mode: scout is demand-only \u2014 combine scout with demand, not issue");if(t.issue!==void 0&&t.mode!==void 0)throw new Error("mode is only valid for demand dispatches");return t}function m1e(e){return[{name:"worker_dispatch",title:"Dispatch AFK worker",description:"MUTATING: run one tracked issue or mint and run one disposable demand through the AFK worker lifecycle.",inputSchema:pre,invoke:t=>{let r;try{r=fre(t)}catch(n){return Promise.resolve(dre(n))}return e.workerDispatch(r)}},{name:"worker_stop",title:"Stop AFK worker",description:"MUTATING: terminate one worker process tree.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!1})},{name:"worker_recycle",title:"Recycle AFK worker",description:"MUTATING: terminate one fleet worker so its supervisor can replace the slot.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!0})}]}function h1e(e){return[{name:"runner_list",title:"List AFK runners",description:"Return the canonical runner specification registry.",inputSchema:{},invoke:()=>e.runnerList()},{name:"runner_detect",title:"Detect AFK runner",description:"Resolve the runner selected by an explicit override or the current host environment.",inputSchema:{runner:w.string().min(1).optional()},invoke:({runner:t})=>e.runnerDetect({runner:t})},{name:"runner_steer",title:"Steer live AFK worker",description:"MUTATING: write a live-steer request into a running worker's next iteration.",inputSchema:{worker:w.string().min(1),text:w.string().min(1)},invoke:t=>e.runnerSteer(t)},{name:"steer_status",title:"Read steer status",description:"Return the live-steer status for a worker: none (no steer ever written), pending (written, not yet consumed), or consumed (consumed at a specific iteration).",inputSchema:{worker:w.string().min(1)},invoke:t=>e.steerStatus(t)},{name:"worker_request",title:"Dispatch worker with request",description:"MUTATING: dispatch a new worker and inject a special request into its spawn-time handoff.",inputSchema:{...pre,text:w.string().min(1)},invoke:t=>{let r;try{r=fre(t)}catch(n){return Promise.resolve(dre(n))}return e.workerRequest({...r,text:t.text})}}]}function g1e(e){return[{name:"statusline_aggregate",title:"Read statusline aggregate",description:"Return the project-side statusline aggregate (project, repo counters, docs drift, drain, Worker rows, aggregated AFK block, queue) as structured data, using the same collector cores and cache discipline as the command-backed statusLine. Host-side fields (session model/effort, context %, usage quotas) are out of scope.",inputSchema:{},invoke:()=>e.statuslineAggregate()}]}ao();f_();function y1e(e,t,r={}){let n=e==="confirm"?ma({state:"dangerous tool requires explicit confirmation",repair:{tool:t,args:{...r,confirmation:!0},why:"retry the same operation with explicit confirmation"}}):ma({state:"dangerous tool is denied by the configured posture",repair:ob("the configured posture deliberately forbids this tool")});return{refused:!0,posture:e,action:t,reason:n.prose,repair:n.repair,...n.repair==="none"?{repair_reason:n.repair_reason}:{}}}function b1e(e,t){return t==="allow"?e:e.map(r=>{if(!r.dangerClass)return r;if(t==="deny")return{...r,invoke:async i=>y1e("deny",r.name)};let n={...r.inputSchema,confirmation:w.boolean().optional()},o=r.invoke.bind(r);return{...r,inputSchema:n,invoke:async i=>{if(i.confirmation!==!0)return y1e("confirm",r.name,i);let{confirmation:s,...a}=i;return o(a)}}})}ao();function x1e(e){return[{name:"wait_start",title:"Start rsp wait",description:"MUTATING: spawn a detached rsp wait (pr | run | release | cmd) and return its registry id.",inputSchema:{kind:w.enum(["pr","run","release","cmd"]),target:w.string().min(1),timeout_ms:w.number().int().positive().optional(),reason:w.string().optional()},invoke:t=>e.waitStart(t)},{name:"wait_list",title:"List active rsp waits",description:"Return the active-wait registry from .red/tmp/waits.",inputSchema:{},invoke:()=>e.waitList()},{name:"wait_status",title:"Read rsp wait status",description:"Return the registry entry for a running wait or the sealed result envelope for a finished one.",inputSchema:{id:w.string().min(1)},invoke:({id:t})=>e.waitStatus({id:t})}]}ao();function S1e(e){return[{name:"worktree_list",title:"List disposable worktrees",description:"Enumerate every checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{},invoke:()=>e.worktreeList()},{name:"worktree_remove",title:"Remove disposable worktree",description:"MUTATING: remove one checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{path:w.string().min(1)},invoke:({path:t})=>e.worktreeRemove({path:t})}]}var tL="Call the redskilled MCP's `help` tool.\nFollow its guidance and invoke the returned `next` call.",mre=[{name:"drain",title:"Drain this project's queue",description:"Find the next action for starting or continuing a project drain.",body:tL},{name:"diagnose",title:"Diagnose redskilled",description:"Find the next action for understanding a redskilled problem.",body:tL},{name:"configure",title:"Configure redskilled",description:"Find the next action for changing project execution configuration.",body:tL},{name:"stop",title:"Stop project work",description:"Find the next action for stopping project work safely.",body:tL}];var k1e="rs_dev";function _1e(e,t="allow"){let r=[],n=[...HDe(e,()=>r),...r1e(e),...s1e(e),...d1e(e),...c1e(e),...m1e(e),...h1e(e),...l1e(e),...a1e(e),...u1e(e),...jDe(e),...qDe(e),...GDe(e),...S1e(e),...x1e(e),...f1e(e),...g1e(e),...p1e(e)];return r=b1e(JDe(n),t),r}Yt();function cw(e){return tn(JSON.parse(JSON.stringify(e??null)),{objectArrayColumns:!0,primitiveArrayColumns:!0})}var sNt=new Map([["drain","drain"],["project_drain","drain"],["project_stop","stop"],["project_status","status"],["status","status"]]),aNt=new Set(["target","runner","scope","registration","live_only","fields","worker"]);async function w1e(e,t,r){let n=sNt.get(t);if(n!=null){let o=Object.keys(r).filter(i=>!aNt.has(i));if(o.length>0)throw new Error(`the Project control surface cannot express ${JSON.stringify(o.sort())} for ${JSON.stringify(t)}`);return n==="status"?await e.control("status"):await e.control(n,cNt(r))}if(!uNt(t))throw new Error(`unsupported ACP Project capability ${JSON.stringify(t)}`);return await e.prompt(lNt(t,r))}function cNt(e){let t=e.target,r=e.runner,n=e.registration;return{...typeof t=="number"&&Number.isInteger(t)&&t>=0?{target:t}:{},...typeof r=="string"&&r.length>0?{runner:r}:{},...n!=null&&typeof n=="object"&&!Array.isArray(n)?{registration:n}:{}}}function lNt(e,t){return`/${e} ${JSON.stringify(t)}`}function uNt(e){return/^[a-z][a-z0-9_]*$/.test(e)&&!e.startsWith("private_")&&!e.includes("worker_birth")&&!e.includes("daemon_protocol")&&!e.includes("github_client")}xre();Xz();import{execFileSync as INt}from"node:child_process";kR();Sd();function Q1e(e){let t=X1e(e.repo).join("/"),r=e.selector??{},n=[`repo:${t}`,"is:issue","is:open",oL(e.readyLabel??su)];r.lane!=null&&r.lane!==""&&n.push(oL(`lane:${r.lane}`)),r.label!=null&&r.label!==""&&n.push(oL(r.label));for(let o of r.tags??[])o!==""&&n.push(oL(`${kre}${o}`));return r.user!=null&&r.user!==""&&r.user!=="@me"&&n.push(`author:${r.user}`),n.join(" ")}function Y1e(e){let[t,r]=X1e(e.repo),n=e.selector??{},o=e.readyLabel??su,i=[o];n.lane!=null&&n.lane!==""&&i.push(`lane:${n.lane}`),n.label!=null&&n.label!==""&&i.push(n.label);for(let a of n.tags??[])a!==""&&i.push(`${kre}${a}`);let s=n.user!=null&&n.user!==""&&n.user!=="@me"?n.user:void 0;return{owner:t,repo:r,labels:i,...s===void 0?{}:{creator:s},counter_labels:{ready:o,human:Ih}}}function oL(e){return`label:${JSON.stringify(e)}`}function X1e(e){let t=e.trim().split("/");if(t.length!==2||t[0]===""||t[1]==="")throw new Error("a registration needs the repository its queue lives in: the daemon polls the string it is handed and cannot work out which tracker a checkout belongs to");return[t[0],t[1]]}var PNt="Work issue #{{work_item}} in this repository to a merged pull request, following the /afk skill: claim it, implement it in this workspace, run the gate, open the PR, and land it. You are already standing in your own dedicated worktree on the Ticket's base branch: work and commit right here, and never create another worktree \u2014 the repository's worktree lanes govern interactive sessions, not Workers. If you cannot claim it or the work is blocked, say so plainly and stop.";function eNe(e){let t={repo:e.repo,...e.selector==null?{}:{selector:e.selector},...e.readyLabel==null?{}:{readyLabel:e.readyLabel}};return{selector:Q1e(t),queue_poll:Y1e(t),argv:zp("red-skills-redskilled",["acp-worker",...e.runner==null?[]:["--child-agent",e.runner]],e.version).split(" "),workspace_path:e.workspacePath,trunk:{remote:"origin",branch:e.trunkBranch??"main"},prompt:PNt,target:e.target}}function rNe(e,t,r={},n=bre){let o=ANt(e,n);if(o==null)return;let i=typeof r.target=="number"&&Number.isInteger(r.target)&&r.target>=0?r.target:1,s=typeof r.runner=="string"&&r.runner.length>0?r.runner:void 0;return eNe({repo:o,workspacePath:e,target:i,version:t,...s==null?{}:{runner:s},...tNe(e)==null?{}:{trunkBranch:tNe(e)}})}function tNe(e){try{let r=INt("git",["-C",e,"symbolic-ref","refs/remotes/origin/HEAD"],{encoding:"utf8",timeout:5e3}).trim().split("/").pop();return r==null||r===""?void 0:r}catch{return}}function ANt(e,t=bre){let r;try{r=t(e).name}catch{return}return/^[^/\s]+\/[^/\s]+$/.test(r)?r:void 0}md();var lw="redskilled://lanes/events",ONt=1e3;function nNe(e,t,r={}){let n=r.bufferLimit??ONt,o=[],i=0,s,a=c=>{o.push(c.record),o.length>n&&o.splice(0,o.length-n),e.sendResourceUpdated({uri:lw})};return e.registerCapabilities({resources:{subscribe:!0}}),e.setRequestHandler(N_,()=>({resources:[{uri:lw,name:"Redskilled lane events",description:"Subscribe to receive AFK lane records (Worker landings, deaths, lost claims, supervisor halts) appended after subscription. Payloads are byte-compatible with the `logs` tool's CastleLaneRecord shape.",mimeType:"application/toon"}]})),e.setRequestHandler(z_,c=>{let l=Ere(c);if(l!==lw)throw new Error(`unknown resource ${JSON.stringify(l)}`);let u=o.splice(0,o.length);return{contents:[{uri:lw,mimeType:"application/toon",text:cw({events:u})}]}}),e.setRequestHandler(cX,async c=>Ere(c)!==lw?{}:(i+=1,i===1&&(s=await t.subscribe(a),t.start(r.intervalMs)),{})),e.setRequestHandler(lX,c=>Ere(c)!==lw?{}:(i>0&&(i-=1),i===0&&(s?.(),s=void 0,t.stop()),{})),{poll:()=>t.poll(),stop:()=>{s?.(),s=void 0,t.stop()}}}function Ere(e){let t=e?.params;return typeof t?.uri=="string"?t.uri:""}function iNe(e){let t=new Set,r,n,o=async()=>{let s=await e("events_since",r===void 0?{}:{cursor:r});if(!oNe(s)||typeof s.cursor!="string")throw new Error("redskilled ACP returned an invalid events_since envelope");let a=Array.isArray(s.lane_records)?s.lane_records.filter(oNe):[];return{cursor:s.cursor,lane_records:a}},i={async subscribe(s){return r===void 0&&(r=(await o()).cursor),t.add(s),()=>t.delete(s)},async poll(){if(t.size===0)return 0;let s=await o();r=s.cursor;for(let a of s.lane_records)for(let c of t)c({path:"redskilled-acp",record:a});return s.lane_records.length},start(s=1e3){n===void 0&&(n=setInterval(()=>void i.poll().catch(()=>{}),s),n.unref())},stop(){n!==void 0&&clearInterval(n),n=void 0,t.clear()}};return i}function oNe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}ao();var Rre="rs_github",sNe="github_request",iL=Ms.githubRequest;function Tre(){return[{name:sNe,title:"Request the Project's forge",description:"MUTATING: forward one REST request to the Project's GitHub gateway. An observing method (GET, HEAD) is served from the daemon's Project cache and carries the age of what it served; concurrent identical reads share one upstream call. A mutating method is scheduled through the daemon's durable outbox and answers with its publication receipt. Paths are repository-relative \u2014 `issues/17` \u2014 or the full `repos/<owner>/<repo>/\u2026` form of this Project's own repository; another repository is refused.",method:iL,inputSchema:{method:w.enum(mPe),path:w.string().min(1),body:w.record(w.unknown()).optional(),headers:w.record(w.string()).optional()}}]}function aNe(e){return{request:{method:e.method,path:e.path,...e.body===void 0?{}:{body:e.body},...e.headers===void 0?{}:{headers:e.headers}}}}function Cre(e){let t=new iw({name:Rre,version:e.version}),r=t.registerTool.bind(t);for(let n of e.tools??Tre())r(n.name,{title:n.title,description:n.description,inputSchema:n.inputSchema},async o=>({content:[{type:"text",text:cw(await e.invoke(n.method,aNe(o)))}]}));return t}var lk=KW("redskilled-mcp");function ulr(e=process.cwd(),t){let r=new iw({name:k1e,version:lk.version}),n=r.registerTool.bind(r),o=t??(async()=>{throw new Error("REDSKILLED_ACP_UNAVAILABLE: the stdio adapter has no ACP client")}),i={},s=(a,c)=>a==="drain"&&c.registration==null?{...c,registration:rNe(e,lk.version,c)}:c;for(let a of _1e(i))n(a.name,{title:a.title,description:a.description,inputSchema:a.inputSchema},async c=>({content:[{type:"text",text:cw(await o(a.name,s(a.name,c)))}]}));for(let a of mre)r.registerPrompt(a.name,{title:a.title,description:a.description},async()=>({messages:[{role:"user",content:{type:"text",text:a.body}}]}));return nNe(r.server,iNe(o)),r}async function Pdt(e,t=process.env,r=process.cwd()){let n=(t.RED_SKILLS_PROJECT_ROOT??t.CLAUDE_PROJECT_DIR??t.CODEX_PROJECT_DIR??t.OPENCODE_PROJECT_DIR??"").trim();if(n!=="")return E$(n);if(e.getClientCapabilities()?.roots!==void 0)try{let o=await e.listRoots();for(let i of o.roots)if(i.uri.startsWith("file:"))return E$(Cdt(i.uri))}catch{}return E$(r)}async function Idt(e){let t,r=new Promise(n=>{t=n});e.server.server.onclose=t,await e.server.connect(e.transport),await r}async function dlr(){let e=process.cwd(),t,r,n=()=>(t??=Pdt(r.server,process.env,e).then(i=>w7({cwd:i,name:"RedSkills GitHub MCP adapter",version:lk.version})),t);r=Cre({version:lk.version,invoke:async(i,s)=>{if(i!==iL)throw new Error(`rs_github: no daemon method ${JSON.stringify(i)}`);return(await n()).github(s.request)}});let o=()=>{r.close()};process.once("SIGINT",o),process.once("SIGTERM",o);try{await Idt({server:r,transport:new fC})}finally{if(t!==void 0)try{(await t).close()}catch{}process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o)}}async function plr(){let e=process.cwd(),t,r,n=()=>(t??=Pdt(r.server,process.env,e).then(i=>w7({cwd:i,name:"RedSkills MCP adapter",version:lk.version})),t);r=ulr(e,async(i,s)=>w1e(await n(),i,s));let o=()=>{r.close()};process.once("SIGINT",o),process.once("SIGTERM",o);try{await Idt({server:r,transport:new fC})}finally{if(t!==void 0)try{(await t).close()}catch{}process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o)}}var flr=`Usage: red-skills-redskilled-mcp [command]
441
441
 
442
442
  Commands:
443
443
  (none) serve the rs_dev MCP surface over stdio