holycodex 0.16.9-dev.108.1 → 0.16.9-dev.110.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,49 +1,49 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var b=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Lr(e,t=new WeakSet){if(t.has(e))return;t.add(e);for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);if(r&&"value"in r&&mg(r.value))Lr(r.value,t)}Object.freeze(e)}function mg(e){return typeof e==="object"&&e!==null}var uo="0.15",Tn="state-0.16";var PR=()=>{};function bs(e){return{ok:!0,value:e}}function Qi(e){return{ok:!1,error:e}}function rl(e,t){return new ut("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var ut;var _s=b(()=>{ut=class ut extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,Lr(this.details),Object.freeze(this)}}});function S(e,t,n,r,o,i,a,s,c){switch(arguments.length){case 1:return e;case 2:return t(e);case 3:return n(t(e));case 4:return r(n(t(e)));case 5:return o(r(n(t(e))));case 6:return i(o(r(n(t(e)))));case 7:return a(i(o(r(n(t(e))))));case 8:return s(a(i(o(r(n(t(e)))))));case 9:return c(s(a(i(o(r(n(t(e))))))));default:{let l=arguments[0];for(let u=1;u<arguments.length;u++)l=arguments[u](l);return l}}}var hg=(e)=>typeof e==="function",h=function(e,t){if(typeof e==="function")return function(){if(e(arguments))return t.apply(this,arguments);return(n)=>t(n,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(n,r){if(arguments.length>=2)return t(n,r);return function(o){return t(o,n)}};case 3:return function(n,r,o){if(arguments.length>=3)return t(n,r,o);return function(i){return t(i,n,r)}};case 4:return function(n,r,o,i){if(arguments.length>=4)return t(n,r,o,i);return function(a){return t(a,n,r,o)}};case 5:return function(n,r,o,i,a){if(arguments.length>=5)return t(n,r,o,i,a);return function(s){return t(s,n,r,o,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(r){return t(r,...n)}}}},we=(e)=>e,ol=(e)=>()=>e,il,Yo,Vd,al;var te=b(()=>{il=ol(!0),Yo=ol(!1),Vd=ol(void 0),al=Vd});var cl=(e)=>(t,n)=>t===n||e(t,n),RL=(e,t)=>e===t,TL=()=>RL,CL,gg,AR,MR=(e)=>cl((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0});var ll=b(()=>{te();CL=TL(),gg=h(2,(e,t)=>cl((n,r)=>e(t(n),t(r)))),AR=gg(CL,(e)=>e.getTime())});var ul,ne=(e,t)=>{if(!ul)globalThis["effect/GlobalValue"]??=new Map,ul=globalThis["effect/GlobalValue"];if(!ul.has(e))ul.set(e,t());return ul.get(e)};var $t=(e)=>typeof e==="string",Cn=(e)=>typeof e==="number",ea=(e)=>typeof e==="boolean",Zo=(e)=>typeof e==="bigint",ta=(e)=>typeof e==="symbol",Xo,NR=(e)=>e===void 0,FR=(e)=>!1,dl=(e)=>typeof e==="object"&&e!==null,rn=(e)=>dl(e)||Xo(e),H,pl,na=(e)=>e===null||e===void 0,LR=(e)=>e!==null&&e!==void 0,zd=(e)=>e instanceof Date,yg=(e)=>typeof e==="string"||H(e,Symbol.iterator),xg=(e)=>dl(e)&&!Array.isArray(e),DR=(e)=>H(e,"then")&&Xo(e.then);var ke=b(()=>{te();Xo=hg,H=h(2,(e,t)=>rn(e)&&(t in e)),pl=h(2,(e,t)=>H(e,"_tag")&&e._tag===t)});var ra=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class bg{_state;constructor(e,t,n,r){if(na(t)&&na(e))t=Math.random()*4294967295>>>0,e=0;else if(na(t))t=e,e=0;if(na(r)&&na(n))r=this._state?this._state[3]:EL,n=this._state?this._state[2]:OL;else if(na(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),qR(this._state,this._state[0],this._state[1],e>>>0,t>>>0),this._next(),this}getState(){return[this._state[0],this._state[1],this._state[2],this._state[3]]}setState(e){this._state[0]=e[0],this._state[1]=e[1],this._state[2]=e[2],this._state[3]=e[3]|1}integer(e){return Math.round(this.number()*Number.MAX_SAFE_INTEGER)%e}number(){let e=(this._next()&67108863)*1,t=(this._next()&134217727)*1;return(e*AL+t)/PL}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;ML(this._state,e,t,kL,IL),qR(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let n=e>>>18,r=(t>>>18|e<<14)>>>0;n=(n^e)>>>0,r=(r^t)>>>0;let o=(r>>>27|n<<5)>>>0,i=e>>>27,a=(-i>>>0&31)>>>0;return(o>>>i|o<<a)>>>0}}function ML(e,t,n,r,o){let i=(n>>>16)*(o&65535)>>>0,a=(n&65535)*(o>>>16)>>>0,s=(n&65535)*(o&65535)>>>0,c=(n>>>16)*(o>>>16)+((a>>>16)+(i>>>16))>>>0;if(a=a<<16>>>0,s=s+a>>>0,s>>>0<a>>>0)c=c+1>>>0;if(i=i<<16>>>0,s=s+i>>>0,s>>>0<i>>>0)c=c+1>>>0;c=c+Math.imul(n,r)>>>0,c=c+Math.imul(t,o)>>>0,e[0]=c,e[1]=s}function qR(e,t,n,r,o){let i=t+r>>>0,a=n+o>>>0;if(a>>>0<n>>>0)i=i+1|0;e[0]=i,e[1]=a}function _g(e){if(typeof e==="object"&&e!==null&&Sg in e)return e[Sg]();throw Error(ra("yieldWrapGet"))}var vs,OL=335903614,EL=4150755663,kL=1481765933,IL=1284865837,PL=9007199254740992,AL=134217728,Sg,po,mn,$R,NL,FL,Ut,jJ;var Qo=b(()=>{ke();vs=class vs{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new vs(this.self)}};Sg=Symbol.for("effect/Utils/YieldWrap");po=class po{#e;constructor(e){this.#e=e}[Sg](){return this.#e}};mn=ne("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),$R={effect_internal_function:(e)=>e()},NL={effect_internal_function:(e)=>{try{return e()}finally{}}},FL=$R.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,Ut=FL?$R.effect_internal_function:NL.effect_internal_function,jJ=function*(){}.constructor});var wg,G,U=(e)=>{if(mn.enabled===!0)return 0;switch(typeof e){case"number":return Jd(e);case"bigint":return Oe(e.toString(10));case"boolean":return Oe(String(e));case"symbol":return Oe(String(e));case"string":return Oe(e);case"undefined":return Oe("undefined");case"function":case"object":if(e===null)return Oe("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return Oe("Invalid Date");return U(e.toISOString())}else if(e instanceof URL)return U(e.href);else if(DL(e))return e[G]();else return fl(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},fl=(e)=>{if(!wg.has(e))wg.set(e,Jd(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return wg.get(e)},se=(e)=>(t)=>t*53^e,Kd=(e)=>e&3221225471|e>>>1&1073741824,DL=(e)=>H(e,G),Jd=(e)=>{if(e!==e||e===1/0)return 0;let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return Kd(t)},Oe=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Kd(t)},qL=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=S(Oe(t[r]),se(U(e[t[r]])));return Kd(n)},Gd=(e)=>qL(e,Object.keys(e)),On=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=S(t,se(U(e[n])));return Kd(t)},ge=function(){if(arguments.length===1){let n=arguments[0];return function(r){return Object.defineProperty(n,G,{value(){return r},enumerable:!1}),r}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,G,{value(){return t},enumerable:!1}),t};var Ke=b(()=>{te();ke();Qo();wg=ne(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),G=Symbol.for("effect/Hash")});function j(){if(arguments.length===1)return(e)=>Yd(e,arguments[0]);return Yd(arguments[0],arguments[1])}function Yd(e,t){if(e===t)return!0;let n=typeof e;if(n!==typeof t)return!1;if(n==="object"||n==="function"){if(e!==null&&t!==null){if(ml(e)&&ml(t))if(U(e)===U(t)&&e[z](t))return!0;else return mn.enabled&&mn.tester?mn.tester(e,t):!1;else if(e instanceof Date&&t instanceof Date){let r=e.getTime(),o=t.getTime();return r===o||Number.isNaN(r)&&Number.isNaN(o)}else if(e instanceof URL&&t instanceof URL)return e.href===t.href}if(mn.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>Yd(r,t[o]));if(Object.getPrototypeOf(e)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let r=Object.keys(e),o=Object.keys(t);if(r.length===o.length){for(let i of r)if(!((i in t)&&Yd(e[i],t[i])))return mn.tester?mn.tester(e,t):!1;return!0}}return mn.tester?mn.tester(e,t):!1}}return mn.enabled&&mn.tester?mn.tester(e,t):!1}var z,ml=(e)=>H(e,z),hl=()=>j;var ve=b(()=>{Ke();ke();Qo();z=Symbol.for("effect/Equal")});function $L(e){try{return e.toISOString()}catch{return"Invalid Date"}}function UL(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function gl(e){return $t(e)?JSON.stringify(e):String(e)}function Dr(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":Cn(n)?" ".repeat(n):n,i=(l)=>o.repeat(l),a=(l,u)=>{let d=l?.constructor;return d&&d!==Object.prototype.constructor&&d.name?`${d.name}(${u})`:u},s=(l)=>{try{return Reflect.ownKeys(l)}catch{return["[ownKeys threw]"]}};function c(l,u=0){if(Array.isArray(l)){if(r.has(l))return vg;if(r.add(l),!o||l.length<=1)return`[${l.map((p)=>c(p,u)).join(",")}]`;let d=l.map((p)=>c(p,u+1)).join(`,
3
+ var w=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function jr(e,t=new WeakSet){if(t.has(e))return;t.add(e);for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);if(r&&"value"in r&&Cg(r.value))jr(r.value,t)}Object.freeze(e)}function Cg(e){return typeof e==="object"&&e!==null}var yo="0.15",On="state-0.16";var DR=()=>{};function ks(e){return{ok:!0,value:e}}function da(e){return{ok:!1,error:e}}function ul(e,t){return new dt("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var dt;var Es=w(()=>{dt=class dt extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,jr(this.details),Object.freeze(this)}}});function b(e,t,n,r,o,i,a,s,c){switch(arguments.length){case 1:return e;case 2:return t(e);case 3:return n(t(e));case 4:return r(n(t(e)));case 5:return o(r(n(t(e))));case 6:return i(o(r(n(t(e)))));case 7:return a(i(o(r(n(t(e))))));case 8:return s(a(i(o(r(n(t(e)))))));case 9:return c(s(a(i(o(r(n(t(e))))))));default:{let l=arguments[0];for(let u=1;u<arguments.length;u++)l=arguments[u](l);return l}}}var Og=(e)=>typeof e==="function",h=function(e,t){if(typeof e==="function")return function(){if(e(arguments))return t.apply(this,arguments);return(n)=>t(n,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(n,r){if(arguments.length>=2)return t(n,r);return function(o){return t(o,n)}};case 3:return function(n,r,o){if(arguments.length>=3)return t(n,r,o);return function(i){return t(i,n,r)}};case 4:return function(n,r,o,i){if(arguments.length>=4)return t(n,r,o,i);return function(a){return t(a,n,r,o)}};case 5:return function(n,r,o,i,a){if(arguments.length>=5)return t(n,r,o,i,a);return function(s){return t(s,n,r,o,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(r){return t(r,...n)}}}},ve=(e)=>e,dl=(e)=>()=>e,pl,ci,rp,fl;var ne=w(()=>{pl=dl(!0),ci=dl(!1),rp=dl(void 0),fl=rp});var hl=(e)=>(t,n)=>t===n||e(t,n),AL=(e,t)=>e===t,ML=()=>AL,NL,kg,qR,UR=(e)=>hl((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0});var gl=w(()=>{ne();NL=ML(),kg=h(2,(e,t)=>hl((n,r)=>e(t(n),t(r)))),qR=kg(NL,(e)=>e.getTime())});var yl,re=(e,t)=>{if(!yl)globalThis["effect/GlobalValue"]??=new Map,yl=globalThis["effect/GlobalValue"];if(!yl.has(e))yl.set(e,t());return yl.get(e)};var Ut=(e)=>typeof e==="string",kn=(e)=>typeof e==="number",pa=(e)=>typeof e==="boolean",li=(e)=>typeof e==="bigint",fa=(e)=>typeof e==="symbol",ui,$R=(e)=>e===void 0,jR=(e)=>!1,xl=(e)=>typeof e==="object"&&e!==null,rn=(e)=>xl(e)||ui(e),H,Sl,ma=(e)=>e===null||e===void 0,HR=(e)=>e!==null&&e!==void 0,ip=(e)=>e instanceof Date,Eg=(e)=>typeof e==="string"||H(e,Symbol.iterator),Ig=(e)=>xl(e)&&!Array.isArray(e),BR=(e)=>H(e,"then")&&ui(e.then);var Ie=w(()=>{ne();ui=Og,H=h(2,(e,t)=>rn(e)&&(t in e)),Sl=h(2,(e,t)=>H(e,"_tag")&&e._tag===t)});var ha=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Ag{_state;constructor(e,t,n,r){if(ma(t)&&ma(e))t=Math.random()*4294967295>>>0,e=0;else if(ma(t))t=e,e=0;if(ma(r)&&ma(n))r=this._state?this._state[3]:LL,n=this._state?this._state[2]:FL;else if(ma(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),VR(this._state,this._state[0],this._state[1],e>>>0,t>>>0),this._next(),this}getState(){return[this._state[0],this._state[1],this._state[2],this._state[3]]}setState(e){this._state[0]=e[0],this._state[1]=e[1],this._state[2]=e[2],this._state[3]=e[3]|1}integer(e){return Math.round(this.number()*Number.MAX_SAFE_INTEGER)%e}number(){let e=(this._next()&67108863)*1,t=(this._next()&134217727)*1;return(e*$L+t)/UL}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;jL(this._state,e,t,DL,qL),VR(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let n=e>>>18,r=(t>>>18|e<<14)>>>0;n=(n^e)>>>0,r=(r^t)>>>0;let o=(r>>>27|n<<5)>>>0,i=e>>>27,a=(-i>>>0&31)>>>0;return(o>>>i|o<<a)>>>0}}function jL(e,t,n,r,o){let i=(n>>>16)*(o&65535)>>>0,a=(n&65535)*(o>>>16)>>>0,s=(n&65535)*(o&65535)>>>0,c=(n>>>16)*(o>>>16)+((a>>>16)+(i>>>16))>>>0;if(a=a<<16>>>0,s=s+a>>>0,s>>>0<a>>>0)c=c+1>>>0;if(i=i<<16>>>0,s=s+i>>>0,s>>>0<i>>>0)c=c+1>>>0;c=c+Math.imul(n,r)>>>0,c=c+Math.imul(t,o)>>>0,e[0]=c,e[1]=s}function VR(e,t,n,r,o){let i=t+r>>>0,a=n+o>>>0;if(a>>>0<n>>>0)i=i+1|0;e[0]=i,e[1]=a}function Mg(e){if(typeof e==="object"&&e!==null&&Pg in e)return e[Pg]();throw Error(ha("yieldWrapGet"))}var Ps,FL=335903614,LL=4150755663,DL=1481765933,qL=1284865837,UL=9007199254740992,$L=134217728,Pg,xo,pn,WR,HL,BL,$t,rG;var di=w(()=>{Ie();Ps=class Ps{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new Ps(this.self)}};Pg=Symbol.for("effect/Utils/YieldWrap");xo=class xo{#e;constructor(e){this.#e=e}[Pg](){return this.#e}};pn=re("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),WR={effect_internal_function:(e)=>e()},HL={effect_internal_function:(e)=>{try{return e()}finally{}}},BL=WR.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,$t=BL?WR.effect_internal_function:HL.effect_internal_function,rG=function*(){}.constructor});var Ng,J,U=(e)=>{if(pn.enabled===!0)return 0;switch(typeof e){case"number":return sp(e);case"bigint":return ke(e.toString(10));case"boolean":return ke(String(e));case"symbol":return ke(String(e));case"string":return ke(e);case"undefined":return ke("undefined");case"function":case"object":if(e===null)return ke("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return ke("Invalid Date");return U(e.toISOString())}else if(e instanceof URL)return U(e.href);else if(WL(e))return e[J]();else return bl(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},bl=(e)=>{if(!Ng.has(e))Ng.set(e,sp(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Ng.get(e)},le=(e)=>(t)=>t*53^e,ap=(e)=>e&3221225471|e>>>1&1073741824,WL=(e)=>H(e,J),sp=(e)=>{if(e!==e||e===1/0)return 0;let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return ap(t)},ke=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return ap(t)},zL=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=b(ke(t[r]),le(U(e[t[r]])));return ap(n)},cp=(e)=>zL(e,Object.keys(e)),En=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=b(t,le(U(e[n])));return ap(t)},ye=function(){if(arguments.length===1){let n=arguments[0];return function(r){return Object.defineProperty(n,J,{value(){return r},enumerable:!1}),r}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,J,{value(){return t},enumerable:!1}),t};var Ge=w(()=>{ne();Ie();di();Ng=re(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),J=Symbol.for("effect/Hash")});function j(){if(arguments.length===1)return(e)=>lp(e,arguments[0]);return lp(arguments[0],arguments[1])}function lp(e,t){if(e===t)return!0;let n=typeof e;if(n!==typeof t)return!1;if(n==="object"||n==="function"){if(e!==null&&t!==null){if(wl(e)&&wl(t))if(U(e)===U(t)&&e[z](t))return!0;else return pn.enabled&&pn.tester?pn.tester(e,t):!1;else if(e instanceof Date&&t instanceof Date){let r=e.getTime(),o=t.getTime();return r===o||Number.isNaN(r)&&Number.isNaN(o)}else if(e instanceof URL&&t instanceof URL)return e.href===t.href}if(pn.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>lp(r,t[o]));if(Object.getPrototypeOf(e)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let r=Object.keys(e),o=Object.keys(t);if(r.length===o.length){for(let i of r)if(!((i in t)&&lp(e[i],t[i])))return pn.tester?pn.tester(e,t):!1;return!0}}return pn.tester?pn.tester(e,t):!1}}return pn.enabled&&pn.tester?pn.tester(e,t):!1}var z,wl=(e)=>H(e,z),_l=()=>j;var Re=w(()=>{Ge();Ie();di();z=Symbol.for("effect/Equal")});function KL(e){try{return e.toISOString()}catch{return"Invalid Date"}}function JL(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function vl(e){return Ut(e)?JSON.stringify(e):String(e)}function Hr(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":kn(n)?" ".repeat(n):n,i=(l)=>o.repeat(l),a=(l,u)=>{let d=l?.constructor;return d&&d!==Object.prototype.constructor&&d.name?`${d.name}(${u})`:u},s=(l)=>{try{return Reflect.ownKeys(l)}catch{return["[ownKeys threw]"]}};function c(l,u=0){if(Array.isArray(l)){if(r.has(l))return Fg;if(r.add(l),!o||l.length<=1)return`[${l.map((p)=>c(p,u)).join(",")}]`;let d=l.map((p)=>c(p,u+1)).join(`,
4
4
  `+i(u+1));return`[
5
5
  ${i(u+1)}${d}
6
- ${i(u)}]`}if(zd(l))return $L(l);if(!t?.ignoreToString&&H(l,"toString")&&Xo(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let d=UL(l);if(l instanceof Error&&l.cause)return`${d} (cause: ${c(l.cause,u)})`;return d}if($t(l))return JSON.stringify(l);if(Cn(l)||l==null||ea(l)||ta(l))return String(l);if(Zo(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return vg;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(rn(l)){if(r.has(l))return vg;r.add(l);let d=s(l);if(!o||d.length<=1){let f=`{${d.map((m)=>`${gl(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,f)}let p=`{
7
- ${d.map((f)=>`${i(u+1)}${gl(f)}: ${c(l[f],u+1)}`).join(`,
6
+ ${i(u)}]`}if(ip(l))return KL(l);if(!t?.ignoreToString&&H(l,"toString")&&ui(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let d=JL(l);if(l instanceof Error&&l.cause)return`${d} (cause: ${c(l.cause,u)})`;return d}if(Ut(l))return JSON.stringify(l);if(kn(l)||l==null||pa(l)||fa(l))return String(l);if(li(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return Fg;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(rn(l)){if(r.has(l))return Fg;r.add(l);let d=s(l);if(!o||d.length<=1){let m=`{${d.map((f)=>`${vl(f)}:${c(l[f],u)}`).join(",")}}`;return a(l,m)}let p=`{
7
+ ${d.map((m)=>`${i(u+1)}${vl(m)}: ${c(l[m],u+1)}`).join(`,
8
8
  `)}
9
- ${i(u)}}`;return a(l,p)}return String(l)}return c(e,0)}var pe,Re=(e)=>{try{if(H(e,"toJSON")&&Xo(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(Re)}catch{return{}}return HR(e)},vg="[Circular]",Ee=(e)=>JSON.stringify(e,null,2),GJ,fo=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?Zd(e,t):String(e)}catch{return String(e)}},Zd=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(oa.fiberRefs!==void 0&&UR(i)?i[Rg](oa.fiberRefs):i):i,t);return n=void 0,r},Rg,UR=(e)=>typeof e==="object"&&e!==null&&(Rg in e),oa,jR=(e,t)=>{let n=oa.fiberRefs;oa.fiberRefs=e;try{return t()}finally{oa.fiberRefs=n}},HR=(e)=>{if(UR(e)&&oa.fiberRefs!==void 0)return e[Rg](oa.fiberRefs);return e};var it=b(()=>{ke();pe=Symbol.for("nodejs.util.inspect.custom");GJ={toJSON(){return Re(this)},[pe](){return this.toJSON()},toString(){return Ee(this.toJSON())}},Rg=Symbol.for("effect/Inspectable/Redactable"),oa=ne("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var L=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let r=0,o=t.length;r<o;r++)n=t[r](n);return n}}};var Ae=()=>{};var aa="Async",sa="Commit",hn="Failure",yl="OnFailure",Rs="OnSuccess",Ts="OnSuccessAndFailure",gn="Success",Xd="Sync",BR="Tag",ca="UpdateRuntimeFlags",Cs="While",Os="Iterator",Qd="WithRuntime",Es="Yield",xl="RevertFlags";var jL="3.22.2",Sl=()=>jL;var WR,zR,KR,JR,ei,HL,BL,mo,bl,ti,Cg,GR;var ho=b(()=>{ve();Ke();Ae();Qo();WR=Symbol.for("effect/Effect"),zR=Symbol.for("effect/Stream"),KR=Symbol.for("effect/Sink"),JR=Symbol.for("effect/Channel"),ei={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Sl()},HL={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},BL={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},mo={[WR]:ei,[zR]:ei,[KR]:HL,[JR]:BL,[z](e){return this===e},[G](){return ge(this,fl(this))},[Symbol.iterator](){return new vs(new po(this))},pipe(){return L(this,arguments)}},bl={[G](){return ge(this,Gd(this))},[z](e){let t=Object.keys(this),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r of t)if(!((r in e)&&j(this[r],e[r])))return!1;return!0}},ti={...mo,_op:sa},Cg={...ti,...bl},GR=function(){function e(){}return e.prototype=ti,e}()});var ZR,XR,VL,WL,zL,Og=(e)=>H(e,ZR),Eg=(e)=>e._tag==="None",kg=(e)=>e._tag==="Some",ep,_l=(e)=>{let t=Object.create(VL);return t.value=e,t};var Ig=b(()=>{ve();Ke();it();ke();ho();ZR=Symbol.for("effect/Option"),XR={...mo,[ZR]:{_A:(e)=>e},[pe](){return this.toJSON()},toString(){return Ee(this.toJSON())}},VL=Object.assign(Object.create(XR),{_tag:"Some",_op:"Some",[z](e){return Og(e)&&kg(e)&&j(this.value,e.value)},[G](){return ge(this,se(U(this._tag))(U(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:Re(this.value)}}}),WL=U("None"),zL=Object.assign(Object.create(XR),{_tag:"None",_op:"None",[z](e){return Og(e)&&Eg(e)},[G](){return WL},toJSON(){return{_id:"Option",_tag:this._tag}}}),ep=Object.create(zL)});var Pg,eT,KL,JL,tp=(e)=>H(e,Pg),Ag=(e)=>e._tag==="Left",Mg=(e)=>e._tag==="Right",tT=(e)=>{let t=Object.create(JL);return t.left=e,t},nT=(e)=>{let t=Object.create(KL);return t.right=e,t};var rT=b(()=>{ve();Ke();it();ke();ho();Pg=Symbol.for("effect/Either"),eT={...mo,[Pg]:{_R:(e)=>e},[pe](){return this.toJSON()},toString(){return Ee(this.toJSON())}},KL=Object.assign(Object.create(eT),{_tag:"Right",_op:"Right",[z](e){return tp(e)&&Mg(e)&&j(this.right,e.right)},[G](){return se(U(this._tag))(U(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:Re(this.right)}}}),JL=Object.assign(Object.create(eT),{_tag:"Left",_op:"Left",[z](e){return tp(e)&&Ag(e)&&j(this.left,e.left)},[G](){return se(U(this._tag))(U(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:Re(this.left)}}})});var ue,ae,Ng,Fe,Tt,np,oT,wl,iT,Fg,aT;var yn=b(()=>{te();rT();ue=nT,ae=tT,Ng=tp,Fe=Ag,Tt=Mg,np=h(2,(e,t)=>Fe(e)?ae(t(e.left)):ue(e.right)),oT=h(2,(e,t)=>Tt(e)?ue(t(e.right)):ae(e.left)),wl=h(2,(e,{onLeft:t,onRight:n})=>Fe(e)?t(e.left):n(e.right)),iT=wl({onLeft:we,onRight:we}),Fg=h(2,(e,t)=>{if(Tt(e))return e.right;throw t(e.left)}),aT=Fg(()=>Error("getOrThrow called on a Left"))});var Lg=(e)=>e.length>0;var sT=(e)=>(t,n)=>t===n?0:e(t,n),cT,rp,Dg=(e)=>h(2,(t,n)=>e(t,n)===1);var op=b(()=>{te();cT=sT((e,t)=>e<t?-1:1),rp=h(2,(e,t)=>sT((n,r)=>e(t(n),t(r))))});var B=()=>ep,Y,Je,De,dt,Le,or,lT,go=(e)=>e==null?B():Y(e),xn,uT=(e)=>(...t)=>{try{return Y(e(...t))}catch{return B()}},ir,ar,dT,XL=(e)=>h(2,(t,n)=>Je(t)?!1:e(t.value,n)),QL,pT,fT;var pt=b(()=>{ve();te();Ig();Y=_l,Je=Eg,De=kg,dt=h(2,(e,{onNone:t,onSome:n})=>Je(e)?t():n(e.value)),Le=h(2,(e,t)=>Je(e)?t():e.value),or=h(2,(e,t)=>Je(e)?t():e),lT=h(2,(e,t)=>Je(e)?Y(t()):e),xn=Le(Vd),ir=h(2,(e,t)=>Je(e)?B():Y(t(e.value))),ar=h(2,(e,t)=>Je(e)?B():t(e.value)),dT=h(2,(e,t)=>Je(e)?B():go(t(e.value))),QL=hl(),pT=XL(QL),fT=h(2,(e,t)=>Je(e)?!1:t(e.value))});var mT=(...e)=>e;var hT=()=>{};var la=(e)=>Array(e),$g,qe=(e)=>Array.isArray(e)?e:Array.from(e),Ug=(e)=>Array.isArray(e)?e:[e],gT,ks,yT,jg,Hg,tD=(e)=>e.length===0,xT,ni,Me,ST=(e,t)=>e<0||e>=t.length,nD=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),rD,Bg,yo,St,bT=(e)=>Me(e)?Y(Vg(e)):B(),Vg=(e)=>e[e.length-1],sr=(e)=>e.slice(1),oD=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},_T,wT,Wg=(e)=>Array.from(e).reverse(),xo,zg,vT,iD,aD,sD,Is=(e)=>e.slice(),cD,ri,So=()=>[],Jt=(e)=>[e],cr,vl,ip,ap,Ps,Kg=(e,t)=>{let n=[],r=e,o;while(De(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},oi,RT,Jg=(e)=>RT(e,hl()),bo;var at=b(()=>{ve();ll();te();pt();hT();$g=h(2,(e,t)=>{let n=Math.max(1,Math.floor(e)),r=Array(n);for(let o=0;o<n;o++)r[o]=t(o);return r}),gT=h(2,(e,{onEmpty:t,onNonEmpty:n})=>Me(e)?n(St(e),sr(e)):t()),ks=h(2,(e,t)=>[t,...e]),yT=h(2,(e,t)=>[...e,t]),jg=h(2,(e,t)=>qe(e).concat(qe(t))),Hg=Array.isArray,xT=tD,ni=Lg,Me=Lg,rD=h(2,(e,t)=>{let n=Math.floor(t);return ST(n,e)?B():Y(e[n])}),Bg=h(2,(e,t)=>{let n=Math.floor(t);if(ST(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),yo=rD(0),St=Bg(0),_T=h(2,(e,t)=>aD(e,oD(e,t))),wT=h(2,(e,t)=>{let n=qe(e);return n.slice(nD(t,n),n.length)}),xo=h(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),zg=h(2,(e,t)=>vT(e,t,mT)),vT=h(3,(e,t,n)=>{let r=qe(e),o=qe(t);if(Me(r)&&Me(o)){let i=[n(St(r),St(o))],a=Math.min(r.length,o.length);for(let s=1;s<a;s++)i[s]=n(r[s],o[s]);return i}return[]}),iD=hl(),aD=h(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(Me(n)){if(r>=1)return sD(n,r);return[[],n]}return[n,[]]}),sD=h(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[Is(e),[]]:[ks(e.slice(1,n),St(e)),e.slice(n)]}),cD=h(3,(e,t,n)=>{let r=qe(e),o=qe(t);if(Me(r)){if(Me(o))return RT(n)(jg(r,o));return r}return o}),ri=h(2,(e,t)=>cD(e,t,iD)),cr=h(2,(e,t)=>e.map(t)),vl=h(2,(e,t)=>{if(xT(e))return[];let n=[];for(let r=0;r<e.length;r++){let o=t(e[r],r);for(let i=0;i<o.length;i++)n.push(o[i])}return n}),ip=vl(we),ap=h(2,(e,t)=>{let n=qe(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if(De(i))r.push(i.value)}return r}),Ps=h(3,(e,t,n)=>qe(e).reduce((r,o,i)=>n(r,o,i),t)),oi=MR,RT=h(2,(e,t)=>{let n=qe(e);if(Me(n)){let r=[St(n)],o=sr(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),bo=h(2,(e,t)=>qe(e).join(t))});function pD(e,t,n,r,o){for(let i=t;i<Math.min(e.length,t+o);i++)n[r+i-t]=e[i];return n}var CT,OT,fD=(e)=>cl((t,n)=>t.length===n.length&&_o(t).every((r,o)=>e(r,As(n,o)))),mD,hD,Ct=(e)=>{let t=Object.create(hD);switch(t.backing=e,e._tag){case"IEmpty":{t.length=0,t.depth=0,t.left=t,t.right=t;break}case"IConcat":{t.length=e.left.length+e.right.length,t.depth=1+Math.max(e.left.depth,e.right.depth),t.left=e.left,t.right=e.right;break}case"IArray":{t.length=e.array.length,t.depth=0,t.left=qr,t.right=qr;break}case"ISingleton":{t.length=1,t.depth=0,t.left=qr,t.right=qr;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=qr,t.right=qr;break}}return t},ET=(e)=>H(e,CT),qr,Hn=()=>qr,Rl=(...e)=>xD(e),bt=(e)=>Ct({_tag:"ISingleton",a:e}),sp=(e)=>ET(e)?e:Tl(qe(e)),Gg=(e,t,n)=>{switch(e.backing._tag){case"IArray":{pD(e.backing.array,0,t,n,e.length);break}case"IConcat":{Gg(e.left,t,n),Gg(e.right,t,n+e.left.length);break}case"ISingleton":{t[n]=e.backing.a;break}case"ISlice":{let r=0,o=n;while(r<e.length)t[o]=As(e,r),r+=1,o+=1;break}}},gD=(e)=>{switch(e.backing._tag){case"IEmpty":return OT;case"IArray":return e.backing.array;default:{let t=Array(e.length);return Gg(e,t,0),e.backing={_tag:"IArray",array:t},e.left=qr,e.right=qr,e.depth=0,t}}},_o,yD=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return Ct({_tag:"IArray",array:Wg(e.backing.array)});case"IConcat":return Ct({_tag:"IConcat",left:ii(e.backing.right),right:ii(e.backing.left)});case"ISlice":return Tl(Wg(_o(e)))}},ii,Tl=(e)=>e.length===0?Hn():e.length===1?bt(e[0]):Ct({_tag:"IArray",array:e}),xD=(e)=>Tl(e),As,kT,Gt,Yg,kn,IT=(e)=>e.length===0,lr=(e)=>e.length>0,Zg=(e)=>As(e,0),ur,dr=(e)=>Yg(e,1);var $r=b(()=>{at();ve();ll();te();Ke();it();Ae();ke();CT=Symbol.for("effect/Chunk");OT=[],mD=fD(j),hD={[CT]:{_A:(e)=>e},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Chunk",values:_o(this).map(Re)}},[pe](){return this.toJSON()},[z](e){return ET(e)&&mD(this,e)},[G](){return ge(this,On(_o(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return OT[Symbol.iterator]();default:return _o(this)[Symbol.iterator]()}},pipe(){return L(this,arguments)}},qr=Ct({_tag:"IEmpty"}),_o=gD,ii=yD,As=h(2,(e,t)=>{switch(e.backing._tag){case"IEmpty":throw Error("Index out of bounds");case"ISingleton":{if(t!==0)throw Error("Index out of bounds");return e.backing.a}case"IArray":{if(t>=e.length||t<0)throw Error("Index out of bounds");return e.backing.array[t]}case"IConcat":return t<e.left.length?As(e.left,t):As(e.right,t-e.left.length);case"ISlice":return As(e.backing.chunk,t+e.backing.offset)}}),kT=h(2,(e,t)=>kn(e,bt(t))),Gt=h(2,(e,t)=>kn(bt(t),e)),Yg=h(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return qr;else switch(e.backing._tag){case"ISlice":return Ct({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return Yg(e.right,t-e.left.length);return Ct({_tag:"IConcat",left:Yg(e.left,t),right:e.right})}default:return Ct({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),kn=h(2,(e,t)=>{if(e.backing._tag==="IEmpty")return t;if(t.backing._tag==="IEmpty")return e;let n=t.depth-e.depth;if(Math.abs(n)<=1)return Ct({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=kn(e.right,t);return Ct({_tag:"IConcat",left:e.left,right:r})}else{let r=kn(e.right.right,t);if(r.depth===e.depth-3){let o=Ct({_tag:"IConcat",left:e.right.left,right:r});return Ct({_tag:"IConcat",left:e.left,right:o})}else{let o=Ct({_tag:"IConcat",left:e.left,right:e.right.left});return Ct({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=kn(e,t.left);return Ct({_tag:"IConcat",left:r,right:t.right})}else{let r=kn(e,t.left.left);if(r.depth===t.depth-3){let o=Ct({_tag:"IConcat",left:r,right:t.left.right});return Ct({_tag:"IConcat",left:o,right:t.right})}else{let o=Ct({_tag:"IConcat",left:t.left.right,right:t.right});return Ct({_tag:"IConcat",left:r,right:o})}}}),ur=Zg});var ai=5,Xg,PT,AT,MT;var cp=b(()=>{Xg=Math.pow(2,5),PT=Xg-1,AT=Xg/2,MT=Xg/4});function SD(e){return e-=e>>1&1431655765,e=(e&858993459)+(e>>2&858993459),e=e+(e>>4)&252645135,e+=e>>8,e+=e>>16,e&127}function si(e,t){return t>>>e&PT}function ci(e){return 1<<e}function lp(e,t){return SD(e&t-1)}var Qg=b(()=>{cp()});var NT=(e,t)=>({value:e,previous:t});function ua(e,t,n,r){let o=r;if(!e){let i=r.length;o=Array(i);for(let a=0;a<i;++a)o[a]=r[a]}return o[t]=n,o}function ey(e,t,n){let r=n.length-1,o=0,i=0,a=n;if(e)o=i=t;else{a=Array(r);while(o<t)a[i++]=n[o++]}++o;while(o<=r)a[i++]=n[o++];if(e)a.length=r;return a}function FT(e,t,n,r){let o=r.length;if(e){let c=o;while(c>=t)r[c--]=r[c];return r[t]=n,r}let i=0,a=0,s=Array(o+1);while(i<t)s[a++]=r[i++];s[t]=n;while(i<o)s[++a]=r[i++];return s}class vo{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(B());if(Je(a))return new vo;return++i.value,new da(e,r,o,a)}}function Bn(e){return pl(e,"EmptyNode")}function _D(e){return Bn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function up(e,t){return Bn(e)?!1:t===e.edit}class da{edit;hash;key;value;_tag="LeafNode";constructor(e,t,n,r){this.edit=e,this.hash=t,this.key=n,this.value=r}modify(e,t,n,r,o,i){if(j(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Je(s))return--i.value,new vo;if(up(this,e))return this.value=s,this;return new da(e,r,o,s)}let a=n(B());if(Je(a))return this;return++i.value,LT(e,t,this.hash,this,r,new da(e,r,o,a))}}class ty{edit;hash;children;_tag="CollisionNode";constructor(e,t,n){this.edit=e,this.hash=t,this.children=n}modify(e,t,n,r,o,i){if(r===this.hash){let s=up(this,e),c=this.updateCollisionList(s,e,this.hash,this.children,n,o,i);if(c===this.children)return this;return c.length>1?new ty(e,this.hash,c):c[0]}let a=n(B());if(Je(a))return this;return++i.value,LT(e,t,this.hash,this,r,new da(e,r,o,a))}updateCollisionList(e,t,n,r,o,i,a){let s=r.length;for(let l=0;l<s;++l){let u=r[l];if("key"in u&&j(i,u.key)){let d=u.value,p=o(d);if(p===d)return r;if(Je(p))return--a.value,ey(e,l,r);return ua(e,l,new da(t,n,i,p),r)}}let c=o(B());if(Je(c))return r;return++a.value,ua(e,s,new da(t,n,i,c),r)}}class Ms{edit;mask;children;_tag="IndexedNode";constructor(e,t,n){this.edit=e,this.mask=t,this.children=n}modify(e,t,n,r,o,i){let a=this.mask,s=this.children,c=si(t,r),l=ci(c),u=lp(a,l),d=a&l,p=up(this,e);if(!d){let x=new vo().modify(e,t+ai,n,r,o,i);if(!x)return this;return s.length>=AT?vD(e,c,x,a,s):new Ms(e,a|l,FT(p,u,x,s))}let f=s[u],m=f.modify(e,t+ai,n,r,o,i);if(f===m)return this;let y=a,g;if(Bn(m)){if(y&=~l,!y)return new vo;if(s.length<=2&&_D(s[u^1]))return s[u^1];g=ey(p,u,s)}else g=ua(p,u,m,s);if(p)return this.mask=y,this.children=g,this;return new Ms(e,y,g)}}class ny{edit;size;children;_tag="ArrayNode";constructor(e,t,n){this.edit=e,this.size=t,this.children=n}modify(e,t,n,r,o,i){let a=this.size,s=this.children,c=si(t,r),l=s[c],u=(l||new vo).modify(e,t+ai,n,r,o,i);if(l===u)return this;let d=up(this,e),p;if(Bn(l)&&!Bn(u))++a,p=ua(d,c,u,s);else if(!Bn(l)&&Bn(u)){if(--a,a<=MT)return wD(e,a,c,s);p=ua(d,c,new vo,s)}else p=ua(d,c,u,s);if(d)return this.size=a,this.children=p,this;return new ny(e,a,p)}}function wD(e,t,n,r){let o=Array(t-1),i=0,a=0;for(let s=0,c=r.length;s<c;++s)if(s!==n){let l=r[s];if(l&&!Bn(l))o[i++]=l,a|=1<<s}return new Ms(e,a,o)}function vD(e,t,n,r,o){let i=[],a=r,s=0;for(let c=0;a;++c){if(a&1)i[c]=o[s++];a>>>=1}return i[t]=n,new ny(e,s+1,i)}function RD(e,t,n,r,o,i){if(n===o)return new ty(e,n,[i,r]);let a=si(t,n),s=si(t,o);if(a===s)return(c)=>new Ms(e,ci(a)|ci(s),[c]);else{let c=a<s?[r,i]:[i,r];return new Ms(e,ci(a)|ci(s),c)}}function LT(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=RD(e,s,n,r,o,i);if(typeof c==="function")a=NT(c,a),s=s+ai;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var DT=b(()=>{ve();pt();ke();Qg();cp()});var qT="effect/HashMap",dp,CD,ry=(e,t,n,r)=>{let o=Object.create(CD);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},fp,pp=(e)=>e?UT(e[0],e[1],e[2],e[3],e[4]):B(),$T=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if(De(e.value))return Y({value:t(e.key,e.value.value),cont:n});return pp(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return UT(r.length,r,0,t,n)}default:return pp(n)}},UT=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!Bn(i))return $T(i,r,[e,t,n,r,o])}return pp(o)},OD,Ns=()=>OD,jT=(e)=>{let t=gp(Ns());for(let n of e)pa(t,n[0],n[1]);return WT(t)},HT=(e)=>H(e,dp),BT=(e)=>e&&Bn(e._root),VT,mp,oy,pa,ED,hp=(e)=>new fp(e,(t)=>t),Cl=(e)=>e._size,gp=(e)=>ry(!0,e._edit+1,e._root,e._size),WT=(e)=>(e._editable=!1,e),yp,zT,xp,KT,iy,Fs;var ay=b(()=>{ve();te();te();Ke();it();pt();Ae();ke();Qg();cp();DT();dp=Symbol.for(qT),CD={[dp]:dp,[Symbol.iterator](){return new fp(this,(e,t)=>[e,t])},[G](){let e=U(qT);for(let t of this)e^=S(U(t[0]),se(U(t[1])));return ge(this,e)},[z](e){if(HT(e)){if(e._size!==this._size)return!1;for(let t of this){let n=S(e,mp(t[0],U(t[0])));if(Je(n))return!1;else if(!j(t[1],n.value))return!1}return!0}return!1},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(Re)}},[pe](){return this.toJSON()},pipe(){return L(this,arguments)}};fp=class fp{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=$T(this.map._root,this.f,void 0)}next(){if(Je(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=pp(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new fp(this.map,this.f)}};OD=ry(!1,0,new vo,0),VT=h(2,(e,t)=>mp(e,t,U(t))),mp=h(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return j(t,r.key)?r.value:B();case"CollisionNode":{if(n===r.hash){let i=r.children;for(let a=0,s=i.length;a<s;++a){let c=i[a];if("key"in c&&j(t,c.key))return c.value}}return B()}case"IndexedNode":{let i=si(o,n),a=ci(i);if(r.mask&a){r=r.children[lp(r.mask,a)],o+=ai;break}return B()}case"ArrayNode":{if(r=r.children[si(o,n)],r){o+=ai;break}return B()}default:return B()}}),oy=h(2,(e,t)=>De(mp(e,t,U(t)))),pa=h(3,(e,t,n)=>yp(e,t,()=>Y(n))),ED=h(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:ry(e._editable,e._edit,t,n)}),yp=h(3,(e,t,n)=>zT(e,t,U(t),n)),zT=h(4,(e,t,n,r)=>{let o={value:e._size},i=e._root.modify(e._editable?e._edit:NaN,0,r,n,t,o);return S(e,ED(i,o.value))}),xp=h(2,(e,t)=>yp(e,t,B)),KT=h(2,(e,t)=>Fs(e,Ns(),(n,r,o)=>pa(n,o,t(r,o)))),iy=h(2,(e,t)=>Fs(e,void 0,(n,r,o)=>t(r,o))),Fs=h(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return De(r.value)?n(t,r.value.value,r.key):t;if(r._tag==="EmptyNode")return t;let o=[r.children],i;while(i=o.pop())for(let a=0,s=i.length;a<s;){let c=i[a++];if(c&&!Bn(c))if(c._tag==="LeafNode"){if(De(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var GT="effect/HashSet",Sp,kD,bp=(e)=>{let t=Object.create(kD);return t._keyMap=e,t},YT=(e)=>H(e,Sp),ID,Ol=()=>ID,ZT=(e)=>{let t=_p(Ol());for(let n of e)Ls(t,n);return wp(t)},XT=(...e)=>{let t=_p(Ol());for(let n of e)Ls(t,n);return wp(t)},QT,eC=(e)=>Cl(e._keyMap),_p=(e)=>bp(gp(e._keyMap)),wp=(e)=>(e._keyMap._editable=!1,e),sy,Ls,cy,tC,nC,rC,oC;var iC=b(()=>{ve();te();Ke();it();Ae();ke();ay();Sp=Symbol.for(GT),kD={[Sp]:Sp,[Symbol.iterator](){return hp(this._keyMap)},[G](){return ge(this,se(U(this._keyMap))(U(GT)))},[z](e){if(YT(e))return Cl(this._keyMap)===Cl(e._keyMap)&&j(this._keyMap,e._keyMap);return!1},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(Re)}},[pe](){return this.toJSON()},pipe(){return L(this,arguments)}},ID=bp(Ns()),QT=h(2,(e,t)=>oy(e._keyMap,t)),sy=h(2,(e,t)=>{let n=_p(e);return t(n),wp(n)}),Ls=h(2,(e,t)=>e._keyMap._editable?(pa(t,!0)(e._keyMap),e):bp(pa(t,!0)(e._keyMap))),cy=h(2,(e,t)=>e._keyMap._editable?(xp(t)(e._keyMap),e):bp(xp(t)(e._keyMap))),tC=h(2,(e,t)=>sy(e,(n)=>{for(let r of t)cy(n,r)})),nC=h(2,(e,t)=>sy(Ol(),(n)=>{rC(e,(r)=>Ls(n,r));for(let r of t)Ls(n,r)})),rC=h(2,(e,t)=>iy(e._keyMap,(n,r)=>t(r))),oC=h(3,(e,t,n)=>Fs(e._keyMap,t,(r,o,i)=>n(r,i)))});var Ur,aC,fa,sC,El,ma,ly,uy,Ro,ha;var ga=b(()=>{iC();Ur=Ol,aC=ZT,fa=XT,sC=QT,El=eC,ma=Ls,ly=cy,uy=tC,Ro=nC,ha=oC});var qs="Die",li="Empty",ui="Fail",ya="Interrupt",xa="Parallel",Sa="Sequential";var uC="effect/Cause",fy,MD,$s,To,Us=(e)=>{let t=Object.create($s);return t._tag=ui,t.error=e,t},In=(e)=>{let t=Object.create($s);return t._tag=qs,t.defect=e,t},pr=(e)=>{let t=Object.create($s);return t._tag=ya,t.fiberId=e,t},wa=(e,t)=>{let n=Object.create($s);return n._tag=xa,n.left=e,n.right=t,n},Yt=(e,t)=>{let n=Object.create($s);return n._tag=Sa,n.left=e,n.right=t,n},dC=(e)=>H(e,fy),my=(e)=>e._tag===li,pC=(e)=>e._tag===ui,vp=(e)=>{if(e._tag===li)return!0;return ba(e,!0,(t,n)=>{switch(n._tag){case li:return Y(t);case qs:case ui:case ya:return Y(!1);default:return B()}})},Rp=(e)=>De(fC(e)),js=(e)=>Op(void 0,DD)(e),hy=(e)=>ii(ba(e,Hn(),(t,n)=>n._tag===ui?Y(S(t,Gt(n.error))):B())),gy=(e)=>ii(ba(e,Hn(),(t,n)=>n._tag===qs?Y(S(t,Gt(n.defect))):B())),yy=(e)=>ba(e,Ur(),(t,n)=>n._tag===ya?Y(S(t,ma(n.fiberId))):B()),xy=(e)=>Sy(e,(t)=>t._tag===ui?Y(t.error):B()),Tp=(e)=>{let t=xy(e);switch(t._tag){case"None":return ue(e);case"Some":return ae(t.value)}},fC=(e)=>Sy(e,(t)=>t._tag===ya?Y(t.fiberId):B()),Cp=(e)=>by(e,{onEmpty:To,onFail:()=>To,onDie:In,onInterrupt:pr,onSequential:Yt,onParallel:wa}),mC=(e)=>by(e,{onEmpty:To,onFail:In,onDie:In,onInterrupt:pr,onSequential:Yt,onParallel:wa}),ND=(e,t)=>{let n=bt(e),r=bt(t);while(lr(n)&&lr(r)){let[o,i]=S(ur(n),ba([Ur(),Hn()],([c,l],u)=>{let[d,p]=dy(u);return Y([S(c,Ro(d)),S(l,kn(p))])})),[a,s]=S(ur(r),ba([Ur(),Hn()],([c,l],u)=>{let[d,p]=dy(u);return Y([S(c,Ro(d)),S(l,kn(p))])}));if(!j(o,a))return!1;n=i,r=s}return!0},FD=(e)=>LD(bt(e),Hn()),LD=(e,t)=>{while(!0){let[n,r]=S(e,Ps([Ur(),Hn()],([i,a],s)=>{let[c,l]=dy(s);return[S(i,Ro(c)),S(a,kn(l))]})),o=El(n)>0?S(t,Gt(n)):t;if(IT(r))return ii(o);e=r,t=o}throw Error(ra("Cause.flattenCauseLoop"))},Sy,dy=(e)=>{let t=e,n=[],r=Ur(),o=Hn();while(t!==void 0)switch(t._tag){case li:{if(n.length===0)return[r,o];t=n.pop();break}case ui:{if(r=ma(r,Rl(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case qs:{if(r=ma(r,Rl(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case ya:{if(r=ma(r,Rl(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case Sa:{switch(t.left._tag){case li:{t=t.right;break}case Sa:{t=Yt(t.left.left,Yt(t.left.right,t.right));break}case xa:{t=wa(Yt(t.left.left,t.right),Yt(t.left.right,t.right));break}default:{o=Gt(o,t.right),t=t.left;break}}break}case xa:{n.push(t.right),t=t.left;break}}throw Error(ra("Cause.evaluateCauseLoop"))},DD,cC="SequentialCase",lC="ParallelCase",by,ba,Op,fr=(e,t)=>{if(js(e))return"All fibers interrupted without errors.";return kl(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
- ${hC(n.cause," ")}
9
+ ${i(u)}}`;return a(l,p)}return String(l)}return c(e,0)}var me,Te=(e)=>{try{if(H(e,"toJSON")&&ui(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(Te)}catch{return{}}return JR(e)},Fg="[Circular]",Ee=(e)=>JSON.stringify(e,null,2),dG,So=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?up(e,t):String(e)}catch{return String(e)}},up=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(ga.fiberRefs!==void 0&&zR(i)?i[Lg](ga.fiberRefs):i):i,t);return n=void 0,r},Lg,zR=(e)=>typeof e==="object"&&e!==null&&(Lg in e),ga,KR=(e,t)=>{let n=ga.fiberRefs;ga.fiberRefs=e;try{return t()}finally{ga.fiberRefs=n}},JR=(e)=>{if(zR(e)&&ga.fiberRefs!==void 0)return e[Lg](ga.fiberRefs);return e};var at=w(()=>{Ie();me=Symbol.for("nodejs.util.inspect.custom");dG={toJSON(){return Te(this)},[me](){return this.toJSON()},toString(){return Ee(this.toJSON())}},Lg=Symbol.for("effect/Inspectable/Redactable"),ga=re("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var F=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let r=0,o=t.length;r<o;r++)n=t[r](n);return n}}};var Ne=()=>{};var xa="Async",Sa="Commit",fn="Failure",Rl="OnFailure",As="OnSuccess",Ms="OnSuccessAndFailure",mn="Success",dp="Sync",GR="Tag",ba="UpdateRuntimeFlags",Ns="While",Fs="Iterator",pp="WithRuntime",Ls="Yield",Tl="RevertFlags";var GL="3.22.2",Cl=()=>GL;var ZR,XR,QR,eT,pi,YL,ZL,bo,Ol,fi,qg,tT;var wo=w(()=>{Re();Ge();Ne();di();ZR=Symbol.for("effect/Effect"),XR=Symbol.for("effect/Stream"),QR=Symbol.for("effect/Sink"),eT=Symbol.for("effect/Channel"),pi={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Cl()},YL={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},ZL={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},bo={[ZR]:pi,[XR]:pi,[QR]:YL,[eT]:ZL,[z](e){return this===e},[J](){return ye(this,bl(this))},[Symbol.iterator](){return new Ps(new xo(this))},pipe(){return F(this,arguments)}},Ol={[J](){return ye(this,cp(this))},[z](e){let t=Object.keys(this),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r of t)if(!((r in e)&&j(this[r],e[r])))return!1;return!0}},fi={...bo,_op:Sa},qg={...fi,...Ol},tT=function(){function e(){}return e.prototype=fi,e}()});var rT,oT,XL,QL,eD,Ug=(e)=>H(e,rT),$g=(e)=>e._tag==="None",jg=(e)=>e._tag==="Some",fp,kl=(e)=>{let t=Object.create(XL);return t.value=e,t};var Hg=w(()=>{Re();Ge();at();Ie();wo();rT=Symbol.for("effect/Option"),oT={...bo,[rT]:{_A:(e)=>e},[me](){return this.toJSON()},toString(){return Ee(this.toJSON())}},XL=Object.assign(Object.create(oT),{_tag:"Some",_op:"Some",[z](e){return Ug(e)&&jg(e)&&j(this.value,e.value)},[J](){return ye(this,le(U(this._tag))(U(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:Te(this.value)}}}),QL=U("None"),eD=Object.assign(Object.create(oT),{_tag:"None",_op:"None",[z](e){return Ug(e)&&$g(e)},[J](){return QL},toJSON(){return{_id:"Option",_tag:this._tag}}}),fp=Object.create(eD)});var Bg,aT,tD,nD,mp=(e)=>H(e,Bg),Vg=(e)=>e._tag==="Left",Wg=(e)=>e._tag==="Right",sT=(e)=>{let t=Object.create(nD);return t.left=e,t},cT=(e)=>{let t=Object.create(tD);return t.right=e,t};var lT=w(()=>{Re();Ge();at();Ie();wo();Bg=Symbol.for("effect/Either"),aT={...bo,[Bg]:{_R:(e)=>e},[me](){return this.toJSON()},toString(){return Ee(this.toJSON())}},tD=Object.assign(Object.create(aT),{_tag:"Right",_op:"Right",[z](e){return mp(e)&&Wg(e)&&j(this.right,e.right)},[J](){return le(U(this._tag))(U(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:Te(this.right)}}}),nD=Object.assign(Object.create(aT),{_tag:"Left",_op:"Left",[z](e){return mp(e)&&Vg(e)&&j(this.left,e.left)},[J](){return le(U(this._tag))(U(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:Te(this.left)}}})});var ue,ce,zg,qe,Tt,hp,uT,El,dT,Kg,pT;var hn=w(()=>{ne();lT();ue=cT,ce=sT,zg=mp,qe=Vg,Tt=Wg,hp=h(2,(e,t)=>qe(e)?ce(t(e.left)):ue(e.right)),uT=h(2,(e,t)=>Tt(e)?ue(t(e.right)):ce(e.left)),El=h(2,(e,{onLeft:t,onRight:n})=>qe(e)?t(e.left):n(e.right)),dT=El({onLeft:ve,onRight:ve}),Kg=h(2,(e,t)=>{if(Tt(e))return e.right;throw t(e.left)}),pT=Kg(()=>Error("getOrThrow called on a Left"))});var Jg=(e)=>e.length>0;var fT=(e)=>(t,n)=>t===n?0:e(t,n),mT,gp,Gg=(e)=>h(2,(t,n)=>e(t,n)===1);var yp=w(()=>{ne();mT=fT((e,t)=>e<t?-1:1),gp=h(2,(e,t)=>fT((n,r)=>e(t(n),t(r))))});var B=()=>fp,Y,Ye,$e,pt,Ue,ur,hT,_o=(e)=>e==null?B():Y(e),gn,gT=(e)=>(...t)=>{try{return Y(e(...t))}catch{return B()}},dr,pr,yT,aD=(e)=>h(2,(t,n)=>Ye(t)?!1:e(t.value,n)),sD,xT,ST;var ft=w(()=>{Re();ne();Hg();Y=kl,Ye=$g,$e=jg,pt=h(2,(e,{onNone:t,onSome:n})=>Ye(e)?t():n(e.value)),Ue=h(2,(e,t)=>Ye(e)?t():e.value),ur=h(2,(e,t)=>Ye(e)?t():e),hT=h(2,(e,t)=>Ye(e)?Y(t()):e),gn=Ue(rp),dr=h(2,(e,t)=>Ye(e)?B():Y(t(e.value))),pr=h(2,(e,t)=>Ye(e)?B():t(e.value)),yT=h(2,(e,t)=>Ye(e)?B():_o(t(e.value))),sD=_l(),xT=aD(sD),ST=h(2,(e,t)=>Ye(e)?!1:t(e.value))});var bT=(...e)=>e;var wT=()=>{};var wa=(e)=>Array(e),Zg,je=(e)=>Array.isArray(e)?e:Array.from(e),Xg=(e)=>Array.isArray(e)?e:[e],_T,Ds,vT,Qg,ey,lD=(e)=>e.length===0,RT,mi,Fe,TT=(e,t)=>e<0||e>=t.length,uD=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),dD,ty,vo,xt,CT=(e)=>Fe(e)?Y(ny(e)):B(),ny=(e)=>e[e.length-1],fr=(e)=>e.slice(1),pD=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},OT,kT,ry=(e)=>Array.from(e).reverse(),Ro,oy,ET,fD,mD,hD,qs=(e)=>e.slice(),gD,hi,To=()=>[],Gt=(e)=>[e],mr,Il,xp,Sp,Us,iy=(e,t)=>{let n=[],r=e,o;while($e(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},gi,IT,ay=(e)=>IT(e,_l()),Co;var st=w(()=>{Re();gl();ne();ft();wT();Zg=h(2,(e,t)=>{let n=Math.max(1,Math.floor(e)),r=Array(n);for(let o=0;o<n;o++)r[o]=t(o);return r}),_T=h(2,(e,{onEmpty:t,onNonEmpty:n})=>Fe(e)?n(xt(e),fr(e)):t()),Ds=h(2,(e,t)=>[t,...e]),vT=h(2,(e,t)=>[...e,t]),Qg=h(2,(e,t)=>je(e).concat(je(t))),ey=Array.isArray,RT=lD,mi=Jg,Fe=Jg,dD=h(2,(e,t)=>{let n=Math.floor(t);return TT(n,e)?B():Y(e[n])}),ty=h(2,(e,t)=>{let n=Math.floor(t);if(TT(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),vo=dD(0),xt=ty(0),OT=h(2,(e,t)=>mD(e,pD(e,t))),kT=h(2,(e,t)=>{let n=je(e);return n.slice(uD(t,n),n.length)}),Ro=h(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),oy=h(2,(e,t)=>ET(e,t,bT)),ET=h(3,(e,t,n)=>{let r=je(e),o=je(t);if(Fe(r)&&Fe(o)){let i=[n(xt(r),xt(o))],a=Math.min(r.length,o.length);for(let s=1;s<a;s++)i[s]=n(r[s],o[s]);return i}return[]}),fD=_l(),mD=h(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(Fe(n)){if(r>=1)return hD(n,r);return[[],n]}return[n,[]]}),hD=h(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[qs(e),[]]:[Ds(e.slice(1,n),xt(e)),e.slice(n)]}),gD=h(3,(e,t,n)=>{let r=je(e),o=je(t);if(Fe(r)){if(Fe(o))return IT(n)(Qg(r,o));return r}return o}),hi=h(2,(e,t)=>gD(e,t,fD)),mr=h(2,(e,t)=>e.map(t)),Il=h(2,(e,t)=>{if(RT(e))return[];let n=[];for(let r=0;r<e.length;r++){let o=t(e[r],r);for(let i=0;i<o.length;i++)n.push(o[i])}return n}),xp=Il(ve),Sp=h(2,(e,t)=>{let n=je(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if($e(i))r.push(i.value)}return r}),Us=h(3,(e,t,n)=>je(e).reduce((r,o,i)=>n(r,o,i),t)),gi=UR,IT=h(2,(e,t)=>{let n=je(e);if(Fe(n)){let r=[xt(n)],o=fr(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),Co=h(2,(e,t)=>je(e).join(t))});function bD(e,t,n,r,o){for(let i=t;i<Math.min(e.length,t+o);i++)n[r+i-t]=e[i];return n}var AT,MT,wD=(e)=>hl((t,n)=>t.length===n.length&&Oo(t).every((r,o)=>e(r,$s(n,o)))),_D,vD,Ct=(e)=>{let t=Object.create(vD);switch(t.backing=e,e._tag){case"IEmpty":{t.length=0,t.depth=0,t.left=t,t.right=t;break}case"IConcat":{t.length=e.left.length+e.right.length,t.depth=1+Math.max(e.left.depth,e.right.depth),t.left=e.left,t.right=e.right;break}case"IArray":{t.length=e.array.length,t.depth=0,t.left=Br,t.right=Br;break}case"ISingleton":{t.length=1,t.depth=0,t.left=Br,t.right=Br;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=Br,t.right=Br;break}}return t},NT=(e)=>H(e,AT),Br,Bn=()=>Br,Pl=(...e)=>CD(e),St=(e)=>Ct({_tag:"ISingleton",a:e}),bp=(e)=>NT(e)?e:Al(je(e)),sy=(e,t,n)=>{switch(e.backing._tag){case"IArray":{bD(e.backing.array,0,t,n,e.length);break}case"IConcat":{sy(e.left,t,n),sy(e.right,t,n+e.left.length);break}case"ISingleton":{t[n]=e.backing.a;break}case"ISlice":{let r=0,o=n;while(r<e.length)t[o]=$s(e,r),r+=1,o+=1;break}}},RD=(e)=>{switch(e.backing._tag){case"IEmpty":return MT;case"IArray":return e.backing.array;default:{let t=Array(e.length);return sy(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Br,e.right=Br,e.depth=0,t}}},Oo,TD=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return Ct({_tag:"IArray",array:ry(e.backing.array)});case"IConcat":return Ct({_tag:"IConcat",left:yi(e.backing.right),right:yi(e.backing.left)});case"ISlice":return Al(ry(Oo(e)))}},yi,Al=(e)=>e.length===0?Bn():e.length===1?St(e[0]):Ct({_tag:"IArray",array:e}),CD=(e)=>Al(e),$s,FT,Yt,cy,Pn,LT=(e)=>e.length===0,hr=(e)=>e.length>0,ly=(e)=>$s(e,0),gr,yr=(e)=>cy(e,1);var Vr=w(()=>{st();Re();gl();ne();Ge();at();Ne();Ie();AT=Symbol.for("effect/Chunk");MT=[],_D=wD(j),vD={[AT]:{_A:(e)=>e},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Chunk",values:Oo(this).map(Te)}},[me](){return this.toJSON()},[z](e){return NT(e)&&_D(this,e)},[J](){return ye(this,En(Oo(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return MT[Symbol.iterator]();default:return Oo(this)[Symbol.iterator]()}},pipe(){return F(this,arguments)}},Br=Ct({_tag:"IEmpty"}),Oo=RD,yi=TD,$s=h(2,(e,t)=>{switch(e.backing._tag){case"IEmpty":throw Error("Index out of bounds");case"ISingleton":{if(t!==0)throw Error("Index out of bounds");return e.backing.a}case"IArray":{if(t>=e.length||t<0)throw Error("Index out of bounds");return e.backing.array[t]}case"IConcat":return t<e.left.length?$s(e.left,t):$s(e.right,t-e.left.length);case"ISlice":return $s(e.backing.chunk,t+e.backing.offset)}}),FT=h(2,(e,t)=>Pn(e,St(t))),Yt=h(2,(e,t)=>Pn(St(t),e)),cy=h(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return Br;else switch(e.backing._tag){case"ISlice":return Ct({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return cy(e.right,t-e.left.length);return Ct({_tag:"IConcat",left:cy(e.left,t),right:e.right})}default:return Ct({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),Pn=h(2,(e,t)=>{if(e.backing._tag==="IEmpty")return t;if(t.backing._tag==="IEmpty")return e;let n=t.depth-e.depth;if(Math.abs(n)<=1)return Ct({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=Pn(e.right,t);return Ct({_tag:"IConcat",left:e.left,right:r})}else{let r=Pn(e.right.right,t);if(r.depth===e.depth-3){let o=Ct({_tag:"IConcat",left:e.right.left,right:r});return Ct({_tag:"IConcat",left:e.left,right:o})}else{let o=Ct({_tag:"IConcat",left:e.left,right:e.right.left});return Ct({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=Pn(e,t.left);return Ct({_tag:"IConcat",left:r,right:t.right})}else{let r=Pn(e,t.left.left);if(r.depth===t.depth-3){let o=Ct({_tag:"IConcat",left:r,right:t.left.right});return Ct({_tag:"IConcat",left:o,right:t.right})}else{let o=Ct({_tag:"IConcat",left:t.left.right,right:t.right});return Ct({_tag:"IConcat",left:r,right:o})}}}),gr=ly});var xi=5,uy,DT,qT,UT;var wp=w(()=>{uy=Math.pow(2,5),DT=uy-1,qT=uy/2,UT=uy/4});function OD(e){return e-=e>>1&1431655765,e=(e&858993459)+(e>>2&858993459),e=e+(e>>4)&252645135,e+=e>>8,e+=e>>16,e&127}function Si(e,t){return t>>>e&DT}function bi(e){return 1<<e}function _p(e,t){return OD(e&t-1)}var dy=w(()=>{wp()});var $T=(e,t)=>({value:e,previous:t});function _a(e,t,n,r){let o=r;if(!e){let i=r.length;o=Array(i);for(let a=0;a<i;++a)o[a]=r[a]}return o[t]=n,o}function py(e,t,n){let r=n.length-1,o=0,i=0,a=n;if(e)o=i=t;else{a=Array(r);while(o<t)a[i++]=n[o++]}++o;while(o<=r)a[i++]=n[o++];if(e)a.length=r;return a}function jT(e,t,n,r){let o=r.length;if(e){let c=o;while(c>=t)r[c--]=r[c];return r[t]=n,r}let i=0,a=0,s=Array(o+1);while(i<t)s[a++]=r[i++];s[t]=n;while(i<o)s[++a]=r[i++];return s}class Eo{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(B());if(Ye(a))return new Eo;return++i.value,new va(e,r,o,a)}}function Vn(e){return Sl(e,"EmptyNode")}function ED(e){return Vn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function vp(e,t){return Vn(e)?!1:t===e.edit}class va{edit;hash;key;value;_tag="LeafNode";constructor(e,t,n,r){this.edit=e,this.hash=t,this.key=n,this.value=r}modify(e,t,n,r,o,i){if(j(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Ye(s))return--i.value,new Eo;if(vp(this,e))return this.value=s,this;return new va(e,r,o,s)}let a=n(B());if(Ye(a))return this;return++i.value,HT(e,t,this.hash,this,r,new va(e,r,o,a))}}class fy{edit;hash;children;_tag="CollisionNode";constructor(e,t,n){this.edit=e,this.hash=t,this.children=n}modify(e,t,n,r,o,i){if(r===this.hash){let s=vp(this,e),c=this.updateCollisionList(s,e,this.hash,this.children,n,o,i);if(c===this.children)return this;return c.length>1?new fy(e,this.hash,c):c[0]}let a=n(B());if(Ye(a))return this;return++i.value,HT(e,t,this.hash,this,r,new va(e,r,o,a))}updateCollisionList(e,t,n,r,o,i,a){let s=r.length;for(let l=0;l<s;++l){let u=r[l];if("key"in u&&j(i,u.key)){let d=u.value,p=o(d);if(p===d)return r;if(Ye(p))return--a.value,py(e,l,r);return _a(e,l,new va(t,n,i,p),r)}}let c=o(B());if(Ye(c))return r;return++a.value,_a(e,s,new va(t,n,i,c),r)}}class js{edit;mask;children;_tag="IndexedNode";constructor(e,t,n){this.edit=e,this.mask=t,this.children=n}modify(e,t,n,r,o,i){let a=this.mask,s=this.children,c=Si(t,r),l=bi(c),u=_p(a,l),d=a&l,p=vp(this,e);if(!d){let y=new Eo().modify(e,t+xi,n,r,o,i);if(!y)return this;return s.length>=qT?PD(e,c,y,a,s):new js(e,a|l,jT(p,u,y,s))}let m=s[u],f=m.modify(e,t+xi,n,r,o,i);if(m===f)return this;let x=a,g;if(Vn(f)){if(x&=~l,!x)return new Eo;if(s.length<=2&&ED(s[u^1]))return s[u^1];g=py(p,u,s)}else g=_a(p,u,f,s);if(p)return this.mask=x,this.children=g,this;return new js(e,x,g)}}class my{edit;size;children;_tag="ArrayNode";constructor(e,t,n){this.edit=e,this.size=t,this.children=n}modify(e,t,n,r,o,i){let a=this.size,s=this.children,c=Si(t,r),l=s[c],u=(l||new Eo).modify(e,t+xi,n,r,o,i);if(l===u)return this;let d=vp(this,e),p;if(Vn(l)&&!Vn(u))++a,p=_a(d,c,u,s);else if(!Vn(l)&&Vn(u)){if(--a,a<=UT)return ID(e,a,c,s);p=_a(d,c,new Eo,s)}else p=_a(d,c,u,s);if(d)return this.size=a,this.children=p,this;return new my(e,a,p)}}function ID(e,t,n,r){let o=Array(t-1),i=0,a=0;for(let s=0,c=r.length;s<c;++s)if(s!==n){let l=r[s];if(l&&!Vn(l))o[i++]=l,a|=1<<s}return new js(e,a,o)}function PD(e,t,n,r,o){let i=[],a=r,s=0;for(let c=0;a;++c){if(a&1)i[c]=o[s++];a>>>=1}return i[t]=n,new my(e,s+1,i)}function AD(e,t,n,r,o,i){if(n===o)return new fy(e,n,[i,r]);let a=Si(t,n),s=Si(t,o);if(a===s)return(c)=>new js(e,bi(a)|bi(s),[c]);else{let c=a<s?[r,i]:[i,r];return new js(e,bi(a)|bi(s),c)}}function HT(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=AD(e,s,n,r,o,i);if(typeof c==="function")a=$T(c,a),s=s+xi;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var BT=w(()=>{Re();ft();Ie();dy();wp()});var VT="effect/HashMap",Rp,ND,hy=(e,t,n,r)=>{let o=Object.create(ND);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},Cp,Tp=(e)=>e?zT(e[0],e[1],e[2],e[3],e[4]):B(),WT=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if($e(e.value))return Y({value:t(e.key,e.value.value),cont:n});return Tp(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return zT(r.length,r,0,t,n)}default:return Tp(n)}},zT=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!Vn(i))return WT(i,r,[e,t,n,r,o])}return Tp(o)},FD,Hs=()=>FD,KT=(e)=>{let t=Ep(Hs());for(let n of e)Ra(t,n[0],n[1]);return ZT(t)},JT=(e)=>H(e,Rp),GT=(e)=>e&&Vn(e._root),YT,Op,gy,Ra,LD,kp=(e)=>new Cp(e,(t)=>t),Ml=(e)=>e._size,Ep=(e)=>hy(!0,e._edit+1,e._root,e._size),ZT=(e)=>(e._editable=!1,e),Ip,XT,Pp,QT,yy,Bs;var xy=w(()=>{Re();ne();ne();Ge();at();ft();Ne();Ie();dy();wp();BT();Rp=Symbol.for(VT),ND={[Rp]:Rp,[Symbol.iterator](){return new Cp(this,(e,t)=>[e,t])},[J](){let e=U(VT);for(let t of this)e^=b(U(t[0]),le(U(t[1])));return ye(this,e)},[z](e){if(JT(e)){if(e._size!==this._size)return!1;for(let t of this){let n=b(e,Op(t[0],U(t[0])));if(Ye(n))return!1;else if(!j(t[1],n.value))return!1}return!0}return!1},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(Te)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}};Cp=class Cp{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=WT(this.map._root,this.f,void 0)}next(){if(Ye(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=Tp(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new Cp(this.map,this.f)}};FD=hy(!1,0,new Eo,0),YT=h(2,(e,t)=>Op(e,t,U(t))),Op=h(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return j(t,r.key)?r.value:B();case"CollisionNode":{if(n===r.hash){let i=r.children;for(let a=0,s=i.length;a<s;++a){let c=i[a];if("key"in c&&j(t,c.key))return c.value}}return B()}case"IndexedNode":{let i=Si(o,n),a=bi(i);if(r.mask&a){r=r.children[_p(r.mask,a)],o+=xi;break}return B()}case"ArrayNode":{if(r=r.children[Si(o,n)],r){o+=xi;break}return B()}default:return B()}}),gy=h(2,(e,t)=>$e(Op(e,t,U(t)))),Ra=h(3,(e,t,n)=>Ip(e,t,()=>Y(n))),LD=h(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:hy(e._editable,e._edit,t,n)}),Ip=h(3,(e,t,n)=>XT(e,t,U(t),n)),XT=h(4,(e,t,n,r)=>{let o={value:e._size},i=e._root.modify(e._editable?e._edit:NaN,0,r,n,t,o);return b(e,LD(i,o.value))}),Pp=h(2,(e,t)=>Ip(e,t,B)),QT=h(2,(e,t)=>Bs(e,Hs(),(n,r,o)=>Ra(n,o,t(r,o)))),yy=h(2,(e,t)=>Bs(e,void 0,(n,r,o)=>t(r,o))),Bs=h(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return $e(r.value)?n(t,r.value.value,r.key):t;if(r._tag==="EmptyNode")return t;let o=[r.children],i;while(i=o.pop())for(let a=0,s=i.length;a<s;){let c=i[a++];if(c&&!Vn(c))if(c._tag==="LeafNode"){if($e(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var tC="effect/HashSet",Ap,DD,Mp=(e)=>{let t=Object.create(DD);return t._keyMap=e,t},nC=(e)=>H(e,Ap),qD,Nl=()=>qD,rC=(e)=>{let t=Np(Nl());for(let n of e)Vs(t,n);return Fp(t)},oC=(...e)=>{let t=Np(Nl());for(let n of e)Vs(t,n);return Fp(t)},iC,aC=(e)=>Ml(e._keyMap),Np=(e)=>Mp(Ep(e._keyMap)),Fp=(e)=>(e._keyMap._editable=!1,e),Sy,Vs,by,sC,cC,lC,uC;var dC=w(()=>{Re();ne();Ge();at();Ne();Ie();xy();Ap=Symbol.for(tC),DD={[Ap]:Ap,[Symbol.iterator](){return kp(this._keyMap)},[J](){return ye(this,le(U(this._keyMap))(U(tC)))},[z](e){if(nC(e))return Ml(this._keyMap)===Ml(e._keyMap)&&j(this._keyMap,e._keyMap);return!1},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(Te)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}},qD=Mp(Hs()),iC=h(2,(e,t)=>gy(e._keyMap,t)),Sy=h(2,(e,t)=>{let n=Np(e);return t(n),Fp(n)}),Vs=h(2,(e,t)=>e._keyMap._editable?(Ra(t,!0)(e._keyMap),e):Mp(Ra(t,!0)(e._keyMap))),by=h(2,(e,t)=>e._keyMap._editable?(Pp(t)(e._keyMap),e):Mp(Pp(t)(e._keyMap))),sC=h(2,(e,t)=>Sy(e,(n)=>{for(let r of t)by(n,r)})),cC=h(2,(e,t)=>Sy(Nl(),(n)=>{lC(e,(r)=>Vs(n,r));for(let r of t)Vs(n,r)})),lC=h(2,(e,t)=>yy(e._keyMap,(n,r)=>t(r))),uC=h(3,(e,t,n)=>Bs(e._keyMap,t,(r,o,i)=>n(r,i)))});var Wr,pC,Ta,fC,Fl,Ca,wy,_y,Io,Oa;var ka=w(()=>{dC();Wr=Nl,pC=rC,Ta=oC,fC=iC,Fl=aC,Ca=Vs,wy=by,_y=sC,Io=cC,Oa=uC});var zs="Die",wi="Empty",_i="Fail",Ea="Interrupt",Ia="Parallel",Pa="Sequential";var gC="effect/Cause",Ty,jD,Ks,Po,Js=(e)=>{let t=Object.create(Ks);return t._tag=_i,t.error=e,t},An=(e)=>{let t=Object.create(Ks);return t._tag=zs,t.defect=e,t},xr=(e)=>{let t=Object.create(Ks);return t._tag=Ea,t.fiberId=e,t},Na=(e,t)=>{let n=Object.create(Ks);return n._tag=Ia,n.left=e,n.right=t,n},Zt=(e,t)=>{let n=Object.create(Ks);return n._tag=Pa,n.left=e,n.right=t,n},yC=(e)=>H(e,Ty),Cy=(e)=>e._tag===wi,xC=(e)=>e._tag===_i,Lp=(e)=>{if(e._tag===wi)return!0;return Aa(e,!0,(t,n)=>{switch(n._tag){case wi:return Y(t);case zs:case _i:case Ea:return Y(!1);default:return B()}})},Dp=(e)=>$e(SC(e)),Gs=(e)=>$p(void 0,WD)(e),Oy=(e)=>yi(Aa(e,Bn(),(t,n)=>n._tag===_i?Y(b(t,Yt(n.error))):B())),ky=(e)=>yi(Aa(e,Bn(),(t,n)=>n._tag===zs?Y(b(t,Yt(n.defect))):B())),Ey=(e)=>Aa(e,Wr(),(t,n)=>n._tag===Ea?Y(b(t,Ca(n.fiberId))):B()),Iy=(e)=>Py(e,(t)=>t._tag===_i?Y(t.error):B()),qp=(e)=>{let t=Iy(e);switch(t._tag){case"None":return ue(e);case"Some":return ce(t.value)}},SC=(e)=>Py(e,(t)=>t._tag===Ea?Y(t.fiberId):B()),Up=(e)=>Ay(e,{onEmpty:Po,onFail:()=>Po,onDie:An,onInterrupt:xr,onSequential:Zt,onParallel:Na}),bC=(e)=>Ay(e,{onEmpty:Po,onFail:An,onDie:An,onInterrupt:xr,onSequential:Zt,onParallel:Na}),HD=(e,t)=>{let n=St(e),r=St(t);while(hr(n)&&hr(r)){let[o,i]=b(gr(n),Aa([Wr(),Bn()],([c,l],u)=>{let[d,p]=vy(u);return Y([b(c,Io(d)),b(l,Pn(p))])})),[a,s]=b(gr(r),Aa([Wr(),Bn()],([c,l],u)=>{let[d,p]=vy(u);return Y([b(c,Io(d)),b(l,Pn(p))])}));if(!j(o,a))return!1;n=i,r=s}return!0},BD=(e)=>VD(St(e),Bn()),VD=(e,t)=>{while(!0){let[n,r]=b(e,Us([Wr(),Bn()],([i,a],s)=>{let[c,l]=vy(s);return[b(i,Io(c)),b(a,Pn(l))]})),o=Fl(n)>0?b(t,Yt(n)):t;if(LT(r))return yi(o);e=r,t=o}throw Error(ha("Cause.flattenCauseLoop"))},Py,vy=(e)=>{let t=e,n=[],r=Wr(),o=Bn();while(t!==void 0)switch(t._tag){case wi:{if(n.length===0)return[r,o];t=n.pop();break}case _i:{if(r=Ca(r,Pl(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case zs:{if(r=Ca(r,Pl(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case Ea:{if(r=Ca(r,Pl(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case Pa:{switch(t.left._tag){case wi:{t=t.right;break}case Pa:{t=Zt(t.left.left,Zt(t.left.right,t.right));break}case Ia:{t=Na(Zt(t.left.left,t.right),Zt(t.left.right,t.right));break}default:{o=Yt(o,t.right),t=t.left;break}}break}case Ia:{n.push(t.right),t=t.left;break}}throw Error(ha("Cause.evaluateCauseLoop"))},WD,mC="SequentialCase",hC="ParallelCase",Ay,Aa,$p,Sr=(e,t)=>{if(Gs(e))return"All fibers interrupted without errors.";return Ll(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
+ ${wC(n.cause," ")}
11
11
  }`}).join(`
12
- `)},hC=(e,t)=>{let n=e.stack.split(`
12
+ `)},wC=(e,t)=>{let n=e.stack.split(`
13
13
  `),r=`${t}[cause]: ${n[0]}`;for(let o=1,i=n.length;o<i;o++)r+=`
14
14
  ${t}${n[o]}`;if(e.cause)r+=` {
15
- ${hC(e.cause,`${t} `)}
16
- ${t}}`;return r},py=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(qD(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:py(e.cause)}:void 0);if(Error.stackTraceLimit=n,r.message==="")r.message="An error has occurred";if(Error.stackTraceLimit=n,r.name=e instanceof Error?e.name:"Error",t){if(_a in e)r.span=e[_a];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=jD(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},qD=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(H(e,"toString")&&Xo(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return Zd(e)},$D,UD,jD=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
15
+ ${wC(e.cause,`${t} `)}
16
+ ${t}}`;return r},Ry=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(zD(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:Ry(e.cause)}:void 0);if(Error.stackTraceLimit=n,r.message==="")r.message="An error has occurred";if(Error.stackTraceLimit=n,r.name=e instanceof Error?e.name:"Error",t){if(Ma in e)r.span=e[Ma];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=GD(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},zD=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(H(e,"toString")&&ui(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return up(e)},KD,JD,GD=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
17
17
  `):t.split(`
18
- `);for(let i=1;i<o.length;i++){if(o[i].includes(" at new BaseEffectError")||o[i].includes(" at new YieldableError")){i++;continue}if(o[i].includes("Generator.next"))break;if(o[i].includes("effect_internal_function"))break;r.push(o[i].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(n){let i=n,a=0;while(i&&i._tag==="Span"&&a<10){let s=UD.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll($D),u=!1;for(let[,d]of l)u=!0,r.push(` at ${i.name} (${d})`);if(!u)r.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else r.push(` at ${i.name}`)}else r.push(` at ${i.name}`);i=xn(i.parent),a++}}return r.join(`
19
- `)},_a,kl=(e)=>Op(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[py(n)],failCase:(t,n)=>[py(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Hs=b(()=>{at();$r();yn();ve();te();Ke();ga();it();pt();Ae();ke();fy=Symbol.for(uC),MD={_E:(e)=>e},$s={[fy]:MD,[G](){return S(U(uC),se(U(FD(this))),ge(this))},[z](e){return dC(e)&&ND(this,e)},pipe(){return L(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:Re(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:Re(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:Re(this.left),right:Re(this.right)}}},toString(){return fr(this)},[pe](){return this.toJSON()}},To=(()=>{let e=Object.create($s);return e._tag=li,e})(),Sy=h(2,(e,t)=>{let n=[e];while(n.length>0){let r=n.pop(),o=t(r);switch(o._tag){case"None":{switch(r._tag){case Sa:case xa:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return B()}),DD={emptyCase:il,failCase:Yo,dieCase:Yo,interruptCase:il,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},by=h(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>Op(e,void 0,{emptyCase:()=>n,failCase:(s,c)=>r(c),dieCase:(s,c)=>t(c),interruptCase:(s,c)=>o(c),sequentialCase:(s,c,l)=>a(c,l),parallelCase:(s,c,l)=>i(c,l)})),ba=h(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=De(a)?a.value:r,o._tag){case Sa:{i.push(o.right),o=o.left;break}case xa:{i.push(o.right),o=o.left;break}default:{o=void 0;break}}if(o===void 0&&i.length>0)o=i.pop()}return r}),Op=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case li:{o.push(ue(n.emptyCase(t)));break}case ui:{o.push(ue(n.failCase(t,a.error)));break}case qs:{o.push(ue(n.dieCase(t,a.defect)));break}case ya:{o.push(ue(n.interruptCase(t,a.fiberId)));break}case Sa:{r.push(a.right),r.push(a.left),o.push(ae({_tag:cC}));break}case xa:{r.push(a.right),r.push(a.left),o.push(ae({_tag:lC}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case cC:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case lC:{let s=i.pop(),c=i.pop(),l=n.parallelCase(t,s,c);i.push(l);break}}break}case"Right":{i.push(a.right);break}}}if(i.length===0)throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()}),$D=/\((.*)\)/g,UD=ne("effect/Tracer/spanToTrace",()=>new WeakMap),_a=Symbol.for("effect/SpanAnnotation")});var gC,Pl,HD="effect/STM",BD,yC,VD,xC=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(yC);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},SC=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,VD),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},wy,WD,di=(e)=>{let t=Object.create(WD);return t.unsafeMap=e,t},zD=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(e.stack){let n=e.stack.split(`
18
+ `);for(let i=1;i<o.length;i++){if(o[i].includes(" at new BaseEffectError")||o[i].includes(" at new YieldableError")){i++;continue}if(o[i].includes("Generator.next"))break;if(o[i].includes("effect_internal_function"))break;r.push(o[i].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(n){let i=n,a=0;while(i&&i._tag==="Span"&&a<10){let s=JD.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(KD),u=!1;for(let[,d]of l)u=!0,r.push(` at ${i.name} (${d})`);if(!u)r.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else r.push(` at ${i.name}`)}else r.push(` at ${i.name}`);i=gn(i.parent),a++}}return r.join(`
19
+ `)},Ma,Ll=(e)=>$p(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[Ry(n)],failCase:(t,n)=>[Ry(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Ys=w(()=>{st();Vr();hn();Re();ne();Ge();ka();at();ft();Ne();Ie();Ty=Symbol.for(gC),jD={_E:(e)=>e},Ks={[Ty]:jD,[J](){return b(U(gC),le(U(BD(this))),ye(this))},[z](e){return yC(e)&&HD(this,e)},pipe(){return F(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:Te(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:Te(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:Te(this.left),right:Te(this.right)}}},toString(){return Sr(this)},[me](){return this.toJSON()}},Po=(()=>{let e=Object.create(Ks);return e._tag=wi,e})(),Py=h(2,(e,t)=>{let n=[e];while(n.length>0){let r=n.pop(),o=t(r);switch(o._tag){case"None":{switch(r._tag){case Pa:case Ia:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return B()}),WD={emptyCase:pl,failCase:ci,dieCase:ci,interruptCase:pl,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},Ay=h(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>$p(e,void 0,{emptyCase:()=>n,failCase:(s,c)=>r(c),dieCase:(s,c)=>t(c),interruptCase:(s,c)=>o(c),sequentialCase:(s,c,l)=>a(c,l),parallelCase:(s,c,l)=>i(c,l)})),Aa=h(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=$e(a)?a.value:r,o._tag){case Pa:{i.push(o.right),o=o.left;break}case Ia:{i.push(o.right),o=o.left;break}default:{o=void 0;break}}if(o===void 0&&i.length>0)o=i.pop()}return r}),$p=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case wi:{o.push(ue(n.emptyCase(t)));break}case _i:{o.push(ue(n.failCase(t,a.error)));break}case zs:{o.push(ue(n.dieCase(t,a.defect)));break}case Ea:{o.push(ue(n.interruptCase(t,a.fiberId)));break}case Pa:{r.push(a.right),r.push(a.left),o.push(ce({_tag:mC}));break}case Ia:{r.push(a.right),r.push(a.left),o.push(ce({_tag:hC}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case mC:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case hC:{let s=i.pop(),c=i.pop(),l=n.parallelCase(t,s,c);i.push(l);break}}break}case"Right":{i.push(a.right);break}}}if(i.length===0)throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()}),KD=/\((.*)\)/g,JD=re("effect/Tracer/spanToTrace",()=>new WeakMap),Ma=Symbol.for("effect/SpanAnnotation")});var _C,ql,YD="effect/STM",ZD,vC,XD,RC=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(vC);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},TC=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,XD),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},Ny,QD,vi=(e)=>{let t=Object.create(QD);return t.unsafeMap=e,t},eq=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(e.stack){let n=e.stack.split(`
20
20
  `);if(n.length>2){let r=n[2].match(/at (.*)/);if(r)t.message=t.message+` (defined at ${r[1]})`}}if(t.stack){let n=t.stack.split(`
21
21
  `);n.splice(1,3),t.stack=n.join(`
22
- `)}return t},bC=(e)=>H(e,wy),_C=(e)=>H(e,Pl),KD,wC=()=>KD,vy=(e,t)=>di(new Map([[e.key,t]])),vC,_y,Ry=(e)=>{if(_y.has(e.key))return _y.get(e.key);let t=e.defaultValue();return _y.set(e.key,t),t},RC=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Ry(t),Ty,TC,CC,OC;var Ep=b(()=>{ve();te();Ke();it();Ae();ke();ho();Ig();gC=Symbol.for("effect/Context/Tag"),Pl=Symbol.for("effect/Context/Reference"),BD=Symbol.for(HD),yC={...mo,_op:"Tag",[BD]:ei,[gC]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[pe](){return this.toJSON()},of(e){return e},context(e){return vy(this,e)}},VD={...yC,[Pl]:Pl},wy=Symbol.for("effect/Context"),WD={[wy]:{_Services:(e)=>e},[z](e){if(bC(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!j(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[G](){return ge(this,Jd(this.unsafeMap.size))},pipe(){return L(this,arguments)},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(Re)}},[pe](){return this.toJSON()}},KD=di(new Map),vC=h(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),di(r)}),_y=ne("effect/Context/defaultValueCache",()=>new Map),Ty=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(Pl in t)return Ry(t);throw zD(t)}return e.unsafeMap.get(t.key)}),TC=Ty,CC=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return _C(t)?_l(Ry(t)):ep;return _l(e.unsafeMap.get(t.key))}),OC=h(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return di(n)})});var Sn,pi,kC,jr,Al,Ml,fi,Nl,Fl;var Vn=b(()=>{Ep();Sn=xC,pi=wC,kC=vy,jr=vC,Al=TC,Ml=Ty,fi=CC,Nl=OC,Fl=SC});var Oy,NC,IC,kp,Ey,PC,AC,JD,Co=(e)=>{if(FC(e))return e;else if(Cn(e))return Ip(e);else if(Zo(e))return Cy(e);else if(Array.isArray(e)&&e.length===2&&e.every(Cn)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return ky;if(e[0]===1/0||e[1]===1/0)return XD;return Cy(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if($t(e)){let t=JD.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return Cy(BigInt(r));case"micro":case"micros":return QD(BigInt(r));case"milli":case"millis":return Ip(i);case"second":case"seconds":return eq(i);case"minute":case"minutes":return tq(i);case"hour":case"hours":return nq(i);case"day":case"days":return rq(i);case"week":case"weeks":return oq(i)}}}throw Error("Invalid DurationInput")},MC,GD,YD,Hr=(e)=>{let t=Object.create(YD);if(Cn(e))if(isNaN(e)||e<=0)t.value=MC;else if(!Number.isFinite(e))t.value=GD;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:BigInt(Math.round(e*1e6))};else t.value={_tag:"Millis",millis:e};else if(e<=NC)t.value=MC;else t.value={_tag:"Nanos",nanos:e};return t},FC=(e)=>H(e,Oy),ZD=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===NC;case"Infinity":return!1}},ky,XD,Cy=(e)=>Hr(e),QD=(e)=>Hr(e*Ey),Ip=(e)=>Hr(e),eq=(e)=>Hr(e*1000),tq=(e)=>Hr(e*60000),nq=(e)=>Hr(e*3600000),rq=(e)=>Hr(e*86400000),oq=(e)=>Hr(e*604800000),Pp=(e)=>sq(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),iq=(e)=>{let t=Co(e);switch(t.value._tag){case"Infinity":throw Error("Cannot convert infinite duration to nanos");case"Nanos":return t.value.nanos;case"Millis":return BigInt(Math.round(t.value.millis*1e6))}},aq=(e)=>{let t=Co(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/AC),Number(t.value.nanos%AC)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},sq,Iy,cq=(e,t)=>Iy(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),LC,DC,lq,uq=(e)=>{let t=Co(e);if(t.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};let n=iq(t),r=n/PC,o=r/Ey,i=o/kp,a=i/kp,s=a/IC;return{days:Number(s),hours:Number(a%IC),minutes:Number(i%kp),seconds:Number(o%kp),millis:Number(r%Ey),nanos:Number(n%PC)}},dq=(e)=>{let t=Co(e);if(t.value._tag==="Infinity")return"Infinity";if(ZD(t))return"0";let n=uq(t),r=[];if(n.days!==0)r.push(`${n.days}d`);if(n.hours!==0)r.push(`${n.hours}h`);if(n.minutes!==0)r.push(`${n.minutes}m`);if(n.seconds!==0)r.push(`${n.seconds}s`);if(n.millis!==0)r.push(`${n.millis}ms`);if(n.nanos!==0)r.push(`${n.nanos}ns`);return r.join(" ")};var Py=b(()=>{ve();te();Ke();it();Ae();ke();Oy=Symbol.for("effect/Duration"),NC=BigInt(0),IC=BigInt(24),kp=BigInt(60),Ey=BigInt(1000),PC=BigInt(1e6),AC=BigInt(1e9),JD=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,MC={_tag:"Millis",millis:0},GD={_tag:"Infinity"},YD={[Oy]:Oy,[G](){return ge(this,Gd(this.value))},[z](e){return FC(e)&&lq(this,e)},toString(){return`Duration(${dq(this)})`},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",hrtime:aq(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[pe](){return this.toJSON()},pipe(){return L(this,arguments)}},ky=Hr(0),XD=Hr(1/0),sq=h(2,(e,t)=>{let n=Co(e);switch(n.value._tag){case"Nanos":return t.onNanos(n.value.nanos);case"Infinity":return t.onMillis(1/0);case"Millis":return t.onMillis(n.value.millis)}}),Iy=h(3,(e,t,n)=>{let r=Co(e),o=Co(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(Pp(r),Pp(o));else if(r.value._tag==="Nanos"||o.value._tag==="Nanos"){let i=r.value._tag==="Nanos"?r.value.nanos:BigInt(Math.round(r.value.millis*1e6)),a=o.value._tag==="Nanos"?o.value.nanos:BigInt(Math.round(o.value.millis*1e6));return n.onNanos(i,a)}return n.onMillis(r.value.millis,o.value.millis)}),LC=h(2,(e,t)=>Iy(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),DC=h(2,(e,t)=>Iy(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),lq=h(2,(e,t)=>cq(Co(e),Co(t)))});var $C,pq,Ap=(e)=>{let t=Object.create(pq);return t.current=e,t},Bs=(e)=>e.current,Mp;var Ay=b(()=>{te();it();Ae();$C=Symbol.for("effect/MutableRef"),pq={[$C]:$C,toString(){return Ee(this.toJSON())},toJSON(){return{_id:"MutableRef",current:Re(this.current)}},[pe](){return this.toJSON()},pipe(){return L(this,arguments)}},Mp=h(2,(e,t)=>(e.current=t,e))});var Ny="effect/FiberId",Vs,Np="None",My="Runtime",fq="Composite",mq,HC,BC,VC,Fy=(e)=>H(e,Vs),Fp=(e)=>{switch(e._tag){case Np:return Ur();case My:return fa(e.id);case fq:return S(Fp(e.left),Ro(Fp(e.right)))}},jC,Lp=(e)=>Array.from(Fp(e)).map((n)=>`#${n}`).join(","),WC=()=>{let e=Bs(jC);return S(jC,Mp(e+1)),new BC(e,Date.now())};var Ly=b(()=>{ve();te();Ke();ga();it();Ay();ke();Vs=Symbol.for(Ny),mq=Oe(`${Ny}-${Np}`);HC=class HC{[Vs]=Vs;_tag=Np;id=-1;startTimeMillis=-1;[G](){return mq}[z](e){return Fy(e)&&e._tag===Np}toString(){return Ee(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[pe](){return this.toJSON()}};BC=class BC{id;startTimeMillis;[Vs]=Vs;_tag=My;constructor(e,t){this.id=e,this.startTimeMillis=t}[G](){return ge(this,Oe(`${Ny}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[z](e){return Fy(e)&&e._tag===My&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Ee(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[pe](){return this.toJSON()}};VC=new HC,jC=ne(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Ap(0))});var Wn,KC,Dp;var Ws=b(()=>{Ly();Wn=VC,KC=Lp,Dp=WC});var zs,JC,GC,Dy,qy,$y,YC,ZC,Uy;var qp=b(()=>{ay();zs=Ns,JC=jT,GC=BT,Dy=VT,qy=pa,$y=hp,YC=yp,ZC=KT,Uy=Fs});var Dl,Hy=(e)=>qe(e),hq=(e)=>gg(oi(e),Hy),gq,yq,$p=(e,t)=>{let n=Object.create(yq);return n.head=e,n.tail=t,n},xq,Sq,XC,QC=(e)=>H(e,Dl),Br=(e)=>e._tag==="Nil",By=(e)=>e._tag==="Cons",bq=()=>XC,Oo=(e,t)=>$p(e,t),mi,ql=(e)=>$p(e,XC),eO,_q,wq,tO,nO=(e)=>{let t=mi(),n=e;while(!Br(n))t=_q(t,n.head),n=n.tail;return t};var Up=b(()=>{at();ve();ll();te();Ke();it();Ae();ke();Dl=Symbol.for("effect/List"),gq=hq(j),yq={[Dl]:Dl,_tag:"Cons",toString(){return Ee(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:Hy(this).map(Re)}},[pe](){return this.toJSON()},[z](e){return QC(e)&&this._tag===e._tag&&gq(this,e)},[G](){return ge(this,On(Hy(this)))},[Symbol.iterator](){let e=!1,t=this;return{next(){if(e)return this.return();if(t._tag==="Nil")return e=!0,this.return();let n=t.head;return t=t.tail,{done:e,value:n}},return(n){if(!e)e=!0;return{done:!0,value:n}}}},pipe(){return L(this,arguments)}},xq=Oe("Nil"),Sq={[Dl]:Dl,_tag:"Nil",toString(){return Ee(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[pe](){return this.toJSON()},[G](){return xq},[z](e){return QC(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return L(this,arguments)}},XC=Object.create(Sq),mi=bq,eO=h(2,(e,t)=>wq(t,e)),_q=h(2,(e,t)=>Oo(t,e)),wq=h(2,(e,t)=>{if(Br(e))return t;else if(Br(t))return e;else{let n=$p(t.head,e),r=n,o=t.tail;while(!Br(o)){let i=$p(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),tO=h(3,(e,t,n)=>{let r=t,o=e;while(!Br(o))r=n(r,o.head),o=o.tail;return r})});var _Y,Ks;var jp=b(()=>{ve();Ke();ho();_Y=Object.assign(Object.create(Array.prototype),{[G](){return ge(this,On(this))},[z](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>j(t,e[n]));else return!1}}),Ks=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=bl,e}()});function rO(e){return e}var Rq,Ul,Tq,Cq,Wy=()=>Cq,Oq,Eq=(e,t)=>{let n=Object.create(Oq);return n.first=e,n.second=t,n},kq,Iq=(e,t)=>{let n=Object.create(kq);return n.key=e,n.service=t,n},Pq,Aq=(e)=>{let t=Object.create(Pq);return t.key=e,t},Mq,Nq=(e,t)=>{let n=Object.create(Mq);return n.key=e,n.update=t,n},oO=(e,t)=>{let n=new Map(e.unsafeMap),r=Wy();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!j(a,i))r=$l(Nq(o,()=>i))(r)}else n.delete(o),r=$l(Iq(o,i))(r);for(let[o]of n.entries())r=$l(Aq(o))(r);return r},$l,iO;var aO=b(()=>{$r();ve();te();Ep();jp();Rq=Symbol.for("effect/DifferContextPatch");Ul={...Ks.prototype,[Rq]:{_Value:rO,_Patch:rO}},Tq=Object.assign(Object.create(Ul),{_tag:"Empty"}),Cq=Object.create(Tq),Oq=Object.assign(Object.create(Ul),{_tag:"AndThen"}),kq=Object.assign(Object.create(Ul),{_tag:"AddService"}),Pq=Object.assign(Object.create(Ul),{_tag:"RemoveService"}),Mq=Object.assign(Object.create(Ul),{_tag:"UpdateService"}),$l=h(2,(e,t)=>Eq(e,t)),iO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=bt(e),o=new Map(t.unsafeMap);while(lr(r)){let a=ur(r),s=dr(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=Gt(Gt(s,a.second),a.first);break}case"RemoveService":{o.delete(a.key),r=s;break}case"UpdateService":{o.set(a.key,a.update(o.get(a.key))),n=!0,r=s;break}}}if(!n)return di(o);let i=new Map;for(let[a]of t.unsafeMap)if(o.has(a))i.set(a,o.get(a)),o.delete(a);for(let[a,s]of o)i.set(a,s);return di(i)})});function zy(e){return e}var Lq,Bp,Dq,qq,Ky=()=>qq,$q,Uq=(e,t)=>{let n=Object.create($q);return n.first=e,n.second=t,n},jq,Hq=(e)=>{let t=Object.create(jq);return t.value=e,t},Bq,Vq=(e)=>{let t=Object.create(Bq);return t.value=e,t},sO=(e,t)=>{let[n,r]=ha([e,Ky()],([o,i],a)=>{if(sC(a)(o))return[ly(a)(o),i];return[o,Hp(Hq(a))(i)]})(t);return ha(r,(o,i)=>Hp(Vq(i))(o))(n)},Hp,cO;var lO=b(()=>{$r();te();ga();jp();Lq=Symbol.for("effect/DifferHashSetPatch");Bp={...Ks.prototype,[Lq]:{_Value:zy,_Key:zy,_Patch:zy}},Dq=Object.assign(Object.create(Bp),{_tag:"Empty"}),qq=Object.create(Dq),$q=Object.assign(Object.create(Bp),{_tag:"AndThen"}),jq=Object.assign(Object.create(Bp),{_tag:"Add"}),Bq=Object.assign(Object.create(Bp),{_tag:"Remove"}),Hp=h(2,(e,t)=>Uq(e,t)),cO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=bt(e);while(lr(r)){let o=ur(r),i=dr(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=Gt(o.first)(Gt(o.second)(i));break}case"Add":{n=ma(o.value)(n),r=i;break}case"Remove":n=ly(o.value)(n),r=i}}return n})});function uO(e){return e}var zq,Hl,Kq,Jq,Jy=()=>Jq,Gq,Yq=(e,t)=>{let n=Object.create(Gq);return n.first=e,n.second=t,n},Zq,Xq=(e)=>{let t=Object.create(Zq);return t.values=e,t},Qq,e$=(e,t)=>{let n=Object.create(Qq);return n.from=e,n.until=t,n},t$,n$=(e,t)=>{let n=Object.create(t$);return n.index=e,n.patch=t,n},dO=(e)=>{let t=0,n=Jy();while(t<e.oldValue.length&&t<e.newValue.length){let r=e.oldValue[t],o=e.newValue[t],i=e.differ.diff(r,o);if(!j(i,e.differ.empty))n=jl(n,n$(t,i));t=t+1}if(t<e.oldValue.length)n=jl(n,e$(0,t));if(t<e.newValue.length)n=jl(n,Xq(wT(t)(e.newValue)));return n},jl,pO;var fO=b(()=>{at();ve();te();jp();zq=Symbol.for("effect/DifferReadonlyArrayPatch");Hl={...Ks.prototype,[zq]:{_Value:uO,_Patch:uO}},Kq=Object.assign(Object.create(Hl),{_tag:"Empty"}),Jq=Object.create(Kq),Gq=Object.assign(Object.create(Hl),{_tag:"AndThen"}),Zq=Object.assign(Object.create(Hl),{_tag:"Append"}),Qq=Object.assign(Object.create(Hl),{_tag:"Slice"}),t$=Object.assign(Object.create(Hl),{_tag:"Update"}),jl=h(2,(e,t)=>Yq(e,t)),pO=h(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=Jt(e);while(ni(o)){let i=St(o),a=sr(o);switch(i._tag){case"Empty":{o=a;break}case"AndThen":{a.unshift(i.first,i.second),o=a;break}case"Append":{for(let s of i.values)r.push(s);o=a;break}case"Slice":{r=r.slice(i.from,i.until),o=a;break}case"Update":{r[i.index]=n.patch(i.patch,r[i.index]),o=a;break}}}return r})});var mO,o$,hi=(e)=>{let t=Object.create(o$);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},Gy=()=>hi({empty:Wy(),combine:(e,t)=>$l(t)(e),diff:(e,t)=>oO(e,t),patch:(e,t)=>iO(t)(e)}),Yy=()=>hi({empty:Ky(),combine:(e,t)=>Hp(t)(e),diff:(e,t)=>sO(e,t),patch:(e,t)=>cO(t)(e)}),Zy=(e)=>hi({empty:Jy(),combine:(t,n)=>jl(t,n),diff:(t,n)=>dO({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>pO(t,n,e)}),Vp=()=>hO((e,t)=>t),hO=(e)=>hi({empty:we,combine:(t,n)=>{if(t===we)return n;if(n===we)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(j(t,n))return we;return ol(n)},patch:(t,n)=>e(n,t(n))});var Wp=b(()=>{ve();te();Ae();aO();lO();fO();mO=Symbol.for("effect/Differ"),o$={[mO]:{_P:we,_V:we},pipe(){return L(this,arguments)}}});var Bl=255,gO=8,zp=(e)=>e&Bl,Kp=(e)=>e>>gO&Bl,va=(e,t)=>(e&Bl)+((t&e&Bl)<<gO),Qy,yO=(e)=>va(e,e),xO=(e)=>va(e,0),SO,ex,bO=(e)=>~e>>>0&Bl;var tx=b(()=>{te();Qy=va(0,0),SO=h(2,(e,t)=>va(zp(e)&~t,Kp(e))),ex=h(2,(e,t)=>e|t)});var i$=0,Eo=1,wO=2,nx=4,Jp=16,rx=32,vO=(e)=>Gp(e,rx),ox,ko=(e)=>ix(e)&&!a$(e),ix=(e)=>Gp(e,Eo),Gp,ax=(...e)=>e.reduce((t,n)=>t|n,0),RO,sx=(e)=>Gp(e,nx),a$=(e)=>Gp(e,Jp),Vl,Wl,cx;var zl=b(()=>{te();Wp();tx();ox=h(2,(e,t)=>e|t),Gp=h(2,(e,t)=>(e&t)!==0),RO=ax(i$),Vl=h(2,(e,t)=>va(e^t,t)),Wl=h(2,(e,t)=>e&(bO(zp(t))|Kp(t))|zp(t)&Kp(t)),cx=hi({empty:Qy,diff:(e,t)=>Vl(e,t),combine:(e,t)=>ex(t)(e),patch:(e,t)=>Wl(t,e)})});var TO,ux,dx;var px=b(()=>{tx();TO=yO,ux=xO,dx=SO});var mx=(e,t)=>({_tag:"Par",left:e,right:t}),Yp=(e,t)=>({_tag:"Seq",left:e,right:t}),OO=(e)=>{let t=ql(e),n=mi();while(!0){let[r,o]=tO(t,[EO(),mi()],([i,a],s)=>{let[c,l]=s$(s);return[p$(i,c),eO(a,l)]});if(n=c$(n,r),Br(o))return nO(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},s$=(e)=>{let t=e,n=EO(),r=mi(),o=mi();while(!0)switch(t._tag){case"Empty":{if(Br(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Oo(t.right,r),t=t.left;break}case"Seq":{let i=t.left,a=t.right;switch(i._tag){case"Empty":{t=a;break}case"Par":{let{left:s,right:c}=i;t=mx(Yp(s,a),Yp(c,a));break}case"Seq":{let{left:s,right:c}=i;t=Yp(s,Yp(c,a));break}case"Single":{t=i,o=Oo(a,o);break}}break}case"Single":{if(n=d$(n,t),Br(r))return[n,o];t=r.head,r=r.tail;break}}throw Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues")},c$=(e,t)=>{if(Br(e))return ql(fx(t));if(f$(t))return e;let n=S$(e.head),r=m$(t);if(n.length===1&&r.length===1&&j(n[0],r[0]))return Oo(x$(e.head,fx(t)),e.tail);return Oo(fx(t),e)},l$,u$,Zp,EO=()=>new Zp(zs()),d$=(e,t)=>new Zp(YC(e.map,t.dataSource,(n)=>lT(ir(n,kT(t.blockedRequest)),()=>bt(t.blockedRequest)))),p$=(e,t)=>new Zp(Uy(e.map,t.map,(n,r,o)=>qy(n,o,dt(Dy(n,o),{onNone:()=>r,onSome:(i)=>kn(r,i)})))),f$=(e)=>GC(e.map),m$=(e)=>Array.from($y(e.map)),fx=(e)=>y$(ZC(e.map,(t)=>bt(t))),h$,g$,hx,y$=(e)=>new hx(e),x$=(e,t)=>new hx(Uy(t.map,e.map,(n,r,o)=>qy(n,o,dt(Dy(n,o),{onNone:()=>Hn(),onSome:(i)=>kn(i,r)})))),S$=(e)=>Array.from($y(e.map)),kO=(e)=>Array.from(e.map);var IO=b(()=>{$r();ve();qp();Up();pt();l$=Symbol.for("effect/RequestBlock/RequestBlockParallel"),u$={_R:(e)=>e};Zp=class Zp{map;[l$]=u$;constructor(e){this.map=e}};h$=Symbol.for("effect/RequestBlock/RequestBlockSequential"),g$={_R:(e)=>e};hx=class hx{map;[h$]=g$;constructor(e){this.map=e}}});var Js="Pending",Xp="Done";var _$="effect/Deferred",AO,MO,NO=(e)=>({_tag:Js,joiners:e}),FO=(e)=>({_tag:Xp,effect:e});var LO=b(()=>{AO=Symbol.for(_$),MO={_E:(e)=>e,_A:(e)=>e}});var Gs;var DO=b(()=>{Gs=class Gs{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new Gs(this.self)}}});class Sx{patch;op;_op=xl;constructor(e,t){this.patch=e,this.op=t}}var tf=(e,t)=>{let n=new Nt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},xx=(e)=>{let t=new Nt("RunBlocked");return t.effect_instruction_i0=e,t},gi,Nt,bx,_x,Ys=(e)=>H(e,gi),jt=(e)=>{let t=new Nt(Qd);return t.effect_instruction_i0=e,t},zO,Io,Po=(e)=>Io(e,void 0),wx=function(){let e=new Nt(sa);switch(arguments.length){case 2:{e.effect_instruction_i0=arguments[0],e.commit=arguments[1];break}case 3:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.commit=arguments[2];break}case 4:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.effect_instruction_i2=arguments[2],e.commit=arguments[3];break}default:throw Error(ra("you're not supposed to end up here"))}return e},Kl=(e,t=Wn)=>{let n=new Nt(aa),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,Zl(n,(o)=>Ys(r)?r:_t)},KO=(e,t=Wn)=>$e(()=>Kl(e,t)),yi=(e,t=Wn)=>wx(e,function(){let n=void 0,r=void 0;function o(c){if(n)n(c);else if(r===void 0)r=c}let i=new Nt(aa);i.effect_instruction_i0=(c)=>{if(n=c,r)c(r)},i.effect_instruction_i1=t;let a=void 0,s=void 0;if(this.effect_instruction_i0.length!==1)s=new AbortController,a=Ut(()=>this.effect_instruction_i0(o,s.signal));else a=Ut(()=>this.effect_instruction_i0(o));return a||s?Zl(i,(c)=>{if(s)s.abort();return a??_t}):i}),Jl,qO,nf=(e,t)=>{if(De(t))return new Proxy(e,{has(n,r){return r===_a||r===qO||r in n},get(n,r){if(r===_a)return t.value;if(r===qO)return e;return n[r]}});return e},rf=(e)=>rn(e)&&!(_a in e)?jt((t)=>Zt(In(nf(e,bf(t))))):Zt(In(e)),vx=(e)=>JO(()=>In(new I$(e))),Ra=(e)=>Zs(e,{onFailure:(t)=>Te(ae(t)),onSuccess:(t)=>Te(ue(t))}),xi=(e)=>GO(e,{onFailure:Ne,onSuccess:We}),Ft=(e)=>rn(e)&&!(_a in e)?jt((t)=>Zt(Us(nf(e,bf(t))))):Zt(Us(e)),Rx=(e)=>re(X(e),Ft),Zt=(e)=>{let t=new bx(hn);return t.effect_instruction_i0=e,t},JO=(e)=>re(X(e),Zt),Tx,Gl=(e)=>jt((t)=>e(t.id())),re,Cx=(e)=>{let t=new Nt("OnStep");return t.effect_instruction_i0=e,t},Yl=(e)=>re(e,we),GO,zn,Zs,Kn,Ta,of=(e)=>{let t=new Nt(ca);return t.effect_instruction_i0=TO(Eo),t.effect_instruction_i1=()=>e,t},st,af,Ca,Xs,Zl,Te=(e)=>{let t=new _x(gn);return t.effect_instruction_i0=e,t},$e=(e)=>{let t=new Nt(sa);return t.commit=e,t},X=(e)=>{let t=new Nt(Xd);return t.effect_instruction_i0=e,t},sf,Ox=(e)=>jt((t)=>{let n=t.getFiberRef(ef),r=S(n,Le(()=>t.scope()));return e(_i(ef,Y(r)))}),cf=(e)=>{let t=new Nt(ca);return t.effect_instruction_i0=ux(Eo),t.effect_instruction_i1=()=>e,t},Si=(e)=>wx(e,function(){let t=new Nt(ca);return t.effect_instruction_i0=ux(Eo),t.effect_instruction_i1=(n)=>ix(n)?Ut(()=>this.effect_instruction_i0(of)):Ut(()=>this.effect_instruction_i0(cf)),t}),_t,Ex=(e)=>{let t=new Nt(ca);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},Xl=(e)=>{let t=new Nt(Cs);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},Ql=(e)=>{let t=new Nt(Es);return typeof e?.priority<"u"?aE(t,e.priority):t},lf,uf,bi,eu,YO=(e)=>re(Tx,(t)=>S(e,tu(t))),tu,ZO,XO,QO,kx,Ix,Px,eE,tE,T$="effect/FiberRef",C$,O$,df=(e)=>jt((t)=>We(t.getFiberRef(e))),Oa,gx,E$,_i,Ht=(e,t)=>Ea(e,{differ:Vp(),fork:t?.fork??we,join:t?.join}),nE=(e)=>{let t=Yy();return Ea(e,{differ:t,fork:t.empty})},k$=(e)=>{let t=Zy(Vp());return Ea(e,{differ:t,fork:t.empty})},pf=(e)=>{let t=Gy();return Ea(e,{differ:t,fork:t.empty})},Ea=(e,t)=>({...ti,[C$]:O$,initial:e,commit(){return df(this)},diff:(r,o)=>t.differ.diff(r,o),combine:(r,o)=>t.differ.combine(r,o),patch:(r)=>(o)=>t.differ.patch(r,o),fork:t.fork,join:t.join??((r,o)=>o)}),rE=(e)=>Ea(e,{differ:cx,fork:cx.empty}),ka,Qs,Ax,oE,Mx,iE,aE,sE,cE,lE,uE,nu,ef,ru,ff,mf,hf=(e,t)=>e.addFinalizer(()=>Po(t)),Nx=(e,t)=>e.close(t),ec=(e,t)=>e.fork(t),gf,Ia=(e,t)=>{class n extends gf{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},$O,I$,yx,XY,dE=(e)=>H(e,yx),UO,P$,jO,ou,HO,QY,BO,e3,VO,t3,WO,A$,tc=(e)=>Ys(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),Fx=(e)=>e._tag==="Success",pE,iu=(e)=>pE(e,void 0),Pa=(e,t)=>M$(e,t?.parallel?wa:Yt),Lx=(e)=>Ne(In(e)),au=(e)=>Ne(Us(e)),Ne=(e)=>{let t=new bx(hn);return t.effect_instruction_i0=e,t},Dx=(e)=>Ne(pr(e)),Qp,yf,We=(e)=>{let t=new _x(gn);return t.effect_instruction_i0=e,t},Jn,qx,M$=(e,t)=>{let n=sp(e);if(!lr(n))return B();return S(dr(n),Ps(S(ur(n),Qp(bt)),(r,o)=>S(r,qx(o,{onSuccess:(i,a)=>S(i,Gt(a)),onFailure:t}))),Qp(ii),Qp((r)=>_o(r)),Y)},fE=(e)=>({...ti,[AO]:MO,state:Ap(NO([])),commit(){return xf(this)},blockingOn:e}),xf=(e)=>KO((t)=>{let n=Bs(e.state);switch(n._tag){case Xp:return t(n.effect);case Js:return n.joiners.push(t),N$(e,t)}},e.blockingOn),Sf=(e,t)=>{let n=Bs(e.state);if(n._tag===Js){Mp(e.state,FO(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},N$=(e,t)=>X(()=>{let n=Bs(e.state);if(n._tag===Js){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),F$,mE=()=>F$,Aa=(e)=>re(mE(),e),L$,$x,bf=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?Y(t):B()};var wt=b(()=>{at();$r();Vn();yn();ve();Ws();te();Ke();qp();it();Up();Ay();pt();Ae();ke();px();Qo();Hs();LO();Wp();ho();zl();DO();gi=Symbol.for("effect/Effect");Nt=class Nt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[gi]=ei;constructor(e){this._op=e}[z](e){return this===e}[G](){return ge(this,fl(this))}pipe(){return L(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:Re(this.effect_instruction_i0),effect_instruction_i1:Re(this.effect_instruction_i1),effect_instruction_i2:Re(this.effect_instruction_i2)}}toString(){return Ee(this.toJSON())}[pe](){return this.toJSON()}[Symbol.iterator](){return new Gs(new po(this))}};bx=class bx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[gi]=ei;constructor(e){this._op=e,this._tag=e}[z](e){return tc(e)&&e._op==="Failure"&&j(this.effect_instruction_i0,e.effect_instruction_i0)}[G](){return S(Oe(this._tag),se(U(this.effect_instruction_i0)),ge(this))}get cause(){return this.effect_instruction_i0}pipe(){return L(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return Ee(this.toJSON())}[pe](){return this.toJSON()}[Symbol.iterator](){return new Gs(new po(this))}};_x=class _x{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[gi]=ei;constructor(e){this._op=e,this._tag=e}[z](e){return tc(e)&&e._op==="Success"&&j(this.effect_instruction_i0,e.effect_instruction_i0)}[G](){return S(Oe(this._tag),se(U(this.effect_instruction_i0)),ge(this))}get value(){return this.effect_instruction_i0}pipe(){return L(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:Re(this.value)}}toString(){return Ee(this.toJSON())}[pe](){return this.toJSON()}[Symbol.iterator](){return new Gs(new po(this))}};zO=h(3,(e,t,n)=>Si((r)=>re(e,(o)=>re(xi($e(()=>r(t(o)))),(i)=>$e(()=>n(o,i)).pipe(zn({onFailure:(a)=>{switch(i._tag){case hn:return Zt(Yt(i.effect_instruction_i0,a));case gn:return Zt(a)}},onSuccess:()=>i})))))),Io=h(2,(e,t)=>re(e,()=>Te(t))),Jl=h(2,(e,t)=>Zs(e,{onFailure:t,onSuccess:Te})),qO=Symbol.for("effect/OriginalAnnotation"),Tx=jt((e)=>Te(e.id())),re=h(2,(e,t)=>{let n=new Nt(Rs);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),GO=h(2,(e,t)=>zn(e,{onFailure:(n)=>Te(t.onFailure(n)),onSuccess:(n)=>Te(t.onSuccess(n))})),zn=h(2,(e,t)=>{let n=new Nt(Ts);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),Zs=h(2,(e,t)=>zn(e,{onFailure:(n)=>{if(gy(n).length>0)return Zt(mC(n));let o=hy(n);if(o.length>0)return t.onFailure(Zg(o));return Zt(n)},onSuccess:t.onSuccess})),Kn=h(2,(e,t)=>$e(()=>{let n=qe(e),r=la(n.length),o=0;return Io(Xl({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),Ta=h(2,(e,t)=>$e(()=>{let n=qe(e),r=0;return Xl({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),st=h(2,(e,t)=>re(e,(n)=>X(()=>t(n)))),af=h(2,(e,t)=>Zs(e,{onFailure:(n)=>Rx(()=>t.onFailure(n)),onSuccess:(n)=>X(()=>t.onSuccess(n))})),Ca=h(2,(e,t)=>zn(e,{onFailure:(n)=>{let r=Tp(n);switch(r._tag){case"Left":return Rx(()=>t(r.left));case"Right":return Zt(r.right)}},onSuccess:Te})),Xs=h(2,(e,t)=>Si((n)=>zn(n(e),{onFailure:(r)=>{let o=Ne(r);return zn(t(o),{onFailure:(i)=>Ne(Yt(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=We(r);return bi(t(o),o)}}))),Zl=h(2,(e,t)=>Xs(e,yf({onFailure:(n)=>js(n)?Po(t(yy(n))):_t,onSuccess:()=>_t}))),sf=h((e)=>e.length===3||e.length===2&&!(rn(e[1])&&("onlyEffect"in e[1])),(e,t)=>re(e,(n)=>{let r=typeof t==="function"?t(n):t;if(Ys(r))return Io(r,n);else if(DR(r))return Kl((o)=>{r.then((i)=>o(Te(n)),(i)=>o(Ft(new A$(i,"An unknown error occurred in Effect.tap"))))});return Te(n)})),_t=Te(void 0),lf=h(2,(e,t)=>re(e,(n)=>st(t,(r)=>[n,r]))),uf=h(2,(e,t)=>re(e,(n)=>Io(t,n))),bi=h(2,(e,t)=>re(e,()=>t)),eu=KO(()=>{let e=setInterval(()=>{},2147483647);return X(()=>clearInterval(e))}),tu=h(2,(e,t)=>re(e.interruptAsFork(t),()=>e.await)),ZO={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return L(this,arguments)}},XO={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return L(this,arguments)}},QO={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return L(this,arguments)}},kx={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return L(this,arguments)}},Ix={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return L(this,arguments)}},Px={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return L(this,arguments)}},eE={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return L(this,arguments)}},tE={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return L(this,arguments)}},C$=Symbol.for(T$),O$={_A:(e)=>e},Oa=h(2,(e,t)=>re(df(e),t)),gx=h(2,(e,t)=>E$(e,()=>[void 0,t])),E$=h(2,(e,t)=>jt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),Te(r)})),_i=h(3,(e,t,n)=>zO(uf(df(t),gx(t,n)),()=>e,(r)=>gx(t,r))),ka=ne(Symbol.for("effect/FiberRef/currentContext"),()=>pf(pi())),Qs=ne(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>Ht(0)),Ax=ne(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>Ht(2048)),oE=ne(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>Ht(zs())),Mx=ne(Symbol.for("effect/FiberRef/currentLogLevel"),()=>Ht(Ix)),iE=ne(Symbol.for("effect/FiberRef/currentLogSpan"),()=>Ht(mi())),aE=h(2,(e,t)=>_i(e,Qs,t)),sE=ne(Symbol.for("effect/FiberRef/currentConcurrency"),()=>Ht("unbounded")),cE=ne(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>Ht(!0)),lE=ne(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>Ht(Y(Px))),uE=ne(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>Ht(Y(kx))),nu=ne(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>k$(So())),ef=ne(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>Ht(B(),{fork:()=>B(),join:(e,t)=>e})),ru=ne(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>Ht(To,{fork:()=>To,join:(e,t)=>e})),ff=Symbol.for("effect/Scope"),mf=Symbol.for("effect/CloseableScope"),gf=function(){class e extends globalThis.Error{commit(){return Ft(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[pe](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
22
+ `)}return t},CC=(e)=>H(e,Ny),OC=(e)=>H(e,ql),tq,kC=()=>tq,Fy=(e,t)=>vi(new Map([[e.key,t]])),EC,My,Ly=(e)=>{if(My.has(e.key))return My.get(e.key);let t=e.defaultValue();return My.set(e.key,t),t},IC=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Ly(t),Dy,PC,AC,MC;var jp=w(()=>{Re();ne();Ge();at();Ne();Ie();wo();Hg();_C=Symbol.for("effect/Context/Tag"),ql=Symbol.for("effect/Context/Reference"),ZD=Symbol.for(YD),vC={...bo,_op:"Tag",[ZD]:pi,[_C]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[me](){return this.toJSON()},of(e){return e},context(e){return Fy(this,e)}},XD={...vC,[ql]:ql},Ny=Symbol.for("effect/Context"),QD={[Ny]:{_Services:(e)=>e},[z](e){if(CC(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!j(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[J](){return ye(this,sp(this.unsafeMap.size))},pipe(){return F(this,arguments)},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(Te)}},[me](){return this.toJSON()}},tq=vi(new Map),EC=h(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),vi(r)}),My=re("effect/Context/defaultValueCache",()=>new Map),Dy=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(ql in t)return Ly(t);throw eq(t)}return e.unsafeMap.get(t.key)}),PC=Dy,AC=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return OC(t)?kl(Ly(t)):fp;return kl(e.unsafeMap.get(t.key))}),MC=h(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return vi(n)})});var yn,Ri,FC,zr,Ul,$l,Ti,jl,Hl;var Wn=w(()=>{jp();yn=RC,Ri=kC,FC=Fy,zr=EC,Ul=PC,$l=Dy,Ti=AC,jl=MC,Hl=TC});var Uy,$C,LC,Hp,$y,DC,qC,nq,Ao=(e)=>{if(jC(e))return e;else if(kn(e))return Bp(e);else if(li(e))return qy(e);else if(Array.isArray(e)&&e.length===2&&e.every(kn)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return jy;if(e[0]===1/0||e[1]===1/0)return aq;return qy(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(Ut(e)){let t=nq.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return qy(BigInt(r));case"micro":case"micros":return sq(BigInt(r));case"milli":case"millis":return Bp(i);case"second":case"seconds":return cq(i);case"minute":case"minutes":return lq(i);case"hour":case"hours":return uq(i);case"day":case"days":return dq(i);case"week":case"weeks":return pq(i)}}}throw Error("Invalid DurationInput")},UC,rq,oq,Kr=(e)=>{let t=Object.create(oq);if(kn(e))if(isNaN(e)||e<=0)t.value=UC;else if(!Number.isFinite(e))t.value=rq;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:BigInt(Math.round(e*1e6))};else t.value={_tag:"Millis",millis:e};else if(e<=$C)t.value=UC;else t.value={_tag:"Nanos",nanos:e};return t},jC=(e)=>H(e,Uy),iq=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===$C;case"Infinity":return!1}},jy,aq,qy=(e)=>Kr(e),sq=(e)=>Kr(e*$y),Bp=(e)=>Kr(e),cq=(e)=>Kr(e*1000),lq=(e)=>Kr(e*60000),uq=(e)=>Kr(e*3600000),dq=(e)=>Kr(e*86400000),pq=(e)=>Kr(e*604800000),Vp=(e)=>hq(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),fq=(e)=>{let t=Ao(e);switch(t.value._tag){case"Infinity":throw Error("Cannot convert infinite duration to nanos");case"Nanos":return t.value.nanos;case"Millis":return BigInt(Math.round(t.value.millis*1e6))}},mq=(e)=>{let t=Ao(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/qC),Number(t.value.nanos%qC)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},hq,Hy,gq=(e,t)=>Hy(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),HC,BC,yq,xq=(e)=>{let t=Ao(e);if(t.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};let n=fq(t),r=n/DC,o=r/$y,i=o/Hp,a=i/Hp,s=a/LC;return{days:Number(s),hours:Number(a%LC),minutes:Number(i%Hp),seconds:Number(o%Hp),millis:Number(r%$y),nanos:Number(n%DC)}},Sq=(e)=>{let t=Ao(e);if(t.value._tag==="Infinity")return"Infinity";if(iq(t))return"0";let n=xq(t),r=[];if(n.days!==0)r.push(`${n.days}d`);if(n.hours!==0)r.push(`${n.hours}h`);if(n.minutes!==0)r.push(`${n.minutes}m`);if(n.seconds!==0)r.push(`${n.seconds}s`);if(n.millis!==0)r.push(`${n.millis}ms`);if(n.nanos!==0)r.push(`${n.nanos}ns`);return r.join(" ")};var By=w(()=>{Re();ne();Ge();at();Ne();Ie();Uy=Symbol.for("effect/Duration"),$C=BigInt(0),LC=BigInt(24),Hp=BigInt(60),$y=BigInt(1000),DC=BigInt(1e6),qC=BigInt(1e9),nq=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,UC={_tag:"Millis",millis:0},rq={_tag:"Infinity"},oq={[Uy]:Uy,[J](){return ye(this,cp(this.value))},[z](e){return jC(e)&&yq(this,e)},toString(){return`Duration(${Sq(this)})`},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",hrtime:mq(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}},jy=Kr(0),aq=Kr(1/0),hq=h(2,(e,t)=>{let n=Ao(e);switch(n.value._tag){case"Nanos":return t.onNanos(n.value.nanos);case"Infinity":return t.onMillis(1/0);case"Millis":return t.onMillis(n.value.millis)}}),Hy=h(3,(e,t,n)=>{let r=Ao(e),o=Ao(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(Vp(r),Vp(o));else if(r.value._tag==="Nanos"||o.value._tag==="Nanos"){let i=r.value._tag==="Nanos"?r.value.nanos:BigInt(Math.round(r.value.millis*1e6)),a=o.value._tag==="Nanos"?o.value.nanos:BigInt(Math.round(o.value.millis*1e6));return n.onNanos(i,a)}return n.onMillis(r.value.millis,o.value.millis)}),HC=h(2,(e,t)=>Hy(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),BC=h(2,(e,t)=>Hy(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),yq=h(2,(e,t)=>gq(Ao(e),Ao(t)))});var WC,bq,Wp=(e)=>{let t=Object.create(bq);return t.current=e,t},Zs=(e)=>e.current,zp;var Vy=w(()=>{ne();at();Ne();WC=Symbol.for("effect/MutableRef"),bq={[WC]:WC,toString(){return Ee(this.toJSON())},toJSON(){return{_id:"MutableRef",current:Te(this.current)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}},zp=h(2,(e,t)=>(e.current=t,e))});var zy="effect/FiberId",Xs,Kp="None",Wy="Runtime",wq="Composite",_q,JC,GC,YC,Ky=(e)=>H(e,Xs),Jp=(e)=>{switch(e._tag){case Kp:return Wr();case Wy:return Ta(e.id);case wq:return b(Jp(e.left),Io(Jp(e.right)))}},KC,Gp=(e)=>Array.from(Jp(e)).map((n)=>`#${n}`).join(","),ZC=()=>{let e=Zs(KC);return b(KC,zp(e+1)),new GC(e,Date.now())};var Jy=w(()=>{Re();ne();Ge();ka();at();Vy();Ie();Xs=Symbol.for(zy),_q=ke(`${zy}-${Kp}`);JC=class JC{[Xs]=Xs;_tag=Kp;id=-1;startTimeMillis=-1;[J](){return _q}[z](e){return Ky(e)&&e._tag===Kp}toString(){return Ee(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[me](){return this.toJSON()}};GC=class GC{id;startTimeMillis;[Xs]=Xs;_tag=Wy;constructor(e,t){this.id=e,this.startTimeMillis=t}[J](){return ye(this,ke(`${zy}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[z](e){return Ky(e)&&e._tag===Wy&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Ee(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[me](){return this.toJSON()}};YC=new JC,KC=re(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Wp(0))});var zn,QC,Yp;var Qs=w(()=>{Jy();zn=YC,QC=Gp,Yp=ZC});var ec,eO,tO,Gy,Yy,Zy,nO,rO,Xy;var Zp=w(()=>{xy();ec=Hs,eO=KT,tO=GT,Gy=YT,Yy=Ra,Zy=kp,nO=Ip,rO=QT,Xy=Bs});var Vl,ex=(e)=>je(e),vq=(e)=>kg(gi(e),ex),Rq,Tq,Xp=(e,t)=>{let n=Object.create(Tq);return n.head=e,n.tail=t,n},Cq,Oq,oO,iO=(e)=>H(e,Vl),Jr=(e)=>e._tag==="Nil",tx=(e)=>e._tag==="Cons",kq=()=>oO,Mo=(e,t)=>Xp(e,t),Ci,Wl=(e)=>Xp(e,oO),aO,Eq,Iq,sO,cO=(e)=>{let t=Ci(),n=e;while(!Jr(n))t=Eq(t,n.head),n=n.tail;return t};var Qp=w(()=>{st();Re();gl();ne();Ge();at();Ne();Ie();Vl=Symbol.for("effect/List"),Rq=vq(j),Tq={[Vl]:Vl,_tag:"Cons",toString(){return Ee(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:ex(this).map(Te)}},[me](){return this.toJSON()},[z](e){return iO(e)&&this._tag===e._tag&&Rq(this,e)},[J](){return ye(this,En(ex(this)))},[Symbol.iterator](){let e=!1,t=this;return{next(){if(e)return this.return();if(t._tag==="Nil")return e=!0,this.return();let n=t.head;return t=t.tail,{done:e,value:n}},return(n){if(!e)e=!0;return{done:!0,value:n}}}},pipe(){return F(this,arguments)}},Cq=ke("Nil"),Oq={[Vl]:Vl,_tag:"Nil",toString(){return Ee(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[me](){return this.toJSON()},[J](){return Cq},[z](e){return iO(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return F(this,arguments)}},oO=Object.create(Oq),Ci=kq,aO=h(2,(e,t)=>Iq(t,e)),Eq=h(2,(e,t)=>Mo(t,e)),Iq=h(2,(e,t)=>{if(Jr(e))return t;else if(Jr(t))return e;else{let n=Xp(t.head,e),r=n,o=t.tail;while(!Jr(o)){let i=Xp(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),sO=h(3,(e,t,n)=>{let r=t,o=e;while(!Jr(o))r=n(r,o.head),o=o.tail;return r})});var DY,tc;var ef=w(()=>{Re();Ge();wo();DY=Object.assign(Object.create(Array.prototype),{[J](){return ye(this,En(this))},[z](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>j(t,e[n]));else return!1}}),tc=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=Ol,e}()});function lO(e){return e}var Aq,Kl,Mq,Nq,rx=()=>Nq,Fq,Lq=(e,t)=>{let n=Object.create(Fq);return n.first=e,n.second=t,n},Dq,qq=(e,t)=>{let n=Object.create(Dq);return n.key=e,n.service=t,n},Uq,$q=(e)=>{let t=Object.create(Uq);return t.key=e,t},jq,Hq=(e,t)=>{let n=Object.create(jq);return n.key=e,n.update=t,n},uO=(e,t)=>{let n=new Map(e.unsafeMap),r=rx();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!j(a,i))r=zl(Hq(o,()=>i))(r)}else n.delete(o),r=zl(qq(o,i))(r);for(let[o]of n.entries())r=zl($q(o))(r);return r},zl,dO;var pO=w(()=>{Vr();Re();ne();jp();ef();Aq=Symbol.for("effect/DifferContextPatch");Kl={...tc.prototype,[Aq]:{_Value:lO,_Patch:lO}},Mq=Object.assign(Object.create(Kl),{_tag:"Empty"}),Nq=Object.create(Mq),Fq=Object.assign(Object.create(Kl),{_tag:"AndThen"}),Dq=Object.assign(Object.create(Kl),{_tag:"AddService"}),Uq=Object.assign(Object.create(Kl),{_tag:"RemoveService"}),jq=Object.assign(Object.create(Kl),{_tag:"UpdateService"}),zl=h(2,(e,t)=>Lq(e,t)),dO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=St(e),o=new Map(t.unsafeMap);while(hr(r)){let a=gr(r),s=yr(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=Yt(Yt(s,a.second),a.first);break}case"RemoveService":{o.delete(a.key),r=s;break}case"UpdateService":{o.set(a.key,a.update(o.get(a.key))),n=!0,r=s;break}}}if(!n)return vi(o);let i=new Map;for(let[a]of t.unsafeMap)if(o.has(a))i.set(a,o.get(a)),o.delete(a);for(let[a,s]of o)i.set(a,s);return vi(i)})});function ox(e){return e}var Vq,nf,Wq,zq,ix=()=>zq,Kq,Jq=(e,t)=>{let n=Object.create(Kq);return n.first=e,n.second=t,n},Gq,Yq=(e)=>{let t=Object.create(Gq);return t.value=e,t},Zq,Xq=(e)=>{let t=Object.create(Zq);return t.value=e,t},fO=(e,t)=>{let[n,r]=Oa([e,ix()],([o,i],a)=>{if(fC(a)(o))return[wy(a)(o),i];return[o,tf(Yq(a))(i)]})(t);return Oa(r,(o,i)=>tf(Xq(i))(o))(n)},tf,mO;var hO=w(()=>{Vr();ne();ka();ef();Vq=Symbol.for("effect/DifferHashSetPatch");nf={...tc.prototype,[Vq]:{_Value:ox,_Key:ox,_Patch:ox}},Wq=Object.assign(Object.create(nf),{_tag:"Empty"}),zq=Object.create(Wq),Kq=Object.assign(Object.create(nf),{_tag:"AndThen"}),Gq=Object.assign(Object.create(nf),{_tag:"Add"}),Zq=Object.assign(Object.create(nf),{_tag:"Remove"}),tf=h(2,(e,t)=>Jq(e,t)),mO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=St(e);while(hr(r)){let o=gr(r),i=yr(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=Yt(o.first)(Yt(o.second)(i));break}case"Add":{n=Ca(o.value)(n),r=i;break}case"Remove":n=wy(o.value)(n),r=i}}return n})});function gO(e){return e}var eU,Gl,tU,nU,ax=()=>nU,rU,oU=(e,t)=>{let n=Object.create(rU);return n.first=e,n.second=t,n},iU,aU=(e)=>{let t=Object.create(iU);return t.values=e,t},sU,cU=(e,t)=>{let n=Object.create(sU);return n.from=e,n.until=t,n},lU,uU=(e,t)=>{let n=Object.create(lU);return n.index=e,n.patch=t,n},yO=(e)=>{let t=0,n=ax();while(t<e.oldValue.length&&t<e.newValue.length){let r=e.oldValue[t],o=e.newValue[t],i=e.differ.diff(r,o);if(!j(i,e.differ.empty))n=Jl(n,uU(t,i));t=t+1}if(t<e.oldValue.length)n=Jl(n,cU(0,t));if(t<e.newValue.length)n=Jl(n,aU(kT(t)(e.newValue)));return n},Jl,xO;var SO=w(()=>{st();Re();ne();ef();eU=Symbol.for("effect/DifferReadonlyArrayPatch");Gl={...tc.prototype,[eU]:{_Value:gO,_Patch:gO}},tU=Object.assign(Object.create(Gl),{_tag:"Empty"}),nU=Object.create(tU),rU=Object.assign(Object.create(Gl),{_tag:"AndThen"}),iU=Object.assign(Object.create(Gl),{_tag:"Append"}),sU=Object.assign(Object.create(Gl),{_tag:"Slice"}),lU=Object.assign(Object.create(Gl),{_tag:"Update"}),Jl=h(2,(e,t)=>oU(e,t)),xO=h(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=Gt(e);while(mi(o)){let i=xt(o),a=fr(o);switch(i._tag){case"Empty":{o=a;break}case"AndThen":{a.unshift(i.first,i.second),o=a;break}case"Append":{for(let s of i.values)r.push(s);o=a;break}case"Slice":{r=r.slice(i.from,i.until),o=a;break}case"Update":{r[i.index]=n.patch(i.patch,r[i.index]),o=a;break}}}return r})});var bO,pU,Oi=(e)=>{let t=Object.create(pU);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},sx=()=>Oi({empty:rx(),combine:(e,t)=>zl(t)(e),diff:(e,t)=>uO(e,t),patch:(e,t)=>dO(t)(e)}),cx=()=>Oi({empty:ix(),combine:(e,t)=>tf(t)(e),diff:(e,t)=>fO(e,t),patch:(e,t)=>mO(t)(e)}),lx=(e)=>Oi({empty:ax(),combine:(t,n)=>Jl(t,n),diff:(t,n)=>yO({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>xO(t,n,e)}),rf=()=>wO((e,t)=>t),wO=(e)=>Oi({empty:ve,combine:(t,n)=>{if(t===ve)return n;if(n===ve)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(j(t,n))return ve;return dl(n)},patch:(t,n)=>e(n,t(n))});var of=w(()=>{Re();ne();Ne();pO();hO();SO();bO=Symbol.for("effect/Differ"),pU={[bO]:{_P:ve,_V:ve},pipe(){return F(this,arguments)}}});var Yl=255,_O=8,af=(e)=>e&Yl,sf=(e)=>e>>_O&Yl,Fa=(e,t)=>(e&Yl)+((t&e&Yl)<<_O),dx,vO=(e)=>Fa(e,e),RO=(e)=>Fa(e,0),TO,px,CO=(e)=>~e>>>0&Yl;var fx=w(()=>{ne();dx=Fa(0,0),TO=h(2,(e,t)=>Fa(af(e)&~t,sf(e))),px=h(2,(e,t)=>e|t)});var fU=0,No=1,kO=2,mx=4,cf=16,hx=32,EO=(e)=>lf(e,hx),gx,Fo=(e)=>yx(e)&&!mU(e),yx=(e)=>lf(e,No),lf,xx=(...e)=>e.reduce((t,n)=>t|n,0),IO,Sx=(e)=>lf(e,mx),mU=(e)=>lf(e,cf),Zl,Xl,bx;var Ql=w(()=>{ne();of();fx();gx=h(2,(e,t)=>e|t),lf=h(2,(e,t)=>(e&t)!==0),IO=xx(fU),Zl=h(2,(e,t)=>Fa(e^t,t)),Xl=h(2,(e,t)=>e&(CO(af(t))|sf(t))|af(t)&sf(t)),bx=Oi({empty:dx,diff:(e,t)=>Zl(e,t),combine:(e,t)=>px(t)(e),patch:(e,t)=>Xl(t,e)})});var PO,_x,vx;var Rx=w(()=>{fx();PO=vO,_x=RO,vx=TO});var Cx=(e,t)=>({_tag:"Par",left:e,right:t}),uf=(e,t)=>({_tag:"Seq",left:e,right:t}),MO=(e)=>{let t=Wl(e),n=Ci();while(!0){let[r,o]=sO(t,[NO(),Ci()],([i,a],s)=>{let[c,l]=hU(s);return[bU(i,c),aO(a,l)]});if(n=gU(n,r),Jr(o))return cO(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},hU=(e)=>{let t=e,n=NO(),r=Ci(),o=Ci();while(!0)switch(t._tag){case"Empty":{if(Jr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Mo(t.right,r),t=t.left;break}case"Seq":{let i=t.left,a=t.right;switch(i._tag){case"Empty":{t=a;break}case"Par":{let{left:s,right:c}=i;t=Cx(uf(s,a),uf(c,a));break}case"Seq":{let{left:s,right:c}=i;t=uf(s,uf(c,a));break}case"Single":{t=i,o=Mo(a,o);break}}break}case"Single":{if(n=SU(n,t),Jr(r))return[n,o];t=r.head,r=r.tail;break}}throw Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues")},gU=(e,t)=>{if(Jr(e))return Wl(Tx(t));if(wU(t))return e;let n=OU(e.head),r=_U(t);if(n.length===1&&r.length===1&&j(n[0],r[0]))return Mo(CU(e.head,Tx(t)),e.tail);return Mo(Tx(t),e)},yU,xU,df,NO=()=>new df(ec()),SU=(e,t)=>new df(nO(e.map,t.dataSource,(n)=>hT(dr(n,FT(t.blockedRequest)),()=>St(t.blockedRequest)))),bU=(e,t)=>new df(Xy(e.map,t.map,(n,r,o)=>Yy(n,o,pt(Gy(n,o),{onNone:()=>r,onSome:(i)=>Pn(r,i)})))),wU=(e)=>tO(e.map),_U=(e)=>Array.from(Zy(e.map)),Tx=(e)=>TU(rO(e.map,(t)=>St(t))),vU,RU,Ox,TU=(e)=>new Ox(e),CU=(e,t)=>new Ox(Xy(t.map,e.map,(n,r,o)=>Yy(n,o,pt(Gy(n,o),{onNone:()=>Bn(),onSome:(i)=>Pn(i,r)})))),OU=(e)=>Array.from(Zy(e.map)),FO=(e)=>Array.from(e.map);var LO=w(()=>{Vr();Re();Zp();Qp();ft();yU=Symbol.for("effect/RequestBlock/RequestBlockParallel"),xU={_R:(e)=>e};df=class df{map;[yU]=xU;constructor(e){this.map=e}};vU=Symbol.for("effect/RequestBlock/RequestBlockSequential"),RU={_R:(e)=>e};Ox=class Ox{map;[vU]=RU;constructor(e){this.map=e}}});var nc="Pending",pf="Done";var EU="effect/Deferred",qO,UO,$O=(e)=>({_tag:nc,joiners:e}),jO=(e)=>({_tag:pf,effect:e});var HO=w(()=>{qO=Symbol.for(EU),UO={_E:(e)=>e,_A:(e)=>e}});var rc;var BO=w(()=>{rc=class rc{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new rc(this.self)}}});class Px{patch;op;_op=Tl;constructor(e,t){this.patch=e,this.op=t}}var hf=(e,t)=>{let n=new Nt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},Ix=(e)=>{let t=new Nt("RunBlocked");return t.effect_instruction_i0=e,t},ki,Nt,Ax,Mx,oc=(e)=>H(e,ki),jt=(e)=>{let t=new Nt(pp);return t.effect_instruction_i0=e,t},XO,Lo,Do=(e)=>Lo(e,void 0),Nx=function(){let e=new Nt(Sa);switch(arguments.length){case 2:{e.effect_instruction_i0=arguments[0],e.commit=arguments[1];break}case 3:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.commit=arguments[2];break}case 4:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.effect_instruction_i2=arguments[2],e.commit=arguments[3];break}default:throw Error(ha("you're not supposed to end up here"))}return e},eu=(e,t=zn)=>{let n=new Nt(xa),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,ou(n,(o)=>oc(r)?r:bt)},QO=(e,t=zn)=>He(()=>eu(e,t)),Ei=(e,t=zn)=>Nx(e,function(){let n=void 0,r=void 0;function o(c){if(n)n(c);else if(r===void 0)r=c}let i=new Nt(xa);i.effect_instruction_i0=(c)=>{if(n=c,r)c(r)},i.effect_instruction_i1=t;let a=void 0,s=void 0;if(this.effect_instruction_i0.length!==1)s=new AbortController,a=$t(()=>this.effect_instruction_i0(o,s.signal));else a=$t(()=>this.effect_instruction_i0(o));return a||s?ou(i,(c)=>{if(s)s.abort();return a??bt}):i}),tu,VO,gf=(e,t)=>{if($e(t))return new Proxy(e,{has(n,r){return r===Ma||r===VO||r in n},get(n,r){if(r===Ma)return t.value;if(r===VO)return e;return n[r]}});return e},yf=(e)=>rn(e)&&!(Ma in e)?jt((t)=>Xt(An(gf(e,Mf(t))))):Xt(An(e)),Fx=(e)=>ek(()=>An(new qU(e))),La=(e)=>ic(e,{onFailure:(t)=>Ce(ce(t)),onSuccess:(t)=>Ce(ue(t))}),Ii=(e)=>tk(e,{onFailure:Le,onSuccess:ze}),Ft=(e)=>rn(e)&&!(Ma in e)?jt((t)=>Xt(Js(gf(e,Mf(t))))):Xt(Js(e)),Lx=(e)=>oe(Q(e),Ft),Xt=(e)=>{let t=new Ax(fn);return t.effect_instruction_i0=e,t},ek=(e)=>oe(Q(e),Xt),Dx,nu=(e)=>jt((t)=>e(t.id())),oe,qx=(e)=>{let t=new Nt("OnStep");return t.effect_instruction_i0=e,t},ru=(e)=>oe(e,ve),tk,Kn,ic,Jn,Da,xf=(e)=>{let t=new Nt(ba);return t.effect_instruction_i0=PO(No),t.effect_instruction_i1=()=>e,t},ct,Sf,qa,ac,ou,Ce=(e)=>{let t=new Mx(mn);return t.effect_instruction_i0=e,t},He=(e)=>{let t=new Nt(Sa);return t.commit=e,t},Q=(e)=>{let t=new Nt(dp);return t.effect_instruction_i0=e,t},bf,Ux=(e)=>jt((t)=>{let n=t.getFiberRef(mf),r=b(n,Ue(()=>t.scope()));return e(Mi(mf,Y(r)))}),wf=(e)=>{let t=new Nt(ba);return t.effect_instruction_i0=_x(No),t.effect_instruction_i1=()=>e,t},Pi=(e)=>Nx(e,function(){let t=new Nt(ba);return t.effect_instruction_i0=_x(No),t.effect_instruction_i1=(n)=>yx(n)?$t(()=>this.effect_instruction_i0(xf)):$t(()=>this.effect_instruction_i0(wf)),t}),bt,$x=(e)=>{let t=new Nt(ba);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},iu=(e)=>{let t=new Nt(Ns);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},au=(e)=>{let t=new Nt(Ls);return typeof e?.priority<"u"?pk(t,e.priority):t},_f,vf,Ai,su,nk=(e)=>oe(Dx,(t)=>b(e,cu(t))),cu,rk,ok,ik,jx,Hx,Bx,ak,sk,MU="effect/FiberRef",NU,FU,Rf=(e)=>jt((t)=>ze(t.getFiberRef(e))),Ua,kx,LU,Mi,Ht=(e,t)=>$a(e,{differ:rf(),fork:t?.fork??ve,join:t?.join}),ck=(e)=>{let t=cx();return $a(e,{differ:t,fork:t.empty})},DU=(e)=>{let t=lx(rf());return $a(e,{differ:t,fork:t.empty})},Tf=(e)=>{let t=sx();return $a(e,{differ:t,fork:t.empty})},$a=(e,t)=>({...fi,[NU]:FU,initial:e,commit(){return Rf(this)},diff:(r,o)=>t.differ.diff(r,o),combine:(r,o)=>t.differ.combine(r,o),patch:(r)=>(o)=>t.differ.patch(r,o),fork:t.fork,join:t.join??((r,o)=>o)}),lk=(e)=>$a(e,{differ:bx,fork:bx.empty}),ja,sc,Vx,uk,Wx,dk,pk,fk,mk,hk,gk,lu,mf,uu,Cf,Of,kf=(e,t)=>e.addFinalizer(()=>Do(t)),zx=(e,t)=>e.close(t),cc=(e,t)=>e.fork(t),Ef,Ha=(e,t)=>{class n extends Ef{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},WO,qU,Ex,m3,yk=(e)=>H(e,Ex),zO,UU,KO,du,JO,h3,GO,g3,YO,y3,ZO,$U,lc=(e)=>oc(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),Kx=(e)=>e._tag==="Success",xk,pu=(e)=>xk(e,void 0),Ba=(e,t)=>jU(e,t?.parallel?Na:Zt),Jx=(e)=>Le(An(e)),fu=(e)=>Le(Js(e)),Le=(e)=>{let t=new Ax(fn);return t.effect_instruction_i0=e,t},Gx=(e)=>Le(xr(e)),ff,If,ze=(e)=>{let t=new Mx(mn);return t.effect_instruction_i0=e,t},Gn,Yx,jU=(e,t)=>{let n=bp(e);if(!hr(n))return B();return b(yr(n),Us(b(gr(n),ff(St)),(r,o)=>b(r,Yx(o,{onSuccess:(i,a)=>b(i,Yt(a)),onFailure:t}))),ff(yi),ff((r)=>Oo(r)),Y)},Sk=(e)=>({...fi,[qO]:UO,state:Wp($O([])),commit(){return Pf(this)},blockingOn:e}),Pf=(e)=>QO((t)=>{let n=Zs(e.state);switch(n._tag){case pf:return t(n.effect);case nc:return n.joiners.push(t),HU(e,t)}},e.blockingOn),Af=(e,t)=>{let n=Zs(e.state);if(n._tag===nc){zp(e.state,jO(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},HU=(e,t)=>Q(()=>{let n=Zs(e.state);if(n._tag===nc){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),BU,bk=()=>BU,Va=(e)=>oe(bk(),e),VU,Zx,Mf=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?Y(t):B()};var wt=w(()=>{st();Vr();Wn();hn();Re();Qs();ne();Ge();Zp();at();Qp();Vy();ft();Ne();Ie();Rx();di();Ys();HO();of();wo();Ql();BO();ki=Symbol.for("effect/Effect");Nt=class Nt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ki]=pi;constructor(e){this._op=e}[z](e){return this===e}[J](){return ye(this,bl(this))}pipe(){return F(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:Te(this.effect_instruction_i0),effect_instruction_i1:Te(this.effect_instruction_i1),effect_instruction_i2:Te(this.effect_instruction_i2)}}toString(){return Ee(this.toJSON())}[me](){return this.toJSON()}[Symbol.iterator](){return new rc(new xo(this))}};Ax=class Ax{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ki]=pi;constructor(e){this._op=e,this._tag=e}[z](e){return lc(e)&&e._op==="Failure"&&j(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return b(ke(this._tag),le(U(this.effect_instruction_i0)),ye(this))}get cause(){return this.effect_instruction_i0}pipe(){return F(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return Ee(this.toJSON())}[me](){return this.toJSON()}[Symbol.iterator](){return new rc(new xo(this))}};Mx=class Mx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ki]=pi;constructor(e){this._op=e,this._tag=e}[z](e){return lc(e)&&e._op==="Success"&&j(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return b(ke(this._tag),le(U(this.effect_instruction_i0)),ye(this))}get value(){return this.effect_instruction_i0}pipe(){return F(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:Te(this.value)}}toString(){return Ee(this.toJSON())}[me](){return this.toJSON()}[Symbol.iterator](){return new rc(new xo(this))}};XO=h(3,(e,t,n)=>Pi((r)=>oe(e,(o)=>oe(Ii(He(()=>r(t(o)))),(i)=>He(()=>n(o,i)).pipe(Kn({onFailure:(a)=>{switch(i._tag){case fn:return Xt(Zt(i.effect_instruction_i0,a));case mn:return Xt(a)}},onSuccess:()=>i})))))),Lo=h(2,(e,t)=>oe(e,()=>Ce(t))),tu=h(2,(e,t)=>ic(e,{onFailure:t,onSuccess:Ce})),VO=Symbol.for("effect/OriginalAnnotation"),Dx=jt((e)=>Ce(e.id())),oe=h(2,(e,t)=>{let n=new Nt(As);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),tk=h(2,(e,t)=>Kn(e,{onFailure:(n)=>Ce(t.onFailure(n)),onSuccess:(n)=>Ce(t.onSuccess(n))})),Kn=h(2,(e,t)=>{let n=new Nt(Ms);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),ic=h(2,(e,t)=>Kn(e,{onFailure:(n)=>{if(ky(n).length>0)return Xt(bC(n));let o=Oy(n);if(o.length>0)return t.onFailure(ly(o));return Xt(n)},onSuccess:t.onSuccess})),Jn=h(2,(e,t)=>He(()=>{let n=je(e),r=wa(n.length),o=0;return Lo(iu({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),Da=h(2,(e,t)=>He(()=>{let n=je(e),r=0;return iu({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),ct=h(2,(e,t)=>oe(e,(n)=>Q(()=>t(n)))),Sf=h(2,(e,t)=>ic(e,{onFailure:(n)=>Lx(()=>t.onFailure(n)),onSuccess:(n)=>Q(()=>t.onSuccess(n))})),qa=h(2,(e,t)=>Kn(e,{onFailure:(n)=>{let r=qp(n);switch(r._tag){case"Left":return Lx(()=>t(r.left));case"Right":return Xt(r.right)}},onSuccess:Ce})),ac=h(2,(e,t)=>Pi((n)=>Kn(n(e),{onFailure:(r)=>{let o=Le(r);return Kn(t(o),{onFailure:(i)=>Le(Zt(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=ze(r);return Ai(t(o),o)}}))),ou=h(2,(e,t)=>ac(e,If({onFailure:(n)=>Gs(n)?Do(t(Ey(n))):bt,onSuccess:()=>bt}))),bf=h((e)=>e.length===3||e.length===2&&!(rn(e[1])&&("onlyEffect"in e[1])),(e,t)=>oe(e,(n)=>{let r=typeof t==="function"?t(n):t;if(oc(r))return Lo(r,n);else if(BR(r))return eu((o)=>{r.then((i)=>o(Ce(n)),(i)=>o(Ft(new $U(i,"An unknown error occurred in Effect.tap"))))});return Ce(n)})),bt=Ce(void 0),_f=h(2,(e,t)=>oe(e,(n)=>ct(t,(r)=>[n,r]))),vf=h(2,(e,t)=>oe(e,(n)=>Lo(t,n))),Ai=h(2,(e,t)=>oe(e,()=>t)),su=QO(()=>{let e=setInterval(()=>{},2147483647);return Q(()=>clearInterval(e))}),cu=h(2,(e,t)=>oe(e.interruptAsFork(t),()=>e.await)),rk={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return F(this,arguments)}},ok={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return F(this,arguments)}},ik={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return F(this,arguments)}},jx={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return F(this,arguments)}},Hx={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return F(this,arguments)}},Bx={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return F(this,arguments)}},ak={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return F(this,arguments)}},sk={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return F(this,arguments)}},NU=Symbol.for(MU),FU={_A:(e)=>e},Ua=h(2,(e,t)=>oe(Rf(e),t)),kx=h(2,(e,t)=>LU(e,()=>[void 0,t])),LU=h(2,(e,t)=>jt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),Ce(r)})),Mi=h(3,(e,t,n)=>XO(vf(Rf(t),kx(t,n)),()=>e,(r)=>kx(t,r))),ja=re(Symbol.for("effect/FiberRef/currentContext"),()=>Tf(Ri())),sc=re(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>Ht(0)),Vx=re(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>Ht(2048)),uk=re(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>Ht(ec())),Wx=re(Symbol.for("effect/FiberRef/currentLogLevel"),()=>Ht(Hx)),dk=re(Symbol.for("effect/FiberRef/currentLogSpan"),()=>Ht(Ci())),pk=h(2,(e,t)=>Mi(e,sc,t)),fk=re(Symbol.for("effect/FiberRef/currentConcurrency"),()=>Ht("unbounded")),mk=re(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>Ht(!0)),hk=re(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>Ht(Y(Bx))),gk=re(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>Ht(Y(jx))),lu=re(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>DU(To())),mf=re(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>Ht(B(),{fork:()=>B(),join:(e,t)=>e})),uu=re(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>Ht(Po,{fork:()=>Po,join:(e,t)=>e})),Cf=Symbol.for("effect/Scope"),Of=Symbol.for("effect/CloseableScope"),Ef=function(){class e extends globalThis.Error{commit(){return Ft(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[me](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
23
23
  ${this.stack.split(`
24
24
  `).slice(1).join(`
25
- `)}`:this.toString();else if("Bun"in globalThis)return fr(Us(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,Cg),e}(),$O=Symbol.for("effect/Cause/errors/RuntimeException"),I$=Ia({[$O]:$O},"RuntimeException"),yx=Symbol.for("effect/Cause/errors/InterruptedException"),XY=Ia({[yx]:yx},"InterruptedException"),UO=Symbol.for("effect/Cause/errors/IllegalArgument"),P$=Ia({[UO]:UO},"IllegalArgumentException"),jO=Symbol.for("effect/Cause/errors/NoSuchElement"),ou=Ia({[jO]:jO},"NoSuchElementException"),HO=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),QY=Ia({[HO]:HO},"InvalidPubSubCapacityException"),BO=Symbol.for("effect/Cause/errors/ExceededCapacityException"),e3=Ia({[BO]:BO},"ExceededCapacityException"),VO=Symbol.for("effect/Cause/errors/Timeout"),t3=Ia({[VO]:VO},"TimeoutException"),WO=Symbol.for("effect/Cause/errors/UnknownException"),A$=function(){class e extends gf{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[WO]:WO,name:"UnknownException"}),e}(),pE=h(2,(e,t)=>{switch(e._tag){case hn:return Ne(e.effect_instruction_i0);case gn:return We(t)}}),Qp=h(2,(e,t)=>{switch(e._tag){case hn:return Ne(e.effect_instruction_i0);case gn:return We(t(e.effect_instruction_i0))}}),yf=h(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case hn:return t(e.effect_instruction_i0);case gn:return n(e.effect_instruction_i0)}}),Jn=We(void 0),qx=h(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case hn:switch(t._tag){case gn:return Ne(e.effect_instruction_i0);case hn:return Ne(n(e.effect_instruction_i0,t.effect_instruction_i0))}case gn:switch(t._tag){case gn:return We(r(e.effect_instruction_i0,t.effect_instruction_i0));case hn:return Ne(t.effect_instruction_i0)}}}),F$=jt((e)=>We(e.currentContext)),L$=h(2,(e,t)=>_i(ka,t)(e)),$x=h(2,(e,t)=>Aa((n)=>L$(e,t(n))))});var hE,gE;var yE=b(()=>{Hs();hE=pC,gE=fr});var _f="And",wf="Or",vf="InvalidData",Rf="MissingData",Tf="SourceUnavailable",Cf="Unsupported";var $$="effect/ConfigError",xE,nc,Of=(e,t)=>{let n=Object.create(nc);return n._op=_f,n.left=e,n.right=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),Object.defineProperty(n,"message",{enumerable:!1,get(){return this.toString()}}),n},Ef=(e,t)=>{let n=Object.create(nc);return n._op=wf,n.left=e,n.right=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(n,"message",{enumerable:!1,get(){return this.toString()}}),n},Ux=(e,t,n={pathDelim:"."})=>{let r=Object.create(nc);return r._op=vf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${S(this.path,bo(n.pathDelim))}: "${this.message}")`}}),r},Vr=(e,t,n={pathDelim:"."})=>{let r=Object.create(nc);return r._op=Rf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${S(this.path,bo(n.pathDelim))}: "${this.message}")`}}),r},jx=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(nc);return o._op=Tf,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${S(this.path,bo(r.pathDelim))}: "${this.message}")`}}),o},Hx=(e,t,n={pathDelim:"."})=>{let r=Object.create(nc);return r._op=Cf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${S(this.path,bo(n.pathDelim))}: "${this.message}")`}}),r},wi,SE;var Bx=b(()=>{at();yn();te();xE=Symbol.for($$),nc={_tag:"ConfigError",[xE]:xE},wi=h(2,(e,t)=>{switch(e._op){case _f:return Of(wi(e.left,t),wi(e.right,t));case wf:return Ef(wi(e.left,t),wi(e.right,t));case vf:return Ux([...t,...e.path],e.message);case Rf:return Vr([...t,...e.path],e.message);case Tf:return jx([...t,...e.path],e.message,e.cause);case Cf:return Hx([...t,...e.path],e.message)}}),SE=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case _f:{r.push(a.right),r.push(a.left),o.push(ae({_op:"AndCase"}));break}case wf:{r.push(a.right),r.push(a.left),o.push(ae({_op:"OrCase"}));break}case vf:{o.push(ue(n.invalidDataCase(t,a.path,a.message)));break}case Rf:{o.push(ue(n.missingDataCase(t,a.path,a.message)));break}case Tf:{o.push(ue(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case Cf:{o.push(ue(n.unsupportedCase(t,a.path,a.message)));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._op){case"Left":{switch(a.left._op){case"AndCase":{let s=i.pop(),c=i.pop(),l=n.andCase(t,s,c);i.push(l);break}case"OrCase":{let s=i.pop(),c=i.pop(),l=n.orCase(t,s,c);i.push(l);break}}break}case"Right":{i.push(a.right);break}}}if(i.length===0)throw Error("BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()})});var U$="effect/Clock",_E,su,j$=2147483647,wE,vE,H$,RE,TE=()=>new RE;var Vx=b(()=>{Vn();Py();te();wt();_E=Symbol.for(U$),su=Sn("effect/Clock"),wE={unsafeSchedule(e,t){let n=Pp(t);if(n>j$)return Yo;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},vE=function(){let e=BigInt(1e6);if(typeof performance>"u"||typeof performance.now!=="function")return()=>BigInt(Date.now())*e;let t;return()=>{if(t===void 0)t=BigInt(Date.now())*e-BigInt(Math.round(performance.now()*1e6));return t+BigInt(Math.round(performance.now()*1e6))}}(),H$=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return vE;let t=vE()-e.bigint();return()=>t+e.bigint()}();RE=class RE{[_E]=_E;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return H$()}currentTimeMillis=X(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=X(()=>this.unsafeCurrentTimeNanos());scheduler(){return Te(wE)}sleep(e){return yi((t)=>{let n=wE.unsafeSchedule(()=>t(_t),e);return Po(X(n))})}}});var Wr;var cu=b(()=>{op();Wr=cT});var rc=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var Wx=()=>{};var EE,If;var kE=b(()=>{at();yn();te();Up();pt();Bx();EE={_tag:"Empty"},If=h(2,(e,t)=>{let n=ql(t),r=e;while(By(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Oo(o.first,Oo(o.second,n.tail));break}case"MapName":{r=cr(r,o.f),n=n.tail;break}case"Nested":{r=ks(r,o.name),n=n.tail;break}case"Unnested":{if(S(yo(r),pT(o.name)))r=sr(r),n=n.tail;else return ae(Vr(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return ue(r)})});var IE="Constant",PE="Fail",AE="Fallback",ME="Described",NE="Lazy",FE="MapOrFail",LE="Nested",DE="Primitive",qE="Redacted",$E="Sequence",UE="HashMap",jE="ZipWith";var Pf=(e,t)=>[...e,...t],G$="effect/ConfigProvider",HE,VE,Y$="effect/ConfigProviderFlat",BE,Z$=(e)=>({[HE]:HE,pipe(){return L(this,arguments)},...e}),X$=(e)=>({[BE]:BE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),Q$=(e)=>Z$({load:(t)=>re(Pn(e,So(),t,!1),(n)=>dt(yo(n),{onNone:()=>Ft(Vr(So(),`Expected a single value having structure: ${t}`)),onSome:Te})),flattened:e}),WE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>S(c,bo(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return Q$(X$({load:(c,l,u=!0)=>{let d=r(c),p=i(),f=d in p?Y(p[d]):B();return S(f,Ca(()=>Vr(c,`Expected ${d} to exist in the process context`)),re((m)=>aU(m,c,l,n,u)))},enumerateChildren:(c)=>X(()=>{let l=i(),p=Object.keys(l).map((f)=>o(f.toUpperCase())).filter((f)=>{for(let m=0;m<c.length;m++){let y=S(c,Bg(m)),g=f[m];if(g===void 0||y!==g)return!1}return!0}).flatMap((f)=>f.slice(c.length,c.length+1));return aC(p)}),patch:EE}))},eU=(e,t,n,r)=>{let o=Kg(n.length,(c)=>c>=r.length?B():Y([e(c),c+1])),i=Kg(r.length,(c)=>c>=n.length?B():Y([t(c),c+1])),a=Pf(n,o),s=Pf(r,i);return[a,s]},tU=(e,t)=>{let n=t;if(n._tag==="Nested"){let r=e.slice();while(n._tag==="Nested")r.push(n.name),n=n.config;return r}return e},nU,rU=(e)=>SE(e,void 0,nU),Pn=(e,t,n,r)=>{let o=n;switch(o._tag){case IE:return Te(Jt(o.value));case ME:return $e(()=>Pn(e,t,o.config,r));case PE:return Ft(Vr(t,o.message));case AE:return S($e(()=>Pn(e,t,o.first,r)),Jl((i)=>{if(o.condition(i))return S(Pn(e,t,o.second,r),Jl((a)=>Ft(Ef(i,a))));return Ft(i)}));case NE:return $e(()=>Pn(e,t,o.config(),r));case FE:return $e(()=>S(Pn(e,t,o.original,r),re(Kn((i)=>S(o.mapOrFail(i),Ca(wi(tU(t,o.original))))))));case LE:return $e(()=>Pn(e,Pf(t,Jt(o.name)),o.config,r));case DE:return S(If(t,e.patch),re((i)=>S(e.load(i,o,r),re((a)=>{if(a.length===0){let s=S(bT(i),Le(()=>"<n/a>"));return Ft(Vr([],`Expected ${o.description} with name ${s}`))}return Te(a)}))));case qE:return $e(()=>S(Pn(e,t,o.original,r),Ca(rU),st(cr(o.redact))));case $E:return S(If(t,e.patch),re((i)=>S(e.enumerateChildren(i),re(cU),re((a)=>{if(a.length===0)return $e(()=>st(Pn(e,t,o.config,!0),Jt));return S(Kn(a,(s)=>Pn(e,yT(t,`[${s}]`),o.config,!0)),st((s)=>{let c=ip(s);if(c.length===0)return Jt(So());return Jt(c)}))}))));case UE:return $e(()=>S(If(t,e.patch),re((i)=>S(e.enumerateChildren(i),re((a)=>S(a,Kn((s)=>Pn(e,Pf(i,Jt(s)),o.valueConfig,r)),st((s)=>{if(s.length===0)return Jt(zs());return S(sU(s),cr((c)=>JC(zg(qe(a),c))))})))))));case jE:return $e(()=>S(Pn(e,t,o.left,r),Ra,re((i)=>S(Pn(e,t,o.right,r),Ra,re((a)=>{if(Fe(i)&&Fe(a))return Ft(Of(i.left,a.left));if(Fe(i)&&Tt(a))return Ft(i.left);if(Tt(i)&&Fe(a))return Ft(a.left);if(Tt(i)&&Tt(a)){let s=S(t,bo(".")),c=oU(t,s),[l,u]=eU(c,c,S(i.right,cr(ue)),S(a.right,cr(ue)));return S(l,zg(u),Kn(([d,p])=>S(lf(d,p),st(([f,m])=>o.zip(f,m)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},oU=(e,t)=>(n)=>ae(Vr(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),iU=(e,t)=>e.split(new RegExp(`\\s*${rc(t)}\\s*`)),aU=(e,t,n,r,o)=>{if(!o)return S(n.parse(e),af({onFailure:wi(t),onSuccess:Jt}));return S(iU(e,r),Kn((i)=>n.parse(i.trim())),Ca(wi(t)))},sU=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),cU=(e)=>S(Kn(e,uU),af({onFailure:()=>So(),onSuccess:xo(Wr)}),Ra,st(iT)),lU,uU=(e)=>{let t=e.match(lU);if(t!==null){let n=t[2];return S(n!==void 0&&n.length>0?Y(n):B(),ar(dU))}return B()},dU=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?B():Y(t)};var zE=b(()=>{at();Vn();yn();te();qp();ga();cu();pt();Ae();Wx();Bx();kE();wt();HE=Symbol.for(G$),VE=Sn("effect/ConfigProvider"),BE=Symbol.for(Y$),nU={andCase:(e,t,n)=>Of(t,n),orCase:(e,t,n)=>Ef(t,n),invalidDataCase:(e,t)=>Ux(t,"<redacted>"),missingDataCase:(e,t)=>Vr(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>jx(t,"<redacted>",r),unsupportedCase:(e,t)=>Hx(t,"<redacted>")},lU=/^(\[(\d+)\])$/});var KE,Af,JE;var zx=b(()=>{Vn();wt();KE=Symbol.for("effect/Console"),Af=Sn("effect/Console"),JE={[KE]:KE,assert(e,...t){return X(()=>{console.assert(e,...t)})},clear:X(()=>{console.clear()}),count(e){return X(()=>{console.count(e)})},countReset(e){return X(()=>{console.countReset(e)})},debug(...e){return X(()=>{console.debug(...e)})},dir(e,t){return X(()=>{console.dir(e,t)})},dirxml(...e){return X(()=>{console.dirxml(...e)})},error(...e){return X(()=>{console.error(...e)})},group(e){return e?.collapsed?X(()=>console.groupCollapsed(e?.label)):X(()=>console.group(e?.label))},groupEnd:X(()=>{console.groupEnd()}),info(...e){return X(()=>{console.info(...e)})},log(...e){return X(()=>{console.log(...e)})},table(e,t){return X(()=>{console.table(e,t)})},time(e){return X(()=>console.time(e))},timeEnd(e){return X(()=>console.timeEnd(e))},timeLog(e,...t){return X(()=>{console.timeLog(e,...t)})},trace(...e){return X(()=>{console.trace(...e)})},warn(...e){return X(()=>{console.warn(...e)})},unsafe:console}});var mU="effect/Random",GE,YE,ZE,hU=(e,t)=>$e(()=>S(X(()=>Array.from(e)),re((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return S(r,Ta((o)=>S(t(o),st((i)=>gU(n,o-1,i)))),Io(sp(n)))}))),gU=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},XE=(e)=>new ZE(U(e));var QE=b(()=>{$r();Vn();te();Ke();Qo();wt();GE=Symbol.for(mU),YE=Sn("effect/Random");ZE=class ZE{seed;[GE]=GE;PRNG;constructor(e){this.seed=e,this.PRNG=new bg(e)}get next(){return X(()=>this.PRNG.number())}get nextBoolean(){return st(this.next,(e)=>e>0.5)}get nextInt(){return X(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return st(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return X(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return hU(e,(t)=>this.nextIntBetween(0,t))}}});class nk{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(e,t,n,r,o,i){this.name=e,this.parent=t,this.context=n,this.startTime=o,this.kind=i,this.status={_tag:"Started",startTime:o},this.attributes=new Map,this.traceId=t._tag==="Some"?t.value.traceId:tk(32),this.spanId=tk(16),this.links=Array.from(r)}end(e,t){this.status={_tag:"Ended",endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}}var ek,xU=(e)=>({[ek]:ek,...e}),lu,Mf,tk,rk,ok;var Nf=b(()=>{Vn();te();ek=Symbol.for("effect/Tracer"),lu=Sn("effect/Tracer"),Mf=Sn("effect/ParentSpan"),tk=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();rk=xU({span:(e,t,n,r,o,i)=>new nk(e,t,n,r,o,i),context:(e)=>e()}),ok=Fl()("effect/Tracer/DisablePropagation",{defaultValue:Yo})});var _U,uu;var ik=b(()=>{Vn();te();Vx();zE();wt();zx();QE();Nf();_U=S(pi(),jr(su,TE()),jr(Af,JE),jr(YE,XE(Math.random())),jr(VE,WE()),jr(lu,rk)),uu=ne(Symbol.for("effect/DefaultServices/currentServices"),()=>pf(_U))});var vU,ak=(e)=>{let t={BaseEffectError:class extends vU{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var sk=b(()=>{wt();vU=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends gf{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)Object.assign(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}.BaseEffectError}()});var ck,RU,Jx;var Gx=b(()=>{ho();ck=mo,RU=GR;Jx=class Jx extends RU{}});var uk="Sequential",dk="Parallel",TU="ParallelN",oc,pk,fk=(e)=>({_tag:TU,parallelism:e}),Yx=(e)=>e._tag===uk,Zx=(e)=>e._tag===dk;var Ff=b(()=>{oc={_tag:uk},pk={_tag:dk}});var Lf,Df,qf;var mk=b(()=>{Ff();Lf=oc,Df=pk,qf=fk});function hk(e){return new Ao(e)}function gk(){return hk(new Map)}var Qx,Ao,OU=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(Me(i)&&Me(a)){let l=St(i)[0],u=sr(i),d=St(a)[0],p=St(a)[1],f=sr(a);if(l.startTimeMillis<d.startTimeMillis)a=f,s=!0;else if(l.startTimeMillis>d.startTimeMillis)i=u;else if(l.id<d.id)a=f,s=!0;else if(l.id>d.id)i=u;else c=[p,s]}else c=[o.initial,!0];return c},tS,nS,yk=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(j(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},du,rS,vi,ic,eS=(e,t,n,r)=>{let o=e.get(n)??[],i;if(Me(o)){let[a,s]=St(o);if(a[z](t))if(j(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},xk;var $f=b(()=>{at();ve();te();pt();Ae();Qx=Symbol.for("effect/FiberRefs");Ao=class Ao{locals;[Qx]=Qx;constructor(e){this.locals=e}pipe(){return L(this,arguments)}};tS=h(3,(e,t,n)=>{let r=new Map(e.locals);return n.locals.forEach((o,i)=>{let a=o[0][1];if(!o[0][0][z](t)){if(!r.has(i)){if(j(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=OU(i,s,o);if(l){let u=i.diff(c,a),d=s[0][1],p=i.join(d,i.patch(u)(d));if(!j(d,p)){let f,m=s[0][0];if(m[z](t))f=[[m,p],...s.slice(1)];else f=[[t,p],...s];r.set(i,f)}}}}),new Ao(r)}),nS=h(2,(e,t)=>{let n=new Map;return yk(e,n,t),new Ao(n)}),du=h(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new Ao(n)}),rS=h(2,(e,t)=>{if(!e.locals.has(t))return B();return Y(St(e.locals.get(t))[1])}),vi=h(2,(e,t)=>S(rS(e,t),Le(()=>t.initial))),ic=h(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new Ao(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return eS(o,t,n,r),new Ao(o)}),xk=h(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new Ao(new Map(t));let r=new Map(e.locals);if(n!==void 0)yk(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)eS(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{eS(r,a,o,s)})}),new Ao(r)})});var Sk,bk,_k;var iS=b(()=>{$f();Sk=vi,bk=xk,_k=gk});var vk="Empty",Rk="Add",Tk="Remove",Ck="Update",Ok="AndThen",Ek,kk=(e,t)=>{let n=new Map(e.locals),r=Ek;for(let[o,i]of t.locals.entries()){let a=St(i)[1],s=n.get(o);if(s!==void 0){let c=St(s)[1];if(!j(c,a))r=Uf({_tag:Ck,fiberRef:o,patch:o.diff(c,a)})(r)}else r=Uf({_tag:Rk,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=Uf({_tag:Tk,fiberRef:o})(r);return r},Uf,Ik;var Pk=b(()=>{at();ve();te();$f();Ek={_tag:vk},Uf=h(2,(e,t)=>({_tag:Ok,first:e,second:t})),Ik=h(3,(e,t,n)=>{let r=n,o=Jt(e);while(Me(o)){let i=St(o),a=sr(o);switch(i._tag){case vk:{o=a;break}case Rk:{r=ic(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case Tk:{r=du(r,i.fiberRef),o=a;break}case Ck:{let s=vi(r,i.fiberRef);r=ic(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case Ok:{o=ks(i.first)(ks(i.second)(a));break}}}return r})});var Ak,Mk;var Nk=b(()=>{Pk();Ak=kk,Mk=Ik});var Hf="effect/FiberStatus",Ri,jf="Done",Fk="Running",Lk="Suspended",IU,Dk,qk,$k,Uk,jk=(e)=>new qk(e),Hk=(e,t)=>new $k(e,t),Bf=(e)=>H(e,Ri),Bk=(e)=>e._tag===jf;var Vk=b(()=>{ve();te();Ke();ke();Ri=Symbol.for(Hf),IU=Oe(`${Hf}-${jf}`);Dk=class Dk{[Ri]=Ri;_tag=jf;[G](){return IU}[z](e){return Bf(e)&&e._tag===jf}};qk=class qk{runtimeFlags;[Ri]=Ri;_tag=Fk;constructor(e){this.runtimeFlags=e}[G](){return S(U(Hf),se(U(this._tag)),se(U(this.runtimeFlags)),ge(this))}[z](e){return Bf(e)&&e._tag===Fk&&this.runtimeFlags===e.runtimeFlags}};$k=class $k{runtimeFlags;blockingOn;[Ri]=Ri;_tag=Lk;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[G](){return S(U(Hf),se(U(this._tag)),se(U(this.runtimeFlags)),se(U(this.blockingOn)),ge(this))}[z](e){return Bf(e)&&e._tag===Lk&&this.runtimeFlags===e.runtimeFlags&&j(this.blockingOn,e.blockingOn)}};Uk=new Dk});var Wk,aS,zk,Kk;var Jk=b(()=>{Vk();Wk=Uk,aS=jk,zk=Hk,Kk=Bk});var MU,NU,FU,LU,DU,qU,$U,UU,jU,Gk,Yk=(e)=>{switch(e){case"All":return MU;case"Debug":return qU;case"Error":return FU;case"Fatal":return NU;case"Info":return DU;case"Trace":return $U;case"None":return UU;case"Warning":return LU}};var Zk=b(()=>{te();wt();cu();op();MU=ZO,NU=XO,FU=QO,LU=kx,DU=Ix,qU=Px,$U=eE,UU=tE,jU=S(Wr,rp((e)=>e.ordinal)),Gk=Dg(jU)});function ZU(e){return cS("Micro.evaluate: Not implemented")}class hS{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,o2(this.afterScheduled)}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let e=this.tasks;this.tasks=[];for(let t=0,n=e.length;t<n;t++)e[t]()}shouldYield(e){return e.currentOpCount>=e.getRef(lI)}flush(){while(this.tasks.length>0)this.runTasks()}}var BU,Wf,Xk,VU,lS,tI,WU=(e,t=[])=>new tI(e,t),nI,zU=(e=[])=>new nI(e),KU=(e)=>e._tag==="Interrupt",Qk,JU,rI,eI,oI,Ot,sS,sc,ac,zf,Vf,GU,YU,Jf=(e)=>({...YU,[oI]:e.op,[sS]:e.eval??ZU,[sc]:e.contA,[ac]:e.contE,[zf]:e.ensure}),uS=(e)=>{let t=Jf(e);return function(){let n=Object.create(t);return n[Ot]=e.single===!1?arguments:arguments[0],n}},iI=(e)=>{let t={...Jf(e),[Wf]:Wf,_tag:e.op,get[e.prop](){return this[Ot]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[Ot]}},[z](n){return n2(n)&&n._tag===e.op&&j(this[Ot],n[Ot])},[G](){return ge(this,se(Oe(e.op))(U(this[Ot])))}};return function(n){let r=Object.create(t);return r[Ot]=n,r[sc]=void 0,r[ac]=void 0,r[zf]=void 0,r}},dS,aI,XU,QU,e2,pS,Kf,t2,n2=(e)=>H(e,Wf),sI,fS,mS,cS=(e)=>fS(WU(e)),r2,o2,i2,cI,lI,Gf,a2,s2,c2,uI,l2=(e)=>pS((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(uI(!1)),t._interrupted)return mS;return e}),u2=(e)=>pS((t)=>{if(!t.interruptible)return e(we);return t.interruptible=!1,t._stack.push(uI(!0)),e(l2)}),dI=(e,t)=>{let n=new rI(Gf.context(t?.scheduler??new hS));if(n.evaluate(e),t?.signal)if(t.signal.aborted)n.unsafeInterrupt();else{let r=()=>n.unsafeInterrupt();t.signal.addEventListener("abort",r,{once:!0}),n.addObserver(()=>t.signal.removeEventListener("abort",r))}return n};var pI=b(()=>{Vn();Gx();ve();te();Ke();it();Ep();Ae();ke();Qo();BU=Symbol.for("effect/Micro"),Wf=Symbol.for("effect/Micro/MicroExit"),Xk=Symbol.for("effect/Micro/MicroCause"),VU={_E:we};lS=class lS extends globalThis.Error{_tag;traces;[Xk];constructor(e,t,n){let r=`MicroCause.${e}`,o,i,a;if(t instanceof globalThis.Error){o=`(${r}) ${t.name}`,i=t.message;let s=i.split(`
25
+ `)}`:this.toString();else if("Bun"in globalThis)return Sr(Js(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,qg),e}(),WO=Symbol.for("effect/Cause/errors/RuntimeException"),qU=Ha({[WO]:WO},"RuntimeException"),Ex=Symbol.for("effect/Cause/errors/InterruptedException"),m3=Ha({[Ex]:Ex},"InterruptedException"),zO=Symbol.for("effect/Cause/errors/IllegalArgument"),UU=Ha({[zO]:zO},"IllegalArgumentException"),KO=Symbol.for("effect/Cause/errors/NoSuchElement"),du=Ha({[KO]:KO},"NoSuchElementException"),JO=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),h3=Ha({[JO]:JO},"InvalidPubSubCapacityException"),GO=Symbol.for("effect/Cause/errors/ExceededCapacityException"),g3=Ha({[GO]:GO},"ExceededCapacityException"),YO=Symbol.for("effect/Cause/errors/Timeout"),y3=Ha({[YO]:YO},"TimeoutException"),ZO=Symbol.for("effect/Cause/errors/UnknownException"),$U=function(){class e extends Ef{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[ZO]:ZO,name:"UnknownException"}),e}(),xk=h(2,(e,t)=>{switch(e._tag){case fn:return Le(e.effect_instruction_i0);case mn:return ze(t)}}),ff=h(2,(e,t)=>{switch(e._tag){case fn:return Le(e.effect_instruction_i0);case mn:return ze(t(e.effect_instruction_i0))}}),If=h(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case fn:return t(e.effect_instruction_i0);case mn:return n(e.effect_instruction_i0)}}),Gn=ze(void 0),Yx=h(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case fn:switch(t._tag){case mn:return Le(e.effect_instruction_i0);case fn:return Le(n(e.effect_instruction_i0,t.effect_instruction_i0))}case mn:switch(t._tag){case mn:return ze(r(e.effect_instruction_i0,t.effect_instruction_i0));case fn:return Le(t.effect_instruction_i0)}}}),BU=jt((e)=>ze(e.currentContext)),VU=h(2,(e,t)=>Mi(ja,t)(e)),Zx=h(2,(e,t)=>Va((n)=>VU(e,t(n))))});var wk,_k;var vk=w(()=>{Ys();wk=xC,_k=Sr});var Nf="And",Ff="Or",Lf="InvalidData",Df="MissingData",qf="SourceUnavailable",Uf="Unsupported";var KU="effect/ConfigError",Rk,uc,$f=(e,t)=>{let n=Object.create(uc);return n._op=Nf,n.left=e,n.right=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),Object.defineProperty(n,"message",{enumerable:!1,get(){return this.toString()}}),n},jf=(e,t)=>{let n=Object.create(uc);return n._op=Ff,n.left=e,n.right=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(n,"message",{enumerable:!1,get(){return this.toString()}}),n},Xx=(e,t,n={pathDelim:"."})=>{let r=Object.create(uc);return r._op=Lf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${b(this.path,Co(n.pathDelim))}: "${this.message}")`}}),r},Gr=(e,t,n={pathDelim:"."})=>{let r=Object.create(uc);return r._op=Df,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${b(this.path,Co(n.pathDelim))}: "${this.message}")`}}),r},Qx=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(uc);return o._op=qf,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${b(this.path,Co(r.pathDelim))}: "${this.message}")`}}),o},eS=(e,t,n={pathDelim:"."})=>{let r=Object.create(uc);return r._op=Uf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${b(this.path,Co(n.pathDelim))}: "${this.message}")`}}),r},Ni,Tk;var tS=w(()=>{st();hn();ne();Rk=Symbol.for(KU),uc={_tag:"ConfigError",[Rk]:Rk},Ni=h(2,(e,t)=>{switch(e._op){case Nf:return $f(Ni(e.left,t),Ni(e.right,t));case Ff:return jf(Ni(e.left,t),Ni(e.right,t));case Lf:return Xx([...t,...e.path],e.message);case Df:return Gr([...t,...e.path],e.message);case qf:return Qx([...t,...e.path],e.message,e.cause);case Uf:return eS([...t,...e.path],e.message)}}),Tk=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case Nf:{r.push(a.right),r.push(a.left),o.push(ce({_op:"AndCase"}));break}case Ff:{r.push(a.right),r.push(a.left),o.push(ce({_op:"OrCase"}));break}case Lf:{o.push(ue(n.invalidDataCase(t,a.path,a.message)));break}case Df:{o.push(ue(n.missingDataCase(t,a.path,a.message)));break}case qf:{o.push(ue(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case Uf:{o.push(ue(n.unsupportedCase(t,a.path,a.message)));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._op){case"Left":{switch(a.left._op){case"AndCase":{let s=i.pop(),c=i.pop(),l=n.andCase(t,s,c);i.push(l);break}case"OrCase":{let s=i.pop(),c=i.pop(),l=n.orCase(t,s,c);i.push(l);break}}break}case"Right":{i.push(a.right);break}}}if(i.length===0)throw Error("BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()})});var JU="effect/Clock",Ok,mu,GU=2147483647,kk,Ek,YU,Ik,Pk=()=>new Ik;var nS=w(()=>{Wn();By();ne();wt();Ok=Symbol.for(JU),mu=yn("effect/Clock"),kk={unsafeSchedule(e,t){let n=Vp(t);if(n>GU)return ci;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},Ek=function(){let e=BigInt(1e6);if(typeof performance>"u"||typeof performance.now!=="function")return()=>BigInt(Date.now())*e;let t;return()=>{if(t===void 0)t=BigInt(Date.now())*e-BigInt(Math.round(performance.now()*1e6));return t+BigInt(Math.round(performance.now()*1e6))}}(),YU=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return Ek;let t=Ek()-e.bigint();return()=>t+e.bigint()}();Ik=class Ik{[Ok]=Ok;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return YU()}currentTimeMillis=Q(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=Q(()=>this.unsafeCurrentTimeNanos());scheduler(){return Ce(kk)}sleep(e){return Ei((t)=>{let n=kk.unsafeSchedule(()=>t(bt),e);return Do(Q(n))})}}});var Yr;var hu=w(()=>{yp();Yr=mT});var dc=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var rS=()=>{};var Nk,Bf;var Fk=w(()=>{st();hn();ne();Qp();ft();tS();Nk={_tag:"Empty"},Bf=h(2,(e,t)=>{let n=Wl(t),r=e;while(tx(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Mo(o.first,Mo(o.second,n.tail));break}case"MapName":{r=mr(r,o.f),n=n.tail;break}case"Nested":{r=Ds(r,o.name),n=n.tail;break}case"Unnested":{if(b(vo(r),xT(o.name)))r=fr(r),n=n.tail;else return ce(Gr(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return ue(r)})});var Lk="Constant",Dk="Fail",qk="Fallback",Uk="Described",$k="Lazy",jk="MapOrFail",Hk="Nested",Bk="Primitive",Vk="Redacted",Wk="Sequence",zk="HashMap",Kk="ZipWith";var Vf=(e,t)=>[...e,...t],r$="effect/ConfigProvider",Jk,Yk,o$="effect/ConfigProviderFlat",Gk,i$=(e)=>({[Jk]:Jk,pipe(){return F(this,arguments)},...e}),a$=(e)=>({[Gk]:Gk,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),s$=(e)=>i$({load:(t)=>oe(Mn(e,To(),t,!1),(n)=>pt(vo(n),{onNone:()=>Ft(Gr(To(),`Expected a single value having structure: ${t}`)),onSome:Ce})),flattened:e}),Zk=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>b(c,Co(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return s$(a$({load:(c,l,u=!0)=>{let d=r(c),p=i(),m=d in p?Y(p[d]):B();return b(m,qa(()=>Gr(c,`Expected ${d} to exist in the process context`)),oe((f)=>m$(f,c,l,n,u)))},enumerateChildren:(c)=>Q(()=>{let l=i(),p=Object.keys(l).map((m)=>o(m.toUpperCase())).filter((m)=>{for(let f=0;f<c.length;f++){let x=b(c,ty(f)),g=m[f];if(g===void 0||x!==g)return!1}return!0}).flatMap((m)=>m.slice(c.length,c.length+1));return pC(p)}),patch:Nk}))},c$=(e,t,n,r)=>{let o=iy(n.length,(c)=>c>=r.length?B():Y([e(c),c+1])),i=iy(r.length,(c)=>c>=n.length?B():Y([t(c),c+1])),a=Vf(n,o),s=Vf(r,i);return[a,s]},l$=(e,t)=>{let n=t;if(n._tag==="Nested"){let r=e.slice();while(n._tag==="Nested")r.push(n.name),n=n.config;return r}return e},u$,d$=(e)=>Tk(e,void 0,u$),Mn=(e,t,n,r)=>{let o=n;switch(o._tag){case Lk:return Ce(Gt(o.value));case Uk:return He(()=>Mn(e,t,o.config,r));case Dk:return Ft(Gr(t,o.message));case qk:return b(He(()=>Mn(e,t,o.first,r)),tu((i)=>{if(o.condition(i))return b(Mn(e,t,o.second,r),tu((a)=>Ft(jf(i,a))));return Ft(i)}));case $k:return He(()=>Mn(e,t,o.config(),r));case jk:return He(()=>b(Mn(e,t,o.original,r),oe(Jn((i)=>b(o.mapOrFail(i),qa(Ni(l$(t,o.original))))))));case Hk:return He(()=>Mn(e,Vf(t,Gt(o.name)),o.config,r));case Bk:return b(Bf(t,e.patch),oe((i)=>b(e.load(i,o,r),oe((a)=>{if(a.length===0){let s=b(CT(i),Ue(()=>"<n/a>"));return Ft(Gr([],`Expected ${o.description} with name ${s}`))}return Ce(a)}))));case Vk:return He(()=>b(Mn(e,t,o.original,r),qa(d$),ct(mr(o.redact))));case Wk:return b(Bf(t,e.patch),oe((i)=>b(e.enumerateChildren(i),oe(g$),oe((a)=>{if(a.length===0)return He(()=>ct(Mn(e,t,o.config,!0),Gt));return b(Jn(a,(s)=>Mn(e,vT(t,`[${s}]`),o.config,!0)),ct((s)=>{let c=xp(s);if(c.length===0)return Gt(To());return Gt(c)}))}))));case zk:return He(()=>b(Bf(t,e.patch),oe((i)=>b(e.enumerateChildren(i),oe((a)=>b(a,Jn((s)=>Mn(e,Vf(i,Gt(s)),o.valueConfig,r)),ct((s)=>{if(s.length===0)return Gt(ec());return b(h$(s),mr((c)=>eO(oy(je(a),c))))})))))));case Kk:return He(()=>b(Mn(e,t,o.left,r),La,oe((i)=>b(Mn(e,t,o.right,r),La,oe((a)=>{if(qe(i)&&qe(a))return Ft($f(i.left,a.left));if(qe(i)&&Tt(a))return Ft(i.left);if(Tt(i)&&qe(a))return Ft(a.left);if(Tt(i)&&Tt(a)){let s=b(t,Co(".")),c=p$(t,s),[l,u]=c$(c,c,b(i.right,mr(ue)),b(a.right,mr(ue)));return b(l,oy(u),Jn(([d,p])=>b(_f(d,p),ct(([m,f])=>o.zip(m,f)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},p$=(e,t)=>(n)=>ce(Gr(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),f$=(e,t)=>e.split(new RegExp(`\\s*${dc(t)}\\s*`)),m$=(e,t,n,r,o)=>{if(!o)return b(n.parse(e),Sf({onFailure:Ni(t),onSuccess:Gt}));return b(f$(e,r),Jn((i)=>n.parse(i.trim())),qa(Ni(t)))},h$=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),g$=(e)=>b(Jn(e,x$),Sf({onFailure:()=>To(),onSuccess:Ro(Yr)}),La,ct(dT)),y$,x$=(e)=>{let t=e.match(y$);if(t!==null){let n=t[2];return b(n!==void 0&&n.length>0?Y(n):B(),pr(S$))}return B()},S$=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?B():Y(t)};var Xk=w(()=>{st();Wn();hn();ne();Zp();ka();hu();ft();Ne();rS();tS();Fk();wt();Jk=Symbol.for(r$),Yk=yn("effect/ConfigProvider"),Gk=Symbol.for(o$),u$={andCase:(e,t,n)=>$f(t,n),orCase:(e,t,n)=>jf(t,n),invalidDataCase:(e,t)=>Xx(t,"<redacted>"),missingDataCase:(e,t)=>Gr(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>Qx(t,"<redacted>",r),unsupportedCase:(e,t)=>eS(t,"<redacted>")},y$=/^(\[(\d+)\])$/});var Qk,Wf,eE;var oS=w(()=>{Wn();wt();Qk=Symbol.for("effect/Console"),Wf=yn("effect/Console"),eE={[Qk]:Qk,assert(e,...t){return Q(()=>{console.assert(e,...t)})},clear:Q(()=>{console.clear()}),count(e){return Q(()=>{console.count(e)})},countReset(e){return Q(()=>{console.countReset(e)})},debug(...e){return Q(()=>{console.debug(...e)})},dir(e,t){return Q(()=>{console.dir(e,t)})},dirxml(...e){return Q(()=>{console.dirxml(...e)})},error(...e){return Q(()=>{console.error(...e)})},group(e){return e?.collapsed?Q(()=>console.groupCollapsed(e?.label)):Q(()=>console.group(e?.label))},groupEnd:Q(()=>{console.groupEnd()}),info(...e){return Q(()=>{console.info(...e)})},log(...e){return Q(()=>{console.log(...e)})},table(e,t){return Q(()=>{console.table(e,t)})},time(e){return Q(()=>console.time(e))},timeEnd(e){return Q(()=>console.timeEnd(e))},timeLog(e,...t){return Q(()=>{console.timeLog(e,...t)})},trace(...e){return Q(()=>{console.trace(...e)})},warn(...e){return Q(()=>{console.warn(...e)})},unsafe:console}});var _$="effect/Random",tE,nE,rE,v$=(e,t)=>He(()=>b(Q(()=>Array.from(e)),oe((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return b(r,Da((o)=>b(t(o),ct((i)=>R$(n,o-1,i)))),Lo(bp(n)))}))),R$=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},oE=(e)=>new rE(U(e));var iE=w(()=>{Vr();Wn();ne();Ge();di();wt();tE=Symbol.for(_$),nE=yn("effect/Random");rE=class rE{seed;[tE]=tE;PRNG;constructor(e){this.seed=e,this.PRNG=new Ag(e)}get next(){return Q(()=>this.PRNG.number())}get nextBoolean(){return ct(this.next,(e)=>e>0.5)}get nextInt(){return Q(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return ct(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return Q(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return v$(e,(t)=>this.nextIntBetween(0,t))}}});class cE{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(e,t,n,r,o,i){this.name=e,this.parent=t,this.context=n,this.startTime=o,this.kind=i,this.status={_tag:"Started",startTime:o},this.attributes=new Map,this.traceId=t._tag==="Some"?t.value.traceId:sE(32),this.spanId=sE(16),this.links=Array.from(r)}end(e,t){this.status={_tag:"Ended",endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}}var aE,C$=(e)=>({[aE]:aE,...e}),gu,zf,sE,lE,uE;var Kf=w(()=>{Wn();ne();aE=Symbol.for("effect/Tracer"),gu=yn("effect/Tracer"),zf=yn("effect/ParentSpan"),sE=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();lE=C$({span:(e,t,n,r,o,i)=>new cE(e,t,n,r,o,i),context:(e)=>e()}),uE=Hl()("effect/Tracer/DisablePropagation",{defaultValue:ci})});var E$,yu;var dE=w(()=>{Wn();ne();nS();Xk();wt();oS();iE();Kf();E$=b(Ri(),zr(mu,Pk()),zr(Wf,eE),zr(nE,oE(Math.random())),zr(Yk,Zk()),zr(gu,lE)),yu=re(Symbol.for("effect/DefaultServices/currentServices"),()=>Tf(E$))});var P$,pE=(e)=>{let t={BaseEffectError:class extends P${_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var fE=w(()=>{wt();P$=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends Ef{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)Object.assign(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}.BaseEffectError}()});var mE,A$,aS;var sS=w(()=>{wo();mE=bo,A$=tT;aS=class aS extends A${}});var gE="Sequential",yE="Parallel",M$="ParallelN",pc,xE,SE=(e)=>({_tag:M$,parallelism:e}),cS=(e)=>e._tag===gE,lS=(e)=>e._tag===yE;var Jf=w(()=>{pc={_tag:gE},xE={_tag:yE}});var Gf,Yf,Zf;var bE=w(()=>{Jf();Gf=pc,Yf=xE,Zf=SE});function wE(e){return new qo(e)}function _E(){return wE(new Map)}var dS,qo,F$=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(Fe(i)&&Fe(a)){let l=xt(i)[0],u=fr(i),d=xt(a)[0],p=xt(a)[1],m=fr(a);if(l.startTimeMillis<d.startTimeMillis)a=m,s=!0;else if(l.startTimeMillis>d.startTimeMillis)i=u;else if(l.id<d.id)a=m,s=!0;else if(l.id>d.id)i=u;else c=[p,s]}else c=[o.initial,!0];return c},fS,mS,vE=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(j(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},xu,hS,Fi,fc,pS=(e,t,n,r)=>{let o=e.get(n)??[],i;if(Fe(o)){let[a,s]=xt(o);if(a[z](t))if(j(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},RE;var Xf=w(()=>{st();Re();ne();ft();Ne();dS=Symbol.for("effect/FiberRefs");qo=class qo{locals;[dS]=dS;constructor(e){this.locals=e}pipe(){return F(this,arguments)}};fS=h(3,(e,t,n)=>{let r=new Map(e.locals);return n.locals.forEach((o,i)=>{let a=o[0][1];if(!o[0][0][z](t)){if(!r.has(i)){if(j(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=F$(i,s,o);if(l){let u=i.diff(c,a),d=s[0][1],p=i.join(d,i.patch(u)(d));if(!j(d,p)){let m,f=s[0][0];if(f[z](t))m=[[f,p],...s.slice(1)];else m=[[t,p],...s];r.set(i,m)}}}}),new qo(r)}),mS=h(2,(e,t)=>{let n=new Map;return vE(e,n,t),new qo(n)}),xu=h(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new qo(n)}),hS=h(2,(e,t)=>{if(!e.locals.has(t))return B();return Y(xt(e.locals.get(t))[1])}),Fi=h(2,(e,t)=>b(hS(e,t),Ue(()=>t.initial))),fc=h(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new qo(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return pS(o,t,n,r),new qo(o)}),RE=h(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new qo(new Map(t));let r=new Map(e.locals);if(n!==void 0)vE(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)pS(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{pS(r,a,o,s)})}),new qo(r)})});var TE,CE,OE;var yS=w(()=>{Xf();TE=Fi,CE=RE,OE=_E});var EE="Empty",IE="Add",PE="Remove",AE="Update",ME="AndThen",NE,FE=(e,t)=>{let n=new Map(e.locals),r=NE;for(let[o,i]of t.locals.entries()){let a=xt(i)[1],s=n.get(o);if(s!==void 0){let c=xt(s)[1];if(!j(c,a))r=Qf({_tag:AE,fiberRef:o,patch:o.diff(c,a)})(r)}else r=Qf({_tag:IE,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=Qf({_tag:PE,fiberRef:o})(r);return r},Qf,LE;var DE=w(()=>{st();Re();ne();Xf();NE={_tag:EE},Qf=h(2,(e,t)=>({_tag:ME,first:e,second:t})),LE=h(3,(e,t,n)=>{let r=n,o=Gt(e);while(Fe(o)){let i=xt(o),a=fr(o);switch(i._tag){case EE:{o=a;break}case IE:{r=fc(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case PE:{r=xu(r,i.fiberRef),o=a;break}case AE:{let s=Fi(r,i.fiberRef);r=fc(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case ME:{o=Ds(i.first)(Ds(i.second)(a));break}}}return r})});var qE,UE;var $E=w(()=>{DE();qE=FE,UE=LE});var tm="effect/FiberStatus",Li,em="Done",jE="Running",HE="Suspended",q$,BE,VE,WE,zE,KE=(e)=>new VE(e),JE=(e,t)=>new WE(e,t),nm=(e)=>H(e,Li),GE=(e)=>e._tag===em;var YE=w(()=>{Re();ne();Ge();Ie();Li=Symbol.for(tm),q$=ke(`${tm}-${em}`);BE=class BE{[Li]=Li;_tag=em;[J](){return q$}[z](e){return nm(e)&&e._tag===em}};VE=class VE{runtimeFlags;[Li]=Li;_tag=jE;constructor(e){this.runtimeFlags=e}[J](){return b(U(tm),le(U(this._tag)),le(U(this.runtimeFlags)),ye(this))}[z](e){return nm(e)&&e._tag===jE&&this.runtimeFlags===e.runtimeFlags}};WE=class WE{runtimeFlags;blockingOn;[Li]=Li;_tag=HE;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[J](){return b(U(tm),le(U(this._tag)),le(U(this.runtimeFlags)),le(U(this.blockingOn)),ye(this))}[z](e){return nm(e)&&e._tag===HE&&this.runtimeFlags===e.runtimeFlags&&j(this.blockingOn,e.blockingOn)}};zE=new BE});var ZE,xS,XE,QE;var eI=w(()=>{YE();ZE=zE,xS=KE,XE=JE,QE=GE});var j$,H$,B$,V$,W$,z$,K$,J$,G$,tI,nI=(e)=>{switch(e){case"All":return j$;case"Debug":return z$;case"Error":return B$;case"Fatal":return H$;case"Info":return W$;case"Trace":return K$;case"None":return J$;case"Warning":return V$}};var rI=w(()=>{ne();wt();hu();yp();j$=rk,H$=ok,B$=ik,V$=jx,W$=Hx,z$=Bx,K$=ak,J$=sk,G$=b(Yr,gp((e)=>e.ordinal)),tI=Gg(G$)});function i2(e){return bS("Micro.evaluate: Not implemented")}class OS{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,p2(this.afterScheduled)}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let e=this.tasks;this.tasks=[];for(let t=0,n=e.length;t<n;t++)e[t]()}shouldYield(e){return e.currentOpCount>=e.getRef(hI)}flush(){while(this.tasks.length>0)this.runTasks()}}var Z$,om,oI,X$,wS,sI,Q$=(e,t=[])=>new sI(e,t),cI,e2=(e=[])=>new cI(e),t2=(e)=>e._tag==="Interrupt",iI,n2,lI,aI,uI,Ot,SS,hc,mc,im,rm,r2,o2,sm=(e)=>({...o2,[uI]:e.op,[SS]:e.eval??i2,[hc]:e.contA,[mc]:e.contE,[im]:e.ensure}),_S=(e)=>{let t=sm(e);return function(){let n=Object.create(t);return n[Ot]=e.single===!1?arguments:arguments[0],n}},dI=(e)=>{let t={...sm(e),[om]:om,_tag:e.op,get[e.prop](){return this[Ot]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[Ot]}},[z](n){return u2(n)&&n._tag===e.op&&j(this[Ot],n[Ot])},[J](){return ye(this,le(ke(e.op))(U(this[Ot])))}};return function(n){let r=Object.create(t);return r[Ot]=n,r[hc]=void 0,r[mc]=void 0,r[im]=void 0,r}},vS,pI,a2,s2,c2,RS,am,l2,u2=(e)=>H(e,om),fI,TS,CS,bS=(e)=>TS(Q$(e)),d2,p2,f2,mI,hI,cm,m2,h2,g2,gI,y2=(e)=>RS((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(gI(!1)),t._interrupted)return CS;return e}),x2=(e)=>RS((t)=>{if(!t.interruptible)return e(ve);return t.interruptible=!1,t._stack.push(gI(!0)),e(y2)}),yI=(e,t)=>{let n=new lI(cm.context(t?.scheduler??new OS));if(n.evaluate(e),t?.signal)if(t.signal.aborted)n.unsafeInterrupt();else{let r=()=>n.unsafeInterrupt();t.signal.addEventListener("abort",r,{once:!0}),n.addObserver(()=>t.signal.removeEventListener("abort",r))}return n};var xI=w(()=>{Wn();sS();Re();ne();Ge();at();jp();Ne();Ie();di();Z$=Symbol.for("effect/Micro"),om=Symbol.for("effect/Micro/MicroExit"),oI=Symbol.for("effect/Micro/MicroCause"),X$={_E:ve};wS=class wS extends globalThis.Error{_tag;traces;[oI];constructor(e,t,n){let r=`MicroCause.${e}`,o,i,a;if(t instanceof globalThis.Error){o=`(${r}) ${t.name}`,i=t.message;let s=i.split(`
26
26
  `).length;a=t.stack?`(${r}) ${t.stack.split(`
27
27
  `).slice(0,s+3).join(`
28
- `)}`:`${o}: ${i}`}else o=r,i=fo(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
28
+ `)}`:`${o}: ${i}`}else o=r,i=So(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
29
29
  ${n.join(`
30
- `)}`;super(i);this._tag=e,this.traces=n,this[Xk]=VU,this.name=o,this.stack=a}pipe(){return L(this,arguments)}toString(){return this.stack}[pe](){return this.stack}};tI=class tI extends lS{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};nI=class nI extends lS{constructor(e=[]){super("Interrupt","interrupted",e)}};Qk=Symbol.for("effect/Micro/MicroFiber"),JU={_A:we,_E:we};rI=class rI{context;interruptible;[Qk];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[Qk]=JU}getRef(e){return RC(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),al;return this._observers.push(e),()=>{let t=this._observers.indexOf(e);if(t>=0)this._observers.splice(t,1)}}_interrupted=!1;unsafeInterrupt(){if(this._exit)return;if(this._interrupted=!0,this.interruptible)this.evaluate(mS)}unsafePoll(){return this._exit}evaluate(e){if(this._exit)return;else if(this._yielded!==void 0){let r=this._yielded;this._yielded=void 0,r()}let t=this.runLoop(e);if(t===Vf)return;let n=eI.interruptChildren&&eI.interruptChildren(this);if(n!==void 0)return this.evaluate(Kf(n,()=>t));this._exit=t;for(let r=0;r<this._observers.length;r++)this._observers[r](t);this._observers.length=0}runLoop(e){let t=!1,n=e;this.currentOpCount=0;try{while(!0){if(this.currentOpCount++,!t&&this.getRef(Gf).shouldYield(this)){t=!0;let r=n;n=Kf(QU,()=>r)}if(n=n[sS](this),n===Vf){let r=this._yielded;if(Wf in r)return this._yielded=void 0,r;return Vf}}}catch(r){if(!H(n,sS))return cS(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return cS(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[zf]&&t[zf](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Vf}children(){return this._children??=new Set}};eI=ne("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),oI=Symbol.for("effect/Micro/identifier"),Ot=Symbol.for("effect/Micro/args"),sS=Symbol.for("effect/Micro/evaluate"),sc=Symbol.for("effect/Micro/successCont"),ac=Symbol.for("effect/Micro/failureCont"),zf=Symbol.for("effect/Micro/ensureCont"),Vf=Symbol.for("effect/Micro/Yield"),GU={_A:we,_E:we,_R:we},YU={...ck,_op:"Micro",[BU]:GU,pipe(){return L(this,arguments)},[Symbol.iterator](){return new vs(new po(this))},toJSON(){return{_id:"Micro",op:this[oI],...Ot in this?{args:this[Ot]}:void 0}},toString(){return Ee(this)},[pe](){return Ee(this)}};dS=iI({op:"Success",prop:"value",eval(e){let t=e.getCont(sc);return t?t[sc](this[Ot],e):e.yieldWith(this)}}),aI=iI({op:"Failure",prop:"cause",eval(e){let t=e.getCont(ac);while(KU(this[Ot])&&t&&e.interruptible)t=e.getCont(ac);return t?t[ac](this[Ot],e):e.yieldWith(this)}}),XU=uS({op:"Yield",eval(e){let t=!1;return e.getRef(Gf).scheduleTask(()=>{if(t)return;e.evaluate(r2)},this[Ot]??0),e.yieldWith(()=>{t=!0})}}),QU=XU(0),e2=dS(void 0),pS=uS({op:"WithMicroFiber",eval(e){return this[Ot](e)}}),Kf=h(2,(e,t)=>{let n=Object.create(t2);return n[Ot]=e,n[sc]=t,n}),t2=Jf({op:"OnSuccess",eval(e){return e._stack.push(this),this[Ot]}}),sI=dS,fS=aI,mS=fS(zU()),r2=sI(void 0),o2="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);i2=h(2,(e,t)=>pS((n)=>{let r=n.context;return n.context=t(r),c2(e,()=>(n.context=r,e2))})),cI=h(2,(e,t)=>i2(e,Nl(t)));lI=class lI extends Fl()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};Gf=class Gf extends Fl()("effect/Micro/currentScheduler",{defaultValue:()=>new hS}){};a2=h(2,(e,t)=>{let n=Object.create(s2);return n[Ot]=e,n[sc]=t.onSuccess,n[ac]=t.onFailure,n}),s2=Jf({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[Ot]}}),c2=h(2,(e,t)=>u2((n)=>a2(n(e),{onFailure:(r)=>Kf(t(fS(r)),()=>aI(r)),onSuccess:(r)=>Kf(t(sI(r)),()=>dS(r))}))),uI=uS({op:"SetInterruptible",ensure(e){if(e.interruptible=this[Ot],e._interrupted&&e.interruptible)return()=>mS}})});class Yf{scheduleDrain;running=!1;tasks=new gS;constructor(e){this.scheduleDrain=e}starveInternal=(e)=>{let t=this.tasks.buckets;this.tasks.buckets=[];for(let[n,r]of t)for(let o=0;o<r.length;o++)r[o]();if(this.tasks.buckets.length===0)this.running=!1;else this.starve(e)};starve(e=0){this.scheduleDrain(e,this.starveInternal)}scheduleTask(e,t){if(this.tasks.scheduleTask(e,t),!this.running)this.running=!0,this.starve()}static cached(e){let t=new Yf(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new Yf(e),n.set(r,o);return o}}}class gS{buckets=[];scheduleTask(e,t){let n=this.buckets.length,r=void 0,o=0;for(;o<n;o++)if(this.buckets[o][0]<=t)r=this.buckets[o];else break;if(r&&r[0]===t)r[1].push(e);else if(o===n)this.buckets.push([t,[e]]);else this.buckets.splice(o,0,[t,[e]])}}class fI{maxNextTickBeforeTimer;getRunner=Yf.cached((e,t)=>{if(e>=this.maxNextTickBeforeTimer)setTimeout(()=>t(0),0);else Promise.resolve(void 0).then(()=>t(e+1))});constructor(e){this.maxNextTickBeforeTimer=e}shouldYield(e){return e.currentOpCount>e.getFiberRef(Ax)?e.getFiberRef(Qs):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class pu{tasks=new gS;deferred=!1;scheduleTask(e,t,n){if(this.deferred)mI.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(Ax)?e.getFiberRef(Qs):!1}flush(){while(this.tasks.buckets.length>0){let e=this.tasks.buckets;this.tasks.buckets=[];for(let[t,n]of e)for(let r=0;r<n.length;r++)n[r]()}this.deferred=!0}}var mI,Zf;var Xf=b(()=>{wt();mI=ne(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new fI(2048));Zf=ne(Symbol.for("effect/FiberRef/currentScheduler"),()=>Ht(mI))});var Qf;var yS=b(()=>{wt();Qf=ne(Symbol.for("effect/FiberRef/currentRequestMap"),()=>Ht(new Map))});var xS=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return Oa(sE,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var gI=b(()=>{wt()});var SS=(e)=>e.replace(/[\s="]/g,"_"),yI=(e)=>(t)=>`${SS(t.label)}=${e-t.startTime}ms`;var xI="effect/MetricLabel",bS,SI,bI=(e,t)=>new SI(e,t),h2=(e)=>H(e,bS);var _I=b(()=>{ve();Ke();Ae();ke();bS=Symbol.for(xI);SI=class SI{key;value;[bS]=bS;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=Oe(xI+this.key+this.value)}[G](){return this._hash}[z](e){return h2(e)&&this.key===e.key&&this.value===e.value}pipe(){return L(this,arguments)}}});var _S;var wI=b(()=>{Vn();pt();Nf();_S=ar((e)=>Al(e.context,ok)?e._tag==="Span"?_S(e.parent):B():Y(e))});var vI;var RI=b(()=>{wt();vI=Fx});var wS="InterruptSignal",vS="Stateful",RS="Resume",TS="YieldNow",em=(e)=>({_tag:"InterruptSignal",cause:e}),cc=(e)=>({_tag:"Stateful",onFiber:e}),Ma=(e)=>({_tag:"Resume",effect:e}),TI=()=>({_tag:"YieldNow"});var _2="effect/FiberScope",tm,OI,EI,kI=(e)=>new EI(e.id(),e),fu;var CS=b(()=>{Ws();tm=Symbol.for(_2);OI=class OI{[tm]=tm;fiberId=Wn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};EI=class EI{fiberId;parent;[tm]=tm;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(cc((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};fu=ne(Symbol.for("effect/FiberScope/Global"),()=>new OI)});var R2="effect/Fiber",OS,ES,T2,C2="effect/Fiber",PI,nm=(e)=>uf(Yl(e.await),e.inheritAll),L6,Ti="effect/FiberCurrent";var AI=b(()=>{Ws();pt();Ae();wt();ho();OS=Symbol.for(R2),ES={_E:(e)=>e,_A:(e)=>e},T2={[OS]:ES,pipe(){return L(this,arguments)}},PI=Symbol.for(C2),L6={...ti,commit(){return nm(this)},...T2,id:()=>Wn,await:eu,children:Te([]),inheritAll:eu,poll:Te(B()),interruptAsFork:()=>eu}});var E2="effect/Logger",MI,NI,rm=(e)=>({[MI]:NI,log:e,pipe(){return L(this,arguments)}}),$6,k2,I2=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(k2)?m:e(m),u=(m,y)=>`${SS(m)}=${l(y)}`,d=(m,y)=>" "+u(m,y),p=u("timestamp",o.toISOString());p+=d("level",a.label),p+=d("fiber",Lp(i));let f=Ug(s);for(let m=0;m<f.length;m++)p+=d("message",fo(f[m],t));if(!my(r))p+=d("cause",fr(r,{renderErrorCause:!0}));for(let m of c)p+=" "+yI(o.getTime())(m);for(let[m,y]of n)p+=d(m,fo(y,t));return p},P2=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,FI,Na,U6,LI,j6,H6;var DI=b(()=>{at();te();it();Ae();Hs();Ly();MI=Symbol.for(E2),NI={_Message:(e)=>e,_Output:(e)=>e},$6={[MI]:NI,log:al,pipe(){return L(this,arguments)}},k2=/^[^\s"=]*$/,FI=rm(I2(P2)),Na={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},U6={None:[],All:[],Trace:[Na.gray],Debug:[Na.blue],Info:[Na.green],Warning:[Na.yellow],Error:[Na.red],Fatal:[Na.bgBrightRed,Na.black]},LI=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,j6=LI&&process.stdout.isTTY===!0,H6=LI||"Deno"in globalThis});var qI="effect/MetricBoundaries",kS,$I,M2=(e)=>H(e,kS),N2=(e)=>{let t=S(e,jg(bt(Number.POSITIVE_INFINITY)),Jg);return new $I(t)},UI=(e)=>S($g(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Tl,N2);var jI=b(()=>{at();$r();ve();te();Ke();Ae();ke();kS=Symbol.for(qI);$I=class $I{values;[kS]=kS;constructor(e){this.values=e,this._hash=S(Oe(qI),se(On(this.values)))}_hash;[G](){return this._hash}[z](e){return M2(e)&&j(this.values,e.values)}pipe(){return L(this,arguments)}}});var L2="effect/MetricKeyType",HI,BI="effect/MetricKeyType/Counter",IS,D2="effect/MetricKeyType/Frequency",q2,$2="effect/MetricKeyType/Gauge",U2,VI="effect/MetricKeyType/Histogram",PS,j2="effect/MetricKeyType/Summary",H2,WI,zI,KI,JI=(e)=>new zI(e?.incremental??!1,e?.bigint??!1),GI=(e)=>new KI(e),AS=(e)=>H(e,IS),YI=(e)=>H(e,q2),ZI=(e)=>H(e,U2),MS=(e)=>H(e,PS),XI=(e)=>H(e,H2);var NS=b(()=>{ve();te();Ke();Ae();ke();HI=Symbol.for(L2),IS=Symbol.for(BI),q2=Symbol.for(D2),U2=Symbol.for($2),PS=Symbol.for(VI),H2=Symbol.for(j2),WI={_In:(e)=>e,_Out:(e)=>e};zI=class zI{incremental;bigint;[HI]=WI;[IS]=IS;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=Oe(BI)}_hash;[G](){return this._hash}[z](e){return AS(e)}pipe(){return L(this,arguments)}};KI=class KI{boundaries;[HI]=WI;[PS]=PS;constructor(e){this.boundaries=e,this._hash=S(Oe(VI),se(U(this.boundaries)))}_hash;[G](){return this._hash}[z](e){return MS(e)&&j(this.boundaries,e.boundaries)}pipe(){return L(this,arguments)}}});var B2="effect/MetricKey",eP,V2,W2,om,z2=(e)=>H(e,eP),tP=(e,t)=>new om(e,JI(t),go(t?.description)),nP=(e,t,n)=>new om(e,GI(t),go(n)),rP;var oP=b(()=>{at();ve();te();Ke();pt();Ae();ke();NS();eP=Symbol.for(B2),V2={_Type:(e)=>e},W2=oi(j);om=class om{name;keyType;description;tags;[eP]=V2;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=S(Oe(this.name+this.description),se(U(this.keyType)),se(On(this.tags)))}_hash;[G](){return this._hash}[z](e){return z2(e)&&this.name===e.name&&j(this.keyType,e.keyType)&&j(this.description,e.description)&&W2(this.tags,e.tags)}pipe(){return L(this,arguments)}};rP=h(2,(e,t)=>t.length===0?e:new om(e.name,e.keyType,e.description,ri(e.tags,t)))});class aP{backing;constructor(e){this.backing=e}currentBucket;next(){if(this.currentBucket===void 0){let t=this.backing.next();if(t.done)return t;this.currentBucket=t.value[Symbol.iterator]()}let e=this.currentBucket.next();if(e.done)return this.currentBucket=void 0,this.next();return e}}var iP,J2,FS,sP=()=>{let e=Object.create(J2);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},Ci,G2=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[z](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return Y(a)}return B()},lc,uc,Y2=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[z](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var cP=b(()=>{ve();te();Ke();it();pt();Ae();iP=Symbol.for("effect/MutableHashMap"),J2={[iP]:iP,[Symbol.iterator](){return new FS(this)},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(Re)}},[pe](){return this.toJSON()},pipe(){return L(this,arguments)}};FS=class FS{self;referentialIterator;bucketIterator;constructor(e){this.self=e,this.referentialIterator=e.referential[Symbol.iterator]()}next(){if(this.bucketIterator!==void 0)return this.bucketIterator.next();let e=this.referentialIterator.next();if(e.done)return this.bucketIterator=new aP(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new FS(this.self)}};Ci=h(2,(e,t)=>{if(ml(t)===!1)return e.referential.has(t)?Y(e.referential.get(t)):B();let n=t[G](),r=e.buckets.get(n);if(r===void 0)return B();return G2(e,r,t)}),lc=h(2,(e,t)=>De(Ci(e,t))),uc=h(3,(e,t,n)=>{if(ml(t)===!1)return e.referential.set(t,n),e;let r=t[G](),o=e.buckets.get(r);if(o===void 0)return e.buckets.set(r,[[t,n]]),e.bucketsSize++,e;return Y2(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var X2="effect/MetricState",mu,lP="effect/MetricState/Counter",LS,uP="effect/MetricState/Frequency",DS,dP="effect/MetricState/Gauge",qS,pP="effect/MetricState/Histogram",$S,fP="effect/MetricState/Summary",US,hu,mP,Q2,hP,gP,yP,xP,SP=(e)=>new mP(e),bP=(e)=>new hP(e),_P=(e)=>new gP(e),wP=(e)=>new yP(e.buckets,e.count,e.min,e.max,e.sum),vP=(e)=>new xP(e.error,e.quantiles,e.count,e.min,e.max,e.sum),ej=(e)=>H(e,LS),tj=(e)=>H(e,DS),nj=(e)=>H(e,qS),rj=(e)=>H(e,$S),oj=(e)=>H(e,US);var RP=b(()=>{at();ve();te();Ke();Ae();ke();mu=Symbol.for(X2),LS=Symbol.for(lP),DS=Symbol.for(uP),qS=Symbol.for(dP),$S=Symbol.for(pP),US=Symbol.for(fP),hu={_A:(e)=>e};mP=class mP{count;[mu]=hu;[LS]=LS;constructor(e){this.count=e}[G](){return S(U(lP),se(U(this.count)),ge(this))}[z](e){return ej(e)&&this.count===e.count}pipe(){return L(this,arguments)}};Q2=oi(j);hP=class hP{occurrences;[mu]=hu;[DS]=DS;constructor(e){this.occurrences=e}_hash;[G](){return S(Oe(uP),se(On(qe(this.occurrences.entries()))),ge(this))}[z](e){return tj(e)&&Q2(qe(this.occurrences.entries()),qe(e.occurrences.entries()))}pipe(){return L(this,arguments)}};gP=class gP{value;[mu]=hu;[qS]=qS;constructor(e){this.value=e}[G](){return S(U(dP),se(U(this.value)),ge(this))}[z](e){return nj(e)&&this.value===e.value}pipe(){return L(this,arguments)}};yP=class yP{buckets;count;min;max;sum;[mu]=hu;[$S]=$S;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[G](){return S(U(pP),se(U(this.buckets)),se(U(this.count)),se(U(this.min)),se(U(this.max)),se(U(this.sum)),ge(this))}[z](e){return rj(e)&&j(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return L(this,arguments)}};xP=class xP{error;quantiles;count;min;max;sum;[mu]=hu;[US]=US;constructor(e,t,n,r,o,i){this.error=e,this.quantiles=t,this.count=n,this.min=r,this.max=o,this.sum=i}[G](){return S(U(fP),se(U(this.error)),se(U(this.quantiles)),se(U(this.count)),se(U(this.min)),se(U(this.max)),se(U(this.sum)),ge(this))}[z](e){return oj(e)&&this.error===e.error&&j(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return L(this,arguments)}}});var aj="effect/MetricHook",sj,cj,gu=(e)=>({[sj]:cj,pipe(){return L(this,arguments)},...e}),TP,OP=(e)=>{let t=e.keyType.bigint?TP:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=TP:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return gu({get:()=>SP(t),update:r,modify:r})},EP=(e)=>{let t=new Map;for(let r of e.keyType.preregisteredWords)t.set(r,0);let n=(r)=>{let o=t.get(r)??0;t.set(r,o+1)};return gu({get:()=>bP(t),update:n,modify:n})},kP=(e,t)=>{let n=t;return gu({get:()=>_P(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},IP=(e)=>{let t=e.keyType.boundaries.values,n=t.length,r=new Uint32Array(n+1),o=new Float64Array(n),i=0,a=0,{MAX_VALUE:s,MIN_VALUE:c}=Number;S(t,xo(Wr),cr((d,p)=>{o[p]=d}));let l=(d)=>{let p=0,f=n;while(p!==f){let m=Math.floor(p+(f-p)/2),y=o[m];if(d<=y)f=m;else p=m;if(f===p+1)if(d<=o[p])f=p;else p=f}if(r[p]=r[p]+1,i=i+1,a=a+d,d<s)s=d;if(d>c)c=d},u=()=>{let d=la(n),p=0;for(let f=0;f<n;f++){let m=o[f],y=r[f];p=p+y,d[f]=[m,p]}return d};return gu({get:()=>wP({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},PP=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=S(o,xo(Wr)),a=la(r),s=0,c=0,l=0,u=0,d=0,p=(m)=>{let y=[],g=0;while(g!==r-1){let x=a[g];if(x!=null){let[P,_]=x,I=Ip(m-P);if(DC(I,ky)&&LC(I,n))y.push(_)}g=g+1}return lj(t,i,xo(y,Wr))},f=(m,y)=>{if(r>0){s=s+1;let g=s%r;a[g]=[y,m]}u=c===0?m:Math.min(u,m),d=c===0?m:Math.max(d,m),c=c+1,l=l+m};return gu({get:()=>vP({error:t,quantiles:p(Date.now()),count:c,min:u,max:d,sum:l}),update:([m,y])=>f(m,y),modify:([m,y])=>f(m,y)})},lj=(e,t,n)=>{let r=n.length;if(!Me(t))return So();let o=t[0],i=t.slice(1),a=CP(e,r,B(),0,o,n),s=Jt(a);return i.forEach((c)=>{s.push(CP(e,r,a.value,a.consumed,c,a.rest))}),cr(s,(c)=>[c.quantile,c.value])},CP=(e,t,n,r,o,i)=>{let a=e,s=t,c=n,l=r,u=o,d=i,p=e,f=t,m=n,y=r,g=o,x=i;while(!0){if(!Me(d))return{quantile:u,value:B(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:Y(Vg(d)),consumed:l+d.length,rest:[]};let P=St(d),_=_T(d,(N)=>N===P),I=u*s,q=a/2*I,O=l+_[0].length,C=Math.abs(O-I);if(O<I-q){p=a,f=s,m=yo(d),y=O,g=u,x=_[1],a=p,s=f,c=m,l=y,u=g,d=x;continue}if(O>I+q){let N=Je(c)?Y(P):c;return{quantile:u,value:N,consumed:l,rest:d}}switch(c._tag){case"None":{p=a,f=s,m=yo(d),y=O,g=u,x=_[1],a=p,s=f,c=m,l=y,u=g,d=x;continue}case"Some":{let N=Math.abs(I-c.value);if(C<N){p=a,f=s,m=yo(d),y=O,g=u,x=_[1],a=p,s=f,c=m,l=y,u=g,d=x;continue}return{quantile:u,value:Y(c.value),consumed:l,rest:d}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var AP=b(()=>{at();Py();te();cu();pt();Ae();RP();sj=Symbol.for(aj),cj={_In:(e)=>e,_Out:(e)=>e},TP=BigInt(0)});var dj="effect/MetricPair",pj,fj,MP=(e,t)=>({[pj]:fj,metricKey:e,metricState:t,pipe(){return L(this,arguments)}});var NP=b(()=>{Ae();pj=Symbol.for(dj),fj={_Type:(e)=>e}});var hj="effect/MetricRegistry",FP,LP,DP=()=>new LP;var qP=b(()=>{te();cP();pt();AP();NS();NP();FP=Symbol.for(hj);LP=class LP{[FP]=FP;map=sP();snapshot(){let e=[];for(let[t,n]of this.map)e.push(MP(t,n.get()));return e}get(e){let t=S(this.map,Ci(e),xn);if(t==null){if(AS(e.keyType))return this.getCounter(e);if(ZI(e.keyType))return this.getGauge(e);if(YI(e.keyType))return this.getFrequency(e);if(MS(e.keyType))return this.getHistogram(e);if(XI(e.keyType))return this.getSummary(e);throw Error("BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues")}else return t}getCounter(e){let t=S(this.map,Ci(e),xn);if(t==null){let n=OP(e);if(!S(this.map,lc(e)))S(this.map,uc(e,n));t=n}return t}getFrequency(e){let t=S(this.map,Ci(e),xn);if(t==null){let n=EP(e);if(!S(this.map,lc(e)))S(this.map,uc(e,n));t=n}return t}getGauge(e){let t=S(this.map,Ci(e),xn);if(t==null){let n=kP(e,e.keyType.bigint?BigInt(0):0);if(!S(this.map,lc(e)))S(this.map,uc(e,n));t=n}return t}getHistogram(e){let t=S(this.map,Ci(e),xn);if(t==null){let n=IP(e);if(!S(this.map,lc(e)))S(this.map,uc(e,n));t=n}return t}getSummary(e){let t=S(this.map,Ci(e),xn);if(t==null){let n=PP(e);if(!S(this.map,lc(e)))S(this.map,uc(e,n));t=n}return t}}});var yj="effect/Metric",xj,Sj,$P,UP=function(e,t,n,r){let o=Object.assign((i)=>sf(i,(a)=>_j(o,a)),{[xj]:Sj,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return L(this,arguments)}});return o},yu=(e,t)=>jP(tP(e,t)),jP=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=$P.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=$P.get(rP(e,o)),n.set(o,i),i};return UP(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},HP=(e,t,n)=>jP(nP(e,t,n)),BP,bj,_j;var VP=b(()=>{at();te();Ae();wt();oP();_I();qP();xj=Symbol.for(yj),Sj={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},$P=ne(Symbol.for("effect/Metric/globalMetricRegistry"),()=>DP()),BP=h(3,(e,t,n)=>bj(e,[bI(t,n)])),bj=h(2,(e,t)=>UP(e.keyType,(n,r)=>e.unsafeUpdate(n,ri(t,r)),(n)=>e.unsafeValue(ri(t,n)),(n,r)=>e.unsafeModify(n,ri(t,r)))),_j=h(2,(e,t)=>Oa(nu,(n)=>X(()=>e.unsafeUpdate(t,n))))});var vj="effect/Request",Rj,Tj,S5,WP;var zP=b(()=>{te();yS();wt();ho();Rj=Symbol.for(vj),Tj={_E:(e)=>e,_A:(e)=>e},S5={...bl,[Rj]:Tj},WP=h(2,(e,t)=>Oa(Qf,(n)=>X(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,Sf(r.result,t)}})))});var Cj="effect/Supervisor",im,jS,am,sm,HS=(e)=>H(e,im)&&pl(e,"Zip"),KP,Oj=(e)=>new KP(e),Fa;var cm=b(()=>{te();ke();wt();im=Symbol.for(Cj),jS={_T:(e)=>e};am=class am{underlying;value0;[im]=jS;constructor(e,t){this.underlying=e,this.value0=t}get value(){return this.value0}onStart(e,t,n,r){this.underlying.onStart(e,t,n,r)}onEnd(e,t){this.underlying.onEnd(e,t)}onEffect(e,t){this.underlying.onEffect(e,t)}onSuspend(e){this.underlying.onSuspend(e)}onResume(e){this.underlying.onResume(e)}map(e){return new am(this,S(this.value,st(e)))}zip(e){return new sm(this,e)}};sm=class sm{left;right;_tag="Zip";[im]=jS;constructor(e,t){this.left=e,this.right=t}get value(){return lf(this.left.value,this.right.value)}onStart(e,t,n,r){this.left.onStart(e,t,n,r),this.right.onStart(e,t,n,r)}onEnd(e,t){this.left.onEnd(e,t),this.right.onEnd(e,t)}onEffect(e,t){this.left.onEffect(e,t),this.right.onEffect(e,t)}onSuspend(e){this.left.onSuspend(e),this.right.onSuspend(e)}onResume(e){this.left.onResume(e),this.right.onResume(e)}map(e){return new am(this,S(this.value,st(e)))}zip(e){return new sm(this,e)}};KP=class KP{effect;[im]=jS;constructor(e){this.effect=e}get value(){return this.effect}onStart(e,t,n,r){}onEnd(e,t){}onEffect(e,t){}onSuspend(e){}onResume(e){}map(e){return new am(this,S(this.value,st(e)))}zip(e){return new sm(this,e)}onRun(e,t){return e()}};Fa=ne("effect/Supervisor/none",()=>Oj(_t))});var JP;var GP=b(()=>{Wp();JP=hi});var YP="Empty",ZP="AddSupervisor",XP="RemoveSupervisor",QP="AndThen",dc,lm=(e,t)=>({_tag:QP,first:e,second:t}),kj=(e,t)=>Ij(t,bt(e)),Ij=(e,t)=>{let n=e,r=t;while(lr(r)){let o=ur(r);switch(o._tag){case YP:{r=dr(r);break}case ZP:{n=n.zip(o.supervisor),r=dr(r);break}case XP:{n=VS(n,o.supervisor),r=dr(r);break}case QP:{r=Gt(o.first)(Gt(o.second)(dr(r)));break}}}return n},VS=(e,t)=>{if(j(e,t))return Fa;else if(HS(e))return VS(e.left,t).zip(VS(e.right,t));else return e},um=(e)=>{if(j(e,Fa))return Ur();else if(HS(e))return S(um(e.left),Ro(um(e.right)));else return fa(e)},Pj=(e,t)=>{if(j(e,t))return dc;let n=um(e),r=um(t),o=S(r,uy(n),ha(dc,(a,s)=>lm(a,{_tag:ZP,supervisor:s}))),i=S(n,uy(r),ha(dc,(a,s)=>lm(a,{_tag:XP,supervisor:s})));return lm(o,i)},eA;var tA=b(()=>{$r();GP();ve();te();ga();cm();dc={_tag:YP},eA=JP({empty:dc,patch:kj,combine:lm,diff:Pj})});var jj,nA,Hj,Bj,Vj,xu="Continue",Wj="Done",rA="Yield",zj,dm=(e)=>{throw Error(`BUG: FiberRuntime - ${fo(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Mo,No,Su,Kj,Jj=(e)=>Ta(OO(e),(t)=>La(kO(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(_o(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return _i(lH(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),Qf,o)},!1,!1)),Gj,pm,Yj,Zj=(e)=>rm((t)=>{let n=Sk(t.context,uu);Al(n,Af).unsafe.log(e.log(t))}),Xj,Qj,eH,aA,sA=(e,t,n)=>$e(()=>{let r=qe(e),o=Array(r.length);return bi(La(r,(a,s)=>re(t(a,s),(c)=>X(()=>o[s]=c)),n,!1),Te(o))}),La=(e,t,n,r,o)=>Si((i)=>Ox((a)=>jt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return _t;let u=0,d=!1,p=o?Math.min(c.length,o):c.length,f=new Set,m=[],y=()=>f.forEach((N)=>{N.currentScheduler.scheduleTask(()=>{N.unsafeInterruptAsFork(s.id())},0,N)}),g=[],x=[],P=[],_=()=>{let N=m.filter(({exit:w})=>w._tag==="Failure").sort((w,A)=>w.index<A.index?-1:w.index===A.index?0:1).map(({exit:w})=>w);if(N.length===0)N.push(Jn);return N},I=(N,w=!1)=>{let A=cf(a(N)),E=nH(A,s,s.currentRuntimeFlags,fu);return s.currentScheduler.scheduleTask(()=>{if(w)E.unsafeInterruptAsFork(s.id());E.resume(A)},0,E),E},q=()=>{if(!r)l-=c.length,c=[];d=!0,y()},O=n?Cx:xi,C=I(yi((N)=>{let w=(E,le)=>{if(E._op==="Blocked")P.push(E);else if(m.push({index:le,exit:E}),E._op==="Failure"&&!d)q()},A=()=>{if(c.length>0){let E=c.pop(),le=u++,He=()=>{let Qe=c.pop();return le=u++,re(Ql(),()=>re(O(i(t(Qe,le))),Be))},Be=(Qe)=>{if(c.length>0){if(w(Qe,le),c.length>0)return He()}return Te(Qe)},gt=re(O(i(t(E,le))),Be),ot=I(gt);if(g.push(ot),f.add(ot),d)ot.currentScheduler.scheduleTask(()=>{ot.unsafeInterruptAsFork(s.id())},0,ot);ot.addObserver((Qe)=>{let fn;if(Qe._op==="Failure")fn=Qe;else fn=Qe.effect_instruction_i0;if(x.push(ot),f.delete(ot),w(fn,le),m.length===l)N(Te(Le(Pa(_(),{parallel:!0}),()=>Jn)));else if(P.length+m.length===l){let tr=_(),hs=P.map((nr)=>nr.effect_instruction_i0).reduce(mx);N(Te(tf(hs,La([Le(Pa(tr,{parallel:!0}),()=>Jn),...P.map((nr)=>nr.effect_instruction_i1)],(nr)=>nr,n,!0,o))))}else A()})}};for(let E=0;E<p;E++)A()}));return Po(Xs(Yl(i(nm(C))),yf({onFailure:(N)=>{q();let w=P.length+1,A=Math.min(typeof o==="number"?o:P.length,P.length),E=Array.from(P);return yi((le)=>{let He=[],Be=0,gt=0,ot=(fn,tr)=>(hs)=>{if(He[fn]=hs,Be++,Be===w)le(We(Ne(N)));if(E.length>0&&tr)Qe()},Qe=()=>{I(E.pop(),!0).addObserver(ot(gt,!0)),gt++};C.addObserver(ot(gt,!1)),gt++;for(let fn=0;fn<A;fn++)Qe()})},onSuccess:()=>Kn(x,(N)=>N.inheritAll)})))}))),WS=(e,t,n,r)=>$e(()=>{let o=qe(e),i=Array(o.length);return bi(La(o,(s,c)=>st(n(s,c),(l)=>i[c]=l),r,!1,t),Te(i))}),JS=(e)=>rH(e,fu),tH=(e,t,n,r=null)=>{let o=cA(e,t,n,r);return o.resume(e),o},nH=(e,t,n,r=null)=>cA(e,t,n,r),cA=(e,t,n,r=null)=>{let o=Dp(),i=t.getFiberRefs(),a=nS(i,o),s=new pm(o,a,n),c=vi(a,ka),l=s.currentSupervisor;return l.onStart(c,e,Y(t),s),s.addObserver((d)=>l.onEnd(d,s)),(r!==null?r:S(t.getFiberRef(ef),Le(()=>t.scope()))).add(n,s),s},rH=(e,t)=>jt((n,r)=>Te(tH(e,n,r.runtimeFlags,t))),zS=(e)=>Aa((t)=>dt(fi(t,bu),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return re(ec(n,Df),(r)=>GS(e,r))}}})),oA=(e)=>(t)=>Aa((n)=>dt(fi(n,bu),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return re(ec(r,qf(e)),(o)=>GS(t,o))}})),pc=(e,t)=>(n)=>Aa((r)=>dt(fi(r,bu),{onNone:()=>n(we),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?zS:e._tag==="Sequential"?KS:oA(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(zS));case"Sequential":return i(n(KS));case"ParallelN":return i(n(oA(o.strategy.parallelism)))}}else return n(we)}})),KS=(e)=>Aa((t)=>dt(fi(t,bu),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return re(ec(n,Lf),(r)=>GS(e,r))}}})),bu,oH=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},iH,aH=(e=oc)=>{let t=Object.create(iH);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},GS,sH=(e)=>Ea(e,{differ:eA,fork:dc}),iA,cH,lA,lH=(e,t,n)=>Gl((r)=>lA(re(JS(of(e)),(o)=>yi((i)=>{let a=t.map((l)=>l.listeners.count),s=()=>{if(a.every((l)=>l===0)){if(t.every((l)=>{if(l.result.state.current._tag==="Pending")return!0;else if(l.result.state.current._tag==="Done"&&tc(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&Rp(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(YO(o))}};o.addObserver((l)=>{c.forEach((u)=>u()),i(l)});let c=t.map((l,u)=>{let d=(p)=>{a[u]=p,s()};return l.listeners.addObserver(d),()=>l.listeners.removeObserver(d)});return s(),X(()=>{c.forEach((l)=>l())})})),$e(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return Ta(o,(i)=>WP(i.request,Dx(r)))})));var YS=b(()=>{at();$r();Vn();Gx();mk();Ws();iS();Nk();Jk();te();ga();it();Zk();pI();pt();Ae();ke();px();Xf();Qo();IO();Hs();Vx();yS();gI();wI();wt();ik();zx();Ff();AI();$f();CS();DI();VP();jI();zP();zl();zl();cm();tA();Nf();jj=yu("effect_fiber_started",{incremental:!0}),nA=yu("effect_fiber_active"),Hj=yu("effect_fiber_successes",{incremental:!0}),Bj=yu("effect_fiber_failures",{incremental:!0}),Vj=BP(HP("effect_fiber_lifetimes",UI({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),zj={_E:(e)=>e,_A:(e)=>e},Mo=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),No=ne("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Su={[Rs]:(e,t,n)=>Ut(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>We(We(n)),[Ts]:(e,t,n)=>Ut(()=>t.effect_instruction_i2(n)),[xl]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),ko(e.currentRuntimeFlags)&&e.isInterrupted())return Ne(e.getInterruptedCause());else return We(n)},[Cs]:(e,t,n)=>{if(Ut(()=>t.effect_instruction_i2(n)),Ut(()=>t.effect_instruction_i0()))return e.pushStack(t),Ut(()=>t.effect_instruction_i1());else return _t},[Os]:(e,t,n)=>{while(!0){let r=Ut(()=>t.effect_instruction_i0.next(n));if(r.done)return We(r.value);let o=_g(r.value);if(!tc(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},Kj={[wS]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),ko(t)?Ne(r.cause):n),[RS]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[vS]:(e,t,n,r)=>(r.onFiber(e,aS(t)),n),[TS]:(e,t,n,r)=>re(Ql(),()=>n)},Gj=Sl();pm=class pm extends Jx{[OS]=ES;[PI]=zj;_fiberRefs;_fiberId;_queue=[];_children=null;_observers=[];_running=!1;_stack=[];_asyncInterruptor=null;_asyncBlockingOn=null;_exitValue=null;_steps=[];_isYielding=!1;currentRuntimeFlags;currentOpCount=0;currentSupervisor;currentScheduler;currentTracer;currentSpan;currentContext;currentDefaultServices;constructor(e,t,n){super();if(this.currentRuntimeFlags=n,this._fiberId=e,this._fiberRefs=t,sx(n)){let r=this.getFiberRef(nu);jj.unsafeUpdate(1,r),nA.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return nm(this)}id(){return this._fiberId}resume(e){this.tell(Ma(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(Kk(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return kI(this)}get children(){return this.ask((e)=>Array.from(e.getChildren()))}getChildren(){if(this._children===null)this._children=new Set;return this._children}getInterruptedCause(){return this.getFiberRef(ru)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return $e(()=>{let t=fE(this._fiberId);return this.tell(cc((n,r)=>{Sf(t,X(()=>e(n,r)))})),xf(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return yi((e)=>{let t=(n)=>e(Te(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(cc((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),X(()=>this.tell(cc((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return jt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=tS(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(iA),c=S(Vl(o,s),dx(Eo),dx(Jp));return Ex(c)})}get poll(){return X(()=>go(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return X(()=>this.tell(em(pr(e))))}unsafeInterruptAsFork(e){this.tell(em(pr(e)))}addObserver(e){if(this._exitValue!==null)e(this._exitValue);else this._observers.push(e)}removeObserver(e){this._observers=this._observers.filter((t)=>t!==e)}getFiberRefs(){return this.setFiberRef(iA,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=du(this._fiberRefs,e)}getFiberRef(e){if(this._fiberRefs.locals.has(e))return this._fiberRefs.locals.get(e)[0][1];return e.initial}setFiberRef(e,t){this._fiberRefs=ic(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(uu),this.currentTracer=this.currentDefaultServices.unsafeMap.get(lu.key),this.currentSupervisor=this.getFiberRef(cH),this.currentScheduler=this.getFiberRef(Zf),this.currentContext=this.getFiberRef(ka),this.currentSpan=this.currentContext.unsafeMap.get(Mf.key)}setFiberRefs(e){this._fiberRefs=e,this.refreshRefCache()}addChild(e){this.getChildren().add(e)}removeChild(e){this.getChildren().delete(e)}transferChildren(e){let t=this._children;if(this._children=null,t!==null&&t.size>0){for(let n of t)if(n._exitValue===null)e.add(this.currentRuntimeFlags,n)}}drainQueueOnCurrentThread(){let e=!0;while(e){let t=xu,n=globalThis[Ti];globalThis[Ti]=this;try{while(t===xu)t=this._queue.length===0?Wj:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Ti]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===rA)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Qs),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=Kj[r._tag](this,e,n,r)}return n}isInterrupted(){return!vp(this.getFiberRef(ru))}addInterruptedCause(e){let t=this.getFiberRef(ru);this.setFiberRef(ru,Yt(t,e))}processNewInterruptSignal(e){this.addInterruptedCause(e),this.sendInterruptSignalToAllChildren()}sendInterruptSignalToAllChildren(){if(this._children===null||this._children.size===0)return!1;let e=!1;for(let t of this._children)t.tell(em(pr(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return Xl({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Po(r.value.await);else return X(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(sx(this.currentRuntimeFlags)){let t=this.getFiberRef(nu),n=this.id().startTimeMillis,r=Date.now();switch(Vj.unsafeUpdate(r-n,t),nA.unsafeUpdate(-1,t),e._tag){case gn:{Hj.unsafeUpdate(1,t);break}case hn:{Bj.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(lE);if(!js(e.cause)&&t._tag==="Some")this.log("Fiber terminated with an unhandled error",e.cause,t)}}setExitValue(e){this._exitValue=e,this.reportExitValue(e);for(let t=this._observers.length-1;t>=0;t--)this._observers[t](e);this._observers=[]}getLoggers(){return this.getFiberRef(eH)}log(e,t,n){let r=De(n)?n.value:this.getFiberRef(Mx),o=this.getFiberRef(Yj);if(Gk(o,r))return;let i=this.getFiberRef(iE),a=this.getFiberRef(oE),s=this.getLoggers(),c=this.getFiberRefs();if(El(s)>0){let l=Al(this.getFiberRef(uu),su),u=new Date(l.unsafeCurrentTimeMillis());jR(c,()=>{for(let d of s)d.log({fiberId:this.id(),logLevel:r,message:e,cause:t,context:c,spans:i,annotations:a,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case TS:return rA;case wS:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Ne(e.cause)),this._asyncInterruptor=null;return xu}case RS:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),xu;case vS:return e.onFiber(this,this._exitValue!==null?Wk:zk(this.currentRuntimeFlags,this._asyncBlockingOn)),xu;default:return dm(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=ko(this.currentRuntimeFlags)&&this.isInterrupted()?Ne(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===Mo){let o=No.currentOp;if(No.currentOp=null,o._op===Es)if(vO(this.currentRuntimeFlags))this.tell(TI()),this.tell(Ma(Jn)),t=null;else t=Jn;else if(o._op===aa)t=null}else{this.currentRuntimeFlags=S(this.currentRuntimeFlags,ox(Jp));let o=this.interruptAllChildren();if(o!==null)t=re(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(Ma(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Ti];globalThis[Ti]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Ti]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(Ma(e))}startFork(e){this.tell(Ma(e))}patchRuntimeFlags(e,t){let n=Wl(e,t);return globalThis[Ti]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(Ma(o))};if(ko(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(Zt(In(o)))}}pushStack(e){if(this._stack.push(e),e._op==="OnStep")this._steps.push({refs:this.getFiberRefs(),flags:this.currentRuntimeFlags})}popStack(){let e=this._stack.pop();if(e){if(e._op==="OnStep")this._steps.pop();return e}return}getNextSuccessCont(){let e=this.popStack();while(e){if(e._op!==yl)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==Rs&&e._op!==Cs&&e._op!==Os)return e;e=this.popStack()}}[BR](e){return X(()=>Ml(this.currentContext,e))}["Left"](e){return Ft(e.left)}["None"](e){return Ft(new ou)}["Right"](e){return We(e.right)}["Some"](e){return We(e.value)}["Micro"](e){return Kl((t)=>{let n=t,r=dI(cI(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(We(o.value));switch(o.cause._tag){case"Interrupt":return n(Ne(pr(Wn)));case"Fail":return n(Ft(o.cause.error));case"Die":return n(rf(o.cause.defect))}}),Kl((o)=>{n=(i)=>{o(_t)},r.unsafeInterrupt()})})}[Xd](e){let t=Ut(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Su))dm(n);return Su[n._op](this,n,t)}else return No.currentOp=We(t),Mo}[gn](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Su))dm(n);return Su[n._op](this,n,t.effect_instruction_i0)}else return No.currentOp=t,Mo}[hn](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case yl:case Ts:if(!(ko(this.currentRuntimeFlags)&&this.isInterrupted()))return Ut(()=>n.effect_instruction_i1(t));else return Ne(Cp(t));case"OnStep":if(!(ko(this.currentRuntimeFlags)&&this.isInterrupted()))return We(Ne(t));else return Ne(Cp(t));case xl:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),ko(this.currentRuntimeFlags)&&this.isInterrupted())return Ne(Yt(t,this.getInterruptedCause()));else return Ne(t);default:dm(n)}else return No.currentOp=Ne(t),Mo}[Qd](e){return Ut(()=>e.effect_instruction_i0(this,aS(this.currentRuntimeFlags)))}["Blocked"](e){let t=this.getFiberRefs(),n=this.currentRuntimeFlags;if(this._steps.length>0){let r=[],o=this._steps[this._steps.length-1],i=this.popStack();while(i&&i._op!=="OnStep")r.push(i),i=this.popStack();this.setFiberRefs(o.refs),this.currentRuntimeFlags=o.flags;let a=Ak(o.refs,t),s=Vl(o.flags,n);return We(tf(e.effect_instruction_i0,jt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(Mk(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=Wl(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return Si((r)=>re(JS(xx(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return Jj(e.effect_instruction_i0)}[ca](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=Wl(n,t);if(ko(r)&&this.isInterrupted())return Ne(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Vl(r,n);return this.pushStack(new Sx(o,e)),Ut(()=>e.effect_instruction_i1(n))}else return Jn}[Rs](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[yl](e){return this.pushStack(e),e.effect_instruction_i0}[Ts](e){return this.pushStack(e),e.effect_instruction_i0}[aa](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),No.currentOp=e,Mo}[Es](e){return this._isYielding=!1,No.currentOp=e,Mo}[Cs](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return Jn}[Os](e){return Su[Os](this,e,void 0)}[sa](e){return Ut(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&wO)!==0)this.currentSupervisor.onEffect(this,t);if(this._queue.length>0)t=this.drainQueueWhileRunning(this.currentRuntimeFlags,t);if(!this._isYielding){this.currentOpCount+=1;let n=this.currentScheduler.shouldYield(this);if(n!==!1){this._isYielding=!0,this.currentOpCount=0;let r=t;t=re(Ql({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(Gj!==t[gi]._V){let n=this.getFiberRef(uE);if(n._tag==="Some"){let r=t[gi]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${Sl()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,To,n)}}return this[t._op](t)},this),t===Mo){let n=No.currentOp;if(n._op===Es||n._op===aa)return Mo;return No.currentOp=null,n._op===gn||n._op===hn?n:Ne(In(n))}}catch(n){if(t!==Mo&&!H(t,"_op")||!(t._op in this))t=vx(`Not a valid effect: ${fo(t)}`);else if(dE(n))t=Ne(Yt(In(n),pr(Wn)));else t=rf(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};Yj=ne("effect/FiberRef/currentMinimumLogLevel",()=>Ht(Yk("Info"))),Xj=ne(Symbol.for("effect/Logger/defaultLogger"),()=>Zj(FI)),Qj=ne(Symbol.for("effect/Logger/tracerLogger"),()=>rm(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=_S(fi(vi(n,ka),Mf));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=Ml(vi(n,uu),su),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=KC(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=fr(t,{renderErrorCause:!0});a.value.event(fo(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),eH=ne(Symbol.for("effect/FiberRef/currentLoggers"),()=>nE(fa(Xj,Qj))),aA=h((e)=>yg(e[0]),(e,t,n)=>jt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(cE);if(n?.discard)return xS(n.concurrency,()=>pc(Lf,n?.concurrentFinalizers)((i)=>o?La(e,(a,s)=>i(t(a,s)),!0,!1,1):Ta(e,(a,s)=>i(t(a,s)))),()=>pc(Df,n?.concurrentFinalizers)((i)=>La(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>pc(qf(i),n?.concurrentFinalizers)((a)=>La(e,(s,c)=>a(t(s,c)),o,!1,i)));return xS(n?.concurrency,()=>pc(Lf,n?.concurrentFinalizers)((i)=>o?WS(e,1,(a,s)=>i(t(a,s)),!0):Kn(e,(a,s)=>i(t(a,s)))),()=>pc(Df,n?.concurrentFinalizers)((i)=>sA(e,(a,s)=>i(t(a,s)),o)),(i)=>pc(qf(i),n?.concurrentFinalizers)((a)=>WS(e,i,(s,c)=>a(t(s,c)),o)))})),bu=Sn("effect/Scope"),iH={[ff]:ff,[mf]:mf,pipe(){return L(this,arguments)},fork(e){return X(()=>{let t=aH(e);if(this.state._tag==="Closed")return t.state=this.state,t;let n={},r=(o)=>t.close(o);return this.state.finalizers.set(n,r),oH(t,(o)=>X(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return $e(()=>{if(this.state._tag==="Closed")return _t;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return _t;return Yx(this.strategy)?S(Kn(t,(n)=>xi(n(e))),re((n)=>S(Pa(n),ir(iu),Le(()=>Jn)))):Zx(this.strategy)?S(sA(t,(n)=>xi(n(e)),!1),re((n)=>S(Pa(n,{parallel:!0}),ir(iu),Le(()=>Jn)))):S(WS(t,this.strategy.parallelism,(n)=>xi(n(e)),!1),re((n)=>S(Pa(n,{parallel:!0}),ir(iu),Le(()=>Jn))))})},addFinalizer(e){return $e(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),_t})}},GS=h(2,(e,t)=>$x(e,Nl(kC(bu,t)))),iA=rE(RO),cH=sH(Fa),lA=h(2,(e,t)=>Si((n)=>zn(n(e),{onFailure:(r)=>zn(t,{onFailure:(o)=>Zt(Yt(r,o)),onSuccess:()=>Zt(r)}),onSuccess:(r)=>Io(t,r)})))});var dA,pA;var fA=b(()=>{wt();dA=Nx,pA=ec});class yA{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return L(this,arguments)}}var XS=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},mA,fH,hA,mH=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new hA(e);return Error.stackTraceLimit=t,n},ZS,fm,gA,hH=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new gA(e);return Error.stackTraceLimit=t,n},gH=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return au(t.left);case"Right":return We(t.right);case"Some":return We(t.value);case"None":return au(new ou)}},yH,xH=(e)=>new yA(e.context,e.runtimeFlags,e.fiberRefs),SH,xA,SA,bA;var _A=b(()=>{Vn();ve();Ws();iS();it();pt();Ae();Xf();fA();Hs();wt();Ff();YS();CS();zl();cm();mA=XS((e,t,n)=>{let r=Dp(),o=[[ka,[[r,e.context]]]];if(n?.scheduler)o.push([Zf,[[r,n.scheduler]]]);let i=bk(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new pm(r,i,e.runtimeFlags),s=t;if(n?.scope)s=re(pA(n.scope,oc),(l)=>bi(hf(l,Gl((u)=>j(u,a.id())?_t:tu(a,u))),Xs(t,(u)=>dA(l,u))));let c=a.currentSupervisor;if(c!==Fa)c.onStart(e.context,s,B(),a),a.addObserver((l)=>c.onEnd(l,a));if(fu.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),fH=XS((e,t)=>{let n=yH(e)(t);if(n._tag==="Failure")throw hH(n.effect_instruction_i0);return n.effect_instruction_i0});hA=class hA extends Error{fiber;_tag="AsyncFiberException";constructor(e){super(`Fiber #${e.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`);this.fiber=e,this.name=this._tag,this.stack=this.message}};ZS=Symbol.for("effect/Runtime/FiberFailure"),fm=Symbol.for("effect/Runtime/FiberFailure/Cause");gA=class gA extends Error{[ZS];[fm];constructor(e){let t=kl(e)[0];super(t?.message||"An error has occurred");if(this[ZS]=ZS,this[fm]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[fm].toJSON()}}toString(){return"(FiberFailure) "+fr(this[fm],{renderErrorCause:!0})}[pe](){return this.toString()}};yH=XS((e,t)=>{let n=gH(t);if(n)return n;let r=new pu,o=mA(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return Lx(nf(mH(o),bf(o)))});SH=ax(Eo,rx,nx),xA=xH({context:pi(),runtimeFlags:SH,fiberRefs:_k()}),SA=mA(xA),bA=fH(xA)});var wA,_u,wu,An,vA,mm,RA,Da,hr,TA,CA;var OA=b(()=>{wt();YS();_A();wA=Ys,_u=aA,wu=$e,An=_t,vA=Jl,mm=st,RA=Ca,Da=Ra,hr=re,TA=SA,CA=bA});var QS=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return QS(e,t.from)}},vu=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},eb=(e)=>Array.isArray(e),kA=(e)=>!Array.isArray(e),EA=(e)=>`[${gl(e)}]`,hm=(e)=>eb(e)?e.map(EA).join(""):EA(e);var Ru=b(()=>{it()});var Oi=(e,t,n,r)=>{let o=e;if(n&&Me(n))o+=`
31
- at path: ${hm(n)}`;if(t!==void 0)o+=`
30
+ `)}`;super(i);this._tag=e,this.traces=n,this[oI]=X$,this.name=o,this.stack=a}pipe(){return F(this,arguments)}toString(){return this.stack}[me](){return this.stack}};sI=class sI extends wS{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};cI=class cI extends wS{constructor(e=[]){super("Interrupt","interrupted",e)}};iI=Symbol.for("effect/Micro/MicroFiber"),n2={_A:ve,_E:ve};lI=class lI{context;interruptible;[iI];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[iI]=n2}getRef(e){return IC(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),fl;return this._observers.push(e),()=>{let t=this._observers.indexOf(e);if(t>=0)this._observers.splice(t,1)}}_interrupted=!1;unsafeInterrupt(){if(this._exit)return;if(this._interrupted=!0,this.interruptible)this.evaluate(CS)}unsafePoll(){return this._exit}evaluate(e){if(this._exit)return;else if(this._yielded!==void 0){let r=this._yielded;this._yielded=void 0,r()}let t=this.runLoop(e);if(t===rm)return;let n=aI.interruptChildren&&aI.interruptChildren(this);if(n!==void 0)return this.evaluate(am(n,()=>t));this._exit=t;for(let r=0;r<this._observers.length;r++)this._observers[r](t);this._observers.length=0}runLoop(e){let t=!1,n=e;this.currentOpCount=0;try{while(!0){if(this.currentOpCount++,!t&&this.getRef(cm).shouldYield(this)){t=!0;let r=n;n=am(s2,()=>r)}if(n=n[SS](this),n===rm){let r=this._yielded;if(om in r)return this._yielded=void 0,r;return rm}}}catch(r){if(!H(n,SS))return bS(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return bS(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[im]&&t[im](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,rm}children(){return this._children??=new Set}};aI=re("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),uI=Symbol.for("effect/Micro/identifier"),Ot=Symbol.for("effect/Micro/args"),SS=Symbol.for("effect/Micro/evaluate"),hc=Symbol.for("effect/Micro/successCont"),mc=Symbol.for("effect/Micro/failureCont"),im=Symbol.for("effect/Micro/ensureCont"),rm=Symbol.for("effect/Micro/Yield"),r2={_A:ve,_E:ve,_R:ve},o2={...mE,_op:"Micro",[Z$]:r2,pipe(){return F(this,arguments)},[Symbol.iterator](){return new Ps(new xo(this))},toJSON(){return{_id:"Micro",op:this[uI],...Ot in this?{args:this[Ot]}:void 0}},toString(){return Ee(this)},[me](){return Ee(this)}};vS=dI({op:"Success",prop:"value",eval(e){let t=e.getCont(hc);return t?t[hc](this[Ot],e):e.yieldWith(this)}}),pI=dI({op:"Failure",prop:"cause",eval(e){let t=e.getCont(mc);while(t2(this[Ot])&&t&&e.interruptible)t=e.getCont(mc);return t?t[mc](this[Ot],e):e.yieldWith(this)}}),a2=_S({op:"Yield",eval(e){let t=!1;return e.getRef(cm).scheduleTask(()=>{if(t)return;e.evaluate(d2)},this[Ot]??0),e.yieldWith(()=>{t=!0})}}),s2=a2(0),c2=vS(void 0),RS=_S({op:"WithMicroFiber",eval(e){return this[Ot](e)}}),am=h(2,(e,t)=>{let n=Object.create(l2);return n[Ot]=e,n[hc]=t,n}),l2=sm({op:"OnSuccess",eval(e){return e._stack.push(this),this[Ot]}}),fI=vS,TS=pI,CS=TS(e2()),d2=fI(void 0),p2="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);f2=h(2,(e,t)=>RS((n)=>{let r=n.context;return n.context=t(r),g2(e,()=>(n.context=r,c2))})),mI=h(2,(e,t)=>f2(e,jl(t)));hI=class hI extends Hl()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};cm=class cm extends Hl()("effect/Micro/currentScheduler",{defaultValue:()=>new OS}){};m2=h(2,(e,t)=>{let n=Object.create(h2);return n[Ot]=e,n[hc]=t.onSuccess,n[mc]=t.onFailure,n}),h2=sm({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[Ot]}}),g2=h(2,(e,t)=>x2((n)=>m2(n(e),{onFailure:(r)=>am(t(TS(r)),()=>pI(r)),onSuccess:(r)=>am(t(fI(r)),()=>vS(r))}))),gI=_S({op:"SetInterruptible",ensure(e){if(e.interruptible=this[Ot],e._interrupted&&e.interruptible)return()=>CS}})});class lm{scheduleDrain;running=!1;tasks=new kS;constructor(e){this.scheduleDrain=e}starveInternal=(e)=>{let t=this.tasks.buckets;this.tasks.buckets=[];for(let[n,r]of t)for(let o=0;o<r.length;o++)r[o]();if(this.tasks.buckets.length===0)this.running=!1;else this.starve(e)};starve(e=0){this.scheduleDrain(e,this.starveInternal)}scheduleTask(e,t){if(this.tasks.scheduleTask(e,t),!this.running)this.running=!0,this.starve()}static cached(e){let t=new lm(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new lm(e),n.set(r,o);return o}}}class kS{buckets=[];scheduleTask(e,t){let n=this.buckets.length,r=void 0,o=0;for(;o<n;o++)if(this.buckets[o][0]<=t)r=this.buckets[o];else break;if(r&&r[0]===t)r[1].push(e);else if(o===n)this.buckets.push([t,[e]]);else this.buckets.splice(o,0,[t,[e]])}}class SI{maxNextTickBeforeTimer;getRunner=lm.cached((e,t)=>{if(e>=this.maxNextTickBeforeTimer)setTimeout(()=>t(0),0);else Promise.resolve(void 0).then(()=>t(e+1))});constructor(e){this.maxNextTickBeforeTimer=e}shouldYield(e){return e.currentOpCount>e.getFiberRef(Vx)?e.getFiberRef(sc):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class Su{tasks=new kS;deferred=!1;scheduleTask(e,t,n){if(this.deferred)bI.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(Vx)?e.getFiberRef(sc):!1}flush(){while(this.tasks.buckets.length>0){let e=this.tasks.buckets;this.tasks.buckets=[];for(let[t,n]of e)for(let r=0;r<n.length;r++)n[r]()}this.deferred=!0}}var bI,um;var dm=w(()=>{wt();bI=re(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new SI(2048));um=re(Symbol.for("effect/FiberRef/currentScheduler"),()=>Ht(bI))});var pm;var ES=w(()=>{wt();pm=re(Symbol.for("effect/FiberRef/currentRequestMap"),()=>Ht(new Map))});var IS=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return Ua(fk,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var _I=w(()=>{wt()});var PS=(e)=>e.replace(/[\s="]/g,"_"),vI=(e)=>(t)=>`${PS(t.label)}=${e-t.startTime}ms`;var RI="effect/MetricLabel",AS,TI,CI=(e,t)=>new TI(e,t),v2=(e)=>H(e,AS);var OI=w(()=>{Re();Ge();Ne();Ie();AS=Symbol.for(RI);TI=class TI{key;value;[AS]=AS;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=ke(RI+this.key+this.value)}[J](){return this._hash}[z](e){return v2(e)&&this.key===e.key&&this.value===e.value}pipe(){return F(this,arguments)}}});var MS;var kI=w(()=>{Wn();ft();Kf();MS=pr((e)=>Ul(e.context,uE)?e._tag==="Span"?MS(e.parent):B():Y(e))});var EI;var II=w(()=>{wt();EI=Kx});var NS="InterruptSignal",FS="Stateful",LS="Resume",DS="YieldNow",fm=(e)=>({_tag:"InterruptSignal",cause:e}),gc=(e)=>({_tag:"Stateful",onFiber:e}),Wa=(e)=>({_tag:"Resume",effect:e}),PI=()=>({_tag:"YieldNow"});var E2="effect/FiberScope",mm,MI,NI,FI=(e)=>new NI(e.id(),e),bu;var qS=w(()=>{Qs();mm=Symbol.for(E2);MI=class MI{[mm]=mm;fiberId=zn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};NI=class NI{fiberId;parent;[mm]=mm;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(gc((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};bu=re(Symbol.for("effect/FiberScope/Global"),()=>new MI)});var A2="effect/Fiber",US,$S,M2,N2="effect/Fiber",DI,hm=(e)=>vf(ru(e.await),e.inheritAll),X6,Di="effect/FiberCurrent";var qI=w(()=>{Qs();ft();Ne();wt();wo();US=Symbol.for(A2),$S={_E:(e)=>e,_A:(e)=>e},M2={[US]:$S,pipe(){return F(this,arguments)}},DI=Symbol.for(N2),X6={...fi,commit(){return hm(this)},...M2,id:()=>zn,await:su,children:Ce([]),inheritAll:su,poll:Ce(B()),interruptAsFork:()=>su}});var L2="effect/Logger",UI,$I,gm=(e)=>({[UI]:$I,log:e,pipe(){return F(this,arguments)}}),t5,D2,q2=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(f)=>f.match(D2)?f:e(f),u=(f,x)=>`${PS(f)}=${l(x)}`,d=(f,x)=>" "+u(f,x),p=u("timestamp",o.toISOString());p+=d("level",a.label),p+=d("fiber",Gp(i));let m=Xg(s);for(let f=0;f<m.length;f++)p+=d("message",So(m[f],t));if(!Cy(r))p+=d("cause",Sr(r,{renderErrorCause:!0}));for(let f of c)p+=" "+vI(o.getTime())(f);for(let[f,x]of n)p+=d(f,So(x,t));return p},U2=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,jI,za,n5,HI,r5,o5;var BI=w(()=>{st();ne();at();Ne();Ys();Jy();UI=Symbol.for(L2),$I={_Message:(e)=>e,_Output:(e)=>e},t5={[UI]:$I,log:fl,pipe(){return F(this,arguments)}},D2=/^[^\s"=]*$/,jI=gm(q2(U2)),za={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},n5={None:[],All:[],Trace:[za.gray],Debug:[za.blue],Info:[za.green],Warning:[za.yellow],Error:[za.red],Fatal:[za.bgBrightRed,za.black]},HI=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,r5=HI&&process.stdout.isTTY===!0,o5=HI||"Deno"in globalThis});var VI="effect/MetricBoundaries",jS,WI,j2=(e)=>H(e,jS),H2=(e)=>{let t=b(e,Qg(St(Number.POSITIVE_INFINITY)),ay);return new WI(t)},zI=(e)=>b(Zg(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Al,H2);var KI=w(()=>{st();Vr();Re();ne();Ge();Ne();Ie();jS=Symbol.for(VI);WI=class WI{values;[jS]=jS;constructor(e){this.values=e,this._hash=b(ke(VI),le(En(this.values)))}_hash;[J](){return this._hash}[z](e){return j2(e)&&j(this.values,e.values)}pipe(){return F(this,arguments)}}});var V2="effect/MetricKeyType",JI,GI="effect/MetricKeyType/Counter",HS,W2="effect/MetricKeyType/Frequency",z2,K2="effect/MetricKeyType/Gauge",J2,YI="effect/MetricKeyType/Histogram",BS,G2="effect/MetricKeyType/Summary",Y2,ZI,XI,QI,eP=(e)=>new XI(e?.incremental??!1,e?.bigint??!1),tP=(e)=>new QI(e),VS=(e)=>H(e,HS),nP=(e)=>H(e,z2),rP=(e)=>H(e,J2),WS=(e)=>H(e,BS),oP=(e)=>H(e,Y2);var zS=w(()=>{Re();ne();Ge();Ne();Ie();JI=Symbol.for(V2),HS=Symbol.for(GI),z2=Symbol.for(W2),J2=Symbol.for(K2),BS=Symbol.for(YI),Y2=Symbol.for(G2),ZI={_In:(e)=>e,_Out:(e)=>e};XI=class XI{incremental;bigint;[JI]=ZI;[HS]=HS;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=ke(GI)}_hash;[J](){return this._hash}[z](e){return VS(e)}pipe(){return F(this,arguments)}};QI=class QI{boundaries;[JI]=ZI;[BS]=BS;constructor(e){this.boundaries=e,this._hash=b(ke(YI),le(U(this.boundaries)))}_hash;[J](){return this._hash}[z](e){return WS(e)&&j(this.boundaries,e.boundaries)}pipe(){return F(this,arguments)}}});var Z2="effect/MetricKey",aP,X2,Q2,ym,ej=(e)=>H(e,aP),sP=(e,t)=>new ym(e,eP(t),_o(t?.description)),cP=(e,t,n)=>new ym(e,tP(t),_o(n)),lP;var uP=w(()=>{st();Re();ne();Ge();ft();Ne();Ie();zS();aP=Symbol.for(Z2),X2={_Type:(e)=>e},Q2=gi(j);ym=class ym{name;keyType;description;tags;[aP]=X2;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=b(ke(this.name+this.description),le(U(this.keyType)),le(En(this.tags)))}_hash;[J](){return this._hash}[z](e){return ej(e)&&this.name===e.name&&j(this.keyType,e.keyType)&&j(this.description,e.description)&&Q2(this.tags,e.tags)}pipe(){return F(this,arguments)}};lP=h(2,(e,t)=>t.length===0?e:new ym(e.name,e.keyType,e.description,hi(e.tags,t)))});class pP{backing;constructor(e){this.backing=e}currentBucket;next(){if(this.currentBucket===void 0){let t=this.backing.next();if(t.done)return t;this.currentBucket=t.value[Symbol.iterator]()}let e=this.currentBucket.next();if(e.done)return this.currentBucket=void 0,this.next();return e}}var dP,nj,KS,fP=()=>{let e=Object.create(nj);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},qi,rj=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[z](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return Y(a)}return B()},yc,xc,oj=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[z](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var mP=w(()=>{Re();ne();Ge();at();ft();Ne();dP=Symbol.for("effect/MutableHashMap"),nj={[dP]:dP,[Symbol.iterator](){return new KS(this)},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(Te)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}};KS=class KS{self;referentialIterator;bucketIterator;constructor(e){this.self=e,this.referentialIterator=e.referential[Symbol.iterator]()}next(){if(this.bucketIterator!==void 0)return this.bucketIterator.next();let e=this.referentialIterator.next();if(e.done)return this.bucketIterator=new pP(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new KS(this.self)}};qi=h(2,(e,t)=>{if(wl(t)===!1)return e.referential.has(t)?Y(e.referential.get(t)):B();let n=t[J](),r=e.buckets.get(n);if(r===void 0)return B();return rj(e,r,t)}),yc=h(2,(e,t)=>$e(qi(e,t))),xc=h(3,(e,t,n)=>{if(wl(t)===!1)return e.referential.set(t,n),e;let r=t[J](),o=e.buckets.get(r);if(o===void 0)return e.buckets.set(r,[[t,n]]),e.bucketsSize++,e;return oj(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var aj="effect/MetricState",wu,hP="effect/MetricState/Counter",JS,gP="effect/MetricState/Frequency",GS,yP="effect/MetricState/Gauge",YS,xP="effect/MetricState/Histogram",ZS,SP="effect/MetricState/Summary",XS,_u,bP,sj,wP,_P,vP,RP,TP=(e)=>new bP(e),CP=(e)=>new wP(e),OP=(e)=>new _P(e),kP=(e)=>new vP(e.buckets,e.count,e.min,e.max,e.sum),EP=(e)=>new RP(e.error,e.quantiles,e.count,e.min,e.max,e.sum),cj=(e)=>H(e,JS),lj=(e)=>H(e,GS),uj=(e)=>H(e,YS),dj=(e)=>H(e,ZS),pj=(e)=>H(e,XS);var IP=w(()=>{st();Re();ne();Ge();Ne();Ie();wu=Symbol.for(aj),JS=Symbol.for(hP),GS=Symbol.for(gP),YS=Symbol.for(yP),ZS=Symbol.for(xP),XS=Symbol.for(SP),_u={_A:(e)=>e};bP=class bP{count;[wu]=_u;[JS]=JS;constructor(e){this.count=e}[J](){return b(U(hP),le(U(this.count)),ye(this))}[z](e){return cj(e)&&this.count===e.count}pipe(){return F(this,arguments)}};sj=gi(j);wP=class wP{occurrences;[wu]=_u;[GS]=GS;constructor(e){this.occurrences=e}_hash;[J](){return b(ke(gP),le(En(je(this.occurrences.entries()))),ye(this))}[z](e){return lj(e)&&sj(je(this.occurrences.entries()),je(e.occurrences.entries()))}pipe(){return F(this,arguments)}};_P=class _P{value;[wu]=_u;[YS]=YS;constructor(e){this.value=e}[J](){return b(U(yP),le(U(this.value)),ye(this))}[z](e){return uj(e)&&this.value===e.value}pipe(){return F(this,arguments)}};vP=class vP{buckets;count;min;max;sum;[wu]=_u;[ZS]=ZS;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[J](){return b(U(xP),le(U(this.buckets)),le(U(this.count)),le(U(this.min)),le(U(this.max)),le(U(this.sum)),ye(this))}[z](e){return dj(e)&&j(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return F(this,arguments)}};RP=class RP{error;quantiles;count;min;max;sum;[wu]=_u;[XS]=XS;constructor(e,t,n,r,o,i){this.error=e,this.quantiles=t,this.count=n,this.min=r,this.max=o,this.sum=i}[J](){return b(U(SP),le(U(this.error)),le(U(this.quantiles)),le(U(this.count)),le(U(this.min)),le(U(this.max)),le(U(this.sum)),ye(this))}[z](e){return pj(e)&&this.error===e.error&&j(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return F(this,arguments)}}});var mj="effect/MetricHook",hj,gj,vu=(e)=>({[hj]:gj,pipe(){return F(this,arguments)},...e}),PP,MP=(e)=>{let t=e.keyType.bigint?PP:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=PP:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return vu({get:()=>TP(t),update:r,modify:r})},NP=(e)=>{let t=new Map;for(let r of e.keyType.preregisteredWords)t.set(r,0);let n=(r)=>{let o=t.get(r)??0;t.set(r,o+1)};return vu({get:()=>CP(t),update:n,modify:n})},FP=(e,t)=>{let n=t;return vu({get:()=>OP(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},LP=(e)=>{let t=e.keyType.boundaries.values,n=t.length,r=new Uint32Array(n+1),o=new Float64Array(n),i=0,a=0,{MAX_VALUE:s,MIN_VALUE:c}=Number;b(t,Ro(Yr),mr((d,p)=>{o[p]=d}));let l=(d)=>{let p=0,m=n;while(p!==m){let f=Math.floor(p+(m-p)/2),x=o[f];if(d<=x)m=f;else p=f;if(m===p+1)if(d<=o[p])m=p;else p=m}if(r[p]=r[p]+1,i=i+1,a=a+d,d<s)s=d;if(d>c)c=d},u=()=>{let d=wa(n),p=0;for(let m=0;m<n;m++){let f=o[m],x=r[m];p=p+x,d[m]=[f,p]}return d};return vu({get:()=>kP({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},DP=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=b(o,Ro(Yr)),a=wa(r),s=0,c=0,l=0,u=0,d=0,p=(f)=>{let x=[],g=0;while(g!==r-1){let y=a[g];if(y!=null){let[v,C]=y,M=Bp(f-v);if(BC(M,jy)&&HC(M,n))x.push(C)}g=g+1}return yj(t,i,Ro(x,Yr))},m=(f,x)=>{if(r>0){s=s+1;let g=s%r;a[g]=[x,f]}u=c===0?f:Math.min(u,f),d=c===0?f:Math.max(d,f),c=c+1,l=l+f};return vu({get:()=>EP({error:t,quantiles:p(Date.now()),count:c,min:u,max:d,sum:l}),update:([f,x])=>m(f,x),modify:([f,x])=>m(f,x)})},yj=(e,t,n)=>{let r=n.length;if(!Fe(t))return To();let o=t[0],i=t.slice(1),a=AP(e,r,B(),0,o,n),s=Gt(a);return i.forEach((c)=>{s.push(AP(e,r,a.value,a.consumed,c,a.rest))}),mr(s,(c)=>[c.quantile,c.value])},AP=(e,t,n,r,o,i)=>{let a=e,s=t,c=n,l=r,u=o,d=i,p=e,m=t,f=n,x=r,g=o,y=i;while(!0){if(!Fe(d))return{quantile:u,value:B(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:Y(ny(d)),consumed:l+d.length,rest:[]};let v=xt(d),C=OT(d,(I)=>I===v),M=u*s,N=a/2*M,O=l+C[0].length,E=Math.abs(O-M);if(O<M-N){p=a,m=s,f=vo(d),x=O,g=u,y=C[1],a=p,s=m,c=f,l=x,u=g,d=y;continue}if(O>M+N){let I=Ye(c)?Y(v):c;return{quantile:u,value:I,consumed:l,rest:d}}switch(c._tag){case"None":{p=a,m=s,f=vo(d),x=O,g=u,y=C[1],a=p,s=m,c=f,l=x,u=g,d=y;continue}case"Some":{let I=Math.abs(M-c.value);if(E<I){p=a,m=s,f=vo(d),x=O,g=u,y=C[1],a=p,s=m,c=f,l=x,u=g,d=y;continue}return{quantile:u,value:Y(c.value),consumed:l,rest:d}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var qP=w(()=>{st();By();ne();hu();ft();Ne();IP();hj=Symbol.for(mj),gj={_In:(e)=>e,_Out:(e)=>e},PP=BigInt(0)});var Sj="effect/MetricPair",bj,wj,UP=(e,t)=>({[bj]:wj,metricKey:e,metricState:t,pipe(){return F(this,arguments)}});var $P=w(()=>{Ne();bj=Symbol.for(Sj),wj={_Type:(e)=>e}});var vj="effect/MetricRegistry",jP,HP,BP=()=>new HP;var VP=w(()=>{ne();mP();ft();qP();zS();$P();jP=Symbol.for(vj);HP=class HP{[jP]=jP;map=fP();snapshot(){let e=[];for(let[t,n]of this.map)e.push(UP(t,n.get()));return e}get(e){let t=b(this.map,qi(e),gn);if(t==null){if(VS(e.keyType))return this.getCounter(e);if(rP(e.keyType))return this.getGauge(e);if(nP(e.keyType))return this.getFrequency(e);if(WS(e.keyType))return this.getHistogram(e);if(oP(e.keyType))return this.getSummary(e);throw Error("BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues")}else return t}getCounter(e){let t=b(this.map,qi(e),gn);if(t==null){let n=MP(e);if(!b(this.map,yc(e)))b(this.map,xc(e,n));t=n}return t}getFrequency(e){let t=b(this.map,qi(e),gn);if(t==null){let n=NP(e);if(!b(this.map,yc(e)))b(this.map,xc(e,n));t=n}return t}getGauge(e){let t=b(this.map,qi(e),gn);if(t==null){let n=FP(e,e.keyType.bigint?BigInt(0):0);if(!b(this.map,yc(e)))b(this.map,xc(e,n));t=n}return t}getHistogram(e){let t=b(this.map,qi(e),gn);if(t==null){let n=LP(e);if(!b(this.map,yc(e)))b(this.map,xc(e,n));t=n}return t}getSummary(e){let t=b(this.map,qi(e),gn);if(t==null){let n=DP(e);if(!b(this.map,yc(e)))b(this.map,xc(e,n));t=n}return t}}});var Tj="effect/Metric",Cj,Oj,WP,zP=function(e,t,n,r){let o=Object.assign((i)=>bf(i,(a)=>Ej(o,a)),{[Cj]:Oj,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return F(this,arguments)}});return o},Ru=(e,t)=>KP(sP(e,t)),KP=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=WP.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=WP.get(lP(e,o)),n.set(o,i),i};return zP(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},JP=(e,t,n)=>KP(cP(e,t,n)),GP,kj,Ej;var YP=w(()=>{st();ne();Ne();wt();uP();OI();VP();Cj=Symbol.for(Tj),Oj={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},WP=re(Symbol.for("effect/Metric/globalMetricRegistry"),()=>BP()),GP=h(3,(e,t,n)=>kj(e,[CI(t,n)])),kj=h(2,(e,t)=>zP(e.keyType,(n,r)=>e.unsafeUpdate(n,hi(t,r)),(n)=>e.unsafeValue(hi(t,n)),(n,r)=>e.unsafeModify(n,hi(t,r)))),Ej=h(2,(e,t)=>Ua(lu,(n)=>Q(()=>e.unsafeUpdate(t,n))))});var Pj="effect/Request",Aj,Mj,F5,ZP;var XP=w(()=>{ne();ES();wt();wo();Aj=Symbol.for(Pj),Mj={_E:(e)=>e,_A:(e)=>e},F5={...Ol,[Aj]:Mj},ZP=h(2,(e,t)=>Ua(pm,(n)=>Q(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,Af(r.result,t)}})))});var Nj="effect/Supervisor",xm,QS,Sm,bm,eb=(e)=>H(e,xm)&&Sl(e,"Zip"),QP,Fj=(e)=>new QP(e),Ka;var wm=w(()=>{ne();Ie();wt();xm=Symbol.for(Nj),QS={_T:(e)=>e};Sm=class Sm{underlying;value0;[xm]=QS;constructor(e,t){this.underlying=e,this.value0=t}get value(){return this.value0}onStart(e,t,n,r){this.underlying.onStart(e,t,n,r)}onEnd(e,t){this.underlying.onEnd(e,t)}onEffect(e,t){this.underlying.onEffect(e,t)}onSuspend(e){this.underlying.onSuspend(e)}onResume(e){this.underlying.onResume(e)}map(e){return new Sm(this,b(this.value,ct(e)))}zip(e){return new bm(this,e)}};bm=class bm{left;right;_tag="Zip";[xm]=QS;constructor(e,t){this.left=e,this.right=t}get value(){return _f(this.left.value,this.right.value)}onStart(e,t,n,r){this.left.onStart(e,t,n,r),this.right.onStart(e,t,n,r)}onEnd(e,t){this.left.onEnd(e,t),this.right.onEnd(e,t)}onEffect(e,t){this.left.onEffect(e,t),this.right.onEffect(e,t)}onSuspend(e){this.left.onSuspend(e),this.right.onSuspend(e)}onResume(e){this.left.onResume(e),this.right.onResume(e)}map(e){return new Sm(this,b(this.value,ct(e)))}zip(e){return new bm(this,e)}};QP=class QP{effect;[xm]=QS;constructor(e){this.effect=e}get value(){return this.effect}onStart(e,t,n,r){}onEnd(e,t){}onEffect(e,t){}onSuspend(e){}onResume(e){}map(e){return new Sm(this,b(this.value,ct(e)))}zip(e){return new bm(this,e)}onRun(e,t){return e()}};Ka=re("effect/Supervisor/none",()=>Fj(bt))});var eA;var tA=w(()=>{of();eA=Oi});var nA="Empty",rA="AddSupervisor",oA="RemoveSupervisor",iA="AndThen",Sc,_m=(e,t)=>({_tag:iA,first:e,second:t}),Dj=(e,t)=>qj(t,St(e)),qj=(e,t)=>{let n=e,r=t;while(hr(r)){let o=gr(r);switch(o._tag){case nA:{r=yr(r);break}case rA:{n=n.zip(o.supervisor),r=yr(r);break}case oA:{n=nb(n,o.supervisor),r=yr(r);break}case iA:{r=Yt(o.first)(Yt(o.second)(yr(r)));break}}}return n},nb=(e,t)=>{if(j(e,t))return Ka;else if(eb(e))return nb(e.left,t).zip(nb(e.right,t));else return e},vm=(e)=>{if(j(e,Ka))return Wr();else if(eb(e))return b(vm(e.left),Io(vm(e.right)));else return Ta(e)},Uj=(e,t)=>{if(j(e,t))return Sc;let n=vm(e),r=vm(t),o=b(r,_y(n),Oa(Sc,(a,s)=>_m(a,{_tag:rA,supervisor:s}))),i=b(n,_y(r),Oa(Sc,(a,s)=>_m(a,{_tag:oA,supervisor:s})));return _m(o,i)},aA;var sA=w(()=>{Vr();tA();Re();ne();ka();wm();Sc={_tag:nA},aA=eA({empty:Sc,patch:Dj,combine:_m,diff:Uj})});var Gj,cA,Yj,Zj,Xj,Tu="Continue",Qj="Done",lA="Yield",eH,Rm=(e)=>{throw Error(`BUG: FiberRuntime - ${So(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Uo,$o,Cu,tH,nH=(e)=>Da(MO(e),(t)=>Ja(FO(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(Oo(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return Mi(yH(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),pm,o)},!1,!1)),rH,Tm,oH,iH=(e)=>gm((t)=>{let n=TE(t.context,yu);Ul(n,Wf).unsafe.log(e.log(t))}),aH,sH,cH,pA,fA=(e,t,n)=>He(()=>{let r=je(e),o=Array(r.length);return Ai(Ja(r,(a,s)=>oe(t(a,s),(c)=>Q(()=>o[s]=c)),n,!1),Ce(o))}),Ja=(e,t,n,r,o)=>Pi((i)=>Ux((a)=>jt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return bt;let u=0,d=!1,p=o?Math.min(c.length,o):c.length,m=new Set,f=[],x=()=>m.forEach((I)=>{I.currentScheduler.scheduleTask(()=>{I.unsafeInterruptAsFork(s.id())},0,I)}),g=[],y=[],v=[],C=()=>{let I=f.filter(({exit:S})=>S._tag==="Failure").sort((S,D)=>S.index<D.index?-1:S.index===D.index?0:1).map(({exit:S})=>S);if(I.length===0)I.push(Gn);return I},M=(I,S=!1)=>{let D=wf(a(I)),A=uH(D,s,s.currentRuntimeFlags,bu);return s.currentScheduler.scheduleTask(()=>{if(S)A.unsafeInterruptAsFork(s.id());A.resume(D)},0,A),A},N=()=>{if(!r)l-=c.length,c=[];d=!0,x()},O=n?qx:Ii,E=M(Ei((I)=>{let S=(A,pe)=>{if(A._op==="Blocked")v.push(A);else if(f.push({index:pe,exit:A}),A._op==="Failure"&&!d)N()},D=()=>{if(c.length>0){let A=c.pop(),pe=u++,De=()=>{let Je=c.pop();return pe=u++,oe(au(),()=>oe(O(i(t(Je,pe))),vt))},vt=(Je)=>{if(c.length>0){if(S(Je,pe),c.length>0)return De()}return Ce(Je)},Rt=oe(O(i(t(A,pe))),vt),et=M(Rt);if(g.push(et),m.add(et),d)et.currentScheduler.scheduleTask(()=>{et.unsafeInterruptAsFork(s.id())},0,et);et.addObserver((Je)=>{let it;if(Je._op==="Failure")it=Je;else it=Je.effect_instruction_i0;if(y.push(et),m.delete(et),S(it,pe),f.length===l)I(Ce(Ue(Ba(C(),{parallel:!0}),()=>Gn)));else if(v.length+f.length===l){let sr=C(),aa=v.map((ii)=>ii.effect_instruction_i0).reduce(Cx);I(Ce(hf(aa,Ja([Ue(Ba(sr,{parallel:!0}),()=>Gn),...v.map((ii)=>ii.effect_instruction_i1)],(ii)=>ii,n,!0,o))))}else D()})}};for(let A=0;A<p;A++)D()}));return Do(ac(ru(i(hm(E))),If({onFailure:(I)=>{N();let S=v.length+1,D=Math.min(typeof o==="number"?o:v.length,v.length),A=Array.from(v);return Ei((pe)=>{let De=[],vt=0,Rt=0,et=(it,sr)=>(aa)=>{if(De[it]=aa,vt++,vt===S)pe(ze(Le(I)));if(A.length>0&&sr)Je()},Je=()=>{M(A.pop(),!0).addObserver(et(Rt,!0)),Rt++};E.addObserver(et(Rt,!1)),Rt++;for(let it=0;it<D;it++)Je()})},onSuccess:()=>Jn(y,(I)=>I.inheritAll)})))}))),rb=(e,t,n,r)=>He(()=>{let o=je(e),i=Array(o.length);return Ai(Ja(o,(s,c)=>ct(n(s,c),(l)=>i[c]=l),r,!1,t),Ce(i))}),ab=(e)=>dH(e,bu),lH=(e,t,n,r=null)=>{let o=mA(e,t,n,r);return o.resume(e),o},uH=(e,t,n,r=null)=>mA(e,t,n,r),mA=(e,t,n,r=null)=>{let o=Yp(),i=t.getFiberRefs(),a=mS(i,o),s=new Tm(o,a,n),c=Fi(a,ja),l=s.currentSupervisor;return l.onStart(c,e,Y(t),s),s.addObserver((d)=>l.onEnd(d,s)),(r!==null?r:b(t.getFiberRef(mf),Ue(()=>t.scope()))).add(n,s),s},dH=(e,t)=>jt((n,r)=>Ce(lH(e,n,r.runtimeFlags,t))),ob=(e)=>Va((t)=>pt(Ti(t,Ou),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return oe(cc(n,Yf),(r)=>sb(e,r))}}})),uA=(e)=>(t)=>Va((n)=>pt(Ti(n,Ou),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return oe(cc(r,Zf(e)),(o)=>sb(t,o))}})),bc=(e,t)=>(n)=>Va((r)=>pt(Ti(r,Ou),{onNone:()=>n(ve),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?ob:e._tag==="Sequential"?ib:uA(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(ob));case"Sequential":return i(n(ib));case"ParallelN":return i(n(uA(o.strategy.parallelism)))}}else return n(ve)}})),ib=(e)=>Va((t)=>pt(Ti(t,Ou),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return oe(cc(n,Gf),(r)=>sb(e,r))}}})),Ou,pH=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},fH,mH=(e=pc)=>{let t=Object.create(fH);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},sb,hH=(e)=>$a(e,{differ:aA,fork:Sc}),dA,gH,hA,yH=(e,t,n)=>nu((r)=>hA(oe(ab(xf(e)),(o)=>Ei((i)=>{let a=t.map((l)=>l.listeners.count),s=()=>{if(a.every((l)=>l===0)){if(t.every((l)=>{if(l.result.state.current._tag==="Pending")return!0;else if(l.result.state.current._tag==="Done"&&lc(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&Dp(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(nk(o))}};o.addObserver((l)=>{c.forEach((u)=>u()),i(l)});let c=t.map((l,u)=>{let d=(p)=>{a[u]=p,s()};return l.listeners.addObserver(d),()=>l.listeners.removeObserver(d)});return s(),Q(()=>{c.forEach((l)=>l())})})),He(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return Da(o,(i)=>ZP(i.request,Gx(r)))})));var cb=w(()=>{st();Vr();Wn();sS();bE();Qs();yS();$E();eI();ne();ka();at();rI();xI();ft();Ne();Ie();Rx();dm();di();LO();Ys();nS();ES();_I();kI();wt();dE();oS();Jf();qI();Xf();qS();BI();YP();KI();XP();Ql();Ql();wm();sA();Kf();Gj=Ru("effect_fiber_started",{incremental:!0}),cA=Ru("effect_fiber_active"),Yj=Ru("effect_fiber_successes",{incremental:!0}),Zj=Ru("effect_fiber_failures",{incremental:!0}),Xj=GP(JP("effect_fiber_lifetimes",zI({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),eH={_E:(e)=>e,_A:(e)=>e},Uo=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),$o=re("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Cu={[As]:(e,t,n)=>$t(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>ze(ze(n)),[Ms]:(e,t,n)=>$t(()=>t.effect_instruction_i2(n)),[Tl]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),Fo(e.currentRuntimeFlags)&&e.isInterrupted())return Le(e.getInterruptedCause());else return ze(n)},[Ns]:(e,t,n)=>{if($t(()=>t.effect_instruction_i2(n)),$t(()=>t.effect_instruction_i0()))return e.pushStack(t),$t(()=>t.effect_instruction_i1());else return bt},[Fs]:(e,t,n)=>{while(!0){let r=$t(()=>t.effect_instruction_i0.next(n));if(r.done)return ze(r.value);let o=Mg(r.value);if(!lc(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},tH={[NS]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),Fo(t)?Le(r.cause):n),[LS]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[FS]:(e,t,n,r)=>(r.onFiber(e,xS(t)),n),[DS]:(e,t,n,r)=>oe(au(),()=>n)},rH=Cl();Tm=class Tm extends aS{[US]=$S;[DI]=eH;_fiberRefs;_fiberId;_queue=[];_children=null;_observers=[];_running=!1;_stack=[];_asyncInterruptor=null;_asyncBlockingOn=null;_exitValue=null;_steps=[];_isYielding=!1;currentRuntimeFlags;currentOpCount=0;currentSupervisor;currentScheduler;currentTracer;currentSpan;currentContext;currentDefaultServices;constructor(e,t,n){super();if(this.currentRuntimeFlags=n,this._fiberId=e,this._fiberRefs=t,Sx(n)){let r=this.getFiberRef(lu);Gj.unsafeUpdate(1,r),cA.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return hm(this)}id(){return this._fiberId}resume(e){this.tell(Wa(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(QE(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return FI(this)}get children(){return this.ask((e)=>Array.from(e.getChildren()))}getChildren(){if(this._children===null)this._children=new Set;return this._children}getInterruptedCause(){return this.getFiberRef(uu)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return He(()=>{let t=Sk(this._fiberId);return this.tell(gc((n,r)=>{Af(t,Q(()=>e(n,r)))})),Pf(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return Ei((e)=>{let t=(n)=>e(Ce(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(gc((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),Q(()=>this.tell(gc((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return jt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=fS(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(dA),c=b(Zl(o,s),vx(No),vx(cf));return $x(c)})}get poll(){return Q(()=>_o(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return Q(()=>this.tell(fm(xr(e))))}unsafeInterruptAsFork(e){this.tell(fm(xr(e)))}addObserver(e){if(this._exitValue!==null)e(this._exitValue);else this._observers.push(e)}removeObserver(e){this._observers=this._observers.filter((t)=>t!==e)}getFiberRefs(){return this.setFiberRef(dA,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=xu(this._fiberRefs,e)}getFiberRef(e){if(this._fiberRefs.locals.has(e))return this._fiberRefs.locals.get(e)[0][1];return e.initial}setFiberRef(e,t){this._fiberRefs=fc(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(yu),this.currentTracer=this.currentDefaultServices.unsafeMap.get(gu.key),this.currentSupervisor=this.getFiberRef(gH),this.currentScheduler=this.getFiberRef(um),this.currentContext=this.getFiberRef(ja),this.currentSpan=this.currentContext.unsafeMap.get(zf.key)}setFiberRefs(e){this._fiberRefs=e,this.refreshRefCache()}addChild(e){this.getChildren().add(e)}removeChild(e){this.getChildren().delete(e)}transferChildren(e){let t=this._children;if(this._children=null,t!==null&&t.size>0){for(let n of t)if(n._exitValue===null)e.add(this.currentRuntimeFlags,n)}}drainQueueOnCurrentThread(){let e=!0;while(e){let t=Tu,n=globalThis[Di];globalThis[Di]=this;try{while(t===Tu)t=this._queue.length===0?Qj:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Di]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===lA)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(sc),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=tH[r._tag](this,e,n,r)}return n}isInterrupted(){return!Lp(this.getFiberRef(uu))}addInterruptedCause(e){let t=this.getFiberRef(uu);this.setFiberRef(uu,Zt(t,e))}processNewInterruptSignal(e){this.addInterruptedCause(e),this.sendInterruptSignalToAllChildren()}sendInterruptSignalToAllChildren(){if(this._children===null||this._children.size===0)return!1;let e=!1;for(let t of this._children)t.tell(fm(xr(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return iu({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Do(r.value.await);else return Q(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(Sx(this.currentRuntimeFlags)){let t=this.getFiberRef(lu),n=this.id().startTimeMillis,r=Date.now();switch(Xj.unsafeUpdate(r-n,t),cA.unsafeUpdate(-1,t),e._tag){case mn:{Yj.unsafeUpdate(1,t);break}case fn:{Zj.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(hk);if(!Gs(e.cause)&&t._tag==="Some")this.log("Fiber terminated with an unhandled error",e.cause,t)}}setExitValue(e){this._exitValue=e,this.reportExitValue(e);for(let t=this._observers.length-1;t>=0;t--)this._observers[t](e);this._observers=[]}getLoggers(){return this.getFiberRef(cH)}log(e,t,n){let r=$e(n)?n.value:this.getFiberRef(Wx),o=this.getFiberRef(oH);if(tI(o,r))return;let i=this.getFiberRef(dk),a=this.getFiberRef(uk),s=this.getLoggers(),c=this.getFiberRefs();if(Fl(s)>0){let l=Ul(this.getFiberRef(yu),mu),u=new Date(l.unsafeCurrentTimeMillis());KR(c,()=>{for(let d of s)d.log({fiberId:this.id(),logLevel:r,message:e,cause:t,context:c,spans:i,annotations:a,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case DS:return lA;case NS:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Le(e.cause)),this._asyncInterruptor=null;return Tu}case LS:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),Tu;case FS:return e.onFiber(this,this._exitValue!==null?ZE:XE(this.currentRuntimeFlags,this._asyncBlockingOn)),Tu;default:return Rm(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=Fo(this.currentRuntimeFlags)&&this.isInterrupted()?Le(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===Uo){let o=$o.currentOp;if($o.currentOp=null,o._op===Ls)if(EO(this.currentRuntimeFlags))this.tell(PI()),this.tell(Wa(Gn)),t=null;else t=Gn;else if(o._op===xa)t=null}else{this.currentRuntimeFlags=b(this.currentRuntimeFlags,gx(cf));let o=this.interruptAllChildren();if(o!==null)t=oe(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(Wa(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Di];globalThis[Di]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Di]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(Wa(e))}startFork(e){this.tell(Wa(e))}patchRuntimeFlags(e,t){let n=Xl(e,t);return globalThis[Di]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(Wa(o))};if(Fo(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(Xt(An(o)))}}pushStack(e){if(this._stack.push(e),e._op==="OnStep")this._steps.push({refs:this.getFiberRefs(),flags:this.currentRuntimeFlags})}popStack(){let e=this._stack.pop();if(e){if(e._op==="OnStep")this._steps.pop();return e}return}getNextSuccessCont(){let e=this.popStack();while(e){if(e._op!==Rl)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==As&&e._op!==Ns&&e._op!==Fs)return e;e=this.popStack()}}[GR](e){return Q(()=>$l(this.currentContext,e))}["Left"](e){return Ft(e.left)}["None"](e){return Ft(new du)}["Right"](e){return ze(e.right)}["Some"](e){return ze(e.value)}["Micro"](e){return eu((t)=>{let n=t,r=yI(mI(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(ze(o.value));switch(o.cause._tag){case"Interrupt":return n(Le(xr(zn)));case"Fail":return n(Ft(o.cause.error));case"Die":return n(yf(o.cause.defect))}}),eu((o)=>{n=(i)=>{o(bt)},r.unsafeInterrupt()})})}[dp](e){let t=$t(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Cu))Rm(n);return Cu[n._op](this,n,t)}else return $o.currentOp=ze(t),Uo}[mn](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Cu))Rm(n);return Cu[n._op](this,n,t.effect_instruction_i0)}else return $o.currentOp=t,Uo}[fn](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case Rl:case Ms:if(!(Fo(this.currentRuntimeFlags)&&this.isInterrupted()))return $t(()=>n.effect_instruction_i1(t));else return Le(Up(t));case"OnStep":if(!(Fo(this.currentRuntimeFlags)&&this.isInterrupted()))return ze(Le(t));else return Le(Up(t));case Tl:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),Fo(this.currentRuntimeFlags)&&this.isInterrupted())return Le(Zt(t,this.getInterruptedCause()));else return Le(t);default:Rm(n)}else return $o.currentOp=Le(t),Uo}[pp](e){return $t(()=>e.effect_instruction_i0(this,xS(this.currentRuntimeFlags)))}["Blocked"](e){let t=this.getFiberRefs(),n=this.currentRuntimeFlags;if(this._steps.length>0){let r=[],o=this._steps[this._steps.length-1],i=this.popStack();while(i&&i._op!=="OnStep")r.push(i),i=this.popStack();this.setFiberRefs(o.refs),this.currentRuntimeFlags=o.flags;let a=qE(o.refs,t),s=Zl(o.flags,n);return ze(hf(e.effect_instruction_i0,jt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(UE(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=Xl(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return Pi((r)=>oe(ab(Ix(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return nH(e.effect_instruction_i0)}[ba](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=Xl(n,t);if(Fo(r)&&this.isInterrupted())return Le(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Zl(r,n);return this.pushStack(new Px(o,e)),$t(()=>e.effect_instruction_i1(n))}else return Gn}[As](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[Rl](e){return this.pushStack(e),e.effect_instruction_i0}[Ms](e){return this.pushStack(e),e.effect_instruction_i0}[xa](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),$o.currentOp=e,Uo}[Ls](e){return this._isYielding=!1,$o.currentOp=e,Uo}[Ns](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return Gn}[Fs](e){return Cu[Fs](this,e,void 0)}[Sa](e){return $t(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&kO)!==0)this.currentSupervisor.onEffect(this,t);if(this._queue.length>0)t=this.drainQueueWhileRunning(this.currentRuntimeFlags,t);if(!this._isYielding){this.currentOpCount+=1;let n=this.currentScheduler.shouldYield(this);if(n!==!1){this._isYielding=!0,this.currentOpCount=0;let r=t;t=oe(au({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(rH!==t[ki]._V){let n=this.getFiberRef(gk);if(n._tag==="Some"){let r=t[ki]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${Cl()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,Po,n)}}return this[t._op](t)},this),t===Uo){let n=$o.currentOp;if(n._op===Ls||n._op===xa)return Uo;return $o.currentOp=null,n._op===mn||n._op===fn?n:Le(An(n))}}catch(n){if(t!==Uo&&!H(t,"_op")||!(t._op in this))t=Fx(`Not a valid effect: ${So(t)}`);else if(yk(n))t=Le(Zt(An(n),xr(zn)));else t=yf(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};oH=re("effect/FiberRef/currentMinimumLogLevel",()=>Ht(nI("Info"))),aH=re(Symbol.for("effect/Logger/defaultLogger"),()=>iH(jI)),sH=re(Symbol.for("effect/Logger/tracerLogger"),()=>gm(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=MS(Ti(Fi(n,ja),zf));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=$l(Fi(n,yu),mu),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=QC(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=Sr(t,{renderErrorCause:!0});a.value.event(So(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),cH=re(Symbol.for("effect/FiberRef/currentLoggers"),()=>ck(Ta(aH,sH))),pA=h((e)=>Eg(e[0]),(e,t,n)=>jt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(mk);if(n?.discard)return IS(n.concurrency,()=>bc(Gf,n?.concurrentFinalizers)((i)=>o?Ja(e,(a,s)=>i(t(a,s)),!0,!1,1):Da(e,(a,s)=>i(t(a,s)))),()=>bc(Yf,n?.concurrentFinalizers)((i)=>Ja(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>bc(Zf(i),n?.concurrentFinalizers)((a)=>Ja(e,(s,c)=>a(t(s,c)),o,!1,i)));return IS(n?.concurrency,()=>bc(Gf,n?.concurrentFinalizers)((i)=>o?rb(e,1,(a,s)=>i(t(a,s)),!0):Jn(e,(a,s)=>i(t(a,s)))),()=>bc(Yf,n?.concurrentFinalizers)((i)=>fA(e,(a,s)=>i(t(a,s)),o)),(i)=>bc(Zf(i),n?.concurrentFinalizers)((a)=>rb(e,i,(s,c)=>a(t(s,c)),o)))})),Ou=yn("effect/Scope"),fH={[Cf]:Cf,[Of]:Of,pipe(){return F(this,arguments)},fork(e){return Q(()=>{let t=mH(e);if(this.state._tag==="Closed")return t.state=this.state,t;let n={},r=(o)=>t.close(o);return this.state.finalizers.set(n,r),pH(t,(o)=>Q(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return He(()=>{if(this.state._tag==="Closed")return bt;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return bt;return cS(this.strategy)?b(Jn(t,(n)=>Ii(n(e))),oe((n)=>b(Ba(n),dr(pu),Ue(()=>Gn)))):lS(this.strategy)?b(fA(t,(n)=>Ii(n(e)),!1),oe((n)=>b(Ba(n,{parallel:!0}),dr(pu),Ue(()=>Gn)))):b(rb(t,this.strategy.parallelism,(n)=>Ii(n(e)),!1),oe((n)=>b(Ba(n,{parallel:!0}),dr(pu),Ue(()=>Gn))))})},addFinalizer(e){return He(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),bt})}},sb=h(2,(e,t)=>Zx(e,jl(FC(Ou,t)))),dA=lk(IO),gH=hH(Ka),hA=h(2,(e,t)=>Pi((n)=>Kn(n(e),{onFailure:(r)=>Kn(t,{onFailure:(o)=>Xt(Zt(r,o)),onSuccess:()=>Xt(r)}),onSuccess:(r)=>Lo(t,r)})))});var yA,xA;var SA=w(()=>{wt();yA=zx,xA=cc});class vA{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return F(this,arguments)}}var ub=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},bA,wH,wA,_H=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new wA(e);return Error.stackTraceLimit=t,n},lb,Cm,_A,vH=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new _A(e);return Error.stackTraceLimit=t,n},RH=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return fu(t.left);case"Right":return ze(t.right);case"Some":return ze(t.value);case"None":return fu(new du)}},TH,CH=(e)=>new vA(e.context,e.runtimeFlags,e.fiberRefs),OH,RA,TA,CA;var OA=w(()=>{Wn();Re();Qs();yS();at();ft();Ne();dm();SA();Ys();wt();Jf();cb();qS();Ql();wm();bA=ub((e,t,n)=>{let r=Yp(),o=[[ja,[[r,e.context]]]];if(n?.scheduler)o.push([um,[[r,n.scheduler]]]);let i=CE(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new Tm(r,i,e.runtimeFlags),s=t;if(n?.scope)s=oe(xA(n.scope,pc),(l)=>Ai(kf(l,nu((u)=>j(u,a.id())?bt:cu(a,u))),ac(t,(u)=>yA(l,u))));let c=a.currentSupervisor;if(c!==Ka)c.onStart(e.context,s,B(),a),a.addObserver((l)=>c.onEnd(l,a));if(bu.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),wH=ub((e,t)=>{let n=TH(e)(t);if(n._tag==="Failure")throw vH(n.effect_instruction_i0);return n.effect_instruction_i0});wA=class wA extends Error{fiber;_tag="AsyncFiberException";constructor(e){super(`Fiber #${e.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`);this.fiber=e,this.name=this._tag,this.stack=this.message}};lb=Symbol.for("effect/Runtime/FiberFailure"),Cm=Symbol.for("effect/Runtime/FiberFailure/Cause");_A=class _A extends Error{[lb];[Cm];constructor(e){let t=Ll(e)[0];super(t?.message||"An error has occurred");if(this[lb]=lb,this[Cm]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[Cm].toJSON()}}toString(){return"(FiberFailure) "+Sr(this[Cm],{renderErrorCause:!0})}[me](){return this.toString()}};TH=ub((e,t)=>{let n=RH(t);if(n)return n;let r=new Su,o=bA(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return Jx(gf(_H(o),Mf(o)))});OH=xx(No,hx,mx),RA=CH({context:Ri(),runtimeFlags:OH,fiberRefs:OE()}),TA=bA(RA),CA=wH(RA)});var kA,ku,Eu,Nn,EA,Om,IA,Ga,wr,PA,AA;var MA=w(()=>{wt();cb();OA();kA=oc,ku=pA,Eu=He,Nn=bt,EA=tu,Om=ct,IA=qa,Ga=La,wr=oe,PA=TA,AA=CA});var db=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return db(e,t.from)}},Iu=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},pb=(e)=>Array.isArray(e),FA=(e)=>!Array.isArray(e),NA=(e)=>`[${vl(e)}]`,km=(e)=>pb(e)?e.map(NA).join(""):NA(e);var Pu=w(()=>{at()});var Ui=(e,t,n,r)=>{let o=e;if(n&&Fe(n))o+=`
31
+ at path: ${km(n)}`;if(t!==void 0)o+=`
32
32
  details: ${t}`;if(r)o+=`
33
- schema (${r._tag}): ${r}`;return o},IA=(e)=>Oi("Invalid Argument",e),PA=(e)=>Oi("Unsupported key schema",void 0,void 0,e),AA=(e)=>Oi("Unsupported literal",`literal value: ${Dr(e)}`),tb=(e)=>Oi("Duplicate index signature",`${e} index signature`),MA,NA,nb=(e)=>Oi("Duplicate property signature transformation",`Duplicate key ${Dr(e)}`),rb=(e)=>Oi("Duplicate property signature",`Duplicate key ${Dr(e)}`);var ob=b(()=>{at();it();Ru();MA=Oi("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),NA=Oi("Invalid element","A required element cannot follow an optional element. ts(1257)")});var LA,DA,qA,$A,UA,jA,HA;var BA=b(()=>{LA=Symbol.for("effect/SchemaId/DateFromSelf"),DA=Symbol.for("effect/SchemaId/GreaterThan"),qA=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),$A=Symbol.for("effect/SchemaId/Int"),UA=Symbol.for("effect/SchemaId/MinLength"),jA=Symbol.for("effect/SchemaId/MaxLength"),HA=Symbol.for("effect/SchemaId/MinItems")});class fc{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(e,t,n,r={}){this.typeParameters=e,this.decodeUnknown=t,this.encodeUnknown=n,this.annotations=r}toString(){return Le(Kr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:nt(this.annotations)}}}class qa{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Le(Kr(this),()=>Dr(this.literal))}toJSON(){return{_tag:this._tag,literal:Zo(this.literal)?String(this.literal):this.literal,annotations:nt(this.annotations)}}}class _m{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Le(Kr(this),()=>Dr(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:nt(this.annotations)}}}class nM{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class rM{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class oM{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class iM{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class aM{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class cM{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class uM{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class pM{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class mM{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class hM{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class yM{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return gr(this)}toJSON(){return{_tag:this._tag,annotations:nt(this.annotations)}}}class mc{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:nt(this.annotations)}}toString(){return String(this.type)}}class Ou{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(e,t,n,r={}){this.elements=e,this.rest=t,this.isReadonly=n,this.annotations=r;let o=!1,i=!1;for(let a of e)if(a.isOptional)o=!0;else if(o){i=!0;break}if(i||o&&t.length>1)throw Error(NA)}toString(){return Le(Kr(this),()=>IH(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:nt(this.annotations)}}}class hc{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,SM(e))this.parameter=e;else throw Error(MA)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class Jr{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(e,t,n={}){this.annotations=n;let r={};for(let i=0;i<e.length;i++){let a=e[i].name;if(Object.prototype.hasOwnProperty.call(r,a))throw Error(rb(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=Lb(t[i].parameter);if(Rm(a)){if(o.string)throw Error(tb("string"));o.string=!0}else if(gM(a)){if(o.symbol)throw Error(tb("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Le(Kr(this),()=>PH(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:nt(this.annotations)}}}class on{types;annotations;static make=(e,t)=>Tm(e)?new on(e,t):e.length===1?e[0]:vm;static unify=(e,t)=>on.make(NH(bM(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Le(Kr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:nt(this.annotations)}}}class Cm{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=vu(e)}toString(){return Kr(this).pipe(or(()=>ar(uT(this.f)(),(e)=>Kr(e))),Le(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=ib.get(e);if(t)return t;return ib.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:nt(this.annotations)},ib.set(e,t),t}}class Eu{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return Tu(this).pipe(Le(()=>dt(TM(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>ku(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:nt(this.annotations)}}}class Pb{from;to;transformation;annotations;_tag="Transformation";constructor(e,t,n,r={}){this.from=e,this.to=t,this.transformation=n,this.annotations=r}toString(){return Le(Kr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:nt(this.annotations)}}}class Ab{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class Mb{propertySignatureTransformations;_tag="TypeLiteralTransformation";constructor(e){this.propertySignatureTransformations=e;let t={},n={};for(let r of e){let o=r.from;if(t[o])throw Error(nb(o));t[o]=!0;let i=r.to;if(n[i])throw Error(nb(i));n[i]=!0}}}function Gn(e,t){let n=!1,r=la(e.length);for(let o=0;o<e.length;o++){let i=e[o],a=t(i);if(a!==i)n=!0;r[o]=a}return n?r:e}function $H(e){return dt(wb(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Dr(n)}>`).join("")})}var WA,sb,zA,cb,ym,xm,bn,Sm,Fo,lb,ub,db,pb,fb,mb,KA,hb,gb,yb,xb,Sb,bb,_b,Xt,wb,JA,GA,vb,Rb,Tu,Tb,YA,ZA,XA,QA,eM,Cb,vH,Ob=(e)=>fT(vH(e),(t)=>t===!0),Eb,RH,TH=(e)=>or(RH(e),()=>Tu(e)),Cu=(e)=>(t)=>t._tag===e,bm,tM,wm,CH,vm,kb,sM,lM,Rm,dM,fM,OH,EH,gM,kH,Ei,xM=(e)=>e.map((t)=>t.type),IH=(e)=>{let t=e.elements.map(String).join(", ");return gT(e.rest,{onEmpty:()=>`readonly [${t}]`,onNonEmpty:(n,r)=>{let o=String(n),i=o.includes(" | ")?`(${o})`:o;if(r.length>0){let a=r.map(String).join(", ");if(e.elements.length>0)return`readonly [${t}, ...${i}[], ${a}]`;else return`readonly [...${i}[], ${a}]`}else if(e.elements.length>0)return`readonly [${t}, ...${i}[]]`;else return`ReadonlyArray<${o}>`}})},Et,SM=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return SM(e.from)}return!1},VA=(e)=>e.map(String).join("; "),PH=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${VA(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${VA(e.indexSignatures)} }`;else return"{}"},AH,MH,bM=(e)=>vl(e,(t)=>Ib(t)?bM(t.types):[t]),NH=(e)=>{let t=AH(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[sM];case"UnknownKeyword":return[kb];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!r[i._tag])r[i._tag]=i,n.push(i);break}case"Literal":{let a=typeof i.literal;switch(a){case"string":case"number":case"bigint":case"boolean":{let s=MH[a];if(!r[s]&&!o.includes(i.literal))o.push(i.literal),n.push(i);break}case"object":{if(!o.includes(i.literal))o.push(i.literal),n.push(i);break}}break}case"UniqueSymbol":{if(!r.SymbolKeyword&&!o.includes(i.symbol))o.push(i.symbol),n.push(i);break}case"TupleType":{if(!r.ObjectKeyword)n.push(i);break}case"TypeLiteral":{if(i.propertySignatures.length===0&&i.indexSignatures.length===0){if(!r["{}"])r["{}"]=i,n.push(i)}else if(!r.ObjectKeyword)n.push(i);break}default:n.push(i)}return n},_M=(e,t)=>e.map(t),Tm=(e)=>e.length>1,Ib,ib,ku,Om,Iu=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[xm];let o={...r,...t},i=Cb(e);if(De(i))o[bb]=Iu(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},FH="[\\s\\S]*?",LH="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",wM=(e,t)=>{switch(e._tag){case"Literal":return rc(String(e.literal));case"StringKeyword":return FH;case"NumberKeyword":return LH;case"TemplateLiteral":return vM(e,t,!1);case"Union":return e.types.map((n)=>wM(n,t)).join("|")}},DH=(e,t,n,r)=>{if(Ib(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},vM=(e,t,n)=>{let r="";if(e.head!==""){let o=rc(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=wM(o.type,t);if(r+=DH(o.type,i,t,n),o.literal!==""){let a=rc(o.literal);r+=t&&n?`(${a})`:a}}return r},RM=(e)=>new RegExp(`^${vM(e,!1,!0)}$`),Nb=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new hc(i,t,!0));break;case"Literal":if($t(i.literal)||Cn(i.literal))n.push(new Et(i.literal,t,!1,!0));else throw Error(AA(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new Et(s,t,!1,!0));break}case"UniqueSymbol":n.push(new Et(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(PA(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},Fb=(e)=>(t)=>{let n=void 0;for(let r of e)if(Object.prototype.hasOwnProperty.call(t.annotations,r)){if(n===void 0)n={};n[r]=t.annotations[r]}return n},qH,vt=(e)=>{switch(e._tag){case"Declaration":{let t=Gn(e.typeParameters,vt);return t===e.typeParameters?e:new fc(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Gn(e.elements,(o)=>{let i=vt(o.type);return i===o.type?o:new Ei(i,o.isOptional)}),n=xM(e.rest),r=Gn(n,vt);return t===e.elements&&r===n?e:new Ou(t,r.map((o)=>new mc(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Gn(e.propertySignatures,(r)=>{let o=vt(r.type);return o===r.type?r:new Et(r.name,o,r.isOptional,r.isReadonly)}),n=Gn(e.indexSignatures,(r)=>{let o=vt(r.type);return o===r.type?r:new hc(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new Jr(t,n,e.annotations)}case"Union":{let t=Gn(e.types,vt);return t===e.types?e:on.make(t,e.annotations)}case"Suspend":return new Cm(()=>vt(e.f()),e.annotations);case"Refinement":{let t=vt(e.from);return t===e.from?e:new Eu(t,e.filter,e.annotations)}case"Transformation":{let t=qH(e);return vt(t!==void 0?Iu(e.to,t):e.to)}}return e},ab=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return ab(e.from);case"Suspend":return ab(e.f())}},zr=(e,t)=>{switch(e._tag){case"Declaration":{let n=Gn(e.typeParameters,(r)=>zr(r,t));return n===e.typeParameters?e:new fc(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=Gn(e.elements,(i)=>{let a=zr(i.type,t);return a===i.type?i:new Ei(a,i.isOptional)}),r=xM(e.rest),o=Gn(r,(i)=>zr(i,t));return n===e.elements&&o===r?e:new Ou(n,o.map((i)=>new mc(i)),e.isReadonly)}case"TypeLiteral":{let n=Gn(e.propertySignatures,(o)=>{let i=zr(o.type,t);return i===o.type?o:new Et(o.name,i,o.isOptional,o.isReadonly)}),r=Gn(e.indexSignatures,(o)=>{let i=zr(o.type,t);return i===o.type?o:new hc(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new Jr(n,r)}case"Union":{let n=Gn(e.types,(r)=>zr(r,t));return n===e.types?e:on.make(n)}case"Suspend":{let n=void 0,r=TH(e);if(De(r)){let o=t?"Bound":"";n={[Eb]:`${r.value}Encoded${o}`}}return new Cm(()=>zr(e.f(),t),n)}case"Refinement":{let n=zr(e.from,t);if(t){if(n===e.from)return e;if(ab(e.from)===void 0&&Ob(e))return new Eu(n,e.filter,e.annotations);return n}else return n}case"Transformation":return zr(e.from,t)}return e},Em=(e)=>zr(e,!1),nt=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},Lb=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return Lb(e.from)}},gr=(e)=>Le(Kr(e),()=>e._tag),TM=(e)=>vb(e).pipe(or(()=>Tb(e)),or(()=>Rb(e)),ir((t)=>t+$H(e))),Kr=(e)=>or(Tu(e),()=>TM(e));var Db=b(()=>{at();te();it();ob();Ru();cu();pt();op();ke();Wx();WA=Symbol.for("effect/annotation/TypeConstructor"),sb=Symbol.for("effect/annotation/Brand"),zA=Symbol.for("effect/annotation/SchemaId"),cb=Symbol.for("effect/annotation/Message"),ym=Symbol.for("effect/annotation/MissingMessage"),xm=Symbol.for("effect/annotation/Identifier"),bn=Symbol.for("effect/annotation/Title"),Sm=Symbol.for("effect/annotation/AutoTitle"),Fo=Symbol.for("effect/annotation/Description"),lb=Symbol.for("effect/annotation/Examples"),ub=Symbol.for("effect/annotation/Default"),db=Symbol.for("effect/annotation/JSONSchema"),pb=Symbol.for("effect/annotation/Arbitrary"),fb=Symbol.for("effect/annotation/Pretty"),mb=Symbol.for("effect/annotation/Equivalence"),KA=Symbol.for("effect/annotation/Documentation"),hb=Symbol.for("effect/annotation/Concurrency"),gb=Symbol.for("effect/annotation/Batching"),yb=Symbol.for("effect/annotation/ParseIssueTitle"),xb=Symbol.for("effect/annotation/ParseOptions"),Sb=Symbol.for("effect/annotation/DecodingFallback"),bb=Symbol.for("effect/annotation/Surrogate"),_b=Symbol.for("effect/annotation/StableFilter"),Xt=h(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?Y(e.annotations[t]):B()),wb=Xt(sb),JA=Xt(cb),GA=Xt(ym),vb=Xt(bn),Rb=Xt(Sm),Tu=Xt(xm),Tb=Xt(Fo),YA=Xt(hb),ZA=Xt(gb),XA=Xt(yb),QA=Xt(xb),eM=Xt(Sb),Cb=Xt(bb),vH=Xt(_b),Eb=Symbol.for("effect/annotation/JSONIdentifier"),RH=Xt(Eb);bm=Cu("Literal"),tM=new qa(null);wm=new nM({[bn]:"undefined"});CH=new rM({[bn]:"void"});vm=new oM({[bn]:"never"});kb=new iM({[bn]:"unknown"});sM=new aM({[bn]:"any"});lM=new cM({[bn]:"string",[Fo]:"a string"}),Rm=Cu("StringKeyword");dM=new uM({[bn]:"number",[Fo]:"a number"});fM=new pM({[bn]:"boolean",[Fo]:"a boolean"});OH=new mM({[bn]:"bigint",[Fo]:"a bigint"});EH=new hM({[bn]:"symbol",[Fo]:"a symbol"}),gM=Cu("SymbolKeyword");kH=new yM({[bn]:"object",[Fo]:"an object in the TypeScript meaning, i.e. the `object` type"});Ei=class Ei extends mc{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:nt(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};Et=class Et extends Ei{name;isReadonly;constructor(e,t,n,r,o){super(t,n,o);this.name=e,this.isReadonly=r}toString(){return(this.isReadonly?"readonly ":"")+String(this.name)+(this.isOptional?"?":"")+": "+this.type}toJSON(){return{name:String(this.name),type:this.type.toJSON(),isOptional:this.isOptional,isReadonly:this.isReadonly,annotations:nt(this.annotations)}}};AH=xo(rp(Wr,(e)=>{switch(e._tag){case"AnyKeyword":return 0;case"UnknownKeyword":return 1;case"ObjectKeyword":return 2;case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":return 3}return 4})),MH={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};Ib=Cu("Union"),ib=ne(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);ku=Cu("Refinement"),Om={};qH=Fb([lb,ub,db,pb,fb,mb])});class kt{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class Ub{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class gc{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class rt{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class Im{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Pm{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Yn{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class jb{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function yr(e){return e.sort(VH).map((t)=>t[1])}function YH(e){return Tb(e).pipe(or(()=>vb(e)),or(()=>Rb(e)),or(()=>Tu(e)),Le(()=>`{ ${e.from} | filter }`))}function ZH(e){if(e.message!==void 0)return e.message;return`Expected ${ku(e.ast)?YH(e.ast):String(e.ast)}, actual ${Dr(e.actual)}`}var OM,IM,Bb=(e)=>new IM({issue:e}),PM,AM,wn,Lo,xr,Am,MM,Vb=(e,t)=>{if(t===void 0||Cn(t))return e;if(e===void 0)return t;return{...e,...t}},NM=(e,t,n)=>{let r=Bt(e,t);return(o,i)=>r(o,Vb(n,i))},UH=(e,t,n)=>{let r=NM(e,t,n);return(o,i)=>Fg(r(o,i),Bb)},FM=(e,t)=>NM(e.ast,!0,t),Fu=(e,t)=>UH(vt(e.ast),!0,t),Mm=(e,t)=>{let n=Bt(vt(e.ast),!0);return(r,o)=>Tt(n(r,{exact:!0,...Vb(t,o)}))},jH,HH,Bt=(e,t)=>{let n=t?jH:HH,r=n.get(e);if(r)return r;let o=BH(e,t),i=QA(e),a=De(i)?(l,u)=>o(l,Vb(u,i.value)):o,s=eM(e),c=t&&De(s)?(l,u)=>Au(MM(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},qb=(e)=>xn(YA(e)),$b=(e)=>xn(ZA(e)),BH=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=Bt(e.from,!0);return(r,o)=>{o=o??Om;let i=o?.errors==="all",a=Lo(MM(n(r,o),(s)=>{let c=new Im(e,r,"From",s);if(i&&Ob(e)&&UM(s))return dt(e.filter(r,o,e),{onNone:()=>ae(c),onSome:(l)=>ae(new rt(e,r,[c,new Im(e,r,"Predicate",l)]))});return ae(c)}),(s)=>dt(e.filter(s,o,e),{onNone:()=>ue(s),onSome:(c)=>ae(new Im(e,r,"Predicate",c))}));return Au(a,e,r,o)}}else{let n=Bt(vt(e),!0),r=Bt(DM(e.from),!1);return(o,i)=>Au(Lo(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=WH(e.transformation,t),r=t?Bt(e.from,!0):Bt(e.to,!1),o=t?Bt(e.to,!0):Bt(e.from,!1);return(i,a)=>Au(Lo(Am(r(i,a),(s)=>new Pm(e,i,t?"Encoded":"Type",s)),(s)=>Lo(Am(n(s,a??Om,e,i),(c)=>new Pm(e,i,"Transformation",c)),(c)=>Am(o(c,a),(l)=>new Pm(e,i,t?"Type":"Encoded",l)))),e,i,a)}case"Declaration":{let n=t?e.decodeUnknown(...e.typeParameters):e.encodeUnknown(...e.typeParameters);return(r,o)=>Au(n(r,o??Om,e),e,r,o)}case"Literal":return _n(e,(n)=>n===e.literal);case"UniqueSymbol":return _n(e,(n)=>n===e.symbol);case"UndefinedKeyword":return _n(e,NR);case"NeverKeyword":return _n(e,FR);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return ue;case"StringKeyword":return _n(e,$t);case"NumberKeyword":return _n(e,Cn);case"BooleanKeyword":return _n(e,ea);case"BigIntKeyword":return _n(e,Zo);case"SymbolKeyword":return _n(e,ta);case"ObjectKeyword":return _n(e,rn);case"Enums":return _n(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>Rm(r.type)))return _n(e,(r)=>{if(!$t(r)||!r.startsWith(e.head))return!1;let o=e.head.length;for(let a=0;a<e.spans.length-1;a++){let s=e.spans[a].literal,c=r.indexOf(s,o);if(c===-1)return!1;o=c+s.length}let i=e.spans[e.spans.length-1].literal;return r.endsWith(i)&&r.length-i.length>=o});let n=RM(e);return _n(e,(r)=>$t(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>Bt(l.type,t)),r=e.rest.map((l)=>Bt(l.type,t)),o=e.elements.filter((l)=>!l.isOptional);if(e.rest.length>0)o=o.concat(e.rest.slice(1));let i=o.length,a=e.elements.length>0?e.elements.map((l,u)=>u).join(" | "):"never",s=qb(e),c=$b(e);return(l,u)=>{if(!Hg(l))return ae(new Yn(e,l));let d=u?.errors==="all",p=[],f=0,m=[],y=l.length;for(let _=y;_<=i-1;_++){let I=new kt(_,l,new gc(o[_-y]));if(d){p.push([f++,I]);continue}else return ae(new rt(e,l,I,m))}if(e.rest.length===0)for(let _=e.elements.length;_<=y-1;_++){let I=new kt(_,l,new Ub(l[_],`is unexpected, expected: ${a}`));if(d){p.push([f++,I]);continue}else return ae(new rt(e,l,I,m))}let g=0,x=void 0;for(;g<n.length;g++)if(y<g+1){if(e.elements[g].isOptional)continue}else{let _=n[g],I=_(l[g],u);if(wn(I)){if(Fe(I)){let q=new kt(g,l,I.left);if(d){p.push([f++,q]);continue}else return ae(new rt(e,l,q,yr(m)))}m.push([f++,I.right])}else{let q=f++,O=g;if(!x)x=[];x.push(({es:C,output:N})=>hr(Da(I),(w)=>{if(Fe(w)){let A=new kt(O,l,w.left);if(d)return C.push([q,A]),An;else return ae(new rt(e,l,A,yr(N)))}return N.push([q,w.right]),An}))}}if(Me(r)){let[_,...I]=r;for(;g<y-I.length;g++){let q=_(l[g],u);if(wn(q))if(Fe(q)){let O=new kt(g,l,q.left);if(d){p.push([f++,O]);continue}else return ae(new rt(e,l,O,yr(m)))}else m.push([f++,q.right]);else{let O=f++,C=g;if(!x)x=[];x.push(({es:N,output:w})=>hr(Da(q),(A)=>{if(Fe(A)){let E=new kt(C,l,A.left);if(d)return N.push([O,E]),An;else return ae(new rt(e,l,E,yr(w)))}else return w.push([O,A.right]),An}))}}for(let q=0;q<I.length;q++){let O=g+q;if(y<O+1)continue;else{let C=I[q](l[O],u);if(wn(C)){if(Fe(C)){let N=new kt(O,l,C.left);if(d){p.push([f++,N]);continue}else return ae(new rt(e,l,N,yr(m)))}m.push([f++,C.right])}else{let N=f++;if(!x)x=[];x.push(({es:w,output:A})=>hr(Da(C),(E)=>{if(Fe(E)){let le=new kt(O,l,E.left);if(d)return w.push([N,le]),An;else return ae(new rt(e,l,le,yr(A)))}return A.push([N,E.right]),An}))}}}}let P=({es:_,output:I})=>ni(_)?ae(new rt(e,l,yr(_),yr(I))):ue(yr(I));if(x&&x.length>0){let _=x;return wu(()=>{let I={es:Is(p),output:Is(m)};return hr(_u(_,(q)=>q(I),{concurrency:s,batching:c,discard:!0}),()=>P(I))})}return P({output:m,es:p})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return _n(e,LR);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([Bt(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Bt(u.parameter,t),Bt(u.type,t),u.parameter]),a=on.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>ta(u)?new _m(u):new qa(u)))),s=Bt(a,t),c=qb(e),l=$b(e);return(u,d)=>{if(!xg(u))return ae(new Yn(e,u));let p=d?.errors==="all",f=[],m=0,y=d?.onExcessProperty==="error",g=d?.onExcessProperty==="preserve",x={},P;if(y||g){P=Reflect.ownKeys(u);for(let O of P){let C=s(O,d);if(wn(C)&&Fe(C))if(y){let N=new kt(O,u,new Ub(u[O],`is unexpected, expected: ${String(a)}`));if(p){f.push([m++,N]);continue}else return ae(new rt(e,u,N,x))}else x[O]=u[O]}}let _=void 0,I=d?.exact===!0;for(let O=0;O<n.length;O++){let C=n[O][1],N=C.name,w=Object.prototype.hasOwnProperty.call(u,N);if(!w){if(C.isOptional)continue;else if(I){let le=new kt(N,u,new gc(C));if(p){f.push([m++,le]);continue}else return ae(new rt(e,u,le,x))}}let A=n[O][0],E=A(u[N],d);if(wn(E)){if(Fe(E)){let le=new kt(N,u,w?E.left:new gc(C));if(p){f.push([m++,le]);continue}else return ae(new rt(e,u,le,x))}x[N]=E.right}else{let le=m++,He=N;if(!_)_=[];_.push(({es:Be,output:gt})=>hr(Da(E),(ot)=>{if(Fe(ot)){let Qe=new kt(He,u,w?ot.left:new gc(C));if(p)return Be.push([le,Qe]),An;else return ae(new rt(e,u,Qe,gt))}return gt[He]=ot.right,An}))}}for(let O=0;O<i.length;O++){let C=i[O],N=C[0],w=C[1],A=QS(u,C[2]);for(let E of A){let le=N(E,d);if(wn(le)&&Tt(le)){let He=w(u[E],d);if(wn(He)){if(Fe(He)){let Be=new kt(E,u,He.left);if(p){f.push([m++,Be]);continue}else return ae(new rt(e,u,Be,x))}else if(!Object.prototype.hasOwnProperty.call(r,E))x[E]=He.right}else{let Be=m++,gt=E;if(!_)_=[];_.push(({es:ot,output:Qe})=>hr(Da(He),(fn)=>{if(Fe(fn)){let tr=new kt(gt,u,fn.left);if(p)return ot.push([Be,tr]),An;else return ae(new rt(e,u,tr,Qe))}else{if(!Object.prototype.hasOwnProperty.call(r,E))Qe[E]=fn.right;return An}}))}}}}let q=({es:O,output:C})=>{if(ni(O))return ae(new rt(e,u,yr(O),C));if(d?.propertyOrder==="original"){let N=P||Reflect.ownKeys(u);for(let A of o)if(N.indexOf(A)===-1)N.push(A);let w={};for(let A of N)if(Object.prototype.hasOwnProperty.call(C,A))w[A]=C[A];return ue(w)}return ue(C)};if(_&&_.length>0){let O=_;return wu(()=>{let C={es:Is(f),output:Object.assign({},x)};return hr(_u(O,(N)=>N(C),{concurrency:c,batching:l,discard:!0}),()=>q(C))})}return q({es:f,output:x})}}case"Union":{let n=LM(e.types,t),r=Reflect.ownKeys(n.keys),o=r.length,i=e.types.length,a=new Map;for(let l=0;l<i;l++)a.set(e.types[l],Bt(e.types[l],t));let s=qb(e)??1,c=$b(e);return(l,u)=>{let d=[],p=0,f=[];if(o>0)if(dl(l))for(let g=0;g<o;g++){let x=r[g],P=n.keys[x].buckets;if(Object.prototype.hasOwnProperty.call(l,x)){let _=String(l[x]);if(Object.prototype.hasOwnProperty.call(P,_))f=f.concat(P[_]);else{let{candidates:I,literals:q}=n.keys[x],O=on.make(q),C=I.length===i?new Jr([new Et(x,O,!1,!0)],[]):on.make(I);d.push([p++,new rt(C,l,new kt(x,l,new Yn(O,l[x])))])}}else{let{candidates:_,literals:I}=n.keys[x],q=new Et(x,on.make(I),!1,!0),O=_.length===i?new Jr([q],[]):on.make(_);d.push([p++,new rt(O,l,new kt(x,l,new gc(q)))])}}else{let g=n.candidates.length===i?e:on.make(n.candidates);d.push([p++,new Yn(g,l)])}if(n.otherwise.length>0)f=f.concat(n.otherwise);let m=void 0;for(let g=0;g<f.length;g++){let x=f[g],P=a.get(x)(l,u);if(wn(P)&&(!m||m.length===0))if(Tt(P))return P;else d.push([p++,P.left]);else{let _=p++;if(!m)m=[];m.push((I)=>wu(()=>{if("finalResult"in I)return An;else return hr(Da(P),(q)=>{if(Tt(q))I.finalResult=q;else I.es.push([_,q.left]);return An})}))}}let y=(g)=>ni(g)?g.length===1&&g[0][1]._tag==="Type"?ae(g[0][1]):ae(new rt(e,l,yr(g))):ae(new Yn(e,l));if(m&&m.length>0){let g=m;return wu(()=>{let x={es:Is(d)};return hr(_u(g,(P)=>P(x),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in x)return x.finalResult;return y(x.es)})})}return y(d)}}case"Suspend":{let n=vu(()=>Bt(e.f(),t));return(r,o)=>n()(r,o)}}},_n=(e,t)=>(n)=>t(n)?ue(n):ae(new Yn(e,n)),Pu=(e,t)=>{switch(e._tag){case"Declaration":{let n=Cb(e);if(De(n))return Pu(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?Em(o.type):vt(o.type);if(bm(i)&&!o.isOptional)n.push([o.name,i])}return n}case"TupleType":{let n=[];for(let r=0;r<e.elements.length;r++){let o=e.elements[r],i=t?Em(o.type):vt(o.type);if(bm(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return Pu(e.from,t);case"Suspend":return Pu(e.f(),t);case"Transformation":return Pu(t?e.from:e.to,t)}return[]},LM=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=Pu(a,t);if(s.length>0){o.push(a);for(let c=0;c<s.length;c++){let[l,u]=s[c],d=String(u.literal);n[l]=n[l]||{buckets:{},literals:[],candidates:[]};let p=n[l].buckets;if(Object.prototype.hasOwnProperty.call(p,d)){if(c<s.length-1)continue;p[d].push(a),n[l].literals.push(u),n[l].candidates.push(a)}else{p[d]=[a],n[l].literals.push(u),n[l].candidates.push(a);break}}}else r.push(a)}return{keys:n,otherwise:r,candidates:o}},DM=(e)=>ku(e)?DM(e.from):e,Au=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(wn(e))return e;let o=new pu,i=TA(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(vI(a))return ue(a.value);let s=a.cause;if(hE(s))return ae(s.error);return ae(new jb(t,n,gE(s)))}return ae(new jb(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},VH=([e],[t])=>e>t?1:e<t?-1:0,WH=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return ue;case"TypeLiteralTransformation":return(n)=>{let r=ue(n);for(let o of e.propertySignatureTransformations){let[i,a]=t?[o.from,o.to]:[o.to,o.from],s=t?o.decode:o.encode;r=xr(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?Y(l[i]):B());if(delete l[i],De(u))l[a]=u.value;return l})}return r}}},an=(e,t=[])=>({value:e,forest:t}),Mu,zH=(e)=>e.value+qM(`
34
- `,e.forest),qM=(e,t)=>{let n="",r=t.length,o;for(let i=0;i<r;i++){o=t[i];let a=i===r-1;n+=e+(a?"\u2514":"\u251C")+"\u2500 "+o.value,n+=qM(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},KH=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},JH=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},$M=(e)=>("ast"in e)?Y(e.ast):B(),Hb,GH=(e)=>$M(e).pipe(ar(JA),dt({onNone:()=>Hb,onSome:(t)=>{let n=t(e);if($t(n))return ue({message:n,override:!1});if(wA(n))return mm(n,(r)=>({message:r,override:!1}));if($t(n.message))return ue({message:n.message,override:n.override});return mm(n.message,(r)=>({message:r,override:n.override}))}})),Wb=(e)=>(t)=>t._tag===e,UM,EM,kM,Nu=(e)=>Lo(GH(e),(t)=>{if(t!==void 0)return!t.override&&(UM(e)||EM(e)&&e.kind==="From"||kM(e)&&e.kind!=="Transformation")?kM(e)||EM(e)?Nu(e.issue):Hb:ue(t.message);return Hb}),jM=(e)=>$M(e).pipe(ar(XA),dT((t)=>t(e)),xn),XH=(e)=>xr(Nu(e),(t)=>t??jM(e)??ZH(e)),km=(e)=>jM(e)??String(e.ast),QH=(e)=>e.message??"is forbidden",e1=(e)=>e.message??"is unexpected",t1=(e)=>{let t=GA(e.ast);if(De(t)){let n=t.value();return $t(n)?ue(n):n}return ue(e.message??"is missing")},yc=(e)=>{switch(e._tag){case"Type":return xr(XH(e),an);case"Forbidden":return ue(an(km(e),[an(QH(e))]));case"Unexpected":return ue(an(e1(e)));case"Missing":return xr(t1(e),an);case"Transformation":return Lo(Nu(e),(t)=>{if(t!==void 0)return ue(an(t));return xr(yc(e.issue),(n)=>an(km(e),[an(KH(e.kind),[n])]))});case"Refinement":return Lo(Nu(e),(t)=>{if(t!==void 0)return ue(an(t));return xr(yc(e.issue),(n)=>an(km(e),[an(JH(e.kind),[n])]))});case"Pointer":return xr(yc(e.issue),(t)=>an(hm(e.path),[t]));case"Composite":return Lo(Nu(e),(t)=>{if(t!==void 0)return ue(an(t));let n=km(e);return eb(e.issues)?xr(_u(e.issues,yc),(r)=>an(n,r)):xr(yc(e.issues),(r)=>an(n,[r]))})}};var zb=b(()=>{at();yE();sk();OA();yn();RI();te();it();Ru();pt();ke();Xf();Db();OM=Symbol.for("effect/Schema/ParseErrorTypeId");IM=class IM extends ak("ParseError"){[OM]=OM;get message(){return this.toString()}toString(){return Mu.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[pe](){return this.toJSON()}};PM=ue,AM=ae,wn=Ng,Lo=h(2,(e,t)=>wn(e)?wl(e,{onLeft:ae,onRight:t}):hr(e,t)),xr=h(2,(e,t)=>wn(e)?oT(e,t):mm(e,t)),Am=h(2,(e,t)=>wn(e)?np(e,t):RA(e,t)),MM=h(2,(e,t)=>wn(e)?wl(e,{onLeft:t,onRight:ue}):vA(e,t)),jH=ne(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),HH=ne(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);Mu={formatIssue:(e)=>xr(yc(e),zH),formatIssueSync:(e)=>{let t=Mu.formatIssue(e);return wn(t)?aT(t):CA(t)},formatError:(e)=>Mu.formatIssue(e.issue),formatErrorSync:(e)=>Mu.formatIssueSync(e.issue)},Hb=ue(void 0),UM=Wb("Composite"),EM=Wb("Refinement"),kM=Wb("Transformation")});var HM,BM;var VM=b(()=>{te();ke();HM=h((e)=>rn(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),BM=h((e)=>rn(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function Vt(e){return class{[Lu]=WM;static ast=e;static annotations(n){return Vt(Gr(this.ast,n))}static pipe(){return L(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Lu]=WM}}function o1(e){return Tm(e)?on.make(_M(e,(t)=>new qa(t))):new qa(e[0])}function XM(e,t=o1(e)){return class extends Vt(t){static annotations(r){return XM(this.literals,Gr(this.ast,r))}static literals=[...e]}}function k(...e){return Me(e)?XM(e):Gb}function Jb(e,t){return class extends Vt(t){static annotations(r){return Jb(this.typeParameters,Gr(this.ast,r))}static typeParameters=[...e]}}function eN(e,t=s1(e)){return class extends Vt(t){static annotations(r){return eN(this.members,Gr(this.ast,r))}static members=[...e]}}function xe(...e){return Tm(e)?eN(e):Me(e)?e[0]:Gb}function Nm(e,t,n=l1(e,t)){return class extends Vt(n){static annotations(o){return Nm(this.elements,this.rest,Gr(this.ast,o))}static elements=[...e];static rest=[...t]}}function tN(...e){return Array.isArray(e[0])?Nm(e[0],e.slice(1)):Nm(e,[])}function nN(e,t){return class extends Nm([],[e],t){static annotations(r){return nN(this.value,Gr(this.ast,r))}static value=e}}class oN{from;to;decode;encode;_tag="PropertySignatureTransformation";constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}toString(){return`PropertySignature<${Kb(this.to.isOptional)}, ${this.to.type}, ${u1(this.from.fromKey)}, ${Kb(this.from.isOptional)}, ${this.from.type}>`}}function e_(e,t,n=p1(e,t)){return class extends Vt(n){static annotations(o){return e_(this.fields,this.records,Gr(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=f1(e,{...o});return o_(i)?a:Fu(this)(a)};static pick(...o){return R(HM(e,...o))}static omit(...o){return R(BM(e,...o))}}}function R(e,...t){return e_(e,t)}function cN(e,t,n){return class extends e_({},[{key:e,value:t}],n){static annotations(o){return cN(e,t,Gr(this.ast,o))}static key=e;static value=t}}function lN(e,t){return class extends Vt(t){static annotations(r){return lN(this.from,Gr(this.ast,r))}static make=(r,o)=>o_(o)?r:Fu(this)(r);static from=e}}function uN(e,t,n){return class extends Vt(n){static annotations(o){return uN(this.from,this.filter,Gr(this.ast,o))}static[m1]=e;static from=e;static filter=t;static make=(o,i)=>o_(i)?o:Fu(this)(o)}}function Ge(e,t){return(n)=>{function r(i,a,s){return h1(e(i,a,s),s,i)}let o=new Eu(n.ast,r,$a(t));return uN(n,r,o)}}function o_(e){return ea(e)?e:e?.disableValidation??!1}var Lu,WM,zM,$a=(e)=>{if(!e)return{};let t={...e};for(let n in zM)if(n in e){let r=zM[n];t[r]=e[n],delete t[n]}return t},Gr=(e,t)=>Iu(e,$a(t)),Du=(e,t)=>{let n=FM(e,t);return(r,o)=>np(n(r,o),Bb)},KM=(e)=>H(e,Lu)&&rn(e[Lu]),i1=(e,t,n)=>Jb(e,new fc(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(Vt)),(...r)=>t.encode(...r.map(Vt)),$a(n))),a1=(e,t)=>{let n=()=>(o,i,a)=>e(o)?PM(o):AM(new Yn(a,o));return Jb([],new fc([],n,n,$a(t)))},Q=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return i1(n,r,o)}let e=arguments[0],t=arguments[1];return a1(e,t)},QM,It,Gb,Yb,D,vn,V,s1=(e)=>on.make(e.map((t)=>t.ast)),c1=(e)=>xe(e,QM),l1=(e,t)=>new Ou(e.map((n)=>KM(n)?new Ei(n.ast,!1):n.ast),t.map((n)=>KM(n)?new mc(n.ast):n.ast),!0),K=(e)=>nN(e),Kb=(e)=>e?'"?:"':'":"',Zb,rN,u1=(e)=>{if(e===void 0)return"never";if($t(e))return JSON.stringify(e);return String(e)},iN=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new Zb(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new oN(e.from,new rN(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},aN,sN=(e)=>H(e,aN),Xb,Qb,v=(e)=>{let t=e.ast===wm||e.ast===vm?wm:c1(e).ast;return new Qb(new Zb(t,!0,!0,{},void 0),e)},d1,p1=(e,t)=>{let n=Reflect.ownKeys(e),r=[];if(n.length>0){let i=[],a=[],s=[];for(let c=0;c<n.length;c++){let l=n[c],u=e[l];if(sN(u)){let d=u.ast;switch(d._tag){case"PropertySignatureDeclaration":{let{type:p,isOptional:f,annotations:m}=d;i.push(new Et(l,p,f,!0,d1(d))),a.push(new Et(l,vt(p),f,!0,m)),r.push(new Et(l,p,f,!0,m));break}case"PropertySignatureTransformation":{let p=d.from.fromKey??l;i.push(new Et(p,d.from.type,d.from.isOptional,!0,d.from.annotations)),a.push(new Et(l,d.to.type,d.to.isOptional,!0,d.to.annotations)),s.push(new Ab(p,l,d.decode,d.encode));break}}}else i.push(new Et(l,u.ast,!1,!0)),a.push(new Et(l,vt(u.ast),!1,!0)),r.push(new Et(l,u.ast,!1,!0))}if(Me(s)){let c=[],l=[];for(let u of t){let{indexSignatures:d,propertySignatures:p}=Nb(u.key.ast,u.value.ast);p.forEach((f)=>{i.push(f),a.push(new Et(f.name,vt(f.type),f.isOptional,f.isReadonly,f.annotations))}),d.forEach((f)=>{c.push(f),l.push(new hc(f.parameter,vt(f.type),f.isReadonly))})}return new Pb(new Jr(i,c,{[Sm]:"Struct (Encoded side)"}),new Jr(a,l,{[Sm]:"Struct (Type side)"}),new Mb(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=Nb(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new Jr(r,o)},f1=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&sN(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},Fm=(e)=>cN(e.key,e.value),qu=(e,t)=>(n)=>{let r=dt(wb(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=Iu(n.ast,$a({[sb]:r,...t}));return lN(n,o)},m1,JM=(e,t,n)=>{if(ea(e))return e?B():Y(new Yn(t,n));if($t(e))return Y(new Yn(t,n,e));if(e!==void 0){if("_tag"in e)return Y(e);let r=new Yn(t,n,e.message);return Y(Me(e.path)?new kt(e.path,n,r):r)}return B()},h1=(e,t,n)=>{if(kA(e))return JM(e,t,n);if(Me(e)){let r=ap(e,(o)=>JM(o,t,n));if(Me(r))return Y(r.length===1?r[0]:new rt(t,n,r))}return B()},g1,t_=(e,t)=>(n)=>n.pipe(Ge((r)=>r.length<=e,{schemaId:g1,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),y1,xc=(e,t)=>(n)=>n.pipe(Ge((r)=>r.length>=e,{schemaId:y1,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),GM,be=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ge((o)=>(e.lastIndex=0,e.test(o)),{schemaId:GM,[GM]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},x1,YM,S1,b1,n_=(e,t)=>(n)=>n.pipe(Ge((r)=>r>e,{schemaId:b1,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),_1,dN=(e,t)=>(n)=>n.pipe(Ge((r)=>r>=e,{schemaId:_1,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),w1,Lm=(e)=>(t)=>t.pipe(Ge((n)=>Number.isSafeInteger(n),{schemaId:w1,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),r_=(e)=>n_(0,{title:"positive",...e}),Dm,v1,Yr=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(IA(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ge((o)=>o.length>=r,{schemaId:v1,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[_b]:!0,...t}))},ZM,R1;var Dt=b(()=>{at();yn();ll();ob();BA();Ru();pt();zb();Ae();ke();Db();VM();zb();Lu=Symbol.for("effect/Schema");WM={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},zM={typeConstructor:WA,schemaId:zA,message:cb,missingMessage:ym,identifier:xm,title:bn,description:Fo,examples:lb,default:ub,documentation:KA,jsonSchema:db,arbitrary:pb,pretty:fb,equivalence:mb,concurrency:hb,batching:gb,parseIssueTitle:yb,parseOptions:xb,decodingFallback:Sb};QM=class QM extends Vt(wm){};It=class It extends Vt(tM){};Gb=class Gb extends Vt(vm){};Yb=class Yb extends Vt(kb){};D=class D extends Vt(lM){};vn=class vn extends Vt(dM){};V=class V extends Vt(fM){};Zb=class Zb extends Ei{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=Kb(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};rN=class rN extends Ei{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};aN=Symbol.for("effect/PropertySignature");Xb=class Xb{ast;[Lu];[aN]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return L(this,arguments)}annotations(e){return new Xb(iN(this.ast,$a(e)))}toString(){return String(this.ast)}};Qb=class Qb extends Xb{from;constructor(e,t){super(e);this.from=t}annotations(e){return new Qb(iN(this.ast,$a(e)),this.from)}};d1=Fb([ym]);m1=Symbol.for("effect/SchemaId/Refine");g1=jA,y1=UA,GM=Symbol.for("effect/SchemaId/Pattern"),x1=Symbol.for("effect/SchemaId/UUID"),YM=/^[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}$/i;S1=class S1 extends D.pipe(be(YM,{schemaId:x1,identifier:"UUID",jsonSchema:{format:"uuid",pattern:YM.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};b1=DA,_1=qA,w1=$A;Dm=class Dm extends vn.pipe(Lm({identifier:"Int"})){};v1=HA,ZM=LA;R1=class R1 extends Q(zd,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:ZM,[ZM]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>AR}){}});function Zn(e,t){return Du(e,T1)(t)}var T1;var Sc=b(()=>{Dt();T1={onExcessProperty:"error"}});function gN(e){let t=Du(bc)(e);return Tt(t)?t.right:void 0}function i_(e){return gN(e)!==void 0}function yN(e){return i_(e)&&!e.includes("-")}function pN(e){if(e===void 0||e.length===0||e[0]==="0")return!1;for(let t of e)if(t<"0"||t>"9")return!1;return!0}function C1(e){let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!yN(t))return!1;let[o,i,a,s]=n.split(".");return o==="dev"&&s===void 0&&pN(i)&&pN(a)}function qm(e){let t=gN(e);if(t===void 0)throw Error(`The canonical version ${e} is invalid.`);let n=t.split("-",1)[0];if(n===void 0)throw Error(`The canonical version ${e} has no base version.`);return n}function Uu(e,t){let n=fN(e),r=fN(t),o=$u(n.minor,r.minor);if(o!==0)return o;let i=$u(n.patch,r.patch);if(i!==0)return i;return O1(n.suffix,r.suffix)}function s_(e,t){let n=qm(t);if(e!=="patch"&&e!=="minor"){if(!i_(e))throw Error("The version target is invalid.");return e}let[,r,o]=n.split(".");if(r===void 0||o===void 0)throw Error(`The canonical version ${t} has an invalid base version.`);let i=BigInt(r),a=BigInt(o);return e==="minor"?`0.${i+1n}.0`:`0.${i}.${a+1n}`}function fN(e){let[t,n]=e.split("-",2),r=t?.split("."),o=r?.[1],i=r?.[2];if(o===void 0||i===void 0)throw Error(`The release version ${e} has an invalid base version.`);if(n===void 0)return{minor:o,patch:i,suffix:{kind:"base"}};if(n.startsWith("dev.")){let[,a,s]=n.split(".");if(a===void 0||s===void 0)throw Error(`The development version ${e} has an invalid release suffix.`);return{minor:o,patch:i,suffix:{kind:"development",runNumber:a,runAttempt:s}}}return{minor:o,patch:i,suffix:{kind:"numeric",value:n}}}function $u(e,t){let n=BigInt(e),r=BigInt(t);if(n<r)return-1;if(n>r)return 1;return 0}function O1(e,t){let n=mN(e),r=mN(t);if(n<r)return-1;if(n>r)return 1;if(e.kind==="numeric"&&t.kind==="numeric")return $u(e.value,t.value);if(e.kind==="development"&&t.kind==="development"){let o=$u(e.runNumber,t.runNumber);return o===0?$u(e.runAttempt,t.runAttempt):o}return 0}function mN(e){if(e.kind==="development")return 0;if(e.kind==="base")return 1;return 2}var hN,bc,a_,xN,_c;var SN=b(()=>{yn();Dt();hN=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,bc=D.pipe(be(hN));a_=D.pipe(Ge(yN));xN=D.pipe(Ge(C1)),_c=xe(bc,xN)});function u_(e,t){if(typeof t!=="string")return;let n=e.lastIndexOf("@");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(r==="sites"&&o==="openai-curated-remote"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:"sites@openai-bundled"};if(l_.includes(r)&&o==="openai-bundled"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:e};if(!wN(r)||!_N(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function Sr(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(n==="sites"&&r==="openai-curated-remote")return"sites@openai-bundled";if(wN(n)&&_N(r))return`${n}@openai-curated`;if(l_.includes(n)&&r==="openai-bundled")return`${n}@openai-bundled`;return}function d_(e){let t=Sr(e);if(t===void 0)return[];if(t==="sites@openai-bundled")return Object.freeze([t,"sites@openai-curated-remote"]);if(t.endsWith("@openai-bundled"))return Object.freeze([t]);let n=t.slice(0,t.lastIndexOf("@"));return Object.freeze([t,`${n}@openai-curated-remote`])}function _N(e){return bN.includes(e)}function wN(e){return $m.includes(e)}function p_(e,t){let n=t??Qt;return{browser_use:e?.browser_use??n.browser_use,computer_use:e?.computer_use??n.computer_use,sites:e?.sites??n.sites}}function wc(e,t=[]){let n=[...RN],r=new Set(n);for(let o of vN){if(!e[o])continue;for(let i of Do[o].pluginIds)if(!r.has(i))r.add(i),n.push(i)}for(let o of t){if(o==="browser@openai-bundled")continue;if(!r.has(o))r.add(o),n.push(o)}return n}var ju,c_,E1,k1,bN,$m,l_,Pt,ki,I1,P1,Do,vN,A1,RN,M1,Qt;var f_=b(()=>{Dt();ju=k("browser_use","computer_use","frontend","security","sites"),c_=k("browser_use","computer_use","sites"),E1=k("installed","disabled","missing","uncertain"),k1=k("healthy","missing","disabled","uncertain"),bN=Object.freeze(["openai-curated","openai-curated-remote"]),$m=Object.freeze(["build-web-apps","codex-security"]),l_=Object.freeze(["browser","computer-use","sites"]);Pt=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),ki=Object.freeze({frontend:Object.freeze([{skillId:"build-web-apps:frontend-app-builder",appliesWhen:"a new visually-driven UI or meaningful redesign"},{skillId:"build-web-apps:frontend-testing-debugging",appliesWhen:"a rendered UI or interaction defect"},{skillId:"build-web-apps:react-best-practices",appliesWhen:"a relevant React or Next implementation or review"}]),security:Object.freeze([]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([])}),I1=ki.frontend,P1={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Pt.frontend,semanticSkillIds:Object.freeze(ki.frontend.map(({skillId:e})=>e)),applicability:ki.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Pt.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:ki.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Pt.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:ki.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:Pt.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:ki.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:Pt.sites,migrationKey:"sites",semanticSkillIds:[],applicability:ki.sites,ownership:"shared-preserve"}},Do=Object.freeze(P1),vN=Object.freeze(["browser_use","computer_use","sites"]),A1=Object.freeze(["frontend","security"]),RN=Object.freeze([...Do.frontend.pluginIds,...Do.security.pluginIds]),M1=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),Qt=Object.freeze({browser_use:Pt.browser_use,computer_use:Pt.computer_use,sites:Pt.sites})});function Zr(e){return R({identifier:k(e),label:D,requiresRootApproval:V})}function TN(e){let t=e.map((r)=>r.label),n=t.at(-1);if(n===void 0)return"";if(t.length===1)return n;return`${t.slice(0,-1).join(", ")}, and ${n}`}function CN(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var ON,N1,F1,m_,L1,EN,D1,q1,$1;var kN=b(()=>{Dt();ON=k("local.repository.edit","local.repository.check","local.repository.lint","local.repository.format","local.repository.commit","external.read","specialist.dispatch","vcs.server.mutation","vcs.server.ci-trigger","unknown.effect"),N1=R({identifier:ON,label:D,requiresRootApproval:V});F1=R({localRepositoryEdit:Zr("local.repository.edit"),localRepositoryCheck:Zr("local.repository.check"),localRepositoryLint:Zr("local.repository.lint"),localRepositoryFormat:Zr("local.repository.format"),localRepositoryCommit:Zr("local.repository.commit"),externalRead:Zr("external.read"),specialistDispatch:Zr("specialist.dispatch"),versionControlServerMutation:Zr("vcs.server.mutation"),versionControlServerCiTrigger:Zr("vcs.server.ci-trigger"),unknownEffect:Zr("unknown.effect")}),m_={localRepositoryEdit:{identifier:"local.repository.edit",label:"local repository edit",requiresRootApproval:!1},localRepositoryCheck:{identifier:"local.repository.check",label:"local repository check",requiresRootApproval:!1},localRepositoryLint:{identifier:"local.repository.lint",label:"local repository lint",requiresRootApproval:!1},localRepositoryFormat:{identifier:"local.repository.format",label:"local repository format",requiresRootApproval:!1},localRepositoryCommit:{identifier:"local.repository.commit",label:"local repository commit",requiresRootApproval:!1},externalRead:{identifier:"external.read",label:"external read",requiresRootApproval:!1},specialistDispatch:{identifier:"specialist.dispatch",label:"specialist dispatch",requiresRootApproval:!1},versionControlServerMutation:{identifier:"vcs.server.mutation",label:"version-control-server mutation",requiresRootApproval:!0},versionControlServerCiTrigger:{identifier:"vcs.server.ci-trigger",label:"version-control-server CI triggering",requiresRootApproval:!0},unknownEffect:{identifier:"unknown.effect",label:"unclassified effect",requiresRootApproval:!0}};Lr(m_);L1=k("never","root"),EN=Object.values(m_);D1=EN.filter((e)=>!e.requiresRootApproval),q1=EN.filter((e)=>e.requiresRootApproval),$1=Object.freeze({noRootApproval:`${CN(TN(D1))} actions do not require Root approval.`,rootApproval:`${CN(TN(q1))} require Root approval.`})});function Um(e){let t=Zn(U1,e);if(Fe(t))return Qi(rl("sha256 digest",t.left));return bs(t.right)}var br,h_,TZ,CZ,OZ,U1,j1,H1,B1,V1;var jm=b(()=>{yn();Dt();_s();Sc();br=D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),h_=D.pipe(be(/^[0-9a-f]{64}$/u)),TZ=br.pipe(qu("RunId")),CZ=br.pipe(qu("ProjectId")),OZ=br.pipe(qu("TrustId")),U1=h_.pipe(qu("Sha256Digest"));j1=R({run_id:br,objective_lineage:br,parent_run_id:v(xe(br,It))}),H1=R({project_id:br,trust_id:br,trust_digest:h_}),B1=R({project_id:br,project_digest:h_}),V1=D.pipe(be(/^state-[0-9]+\.[0-9]+$/u))});function Bm(e){switch(e){case"go":case"Go":throw Error(`Legacy profile ${e} was removed and requires an explicit replacement.`);case"plus-low":return"low";case"plus":return"default";case"plus-high":return"high";case"pro-5x":case"pro-20x":throw Error(`Legacy profile ${e} was removed and requires an explicit replacement.`);default:return e}}function MN(e){return typeof e==="string"&&G1.has(e)}function Z1(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!MN(t)||typeof n!=="string")return!1;return Hu.get(t)?.tasks.some((r)=>r.name===n)===!0}function Wm(e,t){return typeof t==="string"&&Hu.get(e)?.tasks.some((n)=>n.name===t)===!0}function NN(e){return typeof e==="string"&&Y1.has(e)}function S_(e){let t=`${e.role}.${e.task}`;if(!y_.has(t))throw Error("Unknown native specialist agent type.");return t}function b_(e){let t=Hu.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return e.role==="Librarian"?`${z1} ${t.instruction}`:t.instruction}function __(e){let t=Hu.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function LN(e){let t=Hu.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function w_(e){let n=LN(e.role).tasks.find((o)=>o.name===e.task);if(n===void 0)throw Error("Unknown specialist task policy.");let r=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":n.permissions.network?"current_sources":"disabled";return Object.freeze({network:n.permissions.network,filesystem:n.permissions.filesystem,sourceMutation:n.permissions.sourceMutation,networkScope:r})}var Xr,IN,_r,qo,W1,Vm="Satisfy the complete requested outcome correctly, elegantly, and mergeably; never weaken or reinterpret it to shrink the patch. Then make the smallest coherent patch within the authorized boundary. Prefer simple, cohesive, idiomatic solutions with appropriate abstraction and minimal accidental complexity. Avoid unrelated code, prose, configuration, documentation, instructions, tests, restructuring, formatting churn, files, and operations. Preserve unrelated work; return material scope expansion to Root.",Ii="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",z1="For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or web search. Return the typed context7 evidence state with version/source evidence. Use web search only when Context7 is unavailable, lacks relevant coverage or the required version, fails for authentication or quota, or a conflict remains after checking authoritative first-party documentation.",K1,PN,J1,$o,Hu,G1,g_,Y1,AN,y_,x_,X1,Q1,eB,tB,Bu,Ua,FN,Uo,nB,zm,DN,Hm,rB,oB,iB,v_,Vu,aB,Qr,sB,cB,W;var Wu=b(()=>{Dt();Xr=k("low","default","high"),IN=k("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),_r=xe(Xr,IN);qo=k("standard","fast","fast-all"),W1=k("low","medium","high","xhigh","max"),K1=k("none"),PN=Object.freeze(["implementation","review","validation","integration","vcs"]),J1=k("read-only","workspace-write"),$o=[{role:"Explorer",tasks:[{name:"map",description:"Bounded repository structure mapping specialist.",instruction:`Map the assigned repository area: locate its relevant packages, entry points, ownership boundaries, and nearby tests or docs. Return a compact path map and identify where a follow-up lookup or trace should start; do not trace runtime behavior or resolve an unrelated fact. ${Ii}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"lookup",description:"Repository fact lookup specialist.",instruction:`Find the specific requested repository fact and cite its exact path or symbol; keep the search narrower than a structure map or execution trace. ${Ii}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:`Follow the assigned execution or reference path across callers, boundaries, and tests; explain the evidence-backed flow and stop at the assigned boundary. ${Ii}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:`Answer the specific external fact with its current authoritative source. ${Ii}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:`Compare and synthesize the assigned current sources with citations, noting conflicts and uncertainty. ${Ii}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply the exact already-decided transformation within the assigned files and verify it.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Design and implement the assigned behavior within its bounded seam, then verify the changed behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Connect already-decided component seams, resolve interface mismatches within the assigned boundary, and verify their combined behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Use babysit-ci to observe the assigned CI or release gate for the Root-supplied exact ref or SHA until terminal; report the matching result and failure evidence. ${Ii}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`Independently exercise the assigned local behavior with the smallest relevant checks, classify failures, and report reproducible evidence; generated proof state is allowed, but do not repair the implementation or substitute for code review. ${Ii}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Use the debugging skill to repair the assigned defect within its bounded seam.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-assignment",authority:"Concrete task permissions govern observation, proof writes, or source repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",tasks:[{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. Batch relevant evidence, then follow up on concrete uncertainty. Check correctness, safety, compatibility, test quality, generated-artifact hygiene, and the canonical patch-quality rule.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Inspect the assigned produced artifact against its requested content, usability, and delivery constraints; repair concrete defects within the artifact boundary and repeat inspection until no actionable findings remain.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-review",authority:"Concrete task permissions govern observational review or bounded repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}];Lr($o);Hu=new Map($o.map((e)=>[e.role,e])),G1=new Set($o.map((e)=>e.role)),g_=$o.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),Y1=new Set(g_),AN=g_.map((e)=>e.replace(":",".")),y_=new Set(AN);x_=Q(MN),X1=Q((e)=>Wm("Explorer",e)),Q1=Q((e)=>Wm("Librarian",e)),eB=Q((e)=>Wm("Worker",e)),tB=Q((e)=>Wm("Reviewer",e)),Bu=Q(Z1),Ua=Object.freeze(g_.filter((e)=>NN(e))),FN=Q(NN),Uo=Object.freeze(AN.filter((e)=>y_.has(e))),nB=Q((e)=>typeof e==="string"&&y_.has(e)),zm=Object.freeze(["worker","explorer","reviewer","librarian"]);DN=R({profile:Xr,service_tier:v(qo)}),Hm=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),rB=k(...Hm),oB=k("delegated","root_direct","unavailable"),iB=k(...Hm),v_=k("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),Vu=Object.freeze({rule:"Use the smallest meaningful proof proportionate to changed behavior, scope, and risk, plus repository-required gates. Reuse current evidence; broaden or repeat checks only after relevant changes, failures, or unresolved concerns. Avoid tests that mirror implementation for reversible low-impact changes.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),aB=Object.freeze({requiredFor:Object.freeze(["library","framework","sdk","api","cli","cloud_service"]),resolveIdentityBeforeQuery:!0,queryNarrowly:!0,evidenceStates:Object.freeze(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),webFallbackEvidenceStates:Object.freeze(["no_coverage","unavailable","auth_or_quota_failure"]),missingRequiredVersionAllowsFallback:!0,successfulEvidenceAloneAllowsFallback:!1,checkFirstPartyDocsBeforeFallbackForConflict:!0,unresolvedConflictAfterFirstPartyAllowsFallback:!0,materialDecisionsRemainRootOwned:!0}),Qr=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnImplementationAndInteractionProof:!0,rootOwnsVisualJudgment:!0,rootOwnsSharedDevServer:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["specialist_implements","specialist_renders_and_interacts","root_judges_current_render","root_assigns_discrepancies","specialist_repairs","root_rerenders_and_retests"])}),sB=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),cB=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),W=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:Uo,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:zm,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","browser_use","computer_use","review","ci_release_observation"]),directExecutionExceptions:Hm,rootOwnedAuthority:Hm,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","ambiguity_or_missing_material_input"]),surgicalMutationRule:Vm,phaseOrder:PN,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,collectiveWaits:!0,evidenceReusedAcrossPhases:!0}),atomicLifecycleTransitions:Object.freeze({relatedAssignmentAndIntentWrites:!0,oneLockOneCommit:!0,staleRevisionChecksRetained:!0,repositoryDriftChecksRetained:!0}),supersession:Object.freeze({explicitOnly:!0,unfinishedPredecessorOnly:!0,validatedRelatedReplacement:!0,reasonAndProvenanceRequired:!0,supersededExcludedFromCompletionBlockers:!0}),specialistTerminalResultPersistence:Object.freeze({ownActiveInvocationCapabilityRequired:!0,ownAssignmentOnly:!0,terminalOutcomeOnly:!0,rootOwnedIntentLifecycle:!0,rootOwnedAcceptanceReviewAndCiGates:!0,rootOwnedVcsAndExternalEffects:!0,sharedRuntimeCallerIdentityUnavailable:!0,legacyResultCompatibilityPreserved:!0}),normalSpawnForkTurns:"none",normalSpawnRequiresExplicitForkTurns:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,semanticStateBoundary:"Use holycodex-agent semantic operations for Intent and Assignment state. Do not edit TOON state. Resume the current Intent or create one for new work; record verification, acceptance, and readiness, and complete only when holycodex-agent confirms every completion predicate. There is no HolyCodex planning workflow or automatic Plan approval gate; preserve existing Plan state when resuming work that uses it.",routeConfigurationBeforeDispatch:"Use the active profile's registered Role.task configuration, including model, effort, tier, permissions, shell, and capabilities. Verify the registration once per configuration generation; recheck after configuration changes or when resuming an unverified thread. Pass fields required by the dispatch tool; registered settings need not be copied into Assignment prose. Never inherit Root settings, substitute a generic route, or override the selected route. Report a missing or incompatible route before dispatch.",assignmentInvocationLifecycle:"Before each specialist spawn, persist the bounded Assignment and call holycodex-agent assignment start. Keep the returned active_invocation_id and capability in Root; give the specialist only the bounded Assignment, never the capability. After a terminal report, record the result with that invocation ID and capability. Recover an interrupted invocation only after confirming it stopped, using the matching Root-held capability; never share that capability.",assignmentContextIsTaskSpecificOnly:!0,configuredRouteModelAndEffortPreserved:!0,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["significant_findings_or_decisions","consequential_blockers_or_input_needs","release_milestones"]),outOfBoundaryRequiresNewAssignment:!0,routineWaitTool:"collaboration.wait_agent",routineWaitMaximumTimeoutMs:1200000,routineWaitUsesMaximumRuntimeTimeout:!0,earlySpecialistCompletionWakesWait:!0,collectiveMailboxIncludesRelevantAgents:!0,idleTimeoutRepeatsMaximumWait:!0,shortRoutineWaitsForbidden:!0,longestPracticalEventWait:!0,busyPollingForbidden:!0,statusOnlyCoordinationLoopsForbidden:!0,batchIndependentLifecycleActions:!0,releaseLeavesAfterAcceptedOutcome:!0,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),evidenceFirstConciseStructuredReports:!0,specialistReportFields:Object.freeze(["changed paths","checks","observable evidence","blockers","Root decisions needed","remaining risk"]),rootLargeReadsOnlyFor:Object.freeze(["material decisions","conflicts","failures","findings"]),stableFactsReused:!0,duplicatePolicyForbidden:!0,stableBoundedComponentScopesAreCanonical:!0,lifecycleWorkerOwnsDeterministicApi:!0,materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,routineSafeReversibleInScopeDecisionsProceedAutonomously:!0,userInstructionsOverrideSkillGuidelinesExceptHardInvariants:!0,authorizedWorkContinuesThroughRequestedTerminalState:!0,testingPolicy:Vu,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function en(e,t){return new ut("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function R_(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw en(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw en(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw en(t,"invalid number");return r}case"undefined":throw en(t,"undefined is not JSON");case"bigint":throw en(t,"bigint is not JSON");case"function":throw en(t,"function is not JSON");case"symbol":throw en(t,"symbol is not JSON");case"object":break}if(n.has(e))throw en(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw en(t,`symbol property ${String(s)}`);let i=e,a=[];for(let s=0;s<i.length;s+=1){let c=Object.getOwnPropertyDescriptor(i,String(s));if(!c||!c.enumerable||!("value"in c))throw en(`${t}[${s}]`,"sparse or accessor array item");a.push(R_(c.value,`${t}[${s}]`,n))}for(let s of Object.getOwnPropertyNames(i)){if(s==="length")continue;let c=Number(s);if(!Number.isInteger(c)||c<0||c>=i.length||String(c)!==s)throw en(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw en(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw en(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw en(t,`symbol property ${String(i)}`);for(let i of Object.getOwnPropertyNames(e)){let a=Object.getOwnPropertyDescriptor(e,i);if(!a||!a.enumerable||!("value"in a))throw en(`${t}.${i}`,"non-enumerable or accessor property")}let o=[];for(let i of Object.keys(e).sort()){let a=Object.getOwnPropertyDescriptor(e,i);if(!a||!("value"in a))throw en(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${R_(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function Mn(e){return R_(e,"$",new Set)}function Nn(e){return new TextEncoder().encode(Mn(e))}function qN(e,t){if(e.length===0||e.includes("\x00"))throw new ut("invalid_digest_domain","Digest domains must be non-empty and NUL-free.",{field:"domain"});let n=new TextEncoder().encode("holycodex-sha256\x00"),r=new TextEncoder().encode(e),o=n.byteLength+8+r.byteLength;for(let c of t){if(c.byteLength>4294967295||o>4294967291-c.byteLength)throw new ut("invalid_digest_domain","Digest input is too large.");o+=4+c.byteLength}let i=new Uint8Array(o),a=new DataView(i.buffer);i.set(n,0);let s=n.byteLength;a.setUint32(s,r.byteLength,!1),s+=4,i.set(r,s),s+=r.byteLength,a.setUint32(s,t.length,!1),s+=4;for(let c of t)a.setUint32(s,c.byteLength,!1),s+=4,i.set(c,s),s+=c.byteLength;return i}function uB(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function Fn(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new ut("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",dB(qN(e,t)));return uB(new Uint8Array(r))}function dB(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var T_=b(()=>{_s();jm()});function jN(e){try{return Mn(e)!==void 0}catch{return!1}}function Jm(e){let t=Zn(JN,e);if(Fe(t))return Qi(rl("CLI envelope",t.left));return bs(t.right)}var $N,UN,HN,pB,fB,C_="holycodex-specialist-outcome-2",zt,vc,zu,mB,hB,gB,yB,xB,SB,Km,bB,_B,wB,vB,RB,BN,VN,WN,TB,zN,KN,JN;var O_=b(()=>{yn();Dt();T_();f_();_s();jm();Wu();Sc();$N=k("blocked","completed","failed","partial"),UN=xe(k("high","max","xhigh"),It);HN=Q((e)=>jN(e)),pB=Q((e)=>mg(e)&&!Array.isArray(e)&&jN(e)),fB=R({blocked:V,changed_files:K(D),confidence:vn,context_owner:xe(D,It),material_findings:K(D),needs_more_context:V,needs_root_decision:V,needs_verification:V,relevant_files:K(D),remaining_risk:K(D),reuse_recommended:V,status:$N,suggested_followup:xe(D,It),suggested_luna_effort:UN,suggested_specialist:xe(x_,It),verification:K(D),verification_passed:V}),zt=D.pipe(xc(1)),vc=R({state:v_,evidence:K(zt).pipe(Yr(1)),library:v(zt),version:v(zt)}),zu={protocol_version:k(C_),route:Bu,evidence:K(zt),context7:v(vc)},mB=R(zu),hB=R({...zu,status:k("completed"),summary:zt}),gB=R({...zu,status:k("blocked"),reason:zt,needs_root_decision:V}),yB=R({...zu,status:k("partial"),summary:zt,completed:K(zt),remaining:K(zt),needs_root_decision:V}),xB=R({...zu,status:k("failed"),error:zt}),SB=xe(hB,gB,yB,xB),Km={protocol_version:k(C_),capability:ju,route:xe(Bu,It),evidence:K(zt),context7:v(vc),data:HN},bB=R({...Km,status:k("completed"),summary:zt}),_B=R({...Km,status:k("blocked"),reason:zt,needs_root_decision:V}),wB=R({...Km,status:k("partial"),summary:zt,completed:K(zt),remaining:K(zt),needs_root_decision:V}),vB=R({...Km,status:k("failed"),error:zt}),RB=xe(bB,_B,wB,vB),BN=K(D),VN=D.pipe(be(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),WN=k(uo),TB=R({code:br,message:D,details:pB}),zN=R({schema_version:WN,ok:k(!0),command:VN,data:HN,warnings:BN}),KN=R({schema_version:WN,ok:k(!1),command:VN,error:TB,warnings:BN}),JN=xe(zN,KN)});function CB(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:Ku,effort:n}}function kB(e){let t=EB.get(e);if(t===void 0)throw new ut("catalog_invalid","A profile has no route effort policy.",{profile:e});return $o.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new ut("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return CB(n.role,r.name,i)}))}function E_(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:Ku,defaultServiceTier:"standard",routes:kB(e.name)}}function IB(e){let t=["low","default","high"];if(e.length!==t.length)throw new ut("catalog_invalid","The profile catalog has an invalid size.");for(let n=0;n<t.length;n+=1){let r=e[n],o=t[n];if(!r||r.name!==o)throw new ut("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=o==="high"?I_:k_,a=o==="low"?"medium":"high";if(r.root.model!==i||r.root.effort!==a||r.specialistModel!==Ku)throw new ut("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==Ua.length)throw new ut("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let c of r.routes){if(s.has(c.key)||!OB.has(c.key)||c.model!==Ku||`${c.role}:${c.task}`!==c.key)throw new ut("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(c.key)}if(s.size!==Ua.length)throw new ut("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<Ua.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||GN[i.effort]<r)throw new ut("catalog_invalid","Profile route effort is not monotonic.",{route:Ua[n]??"unknown"});r=GN[i.effort]}}}function eo(e){let t=Zn(Xr,e);if(Fe(t))return Qi(new ut("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=ZN.get(t.right);if(!n)return Qi(new ut("invalid_profile","Unknown profile selection.",{profile:t.right}));return bs(n)}var I_="gpt-6-astra",k_="gpt-6.1-sol",Ku="gpt-6-luna",OB,GN,P_,EB,A_,YN,ZN,PB;var XN=b(()=>{yn();_s();Wu();Sc();OB=new Set(Ua),GN={low:0,medium:1,high:2,xhigh:3,max:4},P_=[{profile:"low",rationale:"The low profile keeps bounded specialist work economical.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"high","Worker:implementation":"high","Worker:integration":"max","Worker:operations":"high","Worker:validation":"medium","Worker:debugging":"high","Reviewer:code":"max","Reviewer:artifact":"high"}},{profile:"default",rationale:"The default profile is the recommended balanced route.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"xhigh","Librarian:lookup":"medium","Librarian:research":"xhigh","Worker:mechanical":"high","Worker:implementation":"xhigh","Worker:integration":"max","Worker:operations":"high","Worker:validation":"high","Worker:debugging":"xhigh","Reviewer:code":"max","Reviewer:artifact":"xhigh"}},{profile:"high",rationale:"The high profile maximizes specialist reasoning where specified.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"max","Librarian:lookup":"medium","Librarian:research":"max","Worker:mechanical":"xhigh","Worker:implementation":"max","Worker:integration":"max","Worker:operations":"xhigh","Worker:validation":"xhigh","Worker:debugging":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];Lr(P_);EB=new Map(P_.map((e)=>[e.profile,e]));A_=[E_({name:"low",rootModel:k_,rootEffort:"medium"}),E_({name:"default",rootModel:k_,rootEffort:"high"}),E_({name:"high",rootModel:I_,rootEffort:"high"})];IB(A_);Lr(A_);YN=A_,ZN=new Map,PB=new Map;for(let e of YN){ZN.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);PB.set(e.name,t)}});import{execFile as MB}from"child_process";import{promisify as NB}from"util";var e0="holycodex-intent-1",t0="holycodex-plan-1",n0="holycodex-assignment-1",Gm="toon-4",ee,wr,Ym,r0,Rc,Xn,mt,XZ,M_,ja,N_,F_,FB,QN,LB,DB,L_,o0,i0,Tc,D_,qB,$B,QZ,UB="holycodex-work-state-transaction-1",eX,tX,jB,HB,BB,VB,WB,zB,KB,JB,nX,GB,rX;var a0=b(()=>{Dt();O_();Wu();Sc();ee=D.pipe(Ge((e)=>e.trim().length>0)),wr=D.pipe(be(/^[a-z0-9][a-z0-9-]{0,95}$/u)),Ym=D.pipe(be(/^[a-f0-9]{64}$/u)),r0=D.pipe(be(/^[a-f0-9]{40}$/u)),Rc=Dm.pipe(dN(1)),Xn=D.pipe(Ge((e)=>!Number.isNaN(Date.parse(e)))),mt=K(ee),XZ=R({pid:Dm.pipe(n_(0)),token:ee}),M_=R({role:k("Explorer","Librarian","Worker","Reviewer"),task:ee}).pipe(Ge((e)=>$o.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),ja=R({kind:k("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:ee,result:v(k("passed","failed","observed","unknown"))}),N_=R({root:ee,git_common_dir:ee,initial_head:ee,expected_head:ee,expected_changes:mt,expected_status_digest:Ym,integrated_commit:v(r0),updated_at:Xn}),F_=k("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),FB=k("scoping","ready","executing","verifying","reviewing"),QN=R({required:V,status:k("not_required","missing","passed","failed","accepted","rejected"),evidence:K(ja)}),LB=R({schema_version:k(e0),toon_compatibility:k(Gm),id:wr,slug:wr,title:ee,goal:ee,acceptance_criteria:mt,state:F_,revision:Rc,plan_required:V,active_plan_revision:v(Rc),active_plan_digest:v(Ym),blockers:mt,resume_state:v(FB),verification:QN,review:QN,acceptance_met:V,root_readiness:V,evidence:K(ja),baseline:N_,created_at:Xn,updated_at:Xn}),DB=R({schema_version:k(t0),toon_compatibility:k(Gm),intent_id:wr,revision:Rc,predecessor_digest:v(Ym),approach:ee,scope:mt,exclusions:mt,assignments:mt,dependencies:mt,architecture:mt,risks:mt,assumptions:mt,open_questions:mt,verification:mt,recovery:mt,updated_at:Xn}),L_=k("completed","blocked","needs_root_input","failed"),o0=k("pending","executing","completed","blocked","needs_root_input","failed","superseded"),i0=R({id:wr,outcome:L_,started_at:Xn,finished_at:Xn,summary:ee,evidence:K(ja),context7:v(vc),blocker:v(ee),remaining_risk:mt}),Tc=Ym,D_={schema_version:k(n0),toon_compatibility:k(Gm),intent_id:wr,id:wr,objective:ee,owner:xe(M_,R({role:k("Reviewer"),task:k("plan")})),scope:mt,constraints:mt,exclusions:mt,dependencies:mt,acceptance_criteria:mt,status:o0,revision:Rc,invocations:K(i0),active_invocation_id:v(ee),active_started_at:v(Xn),supersedes:v(wr),superseded_by:v(wr),supersession_reason:v(ee),supersession_provenance:v(ee),evidence:K(ja),blocker:v(ee),remaining_risk:mt,created_at:Xn,updated_at:Xn},qB=R(D_),$B=R({...D_,capability:Tc}),QZ=R({...D_,active_invocation_capability_verifier:v(Tc),active_invocation_capability:v(Tc)}),eX=R({schema_version:k(UB),state:k("prepared","committed"),files:K(R({path:ee,previous:D,next:D})).pipe(Yr(1))}),tX=R({schema_version:k("holycodex-intent-0"),id:wr,slug:wr,title:ee,goal:ee,acceptance_criteria:mt,state:F_,revision:Rc,baseline:N_,created_at:Xn,updated_at:Xn}),jB=R({title:ee,goal:ee,acceptanceCriteria:K(ee).pipe(Yr(1)),planRequired:v(V),verificationRequired:v(V),reviewRequired:v(V)}),HB=R({approach:ee,scope:v(K(ee)),exclusions:v(K(ee)),assignments:v(K(ee)),dependencies:v(K(ee)),architecture:v(K(ee)),risks:v(K(ee)),assumptions:v(K(ee)),openQuestions:v(K(ee)),verification:v(K(ee)),recovery:v(K(ee))}),BB=R({id:v(ee),objective:ee,owner:M_,scope:K(ee).pipe(Yr(1)),constraints:v(K(ee)),exclusions:v(K(ee)),dependencies:v(K(ee)),acceptanceCriteria:K(ee).pipe(Yr(1))}),VB=R({scope:K(ee).pipe(Yr(1))}),WB=R({scope:v(K(ee).pipe(Yr(1)))}),zB=R({replacementId:wr,replacementRevision:v(Rc),reason:ee,provenance:ee}),KB=R({commit:r0}),JB=R({invocationId:v(ee),capability:v(Tc),outcome:L_,startedAt:v(ee),summary:ee,scope:v(K(ee).pipe(Yr(1))),evidence:v(K(ja)),context7:v(vc),blocker:v(ee),remainingRisk:v(K(ee))}),nX=R({invocationId:ee,startedAt:Xn,capability:Tc,interruptionReason:ee}),GB=R({evidence:v(K(ja)),verification:v(k("passed","failed")),review:v(k("accepted","rejected")),acceptanceMet:v(V),rootReadiness:v(V),clearBlockers:v(V)}),rX=NB(MB)});var ht=b(()=>{PR();_s();Sc();SN();f_();kN();jm();Wu();O_();XN();T_();a0()});function de(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ye(e){try{return Mn(e),!0}catch{return!1}}function XB(e){switch(e){case"invalid_external_data":case"manifest_invalid":case"empty_output_directory":return"validation";case"discovery_failed":return"identity";case"protocol_mismatch":case"method_unsupported":case"server_request_unsupported":case"unexpected_response":return"protocol";case"invalid_transport_line":case"transport_closed":case"transport_failure":return"transport";case"approval_required":case"permission_denied":return"approval";case"cancellation":return"interruption";case"timeout":return"timeout";case"turn_failed":return"turn";case"closed":return"closed";case"server_error":return"server"}}function c0(e){return{ok:!1,error:e}}function l0(e){return{ok:!0,value:e}}function Ln(e,t=512){let n="";for(let r of e){let o=r.codePointAt(0)??0;n+=o<=8||o===11||o===12||o>=14&&o<=31||o===127?" ":r}return n.replace(/\s+/gu," ").trim().slice(0,t)}function Ha(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return Ln(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>Ha(n,t+1));if(de(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=Ln(r,96);if(i.length>0)n[i]=Ha(o,t+1)}return n}return"[redacted]"}function u0(e){let t=Ha(e);return de(t)?t:{value:t}}function Ze(e,t,n){return new oe("invalid_external_data",`Invalid ${e}.`,{field:e,received:Ha(t)},n===void 0?void 0:{cause:n})}function Ue(e,t,n){let r=Zn(e,t);if(Fe(r))throw Ze(n,t,String(r.left));return r.right}function d0(e,t){try{return Ue(e,t,"value"),!0}catch{return!1}}var q_,Ju=1048576,$_=65536,Dn,Pi,JX,jo,ZB,oe;var to=b(()=>{ht();yn();Dt();q_=uo;Dn=Q((e)=>Ye(e)),Pi=Q((e)=>de(e)&&Ye(e)),JX=D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),jo=D.pipe(Ge((e)=>e.length>0&&e.length<=4096)),ZB=vn.pipe(Ge((e)=>Number.isFinite(e)&&e>=0));oe=class oe extends Error{code;kind;details;retryable;constructor(e,t,n={},r){super(t,r?.cause===void 0?void 0:{cause:r.cause});this.name="CodexError",this.code=e,this.kind=XB(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var U_,Gu,Yu,j_,H_,B_,V_="turn/completed";var Zm=b(()=>{U_=["initialize","thread/start","thread/resume","thread/read","thread/list","thread/fork","thread/unsubscribe","turn/start","turn/steer","turn/interrupt","model/list","modelProvider/capabilities/read","config/read","permissionProfile/list"],Gu=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],Yu=["item/permissions/requestApproval"],j_=["mcpServer/elicitation/request"],H_=["item/tool/call"],B_={method:"initialized"}});class Qm{transport;maxLineBytes;requestTimeoutMs;signal;notificationListeners=new Set;serverRequestHandlers=new Set;pending=new Map;serverRequestWork=new Set;serverRequestTasks=new Set;nextRequestId=1;readerPromise;initializePromise;transportClosePromise;initializeAttempted=!1;initialized=!1;closed=!1;constructor(e,t={}){if(this.transport=e,this.maxLineBytes=t.maxLineBytes??Ju,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new oe("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new oe("invalid_external_data","The request timeout is invalid.");if(t.onNotification)this.notificationListeners.add(t.onNotification);if(t.onServerRequest)this.serverRequestHandlers.add(t.onServerRequest);if(this.signal?.aborted)this.close();else if(this.signal)this.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get isInitialized(){return this.initialized}onNotification(e){return this.notificationListeners.add(e),()=>this.notificationListeners.delete(e)}onServerRequest(e){return this.serverRequestHandlers.add(e),()=>this.serverRequestHandlers.delete(e)}async initialize(e=QB){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new oe("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Ue(Xm,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",tw,e,Qu)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",nw,t,G_)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",rw,t,Q_)}async listThreads(e={}){return this.action("thread/list",iw,e,ew)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",ow,t,Y_)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",Z_,t,X_)}async startTurn(e){return this.action("turn/start",aw,e,cw)}async steerTurn(e){return this.action("turn/steer",sw,e,lw)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",uw,n,dw)}async listModels(e={}){return this.action("model/list",fw,e,mw)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",hw,e,gw)}async readConfig(e={}){return this.action("config/read",yw,e,xw)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",Sw,e,bw)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Ue(Xm,t,"initialize parameters"));return Ue(Dn,r,"initialize result")}let n=Ue(Xu,{id:1,method:e,params:t},"App Server method");if(!eV.has(n.method))throw new oe("method_unsupported",`Unsupported App Server method: ${e}.`,{method:e});return this.request(n.method,n.params===void 0?{}:n.params)}async close(){await this.closeWithError(new oe("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Ue(Dn,e,"initialize parameters")),n=Ue(K_,t,"initialize result"),r=Ue(J_,B_,"initialized notification");return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(t){let n=t instanceof oe?t:new oe("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(n),n}}async action(e,t,n,r){let o=Ue(t,n,`${e} parameters`),i=Ue(Dn,o,`${e} parameters`),a=await this.request(e,i);return Ue(r,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new oe("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=Ue(Xu,{id:n,method:e,params:t},`${e} request`);return new Promise((o,i)=>{let a=!1,s,c,l=(d)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(d)};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new oe("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let d=()=>l(new oe("cancellation",`The ${e} request was cancelled.`,{method:e}));this.signal.addEventListener("abort",d,{once:!0}),c=()=>this.signal?.removeEventListener("abort",d)}let u={method:e,resolve:(d)=>{if(a)return;if(a=!0,s!==void 0)clearTimeout(s);c?.(),o(d)},reject:l,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,u),this.transport.writeLine(JSON.stringify(r)).catch((d)=>{l(d instanceof oe?d:new oe("transport_failure","The App Server request could not be written.",{},{cause:d}))})})}startReader(){if(!this.readerPromise)this.readerPromise=this.readLoop().catch((e)=>this.handleReaderFailure(e)).catch(()=>{return})}async readLoop(){while(!this.closed){let e=await this.transport.readLine();if(e===null){if(!this.closed)throw new oe("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new oe("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof oe?e:new oe("transport_failure","The App Server transport failed.",{},{cause:e});await this.closeWithError(t)}handleLine(e){let t;try{t=JSON.parse(e)}catch(i){throw new oe("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let n=this.tryDecode(Zu,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(Xu,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(z_,t);if(o!==void 0){this.handleNotification(o);return}throw Ze("JSON-RPC message",t)}tryDecode(e,t){try{return Ue(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new oe("unexpected_response","The App Server returned an unknown request id.",{id:e.id});if(this.pending.delete(e.id),"error"in e){let n=e.error.code===-32001,r=nV(t.method);t.reject(new oe(r,`The App Server rejected ${t.method}: ${Ln(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:Ha(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Ue(_w,{...e,params:t,category:p0(e.method)},"server request");this.emitNotification({kind:"server_request",method:e.method,params:t});let r=[...this.serverRequestHandlers];if(r.length===0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let o=r[0];if(o===void 0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let i={active:!0};this.serverRequestWork.add(i);let a;try{a=o(n)}catch(s){this.completeServerRequest(i,()=>this.writeServerError(e.id,-32000,Ln(String(s))));return}if(a instanceof Promise){this.trackServerRequestTask(a.then((s)=>this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,s)),(s)=>this.completeServerRequest(i,()=>this.writeServerError(e.id,-32000,Ln(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Ue(ww,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,Ln(String(n)))}}completeServerRequest(e,t){if(!e.active)return;e.active=!1,this.serverRequestWork.delete(e);try{this.trackServerRequestTask(t())}catch{}}trackServerRequestTask(e){let t=e.catch(()=>{return});this.serverRequestTasks.add(t),t.then(()=>this.serverRequestTasks.delete(t),()=>this.serverRequestTasks.delete(t))}async writeServerResult(e,t){let n=Ue(Zu,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Ue(Zu,{id:e,error:{code:t,message:tV(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===V_){let n=Ue(pw,t,"turn/completed notification");this.emitNotification({kind:"turn_completed",method:e.method,params:n});return}if(e.method.includes("agent")||e.method.includes("subagent")){this.emitNotification({kind:"multi_agent",method:e.method,...t===void 0?{}:{params:t}});return}this.emitNotification({kind:"unknown",method:e.method,metadata:u0({params:Ha(t)})})}emitNotification(e){for(let t of this.notificationListeners)try{t(e)}catch{}}rejectPending(e){for(let t of this.pending.values())t.reject(e);this.pending.clear()}async closeWithError(e){if(this.transportClosePromise!==void 0){await this.transportClosePromise;return}this.closed=!0,this.rejectPending(e);for(let t of this.serverRequestWork)t.active=!1;this.serverRequestWork.clear(),this.serverRequestTasks.clear(),this.transportClosePromise=Promise.resolve().then(()=>this.transport.close()).catch(()=>{return}),await this.transportClosePromise}ensureOpen(){if(this.closed)throw new oe("closed","The App Server client is closed.")}}function tV(e){let t=Ln(e);return t.length>0?t:"server request failed"}function nV(e){if(Yu.some((t)=>t===e))return"permission_denied";if(Gu.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var QB,eV;var W_=b(()=>{to();Zm();vw();QB={clientInfo:{name:"holycodex",title:null,version:q_},capabilities:null},eV=new Set(U_)});import{isAbsolute as rV}from"path";function Ai(e=process.env){let t=["PATH","HOME","USER","CODEX_HOME","TMPDIR","TEMP","TMP","LANG","LC_ALL"],n={};for(let r of t){let o=e[r];if(o!==void 0&&o.length>0)n[r]=o}return n}function Rw(e=process.env){return Object.freeze(Ai(e))}async function eh(e,t){let n=e.getReader(),r=[],o=0;try{while(!0){let s=await n.read();if(s.done)break;if(o+=s.value.byteLength,o>t)throw new oe("invalid_transport_line","A subprocess stream exceeded its limit.");r.push(s.value)}}finally{n.releaseLock()}let i=new Uint8Array(o),a=0;for(let s of r)i.set(s,a),a+=s.byteLength;return i}function th(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new oe("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}}function Ba(e){return Ln(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}function ed(e){return e.split(/\r?\n/u).map((t)=>Ba(t)).filter((t)=>t.length>0).slice(0,128)}class nh{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!rV(e.executablePath))throw new oe("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??Ju,this.maxDiagnosticBytes=e.maxDiagnosticBytes??$_,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new oe("invalid_external_data","The transport bounds are invalid.");if(this.process=Bun.spawn([e.executablePath,"app-server"],{...e.cwd===void 0?{}:{cwd:e.cwd},env:Ai(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new oe("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new oe("transport_failure","The Codex App Server did not expose stdin.");if(this.stdin=this.process.stdin,this.stdoutReader=this.process.stdout,this.stderrStream=this.process.stderr,this.stderrPromise=this.collectStderr(),e.signal)if(e.signal.aborted)this.close();else e.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get diagnostics(){return[...this.stderrDiagnostics]}async readLine(){if(this.closed&&this.stdoutBuffer.byteLength===0)return null;let e=this.stdoutReader.getReader();try{while(!0){let t=this.stdoutBuffer.indexOf(10);if(t>=0){if(t>this.maxLineBytes)throw await this.close(),new oe("invalid_transport_line","The App Server emitted an overlong line.");let o=this.stdoutBuffer.slice(0,t);this.stdoutBuffer=this.stdoutBuffer.slice(t+1);let i=o.at(-1)===13?o.slice(0,-1):o;return this.lineDecoder.decode(i)}if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new oe("invalid_transport_line","The App Server emitted an overlong line.");let n=await e.read();if(n.done){if(this.stdoutBuffer.byteLength===0)return null;if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new oe("invalid_transport_line","The App Server emitted an overlong line.");let o=this.stdoutBuffer;return this.stdoutBuffer=new Uint8Array(0),this.lineDecoder.decode(o)}let r=new Uint8Array(this.stdoutBuffer.byteLength+n.value.byteLength);r.set(this.stdoutBuffer,0),r.set(n.value,this.stdoutBuffer.byteLength),this.stdoutBuffer=r}}catch(t){if(t instanceof oe)throw t;throw new oe("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new oe("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new oe("invalid_transport_line","The App Server request exceeded the line limit.");try{await this.stdin.write(`${e}
35
- `),await this.stdin.flush()}catch(t){throw new oe("transport_failure","The App Server stdin could not be written.",{},{cause:t})}}async close(){if(this.closed)return;this.closed=!0;try{await Promise.resolve(this.stdin.end())}catch{}try{this.process.kill()}catch{}await Promise.race([this.process.exited,new Promise((e)=>setTimeout(()=>e(-1),1000))]),await this.stderrPromise.catch(()=>{return})}async collectStderr(){try{let e=await eh(this.stderrStream,this.maxDiagnosticBytes),t=th(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=Ba(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var rh=b(()=>{to()});import{spawn as oV}from"child_process";import{lstat as Ni,mkdir as iV,mkdtemp as aV,readFile as sV,readdir as cV,realpath as Tw,rename as lV,rm as uV,stat as aQ}from"fs/promises";import{dirname as h0,isAbsolute as Pw,join as Mi,relative as g0,resolve as oh,sep as y0}from"path";async function S0(e){let t=Lw(e.selectedPluginIds);if(t.length===0)return;if(v0(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new ye("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>Fw(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&ah(r,t))return r;let o=e.initializeRuntime??(()=>wV(e)),i,a;try{i=await o()}catch(s){a=ce("marketplace_unavailable","Codex runtime initialization could not start the official marketplace sync. Check that Codex is available and its network/policy settings permit the official marketplace.",s)}if(a===void 0)try{let s=e.timeoutMs??Nw,c=e.pollIntervalMs??pV,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new ye("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&ah(u,t))return u;let d=s-(Date.now()-l);if(d<=0)break;await(e.sleep??RV)(Math.min(c,d))}a=ce("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired. Check network access and Codex marketplace policy, then retry.")}catch(s){if(s instanceof ye&&s.code==="cancelled")throw s;a=s instanceof ye?s:ce("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await b0({codexHome:e.codexHome,selectedPluginIds:e.selectedPluginIds,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.signal===void 0?{}:{signal:e.signal},...e.gitFallback===void 0?{}:e.gitFallback})}catch(s){if(s instanceof ye)throw s;throw ce("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??ce("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function b0(e){let t=Lw(e.selectedPluginIds);if(t.length===0)throw ce("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(v0(e.timeoutMs,void 0),!Pw(e.codexHome))throw ce("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new ye("cancelled","Official Codex marketplace fallback was cancelled.");let n=Ai(e.environment),r=e.gitRunner??C0("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??Nw,i;try{i=await hV(r,o,e.signal)}catch(u){if(u instanceof ye)throw u;throw ce("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Mi(e.codexHome,"plugins"),s=Mi(a,Mw[1]);if(await yV(a,e.codexHome),await Ni(s).catch((u)=>{if(rd(u))return;throw ce("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw ce("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await aV(Mi(a,".openai-plugins-stage-"));try{if(await Ow(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(Wa,l)}catch(m){if(vV(m))throw ce("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",m);throw m}else{let m=await r.run(["clone","--depth=1","--no-tags",Wa,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw ce("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await ih(l);let u=await _0(l,e.codexHome,t);if(u===void 0||!ah(u,t))throw ce("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await gV(r,l,o,e.signal)!==i)throw ce("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Ni(s).catch((m)=>{if(rd(m))return;throw ce("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw ce("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await lV(l,s);let f=await Fw(e.codexHome,e.selectedPluginIds);if(f===void 0||!ah(f,t))throw ce("marketplace_invalid","The published official marketplace failed validation.");return f}catch(u){if(u instanceof ye)throw u;throw ce("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await uV(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function hV(e,t,n){let r=await e.run(["ls-remote",Wa,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw ce("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",r.stderr);let o=r.stdout.trim().split(/\r?\n/u).map((a)=>a.trim()).filter((a)=>a.length>0),i=o.length===1?/^([0-9a-f]{40}|[0-9a-f]{64})\s+HEAD$/iu.exec(o[0]??""):null;if(i?.[1]===void 0)throw ce("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function gV(e,t,n,r){let o=await e.run(["rev-parse","HEAD"],{timeoutMs:n,cwd:t,...r===void 0?{}:{signal:r}}),i=o.stdout.trim().toLowerCase();if(o.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(i))throw ce("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function yV(e,t){await Cw(t,e),await iV(e,{recursive:!0}),await Cw(t,e)}async function Cw(e,t){let n=oh(e),r=oh(t);while(!0){if((await Ni(r).catch((a)=>{if(rd(a))return;throw a}))?.isSymbolicLink())throw ce("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=h0(r);if(i===r||i!==n&&!xV(n,i))throw ce("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function xV(e,t){let n=g0(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${y0}`)&&!Pw(n)}async function ih(e){let t=await Ni(e);if(t.isSymbolicLink())throw ce("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw ce("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await cV(e,{withFileTypes:!0});for(let r of n){let o=Mi(e,r.name),i=await Ni(o);if(i.isSymbolicLink())throw ce("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await ih(o)}}async function Fw(e,t=[]){return await _0(Mi(e,...Mw),e,Lw(t))}async function _0(e,t,n=[]){if(t!==void 0)await Cw(t,e);let r=await Ni(e).catch((l)=>{if(rd(l))return;throw ce("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",l)});if(r===void 0)return;if(r.isSymbolicLink()||!r.isDirectory())throw ce("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await Ow(t,e);else await ih(e);if(t!==void 0)await ih(e);let o=await Tw(e),i=[Mi(o,".agents","plugins","marketplace.json"),Mi(o,".codex-plugin","marketplace.json"),Mi(o,"marketplace.json")],a,s;for(let l of i){let u=await Ni(l).catch((d)=>{if(rd(d))return;throw ce("marketplace_invalid","The official marketplace manifest could not be read safely.",d)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw ce("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await Ow(o,l),a!==void 0)throw ce("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await sV(l))}catch(d){throw ce("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",d)}}if(a===void 0||s===void 0)return;let c;try{c=JSON.parse(s)}catch(l){throw ce("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return w0(c,o,a,n)}function w0(e,t=`${Mw.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!de(e)||e.name!==nd)throw ce("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");SV(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw ce("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!de(s)||typeof s.name!=="string"){if(r.length>0)continue;throw ce("marketplace_invalid","The official marketplace contains a malformed plugin entry.")}let c=s.name;if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(c)){if(r.length>0)continue;throw ce("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw ce("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=bV(s);if(!_V(l))throw ce("marketplace_invalid",`The official marketplace source for ${c} is unsafe.`);i.push({name:c,source:l})}if(r.some((s)=>!i.some((c)=>c.name===s)))throw ce("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:nd,source:Wa,rootPath:t,manifestPath:n,plugins:i}}function SV(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:de(n)&&typeof n.url==="string"?n.url:void 0)!==Wa)throw ce("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function bV(e){let t=e.source;if(typeof t==="string")return t;if(de(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function _V(e){if(e===void 0||e.length===0||Pw(e))return!1;if(/^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(t))return!1;return t.split("/").every((n)=>n.length===0||n==="."||n!=="..")}function Lw(e){let t=[],n=new Set;for(let r of e){let o=r.lastIndexOf("@");if(o<1)continue;let i=r.slice(o+1);if(i!==nd&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw ce("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!R0(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function ah(e,t){return t.every((n)=>{let r=e.plugins.find((i)=>i.name===n);if(r===void 0)return!1;return r.source.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)===n})}async function wV(e){let t=Ai(e.environment),n;try{n=new nh({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new Qm(n,{requestTimeoutMs:Math.min(e.timeoutMs??Nw,1e4),...e.signal===void 0?{}:{signal:e.signal}});return await r.initialize(),async()=>{await r.close()}}catch(r){throw await n?.close().catch(()=>{return}),r}}function v0(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw ce("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw ce("marketplace_invalid","The official marketplace poll interval is invalid.")}async function Ow(e,t){let n=await Tw(e),r=await Tw(t),o=g0(n,r);if(o===""||o===".."||o.startsWith(`..${y0}`))throw ce("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=oh(e),a=oh(t);while(!0){if((await Ni(a)).isSymbolicLink())throw ce("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=h0(a);if(c===a)throw ce("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function rd(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function vV(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function RV(e){await new Promise((t)=>setTimeout(t,e))}function ce(e,t,n){return new ye(e,t,n instanceof Error?{cause:Ba(n.message)}:{})}function no(e,t){let n=Sr(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=u_(i.pluginId,i.marketplaceName);return a?.canonicalPluginId===n?[{identity:a,entry:i}]:[]});return o.find((i)=>i.entry.pluginId===n&&i.entry.installed)??o.find((i)=>i.entry.installed)??o.find((i)=>i.entry.pluginId===n)??o[0]}function R0(e){return $m.includes(e)}function T0(e){if(!d0(kw,e))return c0(Ze("live official plugin list",e));return l0(Ue(kw,e,"live official plugin list"))}function sh(e){let t=e.runner??C0(e.executable,{environment:e.environment??Ai(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=async()=>{let o=await t.run(["plugin","list","--json"]);if(o.exitCode!==0)throw Oc("list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new ye("command_failed","Codex returned invalid plugin data.")}let a=T0(i);if(!a.ok)throw new ye("command_failed","Codex returned an invalid official plugin list.");return a.value},r=async()=>{let o=await t.run(["plugin","marketplace","list","--json"]);if(o.exitCode!==0)throw Oc("marketplace list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new ye("command_failed","Codex returned invalid marketplace data.")}if(!de(i)||!Array.isArray(i.marketplaces))throw new ye("command_failed","Codex returned an invalid marketplace list.");return i.marketplaces.map((a)=>{if(!de(a)||typeof a.name!=="string"||typeof a.root!=="string")throw new ye("command_failed","Codex returned an invalid marketplace entry.");let s=a.marketplaceSource;if(s===void 0)return{name:a.name,root:a.root};if(!de(s)||typeof s.sourceType!=="string"||typeof s.source!=="string")throw new ye("command_failed",`Codex returned an invalid source for marketplace ${a.name}.`);return{name:a.name,root:a.root,marketplaceSource:{sourceType:s.sourceType,source:s.source}}})};return{list:n,ensureOfficialMarketplace:async(o)=>{if(e.codexHome===void 0)throw new ye("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await S0({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:o,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(o,i)=>{let a=Ue(Va,o,"plugin marketplace source");if(a===nd||a===Wa)throw new ye("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.");if(a!==Aw)throw new ye("marketplace_invalid",`Unsupported managed marketplace source: ${a}.`);let s=await r(),c=f0(s,Cc);if(c!==void 0)throw new ye("marketplace_invalid",c);if(s.find((f)=>f.name===Cc)===void 0){let f=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(f.exitCode!==0)throw Oc("marketplace add",f,a)}else{let f=await t.run(["plugin","marketplace","upgrade",Cc],i===void 0?void 0:{signal:i});if(f.exitCode!==0)throw Oc("marketplace upgrade",f,Cc)}let u=await r(),d=f0(u,Cc);if(d!==void 0)throw new ye("marketplace_invalid",d);let p=u.find((f)=>f.name===Cc);if(p===void 0||!Iw(p.marketplaceSource))throw new ye("readback_mismatch","Codex did not report the canonical HolyCodex marketplace after installation or refresh.")},add:async(o,i)=>{let a=Ue(Va,o,"official plugin id"),s=await t.run(["plugin","add",a,"--json"],i===void 0?void 0:{signal:i});if(s.exitCode!==0)throw Oc("add",s,a);let c=await n(),l=no(c,a),u=Sr(a),d=[...c.installed,...c.available].filter((f)=>f.pluginId===a&&(u===void 0||f.marketplaceName==null)),p=l?.entry??d.find((f)=>f.installed)??d[0];if(!p)throw new ye("readback_mismatch",`Codex did not report ${a} after installation.`,{plugin_id:a});if(!p.installed)throw new ye("plugin_missing",`Codex reported ${a} as unavailable after installation.`,{plugin_id:a});if(!p.enabled)throw new ye("plugin_disabled",`Codex installed ${a} but it is disabled; enable it in Codex and retry.`,{plugin_id:a})},remove:async(o,i)=>{let a=Ue(Va,o,"official plugin id"),s=a;if(Sr(a)===a){let d=await n(),p=no(d,a);if(p?.entry.installed)s=p.entry.pluginId}let c=await t.run(["plugin","remove",s,"--json"],i===void 0?void 0:{signal:i});if(c.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(c.stderr))throw Oc("remove",c,s);let l=await n(),u=[...l.installed,...l.available].find((d)=>d.pluginId===s);if(u?.installed)throw new ye("readback_mismatch",`Codex still reports ${a} after removal.`,{plugin_id:a,observed_plugin_id:u.pluginId})}}}function Oc(e,t,n){let r=Ba(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new ye("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function f0(e,t){let n=e.filter((o)=>o.name===t);if(n.length>1)return`Multiple Codex marketplaces use the reserved name ${t}; resolve the duplicate configuration before installing HolyCodex.`;if(n[0]!==void 0&&!Iw(n[0].marketplaceSource)){let o=n[0].marketplaceSource?.source??"an unknown source";return`Codex marketplace ${t} points to ${o}, not the canonical HolyCodex source ${Aw}; resolve the conflict before installing.`}let r=e.find((o)=>o.name!==t&&Iw(o.marketplaceSource));if(r!==void 0)return`The canonical HolyCodex source is already registered as Codex marketplace ${r.name}; resolve the noncanonical marketplace name before installing.`;return}function Iw(e){if(e?.sourceType!=="git")return!1;return dV.some((t)=>t===e.source)}function C0(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>CV(e,i,{...t.environment===void 0?{}:{environment:t.environment},timeoutMs:a?.timeoutMs??n,stdoutLimit:r,stderrLimit:o,...a?.cwd===void 0?{}:{cwd:a.cwd},...a?.signal===void 0?{}:{signal:a.signal}})}}async function CV(e,t,n){if(n.signal?.aborted)throw new ye("cancelled","The Codex plugin command was cancelled.");let r=oV(e,[...t],{env:n.environment===void 0?void 0:{...n.environment},...n.cwd===void 0?{}:{cwd:n.cwd},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=m0(r.stdout,n.stdoutLimit),i=m0(r.stderr,n.stderrLimit),a=new Promise((d,p)=>{r.once("error",p),r.once("close",(f)=>d(f??-1))}),s,c,l=new Promise((d,p)=>{c=()=>{try{r.kill()}catch{}p(new ye("cancelled","The Codex plugin command was cancelled."))},n.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((d,p)=>{s=setTimeout(()=>{try{r.kill()}catch{}p(new ye("timeout","The Codex plugin command timed out."))},n.timeoutMs)});try{let[d,p,f]=await Promise.race([Promise.all([o,i,a]),l,u]);return{stdout:d,stderr:p,exitCode:f}}catch(d){try{r.kill()}catch{}if(d instanceof ye)throw d;throw new ye("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function m0(e,t){if(e===null)return Promise.reject(new ye("command_failed","Codex plugin command output is unavailable."));return new Promise((n,r)=>{let o=[],i=0;e.on("data",(a)=>{let s=typeof a==="string"?new TextEncoder().encode(a):a instanceof Uint8Array?a:void 0;if(s===void 0){r(new ye("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new ye("output_limit","Codex plugin output exceeded its limit."));return}o.push(s)}),e.once("end",()=>{let a=new Uint8Array(i),s=0;for(let c of o)a.set(c,s),s+=c.byteLength;try{n(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(c){r(c)}}),e.once("error",(a)=>r(a))})}var nd="openai-curated",Wa="https://github.com/openai/plugins.git",Cc="holycodex",Aw="davidbasilefilho/holycodex",dV,Mw,Nw=30000,pV=100,x0,fV,td,Va,mV,TV,Ew,kw,ye;var ch=b(()=>{ht();Dt();W_();to();rh();dV=[Aw,"https://github.com/davidbasilefilho/holycodex.git","https://github.com/davidbasilefilho/holycodex","https://github.com/davidbasilefilho/holycodex.git/","https://github.com/davidbasilefilho/holycodex/","git@github.com:davidbasilefilho/holycodex.git","git@github.com:davidbasilefilho/holycodex","ssh://git@github.com/davidbasilefilho/holycodex.git","ssh://git@github.com/davidbasilefilho/holycodex"],Mw=["plugins","openai-plugins"],x0=D.pipe(be(/^[a-z][a-z0-9._-]{1,63}$/u)),fV=D.pipe(be(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),td=K(D),Va=D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),mV=R({name:x0,version:fV,description:jo,author:v(Dn),license:v(jo),homepage:v(jo),repository:v(jo),keywords:v(td),skills:v(td),commands:v(td),hooks:v(td),assets:v(td),official:v(V)});TV=R({id:x0,selected:k(!0)}),Ew=R({pluginId:Va,installed:V,enabled:V,name:v(xe(D,It)),marketplaceName:v(xe(D,It)),version:v(xe(D,It))},Fm({key:D,value:Yb})),kw=R({installed:K(Ew),available:K(Ew)});ye=class ye extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});function Ec(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object")return!1;if(t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>Ec(n,t));return de(e)&&Object.values(e).every((n)=>Ec(n,t))}finally{t.delete(e)}}function vr(e){return de(e)&&Ec(e)}function qw(e){let t=[],n=0,r=!1,o=!1;for(let i=0;i<=e.length;i+=1){let a=e[i];if(i===e.length||a==="."&&!r){let s=e.slice(n,i),c=s.startsWith('"')?EV(s):s,l=s.startsWith('"'),u=l&&t.length===1&&t[0]==="plugins"&&Mm(Va)(c),d=l&&t.length===1&&t[0]==="agents"&&Dw.includes(c);if(l?!u&&!d:!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Dw.includes(c))throw Ze("TOML key path",e);if(c==="__proto__"||(c==="constructor"||c==="prototype")&&!u)throw Ze("TOML key path",e);t.push(c),n=i+1;continue}if(r){if(o)o=!1;else if(a==="\\")o=!0;else if(a==='"')r=!1}else if(a==='"')r=!0}if(r||o||t.length===0)throw Ze("TOML key path",e);return t}function EV(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Ze("TOML quoted key",e)}function fe(e,t){if(!vr(e))throw Ze("TOML document",e);let n=e,r=qw(t);for(let o=0;o<r.length;o+=1){let i=r[o];if(!vr(n)||!Object.prototype.hasOwnProperty.call(n,i))return;if(n=n[i],o===1&&r[0]==="features"&&i==="context_management"&&typeof n==="boolean"&&r[2]==="experimental_mode")return n}return n}function lh(e){if(Array.isArray(e))return e.map(lh);if(de(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,lh(n)]));return e}function uh(e){return lh(e)}function Li(e,t,n){if(!vr(e)||!Ec(n))throw Ze("TOML write",{keyPath:t});let r=qw(t),o={...uh(e)},i=o;for(let a of r.slice(0,-1)){let s=Object.prototype.hasOwnProperty.call(i,a)?i[a]:void 0;if(s!==void 0&&!vr(s)){if(a!=="context_management"||typeof s!=="boolean"||i!==o.features)throw Ze("TOML table path",t);if(r.at(-1)==="experimental_mode"&&s===n)return o;i[a]={experimental_mode:s}}let c=s===void 0?{}:vr(i[a])?{...i[a]}:{};i[a]=c,i=c}return i[r.at(-1)]=lh(n),o}function Rr(e,t){if(!vr(e))throw Ze("TOML document",e);let n=qw(t),r={...uh(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!vr(c))return r;let l={...c};o.push({table:i,key:s}),i[s]=l,i=l}let a=n.at(-1);if(!Object.prototype.hasOwnProperty.call(i,a))return r;delete i[a];for(let s=o.length-1;s>=0;s-=1){let c=o[s],l=c.table[c.key];if(vr(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function Ka(e){if(typeof e!=="string")return!1;if(E0.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Dw.some((t)=>e===`agents."${t}".config_file`)}function dh(e){return Ka(e)||Di.includes(e)}function Fi(e){return typeof e==="string"&&IV.test(e)}function $w(e){return e==="gpt-6-astra"||e==="gpt-6.1-sol"||e==="gpt-6-sol"||e==="gpt-6-luna"||e==="gpt-5.6-terra"||e==="gpt-5.6-sol"||e==="gpt-5.6-luna"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"||e==="default"||e==="fast"||e==="live"||e==="cached"||e==="indexed"||e==="disabled"}function PV(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function Uw(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function jw(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function Hw(e){if(!de(e)||!jw(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return $w(e.value);case"number":return Uw(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&mh(e.value);case"digest":return PV(e.value);default:return!1}}function O0(e,t){switch(Vw(e)){case"number":return t.kind==="number";case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"digest":return t.kind==="digest";case"enum":if(t.kind!=="enum")return!1;if(e==="model")return t.value==="gpt-6-astra"||t.value==="gpt-6.1-sol"||t.value==="gpt-6-sol"||t.value==="gpt-6-luna"||t.value==="gpt-5.6-terra"||t.value==="gpt-5.6-sol"||t.value==="gpt-5.6-luna";if(e==="model_reasoning_effort")return t.value==="low"||t.value==="medium"||t.value==="high"||t.value==="xhigh"||t.value==="max";if(e==="service_tier")return t.value==="default"||t.value==="fast";if(e==="web_search")return t.value==="live"||t.value==="cached"||t.value==="indexed"||t.value==="disabled";return t.value==="low"||t.value==="medium"||t.value==="high"}}function A0(e){return de(e)&&e.kind==="absent"?Object.keys(e).length===1:Hw(e)}function M0(e){return de(e)&&jw(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Fi(e.schema)&&Fi(e.installId)&&dh(e.keyPath)&&A0(e.originalValue)&&Hw(e.lastManagedValue)&&O0(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||O0(e.keyPath,e.originalValue))}function kc(e){if(!de(e)||!jw(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Fi(e.schema)||!Fi(e.installId)||!de(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>dh(t)&&M0(n)&&n.keyPath===t)}function fh(e){if(!Fi(e.schema)||!Fi(e.installId))throw Ze("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function mh(e){if(e.length===0||e.includes("\x00")||/^[\\/]|^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/").split("/");return t.some((n)=>n!==".")&&t.every((n)=>n.length>0&&n!=="..")}function Bw(e){if(!mh(e))throw Ze("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function Ja(e,t){let n=Bw(t),r=e.replaceAll("\\","/").split("/");r.pop();let o=[...r,...n.split("/")].join("/"),i=[];for(let c of o.split("/")){if(c.length===0||c===".")continue;if(c==="..")i.pop();else i.push(c)}let a=e.replaceAll("\\","/");return`${a.startsWith("//")?"//":a.startsWith("/")?"/":""}${i.join("/")}`}function Vw(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="agents.max_concurrent_threads_per_session")return"number";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="features.multi_agent"||e==="features.default_mode_request_user_input"||e==="features.multi_agent_v2"||e==="features.agent_message_board"||e==="features.context_management.experimental_mode"||Di.includes(e)||e==="sandbox_workspace_write.network_access")return"boolean";return"enum"}function AV(e,t){let n=Vw(e);if(n==="number")return Uw(t);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&mh(t);if(n==="digest")return typeof t==="string";if(e==="model")return t==="gpt-6-astra"||t==="gpt-6.1-sol"||t==="gpt-6-luna";return typeof t==="string"&&$w(t)}async function sn(e,t){if(!dh(e)||!Ec(t))throw Ze("managed config value",{keyPath:e});let n=Vw(e);if(n==="number"&&Uw(t))return{kind:n,value:t};if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&mh(t))return{kind:n,value:Bw(t)};if(n==="enum"&&typeof t==="string"&&$w(t))return{kind:n,value:t};return{kind:"digest",value:await Fn("holycodex-managed-config-value",[Nn({keyPath:e,value:t})])}}function MV(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function Ic(e,t,n,r){if(!vr(e)||!kc(t)||!Fi(r.schema)||!Fi(r.installId))throw Ze("managed runtime config",{});let o={...t.managed},i=uh(e),a=[];for(let[c,l]of Object.entries(n)){if(!Ka(c)||typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Ze("managed config key",c);let u=c,d=t.managed[u],p=fe(i,u);if(d&&(d.schema!==r.schema||d.installId!==r.installId)){a.push(u);continue}if(d&&d.owner==="holycodex"){let m=p===void 0?void 0:await sn(u,p);if(m===void 0||JSON.stringify(m)!==JSON.stringify(d.lastManagedValue)){a.push(u);continue}}let f=d?.originalValue??(p===void 0?{kind:"absent"}:await sn(u,p));if(!AV(u,l))throw Ze("managed config value",{keyPath:u});i=Li(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:f,lastManagedValue:await sn(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!kc(s))throw Ze("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Tr(e,t,n){if(!vr(e)||!kc(t))throw Ze("managed runtime config",{});let r=uh(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!dh(c))throw Ze("managed config key",c);let u=c;if(l.owner!=="holycodex"||l.schema!==n.schema||l.installId!==n.installId){if(l.schema!==n.schema||l.installId!==n.installId)s.push(u);continue}let d=fe(r,u);if(!(d!==void 0&&JSON.stringify(await sn(u,d))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=Rr(r,u),i.push(u),delete o[u];else{let f=MV(l.originalValue);if(f===void 0){s.push(u),a.push(u);continue}r=Li(r,u,f),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function Ga(e,t,n){if(!Ka(n)||!kc(t))throw Ze("managed config key",n);let r=t.managed[n],o=fe(e,n),i=o===void 0?void 0:await sn(n,o);if(!r)return i===void 0?{keyPath:n,status:"unmanaged"}:{keyPath:n,status:"unmanaged",current:i};return{keyPath:n,status:i!==void 0&&JSON.stringify(i)===JSON.stringify(r.lastManagedValue)?"unchanged":"drifted",expected:r.lastManagedValue,...i===void 0?{}:{current:i}}}var Dw,OV,za,E0,Di,kV,k0,I0,P0,ph,IV;var hh=b(()=>{ht();ht();Dt();to();ch();Dw=[...Uo,"Reviewer.plan"];OV=Q((e)=>Ec(e)),za=Q((e)=>vr(e));E0=["model","model_reasoning_effort","service_tier","agents.max_concurrent_threads_per_session","web_search","sandbox_workspace_write.network_access","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.multi_agent","features.default_mode_request_user_input","features.multi_agent_v2","features.agent_message_board","features.context_management.experimental_mode"],Di=["model_auto_compact_token_limit","features.context_management"],kV=Q((e)=>Ka(e));k0=Q((e)=>Hw(e)),I0=Q((e)=>A0(e)),P0=Q((e)=>M0(e)),ph=Q((e)=>kc(e)),IV=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function FV(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function N0(e,t,n){let r=new Set([...t,n]),o=Object.keys(e);if(Object.keys(e).some((i)=>!r.has(i)))return!1;return o.length>0&&o.every((i)=>FV(e[i]))}function D0(e){if(!de(e)||!Ye(e))return!1;return N0(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||N0(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function gh(e){return de(e)&&Ye(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function q0(e){return de(e)&&Ye(e)&&gh(e.thread)}function qV(e){return de(e)&&Ye(e)&&typeof e.id==="string"}function qi(e){return de(e)&&Ye(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function $0(e){return de(e)&&Ye(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||D0(e.usage))}function $V(e){return de(e)&&Ye(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>de(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>de(t)&&typeof t.id==="string"))&&(e.defaultServiceTier===void 0||e.defaultServiceTier===null||typeof e.defaultServiceTier==="string")&&(e.multiAgentVersion===void 0||e.multiAgentVersion===null||e.multiAgentVersion==="disabled"||e.multiAgentVersion==="v1"||e.multiAgentVersion==="v2")}function p0(e){if(Yu.some((t)=>t===e))return"permissions";if(Gu.some((t)=>t===e))return"approval";if(j_.some((t)=>t===e))return"elicitation";if(H_.some((t)=>t===e))return"dynamic_tool";return"other"}var F0,od,L0,Zu,NV,z_,Xu,LV,Xm,K_,J_,DV,Qu,G_,Y_,Z_,X_,Q_,ew,tw,nw,rw,ow,iw,aw,sw,cw,lw,uw,dw,pw,fw,mw,hw,gw,yw,xw,Sw,bw,_w,ww,_Q,UV,wQ;var vw=b(()=>{Dt();to();Zm();hh();F0=D.pipe(be(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),od=xe(D.pipe(xc(1)),vn.pipe(Ge((e)=>Number.isSafeInteger(e)))),L0=R({code:vn.pipe(Ge((e)=>Number.isSafeInteger(e))),message:D,data:v(Dn)}),Zu=xe(R({id:od,result:Dn}),R({id:od,error:L0})),NV=R({id:od,error:L0}),z_=R({method:F0,params:v(Dn)}),Xu=R({id:od,method:F0,params:v(Dn),trace:v(Dn)});LV=Q(D0),Xm=R({clientInfo:R({name:jo,version:jo,title:xe(jo,It)}),capabilities:xe(R({experimentalApi:V,requestAttestation:V,mcpServerOpenaiFormElicitation:v(V),optOutNotificationMethods:v(xe(K(D),It)),extensions:v(Pi)}),It)}),K_=Q((e)=>de(e)&&Ye(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),J_=R({method:k("initialized")});DV=Q(gh);Qu=Q((e)=>q0(e)||qV(e)),G_=Qu,Y_=Qu,Z_=Q(qi),X_=Q((e)=>de(e)&&Ye(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),Q_=Q((e)=>q0(e)),ew=Q((e)=>{if(!de(e)||!Ye(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>gh(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>gh(r));return t&&e.threads===void 0||n&&e.data===void 0}),tw=Q((e)=>de(e)&&Ye(e));nw=Q(qi),rw=Q(qi),ow=Q(qi),iw=Q((e)=>de(e)&&Ye(e));aw=Q((e)=>qi(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Ye(t))||typeof e.prompt==="string"&&e.prompt.length>0)),sw=Q((e)=>qi(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Ye(t))),cw=Q((e)=>de(e)&&Ye(e)&&(e.turn!==void 0&&$0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),lw=Q((e)=>de(e)&&Ye(e)&&typeof e.turnId==="string"&&e.turnId.length>0),uw=Q((e)=>qi(e)&&typeof e.turnId==="string"&&e.turnId.length>0),dw=Q((e)=>de(e)&&Ye(e)),pw=Q((e)=>qi(e)&&(e.turn!==void 0&&$0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),fw=Q((e)=>de(e)&&Ye(e));mw=Q((e)=>de(e)&&Ye(e)&&Array.isArray(e.data)&&e.data.every((t)=>$V(t))),hw=Pi,gw=Pi,yw=R({includeLayers:v(V),cwd:v(xe(D,It))}),xw=R({config:za,origins:Pi,layers:xe(K(Pi),It)}),Sw=Pi,bw=Pi,_w=Q((e)=>de(e)&&Ye(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&de(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),ww=Dn,_Q=Q((e)=>de(e)&&Ye(e)&&typeof e.kind==="string"&&typeof e.method==="string");UV=xe(k("stable","experimental","disabled"),V),wQ=Fm({key:D,value:UV})});import{lstat as TQ,mkdir as CQ,readFile as jV,readdir as OQ,realpath as HV,stat as BV}from"fs/promises";import{delimiter as VV,isAbsolute as kQ,join as IQ,relative as PQ,resolve as U0}from"path";async function zV(e){let t=[];if(e.executablePath!==void 0)t.push(U0(e.cwd??process.cwd(),e.executablePath));else{let n=e.pathValue??e.environment?.PATH??process.env.PATH??"",r=process.platform==="win32"?["codex.exe","codex.cmd","codex"]:["codex"];for(let o of n.split(VV).filter((i)=>i.length>0))for(let i of r)t.push(U0(o,i))}for(let n of t)try{let r=await BV(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await HV(n)}catch{if(e.executablePath!==void 0)throw new oe("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new oe("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function KV(e,t){let n=Bun.spawn([e,"--version"],{env:t,stdin:"ignore",stdout:"pipe",stderr:"pipe"});if(!(n.stdout instanceof ReadableStream)||!(n.stderr instanceof ReadableStream))throw new oe("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await GV(Promise.all([eh(n.stdout,16384),eh(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=Ln(th(r,"Codex version output"));if(i!==0||a.length===0){let s=Ba(th(o,"Codex version diagnostics"));throw new oe("discovery_failed","The Codex executable did not provide a version.",{exitCode:i,diagnostics:s})}return a}catch(r){try{n.kill()}catch{}if(r instanceof oe)throw r;throw new oe("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function JV(e){let t=await jV(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=Um(r);if(!o.ok)throw new oe("discovery_failed","The Codex executable digest was invalid.");return o.value}async function Ww(e={}){let t=await zV(e),n=Ai(e.environment),r=e.versionRunner?Ln(await e.versionRunner(t,n)):await KV(t,n);if(r.length===0)throw new oe("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await JV(t)}}async function GV(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new oe("timeout",n))},WV)})])}finally{if(r!==void 0)clearTimeout(r)}}var WV=30000,FQ;var j0=b(()=>{ht();Dt();to();rh();FQ=R({exitCode:vn.pipe(Ge((e)=>Number.isSafeInteger(e))),stdout:D.pipe(t_(1048576)),stderr:D.pipe(t_(1048576))})});var YV="packages/codex/generated",ZV,XV,zw,$Q,UQ;var H0=b(()=>{ht();Dt();to();ZV=/^codex-cli \d+\.\d+\.\d+$/u,XV=/^codex-app-server-\d+\.\d+\.\d+$/u,zw=D.pipe(be(/^[a-f0-9]{64}$/u)),$Q=R({schema_version:k("holycodex-generated-v2"),artifact_root:k(YV),codex_cli_version:D.pipe(be(ZV)),codex_cli_digest:zw,protocol_epoch:D.pipe(be(XV)),generator:R({command:tN(k("app-server"),k("generate-ts")),supported_surface:k("codex app-server generators")}),typescript_root:k("typescript"),files:R({count:vn.pipe(Lm(),r_()),digest:zw})}),UQ=R({path:D.pipe(xc(1)),size:vn.pipe(Lm(),r_()),sha256:zw})});var QV;var B0=b(()=>{Dt();hh();QV=R({owner:k("holycodex"),schema:D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});var Ya=b(()=>{to();to();Zm();vw();W_();rh();j0();H0();B0();hh();ch();ch()});function cn(e){if(!Pc(e))throw Error("The value is not JSON serializable.");return Mn(e),e}function Pc(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object"||t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>Pc(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>Pc(n,t))}finally{t.delete(e)}}var cd=b(()=>{ht()});function Ie(e,t){let n=Zn(e,t);return Tt(n)?n.right:void 0}function Q0(e){return Ie(ld,e)!==void 0}var ld,Pee,lW,uW,ud,dW,Ui,pW,fW,mW,z0,dd,Sh,K0,pd,J0,tn,Yw,hW,gW,yW,xW,SW,bW,_W,wW,vW,xh,RW,W0,TW,bh,Ac,CW,Zw,OW,Xw,EW,G0,Qw,ev,ji,Y0,kW,Z0,IW,X0;var Za=b(()=>{Ya();ht();yn();Dt();cd();ld=Q((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&Pc(e)),Pee=Q(Pc),lW=_c,uW=D.pipe(be(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),ud=D.pipe(be(/^[0-9a-f]{64}$/u)),dW=D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Ui=D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),pW=D.pipe(Ge((e)=>!Number.isNaN(Date.parse(e)))),fW=R({path:D.pipe(be(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:ud}),mW=R({browser_use:V,computer_use:V,sites:V,coding:k(!0)}),z0=R({browser_use:v(V),computer_use:v(V),sites:v(V)}),dd=R({profile:v(Xr),tier:v(qo),optional:v(z0),officialPlugins:v(K(Ui))}),Sh=dd,K0=k("keep","remove","replace","cancel"),pd=R({schema_version:k(1),profile:Xr,tier:qo,capabilities:K(c_),additional_plugins:K(Ui)}),J0=R({schema_version:k(1),profile:Xr,tier:qo,capabilities:K(ju),additional_plugins:K(Ui)}),tn=R({selected:V,status:k("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:K(Ui),reason:v(D)}),Yw=R({browser_use:tn,computer_use:tn,frontend:tn,security:tn,sites:tn}),hW=R({browser_use:v(V),computer_use:V,frontend:V,security:V,sites:v(V),coding:k(!0),work:V}),gW=R({browser_use:v(V),computer_use:v(V),frontend:v(V),security:v(V),sites:v(V),work:v(V)}),yW=R({browser_use:v(tn),computer_use:tn,frontend:tn,security:tn,sites:v(tn),work:tn}),xW=R({computer_use:V,frontend:V,security:V,coding:k(!0)}),SW=R({computer_use:v(V),frontend:v(V),security:v(V)}),bW=R({computer_use:tn,frontend:tn,security:tn}),_W=xe(R({status:k("not_applicable")}),R({status:k("missing")}),R({status:k("healthy"),path:D,installed:V})),wW=R({manager:k("bun","npm","pnpm"),launcher:k("bunx","npx","pnpm dlx"),version:uW,executable:D,ownership:k("user","holycodex"),identity:v(ud)}),vW=R({git_bash:_W,context7:v(wW)}),xh=R({presence:k("absent","present"),digest:ud,safe_value:v(xe(R({kind:k("boolean"),value:V}),R({kind:k("marketplace"),source_type:k("git"),source:k("https://github.com/davidbasilefilho/holycodex.git")})))}),RW=R({plugin_id:k("holycodex@holycodex"),before:R({preference:xh,marketplace:xh}),after:R({preference:xh,marketplace:xh})}),W0=R({presence:k("absent","present"),digest:ud,safe_value:v(R({kind:k("boolean"),value:V}))}),TW=R({plugin_id:Ui,before:W0,after:W0}),bh={owner:k("holycodex"),schema_epoch:k(Tn),install_id:dW,version:lW,digest:ud,profile:Xr,tier:qo,optional_selections:mW,explicit_optional_selections:z0,official_plugins:v(K(Ui)),capability_state:v(Yw),managed_artifacts:K(fW),installed_at:pW,status:v(k("active")),step:v(k("active")),managed_config:v(ph),plugin_snapshot:v(K(R({plugin_id:Ui,status:k("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:v(RW),provider_config:v(K(TW)),owned_plugins:v(K(Ui)),tooling:v(vW)},Ac=R(bh),CW=(({profile:e,...t})=>t)(bh),Zw={...bh,optional_selections:hW,explicit_optional_selections:gW,capability_state:v(yW)},OW=(({profile:e,...t})=>t)(Zw),Xw={...bh,optional_selections:xW,explicit_optional_selections:SW,capability_state:v(bW)},EW=(({profile:e,...t})=>t)(Xw),G0=xe(R({...Zw,profile:_r}),R({...OW,plan:_r}),R({...CW,plan:_r}),R({...Xw,profile:_r}),R({...EW,plan:_r})),Qw=k("preparing","conflicted"),ev=k("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),ji=R({...Ac.fields,status:Qw,step:ev}),Y0={...Zw,status:Qw,step:ev},kW=(({profile:e,...t})=>t)(Y0),Z0={...Xw,status:Qw,step:ev},IW=(({profile:e,...t})=>t)(Z0),X0=xe(ji,R({...Y0,profile:_r}),R({...kW,plan:_r}),R({...Z0,profile:_r}),R({...IW,plan:_r}))});import{lstat as PW,mkdir as AW}from"fs/promises";import{homedir as MW}from"os";import{dirname as NW,join as Hi,posix as eF,resolve as FW,sep as tF,win32 as nF}from"path";function Cr(e={},t=process.env){let n=MW(),r=e.paths?.codexHome??t.CODEX_HOME??Hi(n,".codex"),o=nv(r,"CODEX_HOME"),i=Hi(o,LW);return{codexHome:o,stateRoot:i,activeRecord:Hi(i,DW),preparingRecord:Hi(i,qW),conflictedRecord:Hi(i,$W),installOptions:Hi(i,UW),roleRoot:Hi(i,"agents"),configFile:Hi(o,"config.toml")}}function nv(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||HW(e))throw new Qn("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?nF:eF,o=tv(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new Qn("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":tF).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new Qn("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new Qn("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function HW(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function Mc(e){nv(e,"owned path"),await Ho(e),await AW(e,{recursive:!0}),await Ho(e)}async function Ho(e){let n=FW(e);while(!0){try{if((await PW(n)).isSymbolicLink())throw new Qn("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof Qn)throw o;if(!Xe(o,"ENOENT"))throw o}let r=NW(n);if(r===n)break;n=r}}async function Xa(e){await Ho(e)}function Or(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?nF:eF,o=r.resolve(tv(e,n)),i=r.resolve(tv(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":tF}`)&&a!==".."&&!r.isAbsolute(a)}function tv(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function Xe(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var LW="holycodex",DW="active.json",qW="preparing.json",$W="conflicted.json",UW="install.toml",jW,Qn;var Qa=b(()=>{ht();jW=Tn;Qn=class Qn extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as rF,open as BW,readFile as oF,rename as VW,unlink as WW,writeFile as zW}from"fs/promises";import{dirname as KW}from"path";async function iF(e){let t;try{t=await BW(e,"r"),await t.sync()}catch(n){if(!aF(n))throw n}finally{await t?.close().catch(()=>{return})}}async function GW(e){await iF(e).catch((t)=>{if(!aF(t))throw t})}async function ts(e,t){await qn(e,`${Mn(t)}
36
- `)}async function qn(e,t){let n=KW(e);await Mc(n),await Ho(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await zW(r,t,{encoding:"utf8",mode:384}),await iF(r),await VW(r,e),await GW(n)}catch(o){throw await WW(r).catch(()=>{return}),o}}async function YW(e,t){let n=await rF(e);if(!n.isFile()||n.isSymbolicLink())throw new es("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await oF(e,"utf8"))}catch(i){throw new es("state_corrupt","A persisted file is not valid JSON.",i)}let o=Ie(t,r);if(o===void 0)throw new es("state_corrupt","A persisted file failed schema validation.");return o}async function je(e){try{let t=await rF(e);if(!t.isFile()||t.isSymbolicLink())throw new es("state_corrupt","A persisted file is not a regular file.");return await oF(e,"utf8")}catch(t){if(Xe(t,"ENOENT"))return;throw t}}async function rv(e,t){try{return await YW(e,t)}catch(n){if(Xe(n,"ENOENT"))return;throw n}}function aF(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return JW.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var JW,es;var Nc=b(()=>{ht();Qa();Za();JW=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);es=class es extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as ZW}from"fs/promises";import{dirname as XW,resolve as QW}from"path";import{fileURLToPath as ez}from"url";async function sF(e=ns){let t=JSON.parse(await ZW(e,"utf8")),n=Ie(tz,t);if(n===void 0)throw new Bo("manifest_invalid","The public package manifest is invalid.");return n}async function Fc(e=ns){let t=(await sF(e)).version,n=Ie(_c,t);if(n===void 0)throw new Bo("manifest_invalid","The public package manifest version is invalid.");return n}async function cF(e=ns){let t=await Fc(e),n=Ie(bc,t);if(n===void 0)throw new Bo("manifest_invalid","The public package manifest must use a canonical stable release version.");return n}async function nz(e=ns){let n=(await Fc(e)).split("-",1)[0],r=Ie(a_,n);if(r===void 0)throw new Bo("manifest_invalid","The public package manifest must use a canonical release base version.");return r}async function fd(e=ns){return await Fc(e)}async function ov(e,t,n=ns){let r=await sF(n),o=await cF(n),i=rz(e,o);if(!t)await ts(n,{...r,version:i});return{previous:o,next:i}}function rz(e,t){if(e!=="patch"&&e!=="minor"){if(Ie(bc,e)===void 0)throw new Bo("version_invalid","The version target is invalid.");return e}try{return s_(e,t)}catch(n){throw new Bo("version_invalid",n instanceof Error?n.message:"The current version is invalid.")}}var tz,ns,Bo;var md=b(()=>{ht();Dt();Za();Nc();tz=Q((e)=>Q0(e)&&e.name==="holycodex"&&Ie(_c,e.version)!==void 0),ns=QW(XW(ez(import.meta.url)),"../package.json");Bo=class Bo extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as oz}from"crypto";import{lstat as iv,readFile as av,rm as _h}from"fs/promises";import{join as At,relative as lF}from"path";async function vh(e,t,n=[],r="standard",o,i={}){let a=rs(t,r,{...i,...o===void 0?{}:{windowsGitBashExecutable:o}}),s=At(e,"holycodex","agents",a),c=Vo(t,r).map((d)=>({path:At(s,`${d.name}.toml`),contents:Lc(d,{...i,...o===void 0?{}:{windowsGitBashExecutable:o}})})),l=new Map(n.map((d)=>[At(e,d.path),d])),u=[];for(let d of c){let p=await Bi(d.path),f=l.get(d.path);if(p!==void 0&&f===void 0&&p!==d.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${d.path}`);if(p!==void 0&&f!==void 0&&await Kt(p)!==f.digest&&p!==d.contents)u.push(dv(d.path,"replace",{present:!0,digest:await Kt(p)},{present:!0,digest:await Kt(d.contents)},"The managed native role file changed outside the previous HolyCodex transaction."))}return u}async function uF(e,t){let n=At(e,"agents"),r=At(e,"holycodex","agents"),o=[];for(let i of t){let a=At(e,i.path);if(!Or(e,a)||!Or(n,a)&&!Or(r,a)&&a!==At(e,"config.toml"))continue;let s=await Bi(a);if(s!==void 0&&await Kt(s)!==i.digest)o.push({...dv(a,"remove",{present:!0,digest:await Kt(s)},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}return o}async function dF(e,t){let n=At(e,"agents"),r=At(e,"holycodex","agents"),o=[];for(let[i,a]of t){if(!Or(e,i)||!Or(n,i)&&!Or(r,i)){o.push(i);continue}let s=await Bi(i);if(s!==void 0&&await Kt(s)!==a)o.push(i)}return o}function Vo(e,t="standard"){let n=eo(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:S_(o),description:__(o),taskInstruction:b_(o),permissions:w_(o),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function rs(e,t="standard",n={}){let r=Vo(e,t).map((o)=>`${o.name}\x00${Lc(o,n)}`).join("\x00");return oz("sha256").update(r).digest("hex").slice(0,20)}function hd(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function sv(e,t="standard"){let n=eo(e);if(!n.ok)throw Error("Unknown profile.");return{name:"root",description:"Root-directed HolyCodex control agent.",model:n.value.root.model,effort:n.value.root.effort,serviceTier:t==="fast-all"?"fast":"default"}}function cv(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!W.requiresDelegation||!W.assignmentStartAndDispatchPrecedeDelegableExecution||!W.trivialWorkRequiresDelegation||!W.preparatoryAndExploratoryWorkRequiresDelegation||W.genericDirectWorkFallback||W.directExecutionExceptions!==W.rootOwnedAuthority||!W.codeReviewRequiredForImplementation||!W.codeReviewRequiredBeforeVcs||!W.externalVerificationMustBeTerminal||!W.concreteSpecialistDispatchRequired||!W.roleFamiliesAreLabelsOnly||!W.missingConcreteRouteIsBlocker||!W.normalSpawnRequiresExplicitForkTurns||W.normalSpawnForkTurns!=="none"||!W.normalSpawnUsesConcreteRegisteredAgentType||!W.assignmentContextIsTaskSpecificOnly||!W.configuredRouteModelAndEffortPreserved||W.normalProgressMessages||W.normalHeartbeatMessages||W.normalIntermediateEvidence||!W.userUpdatesUsefulOrImportantOnly||!W.routinePerToolOrSubagentNarrationForbidden||!W.routineStatusOnlyChatterForbidden||!W.fixedCadenceUserUpdatesForbidden||!W.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!W.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!W.materialUserUpdateKinds.includes("release_milestones")||!W.outOfBoundaryRequiresNewAssignment||!W.longestPracticalEventWait||!W.busyPollingForbidden||!W.statusOnlyCoordinationLoopsForbidden||!W.batchIndependentLifecycleActions||!W.releaseLeavesAfterAcceptedOutcome||W.routineWaitTool!=="collaboration.wait_agent"||!Number.isSafeInteger(W.routineWaitMaximumTimeoutMs)||W.routineWaitMaximumTimeoutMs<=0||!W.routineWaitUsesMaximumRuntimeTimeout||!W.earlySpecialistCompletionWakesWait||!W.collectiveMailboxIncludesRelevantAgents||!W.idleTimeoutRepeatsMaximumWait||!W.shortRoutineWaitsForbidden||!W.evidenceFirstConciseStructuredReports||W.specialistReportFields.length===0||W.rootLargeReadsOnlyFor.length===0||!W.stableFactsReused||!W.duplicatePolicyForbidden||!W.stableBoundedComponentScopesAreCanonical||!W.lifecycleWorkerOwnsDeterministicApi||W.registeredSpecialistAgentTypes!==Uo||W.forbiddenGenericAgentTypes!==zm)throw Error("The Root orchestration policy is incomplete.");let n=[...t.windowsGitBashExecutable===void 0?[]:[uv(t.windowsGitBashExecutable)],`You are the HolyCodex Root/session orchestrator. Never perform delegable work yourself unless the user explicitly requests direct execution or forbids delegation. Root owns ${W.rootOwnedAuthority.map((r)=>az[r]).join("; ")}, within authorization and capability boundaries.`,`Delegate ${W.delegableActions.map((r)=>sz[r]).join("; ")} through bounded Assignments. Bundle related trivial and preparatory steps into a coherent Assignment rather than spawning per action.`,W.routeConfigurationBeforeDispatch,W.assignmentInvocationLifecycle,`For normal specialist spawns, set fork_turns: "${W.normalSpawnForkTurns}". Give each specialist a self-contained Assignment with objective, bounded scope, constraints, dependencies, acceptance criteria, and evidence needed for acceptance.`,`Dispatch each Assignment to its exact concrete registered Role.task agent_type. Registered targets: ${W.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are labels only; generic built-in agent_type values ${W.forbiddenGenericAgentTypes.join(", ")} are forbidden.`,W.semanticStateBoundary,"User instructions take precedence over skill guidelines. Infer intent from the request and session; carry authorized work through its requested terminal state. Ask only when missing information materially changes the outcome or authorization for a consequential effect is missing. Before orchestration, ask material unresolved questions in waves and in the user's language. Never ask what the session already establishes. If none remain, dispatch immediately. Check existing authorization before asking again. Continue independent work while an answer is pending; prepare the concrete reviewable result before requesting any remaining approval. Credential entry remains user-owned.","Dispatch independent non-conflicting Assignments concurrently as soon as their inputs are ready, including across workflow phases. Order actual dependencies and shared writes. Reuse accepted findings instead of repeating discovery. Batch independent tool reads and lifecycle work where supported; keep revisions and dependent writes ordered. Resolve material contradictions before acceptance.","Delegate ordinary browser and computer execution. For visual tasks, Root uses visual-loop to inspect the current render and judge it, then assigns repairs; use dev-server when a shared background server is needed. Use only selected capabilities available in the active surface and honor its tool precedence. Report a capability blocker without inventing a provider or widening authority.",uz(t),"Use writing-instructions for model-facing contracts. Keep each meaning with one authoritative owner and add only the missing semantic delta for the receiver.","Give the user useful updates for significant findings, decisions, blockers, input needs, and release milestones; avoid per-tool, status-only, heartbeat, or fixed-cadence messages.",lz,`${Vu.rule} ${cz}`,"After integration, Root owns approved VCS writes. For PR or release gates use babysit-ci and dispatch Worker.operations for exact-ref terminal evidence. Pending gates are not complete."];if(t.frontend??!0)n.push(dz());if(t.security??!0)n.push("For security-sensitive changes, use the relevant security review skills before VCS. Validate supported findings; repair introduced or worsened vulnerabilities before VCS unless explicitly risk-accepted. Keep security review current after relevant repairs.");return n.join(`
37
- `)}function uz(e){return`For Root visual judgment, use ${[...e.browserUse?["the in-app browser (IAB)"]:[],...e.computerUse?["Computer Use"]:[],"other available rendered evidence such as screenshots or image tools"].join("; if unavailable, use ")}. Unselected capabilities are not fallbacks. Honor higher-priority active-surface tool rules.`}function dz(){if(!Qr.repositoryAndUserRequirementsPrecedePluginDefaults||!Qr.specialistsOwnImplementationAndInteractionProof||!Qr.rootOwnsVisualJudgment||!Qr.rootOwnsSharedDevServer||!Qr.rootAcceptsTerminalVisualEvidence||!Qr.sourceChangesInvalidateRenderEvidence||!Qr.specialistReportsIncludeObservableRenderedEvidence||Qr.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`For frontend work, ${Do.frontend.applicability.map(({skillId:n,appliesWhen:r})=>`${r} uses ${n}`).join("; ")}. Follow the repository stack, design system, and user requirements. Specialists implement and prove interactions; Root judges current renders with visual-loop for visual changes and assigns discrepancies. Refresh affected visual evidence after relevant changes. Logic-only changes do not require a visual loop. Check responsive layout, accessibility, and interactions in proportion to the change.`}async function lv(e,t,n=[],r="standard",o,i,a=[],s={}){let c=rs(t,r,{...s,...o===void 0?{}:{windowsGitBashExecutable:o}}),l=At(e,"holycodex","agents",c),u=[],d=[],p=Vo(t,r).map((_)=>({path:At(l,`${_.name}.toml`),contents:Lc(_,{...s,...o===void 0?{}:{windowsGitBashExecutable:o}})})),f=new Map(n.map((_)=>[At(e,_.path),_])),m=new Map,y=new Set,g=new Set,x=new Map;for(let _ of p){let I=await Bi(_.path);m.set(_.path,I);let q=a.find((C)=>C.path===_.path&&C.action==="replace"&&C.key===void 0);if(q!==void 0){let C=mz(q);if(C===void 0||I===void 0||await Kt(I)!==C)throw Error(`The native role conflict changed after review; review the latest file and retry: ${_.path}`);if(x.set(_.path,C),q.decision==="keep")g.add(_.path);else y.add(_.path)}let O=f.get(_.path);if(I!==void 0&&O===void 0&&I!==_.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${_.path}`);if(I!==void 0&&O!==void 0){let C=await Kt(I);if(C!==O.digest&&I!==_.contents){let N=dv(_.path,"replace",{present:!0,digest:C},{present:!0,digest:await Kt(_.contents)},"The managed native role file changed outside the previous HolyCodex transaction."),w=q===void 0?await i?.(N):q.decision==="keep"?"decline":"accept";if(w==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${_.path}`);if(w==="accept"||w==="decline"){let A=await Kt(I),E=await Bi(_.path);if(E===void 0||await Kt(E)!==A)throw Error(`The native role conflict changed after review; review the latest file and retry: ${_.path}`);if(x.set(_.path,A),w==="accept")y.add(_.path);else g.add(_.path)}}}}let P=[];try{for(let O of p){let C=m.get(O.path),N=f.get(O.path),w=x.get(O.path);if(w!==void 0){let A=await Bi(O.path);if(A===void 0||await Kt(A)!==w)throw Error(`The native role conflict changed after review; review the latest file and retry: ${O.path}`)}if(g.has(O.path)){if(N!==void 0)u.push(O.path),P.push(N);continue}if(C!==void 0&&N!==void 0){if(await Kt(C)!==N.digest&&C!==O.contents&&!y.has(O.path)){u.push(O.path),P.push({path:lF(e,O.path).replaceAll("\\","/"),digest:N.digest});continue}}if(C===void 0||C!==O.contents)await qn(O.path,O.contents),d.push({path:O.path,previous:C,installedDigest:await Kt(O.contents)});P.push({path:lF(e,O.path).replaceAll("\\","/"),digest:await Kt(O.contents)})}let _=At(e,"agents","root.toml"),I=await Bi(_),q=await pF(_);if(q==="preserved")u.push(_);if(q==="removed"&&I!==void 0)d.push({path:_,previous:I,installedDigest:void 0});for(let O of n){let C=At(e,O.path);if(!p.some((N)=>N.path===C))P.push(O)}return{managed_artifacts:P,preserved:u,rollback:d}}catch(_){throw await Rh(d).catch(()=>{return}),_}}async function Rh(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await Bi(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await Kt(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await _h(r.path,{force:!1}).catch((a)=>{if(!Xe(a,"ENOENT"))throw a}),t.push(r.path);else await qn(r.path,r.previous)}return{removed:t,preserved:n}}async function Th(e,t,n=new Map){let r=[],o=[],i=At(e,"agents"),a=At(e,"holycodex","agents");for(let l of t){let u=At(e,l.path);if(!Or(e,u)||!Or(i,u)&&!Or(a,u)&&u!==At(e,"config.toml")){o.push(u);continue}try{await Ho(u);let d=await iv(u);if(d.isSymbolicLink()||!d.isFile()){o.push(u);continue}let p=await av(u),f=await Kt(p);if(f!==l.digest){let m=n.get(u);if(m!==void 0&&f===m){await _h(u,{force:!1}),r.push(u);continue}o.push(u);continue}await _h(u,{force:!1}),r.push(u)}catch(d){if(!Xe(d,"ENOENT"))o.push(u)}}let s=At(e,"agents","root.toml"),c=await pF(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);return{removed:r,preserved:o}}function Lc(e,t={}){let n=[...t.windowsGitBashExecutable===void 0?[]:[uv(t.windowsGitBashExecutable)],iz,e.taskInstruction,...e.permissions.sourceMutation?[`Patch quality: ${Vm}`]:[],...t.browserUse?["Use Browser Use only for this Assignment and only when the capability is actually available in the current Codex surface/runtime. Never assume support or substitute another provider; report unavailability as a blocker. Tool availability does not grant authority, and consequential external effects remain Root-owned."]:[],...t.computerUse?["Use Computer Use only for this Assignment and only when the capability is actually available in the current Codex surface/runtime. Its platform restrictions and ability to cause external actions require explicit task authority. Never assume support or substitute another provider; report unavailability as a blocker. Tool availability does not grant authority. Credential entry and submission remain user-owned; never request, enter, retrieve, expose, or store credentials."]:[]].join(`
38
- `);return[`name = ${JSON.stringify(e.name)}`,`description = ${JSON.stringify(e.description)}`,`model = ${JSON.stringify(e.model)}`,`model_reasoning_effort = ${JSON.stringify(e.effort)}`,`service_tier = ${JSON.stringify(e.serviceTier)}`,'model_reasoning_summary = "none"','model_verbosity = "low"',`sandbox_mode = ${JSON.stringify(wh(e))}`,'approval_policy = "never"','web_search = "live"',`developer_instructions = ${JSON.stringify(n)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent = false","multi_agent_v2 = false","agent_message_board = false","[features.context_management]","experimental_mode = true","",...wh(e)==="workspace-write"?["[sandbox_workspace_write]","network_access = true"]:[],""].join(`
39
- `)}function uv(e){if(e===void 0||e.trim().length===0)throw Error("Git Bash executable is required.");return`On Windows, set the shell parameter to exactly ${JSON.stringify(e)} for every shell command, including read-only commands; never rely on the default shell. Run all shell actions in the verified Git for Windows Bash environment there. If that environment is unavailable or inactive, stop and report the mismatch; never fall back to another shell.`}function wh(e){return e.permissions.filesystem}function Ch(e,t){return t.sandbox_mode===wh(e)&&t.default_permissions===void 0&&(wh(e)==="workspace-write"?fe(t,"sandbox_workspace_write.network_access")===!0:fe(t,"sandbox_workspace_write.network_access")===void 0)}function pz(e,t,n){return['name = "root"','description = "Root-directed HolyCodex control agent."',`model = ${JSON.stringify(e)}`,`model_reasoning_effort = ${JSON.stringify(t)}`,`service_tier = ${JSON.stringify(n)}`,'model_verbosity = "low"',""].join(`
40
- `)}function Dc(e){return fz.has(e)}async function pF(e){try{await Ho(e);let t=await iv(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await av(e,"utf8");if(!Dc(n))return"preserved";return await _h(e,{force:!1}),"removed"}catch(t){if(Xe(t,"ENOENT"))return"absent";throw t}}async function Bi(e){try{await Ho(e);let t=await iv(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await av(e))}catch(t){if(Xe(t,"ENOENT"))return;throw t}}async function Kt(e){let t=typeof e==="string"?new TextEncoder().encode(e):e,n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),(r)=>r.toString(16).padStart(2,"0")).join("")}function dv(e,t,n,r,o){return{identity:`role-asset:${e}:${t}`,category:"role-asset",target:e,existing:n,desired:r,defaultDecision:"replace",validDecisions:["keep","replace","cancel"],explanation:o,path:e,action:t}}function mz(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var iz,az,sz,cz="Before acceptance or VCS writes, require a Reviewer.code fixed point and current relevant validation. Review and validation may overlap on non-conflicting scopes; serialize repairs against checks of the same source. Reuse worker proof and assign Worker.validation only for independent proof or an evidence gap. Repairs invalidate only affected evidence.",lz,fz;var Oh=b(()=>{Ya();ht();Qa();Nc();iz=[`Execute the bounded Assignment through its acceptance criteria; make routine in-scope choices without asking. ${Vu.rule} Return material decisions or scope expansion to Root. Do not message Root or peers during execution, delegate, change Intent lifecycle, or perform external effects. Read-only Git/VCS, CI, and PR-comment inspection is allowed when relevant and within the Assignment; Git/VCS writes remain Root-only. Source mutation requires permission from the concrete task; proof and cache writes do not grant it. Preserve others' work in the shared tree and adapt to their changes. Root owns the shared background dev server and visual judgment; do not run dev-server or visual-loop.`,"Do not recover an Assignment or mutate another Assignment's lifecycle. Root keeps active invocation capabilities and records terminal results; never request or use those capabilities.",`Return only one compact, evidence-first terminal outcome (${W.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${W.specialistReportFields.join(", ")}.`].join(" "),az={user_interaction:"user interaction",intent:"Intent",material_decisions:"material decisions",orchestration_lifecycle:"orchestration and lifecycle",integration_acceptance:"integration acceptance",completion:"completion",git_vcs:"Git/VCS writes",external_effects:"external effects",visual_judgment:"visual judgment and its browser inspection",dev_server:"the shared background dev server"},sz={repository_discovery:"repository discovery",file_source_test_doc_inspection:"file, source, test, and documentation inspection",fact_finding:"fact finding",research:"research",implementation:"implementation",debugging:"debugging",testing:"testing",validation:"validation",frontend_work:"frontend work",security_work:"security work",browser_use:"authorized Browser Use",computer_use:"authorized Computer Use",review:"review",ci_release_observation:"CI or release observation"},lz=`Wait for specialist results with ${W.routineWaitTool} at timeout_ms=${W.routineWaitMaximumTimeoutMs}; repeat after an idle timeout. Do not poll status or send routine progress messages. Release specialist leaves after accepting their terminal outcomes.`;fz=new Set([{model:"gpt-5.6-terra",effort:"high"},{model:"gpt-5.6-sol",effort:"low"},{model:"gpt-5.6-sol",effort:"medium"},{model:"gpt-5.6-sol",effort:"high"}].flatMap(({model:e,effort:t})=>["default","fast"].map((n)=>pz(e,t,n))))});import{access as hz,readFile as gz,readdir as yz}from"fs/promises";import{join as pv}from"path";class os{adapter;observedIdentities={};constructor(e){if("run"in e){let t=sh({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await Ww({environment:e}),n=sh({executable:t.path,environment:Rw(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new os(n)}async list(){try{return await this.adapter.list()}catch(e){throw gd("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw gd("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw gd("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw gd("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw gd("add",t,e)}}async status(e){let t=await this.list(),n={},r=new Map;for(let i of[...t.installed,...t.available])if(!r.has(i.pluginId)||i.installed)r.set(i.pluginId,i);let o=Object.fromEntries(await Promise.all(e.map(async(i)=>{let a=no(t,i),s=Sr(i),c=r.get(i),l=a?.entry??(s===void 0||c?.marketplaceName==null?c:void 0),u=a;if(l!==void 0)n[i]=u?.entry.pluginId??l.pluginId;let d=l===void 0?"missing":l.installed&&l.enabled?"installed":l.installed?"disabled":"missing";return[i,d]})));return this.observedIdentities=Object.freeze(n),o}getObservedIdentities(){return this.observedIdentities}}class Eh{codexHome;observedIdentities={};constructor(e){this.codexHome=e}async status(e){let t;try{t=await gz(pv(this.codexHome,"config.toml"),"utf8")}catch(c){if(fv(c))return this.observedIdentities=Object.freeze({}),Object.fromEntries(e.map((l)=>[l,"missing"]));throw c}let n=globalThis.Bun;if(!n?.TOML?.parse)throw Error("A TOML parser is unavailable.");let r=Ie(za,n.TOML.parse(t));if(r===void 0)throw Error("Codex configuration is invalid.");let o=r.plugins,i=typeof o==="object"&&o!==null&&!Array.isArray(o)?o:void 0,a={},s=Object.fromEntries(await Promise.all(e.map(async(c)=>{let l=d_(c),d=(l.length>0?l:[c]).flatMap((g)=>{if(i===void 0||!Object.hasOwn(i,g))return[];let x=i?.[g],P=typeof x==="object"&&x!==null&&!Array.isArray(x)?x.enabled:void 0;return[{id:g,enabled:P}]});if(d.length===0)return[c,"missing"];let p=d.filter((g)=>g.enabled===!0),m=(await Promise.all(p.map(async(g)=>({...g,cached:await xz(this.codexHome,[g.id])})))).find((g)=>g.cached),y=m?.id??p[0]?.id??d[0]?.id;if(y!==void 0)a[c]=y;if(m!==void 0)return[c,"installed"];if(p.length>0)return[c,"missing"];if(d.every((g)=>g.enabled===!1))return[c,"disabled"];return[c,"unknown"]})));return this.observedIdentities=Object.freeze(a),s}getObservedIdentities(){return this.observedIdentities}}async function xz(e,t){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let o=pv(e,"plugins","cache",n.slice(r+1),n.slice(0,r));try{let i=await yz(o,{withFileTypes:!0,encoding:"utf8"});for(let a of i){if(!a.isDirectory())continue;try{return await hz(pv(o,a.name,".codex-plugin","plugin.json")),!0}catch(s){if(!fv(s))throw s}}}catch(i){if(fv(i))continue;throw i}}return!1}function fv(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function gd(e,t,n){if(t instanceof ro)return t;let o=(t instanceof ye?t:void 0)?.code,i=o==="timeout"||o==="output_limit"||o==="cancelled"||o==="readback_mismatch"||o==="plugin_disabled"||o==="plugin_missing"||o==="marketplace_invalid"||o==="marketplace_timeout"||o==="marketplace_unavailable"?o:o==="command_failed"?e==="list"?"list_failed":e==="remove"?"remove_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed":e==="list"?"list_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed",a=t instanceof Error?t.message:e==="list"?"Codex could not list official plugins.":e==="remove"?`Codex could not remove ${n??"the selected official plugin"}.`:e==="bootstrap"?"Codex could not initialize the official marketplace.":`Codex could not add ${n??"the selected official plugin"}.`;return new ro(i,a,t,n===void 0?{}:{plugin_id:n})}var ro;var yd=b(()=>{Ya();ht();Za();ro=class ro extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t);this.name="OfficialPluginManagerError",this.code=e,this.causeValue=n,this.details=r}}});function gv(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=bz(r).trim();if(o.length===0)continue;if(o.startsWith("[[")||o.endsWith("]]"))throw Error("Array-of-tables are not supported by the validated fallback.");if(o.startsWith("[")&&o.endsWith("]")){n=mv(o.slice(1,-1).trim()),Sz(t,n);continue}let i=gF(o);if(i<1)throw Error("TOML assignment is invalid.");let a=mv(o.slice(0,i).trim()),s=kh(o.slice(i+1).trim());hF(t,[...n,...a],s)}return t}function yv(e){let t=[];return mF(e,[],t),t.join(`
41
- `)}function mF(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(xv(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(fF).join(".")}]`)}for(let[i,a]of r)n.push(`${fF(i)} = ${yF(a)}`);for(let[i,a]of o)mF(a,[...t,i],n)}function kh(e){if(e.length===0)throw Error("TOML value is missing.");if(e.startsWith('"')){let t=JSON.parse(e);if(typeof t!=="string")throw Error("TOML string is invalid.");return t}if(e.startsWith("'")){if(!e.endsWith("'")||e.length<2)throw Error("TOML string is invalid.");return e.slice(1,-1)}if(e==="true")return!0;if(e==="false")return!1;if(e.startsWith("[")){if(!e.endsWith("]"))throw Error("TOML array is invalid.");let t=e.slice(1,-1).trim();return t.length===0?[]:hv(t,",").map((n)=>kh(n.trim()))}if(e.startsWith("{")){if(!e.endsWith("}"))throw Error("TOML inline table is invalid.");let t=e.slice(1,-1).trim(),n={};if(t.length===0)return n;for(let r of hv(t,",")){let o=gF(r);if(o<1)throw Error("TOML inline table entry is invalid.");hF(n,mv(r.slice(0,o).trim()),kh(r.slice(o+1).trim()))}return n}if(/^[+-]?(?:0|[1-9]\d*)(?:\.\d+)?$/u.test(e)){let t=Number(e);if(Number.isFinite(t))return t}throw Error("TOML value is unsupported.")}function mv(e){let t=hv(e,".").map((n)=>n.trim());if(t.length===0||t.some((n)=>!/^(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(n)||n==="__proto__"||n==="constructor"||n==="prototype"))throw Error("TOML key is invalid.");return t.map((n)=>n.startsWith('"')||n.startsWith("'")?kh(n):n)}function hF(e,t,n){if(t.length===0)throw Error("TOML key is missing.");let r=e;for(let i of t.slice(0,-1)){let a=r[i];if(a===void 0){let s={};r[i]=s,r=s}else if(xv(a))r=a;else throw Error("TOML key conflicts with a scalar.")}let o=t.at(-1);if(Object.prototype.hasOwnProperty.call(r,o))throw Error("TOML key is duplicated.");r[o]=n}function Sz(e,t){let n=e;for(let r of t){let o=n[r];if(o===void 0){let i={};n[r]=i,n=i}else if(xv(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function hv(e,t){let n=[],r=0,o=0,i,a=!1;for(let s=0;s<e.length;s+=1){let c=e[s];if(i!==void 0){if(i==='"'&&a)a=!1;else if(i==='"'&&c==="\\")a=!0;else if(c===i)i=void 0;continue}if(c==='"'||c==="'")i=c;else if(c==="["||c==="{")o+=1;else if(c==="]"||c==="}")o-=1;else if(c===t&&o===0)n.push(e.slice(r,s)),r=s+1}if(i!==void 0||o!==0)throw Error("TOML value is unbalanced.");return n.push(e.slice(r)),n}function gF(e){let t,n=!1,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&i==="\\")n=!0;else if(i===t)t=void 0}else if(i==='"'||i==="'")t=i;else if(i==="["||i==="{")r+=1;else if(i==="]"||i==="}")r-=1;else if(i==="="&&r===0)return o}return-1}function bz(e){let t,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&o==="\\")n=!0;else if(o===t)t=void 0}else if(o==='"'||o==="'")t=o;else if(o==="#")return e.slice(0,r)}return e}function xv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function fF(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function yF(e){if(typeof e==="string")return JSON.stringify(e);if(typeof e==="boolean"||typeof e==="number"){if(typeof e==="number"&&!Number.isFinite(e))throw Error("TOML number is invalid.");return String(e)}if(Array.isArray(e))return`[${e.map(yF).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{execFile as _z}from"child_process";import{access as wz,readFile as vz,realpath as Rz}from"fs/promises";import{posix as Tz,win32 as Cz}from"path";import{promisify as Oz}from"util";function ls(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:$c,run:async(t,n)=>{try{let r=await Ez(t,[...n],{encoding:"utf8",windowsHide:!0,env:{...process.env,...e},timeout:120000,maxBuffer:4194304});return{exitCode:0,stdout:r.stdout,stderr:r.stderr}}catch(r){let o=r;return{exitCode:typeof o.code==="number"?o.code:1,stdout:typeof o.stdout==="string"?o.stdout:"",stderr:typeof o.stderr==="string"?o.stderr:r instanceof Error?r.message:"process failed"}}}}}function ss(e){let t=$n(e.npm_execpath??""),n=(e.npm_command??"").toLowerCase(),r=(e.npm_config_user_agent??"").toLowerCase();if(t.includes("yarn")||t.includes("corepack")||r.startsWith("yarn/"))return;if(xd(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(xd(t,"bunx")||xd(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(xd(t,"npx")||t.endsWith("/npx-cli.js")||xd(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function us(e,t){if(e.platform!=="win32")return{status:"not_applicable"};let n=await xF(e);if(n!==void 0)return{status:"healthy",path:n,installed:!1};if(!t)return{status:"missing"};let r=await e.run("winget",["install","--id","Git.Git","-e","--source","winget"]);if(r.exitCode!==0)throw new me("git_bash_unavailable","Git Bash is required. WinGet could not install Git for Windows; install Git.Git and retry.",{stderr:r.stderr.slice(0,512)});let o=await xF(e);if(o===void 0)throw new me("git_bash_unavailable",`Git for Windows was installed, but ${as} could not be verified. Repair Git for Windows and retry.`);return{status:"healthy",path:o,installed:!0}}async function Ih(e,t,n){let r=await bv(e);if(r!==void 0){let o=ss(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},i=n?.ownership==="holycodex"&&typeof n.identity==="string"&&await Uc(e,n.executable,r.executable);return{manager:o.family,launcher:o.launcher,version:r.version,executable:r.executable,ownership:i?"holycodex":"user",...i?{identity:n.identity}:{}}}if(qc(e))return Az(e,t,n);return Pz(e,t,n)}async function Sv(e,t){let n=await bv(e);if(n!==void 0){let i=ss(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&await Uc(e,t.executable,n.executable);return{manager:i.family,launcher:i.launcher,version:n.version,executable:n.executable,ownership:a?"holycodex":"user",...a?{identity:t.identity}:{}}}let r=qc(e)?{launcher:"bunx",family:"bun",executable:"bun"}:ss(e.environment);if(r===void 0)throw new me("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let o=r.family==="bun"&&qc(e)?await Sd(e):await bd(e,r);if(o===void 0)throw new me("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:o.version,executable:o.executable,ownership:_v(t,r,o),identity:o.identity}}async function bv(e){let t=await wF(e.environment,e.platform,e.files??$c);if(t===void 0)return;let n=await e.run(t,["--version"]),r=n.exitCode===0?cs(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}}async function kz(e){if(await bv(e)!==void 0)return;if(qc(e)){await Iz(e);return}let t=ss(e.environment);if(t===void 0)throw new me("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let n=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0)throw new me("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})}async function Iz(e){let t=e.files??$c,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if($z(n.stderr))return;throw new me("context7_unavailable","Bun's managed global installation could not be located before managed changes.",{stderr:n.stderr.slice(0,512)})}let r=nn(e.platform),o=n.stdout.trim(),i=r.join(r.dirname(o),"install","global"),a=r.join(i,"node_modules","ctx7"),s=r.join(a,"package.json"),c=r.join(o,e.platform==="win32"?"ctx7.exe":"ctx7");try{await t.access(o),await t.access(i)}catch(g){throw new me("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:is(g)})}let l;try{await t.access(a)}catch(g){if(qz(g))return;throw new me("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:is(g)})}try{l=await t.readText(s)}catch(g){throw new me("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:is(g)})}let u;try{u=JSON.parse(l)}catch(g){throw new me("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:is(g)})}if(typeof u.version!=="string"||cs(u.version)!==u.version)throw new me("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let d=vF(u);if(d===void 0)throw new me("context7_unavailable","Bun's managed ctx7 package does not declare its executable before managed changes.");let p=r.resolve(a,d),f,m;try{await t.access(p),f=await t.realpath(a),m=await t.realpath(p)}catch(g){throw new me("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:is(g)})}if(!_d(f,a,e.platform)||!$n(m).startsWith(`${$n(f)}/`))throw new me("context7_unavailable","Bun's managed ctx7 executable is outside its package before managed changes.");try{await t.access(c),await t.realpath(c)}catch(g){throw new me("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:is(g)})}let y=await e.run(c,["--version"]);if(y.exitCode!==0||cs(y.stdout)!==u.version)throw new me("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:y.stderr.slice(0,512)})}async function Pz(e,t,n){let r=ss(e.environment);if(r===void 0)throw new me("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await bd(e,r),i=await RF(e,r);if(i===void 0)throw new me("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=_v(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=bF(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new me("context7_install_failed",`${r.family} could not install ${Er}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new me("context7_unavailable",`${Er} is not owned by the ${r.family} global installation.`);let s=await bd(e,r);if(s===void 0)throw new me("context7_verification_failed",`${Er} could not be verified in the ${r.family} global installation.`);if(s.version!==i)throw new me("context7_outdated",`The ${r.family} global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:r.family,launcher:r.launcher,version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Az(e,t,n){let r={launcher:"bunx",family:"bun",executable:"bun"},o=await Sd(e),i=await RF(e,r);if(i===void 0)throw new me("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=_v(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=await e.run(e.processPath,["add","-g",Er]);if(l.exitCode!==0)throw new me("context7_install_failed",`Bun could not install ${Er} in its global installation.`,{stderr:l.stderr.slice(0,512)})}else if(o===void 0)throw new me("context7_unavailable",`${Er} is not present in Bun's exact global installation.`);let s=await Sd(e);if(s===void 0)throw new me("context7_verification_failed",`${Er} could not be verified in Bun's exact global installation.`);if(s.version!==i)throw new me("context7_outdated",`Bun's global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:"bun",launcher:"bunx",version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Sd(e){let t=e.files??$c,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0)return;let r=n.stdout.trim();if(r.length===0)return;let o=nn(e.platform),i=o.join(o.dirname(r),"install","global","node_modules","ctx7"),a;try{a=JSON.parse(await t.readText(o.join(i,"package.json")))}catch{return}if(typeof a.version!=="string"||cs(a.version)!==a.version)return;let s=vF(a);if(s===void 0)return;let c=o.resolve(i,s),l=o.join(r,e.platform==="win32"?"ctx7.exe":"ctx7"),u,d,p;try{await t.access(i),await t.access(c),await t.access(l),u=await t.realpath(i),d=await t.realpath(c),p=await t.realpath(l)}catch{return}if(!_d(u,i,e.platform)||!$n(d).startsWith(`${$n(u)}/`))return;let f=await e.run(l,["--version"]);if(f.exitCode!==0||cs(f.stdout)!==a.version)return;return{version:a.version,executable:l,identity:await _F({launcher:"bunx",family:"bun",executable:"bun"},u,d,p,a)}}function qc(e){let t=nn(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function _v(e,t,n){if(n===void 0)return"holycodex";if(e?.ownership!=="holycodex")return"user";if(e.manager!==t.family)return"user";let r=e.identity;if(!wv(r)||r!==n.identity)return"user";return"holycodex"}async function wd(e,t){if(qc(e))return Mz(e,t);return Nz(e,t)}async function Mz(e,t){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n;try{n=await Sd(e)}catch{return!1}if(n===void 0||n.version!==t.version||!await Uc(e,n.executable,t.executable)||!wv(t.identity)||n.identity!==t.identity)return!1;let r=await e.run(e.processPath,["remove","-g","ctx7"]);if(r.exitCode!==0)throw new me("context7_remove_failed","Bun could not remove ctx7.",{stderr:r.stderr.slice(0,512)});if(await Sd(e)!==void 0)throw new me("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0}async function Nz(e,t){if(t?.ownership!=="holycodex")return!1;let n=ss(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await bd(e,n)}catch(a){if(a instanceof me&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!await Uc(e,r.executable,t.executable)||!wv(t.identity)||r.identity!==t.identity)return!1;let o=Fz(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new me("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await bd(e,n)!==void 0)throw new me("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof me&&a.code==="context7_remove_failed")throw a;throw new me("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function bF(e){switch(e){case"bun":return{executable:"bun",args:["add","-g",Er]};case"npm":return{executable:"npm",args:["install","--global",Er]};case"pnpm":return{executable:"pnpm",args:["add","--global",Er]}}}function Fz(e){switch(e){case"bun":return{executable:"bun",args:["remove","--global","ctx7"]};case"npm":return{executable:"npm",args:["uninstall","--global","ctx7"]};case"pnpm":return{executable:"pnpm",args:["remove","--global","ctx7"]}}}async function xF(e){if(await SF(e.run,as,e.platform))return as;for(let t of(e.environment.PATH??"").split(";")){if(t.length===0)continue;let n=nn(e.platform).join(t,"bash.exe");if(await SF(e.run,n,e.platform))return n}return}async function SF(e,t,n){let r=jz(t,n),[o,i,a]=await Promise.all([e(t,["--version"]),e(t,["--noprofile","--norc","-c","uname -s"]),e(r,["--version"])]);return o.exitCode===0&&/gnu bash/iu.test(o.stdout)&&i.exitCode===0&&/^mingw(?:32|64|)/iu.test(i.stdout.trim())&&a.exitCode===0&&/^git version \d/iu.test(a.stdout.trim())}async function bd(e,t){let n=e.files??$c,r=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(r.exitCode!==0)return;let o=r.stdout.trim();if(o.length===0)return;let i=t.family==="npm"?nn(e.platform).join(o,"node_modules","ctx7"):t.family==="pnpm"?await Uz(e,t):nn(e.platform).join(nn(e.platform).dirname(o),"install","global","node_modules","ctx7");if(i===void 0)return;let a;try{a=JSON.parse(await n.readText(nn(e.platform).join(i,"package.json")))}catch{return}if(typeof a.version!=="string")return;let s=typeof a.bin==="string"?a.bin:vv(a.bin)&&typeof a.bin.ctx7==="string"?a.bin.ctx7:void 0;if(s===void 0)return;let c=nn(e.platform).resolve(i,s),l,u;try{if(await n.access(c),l=await n.realpath(i),u=await n.realpath(c),!$n(u).startsWith(`${$n(l)}/`))return}catch{return}let d=Lz(o,t.family,e.platform),p;try{await n.access(d),p=await n.realpath(d)}catch{return}let f=await wF(e.environment,e.platform,n);if(f!==void 0&&!_d(await Dz(n,f),p,e.platform))throw new me("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:f,expected:d});let m=await e.run(d,["--version"]);if(m.exitCode!==0||cs(m.stdout)!==a.version)return;return{version:a.version,executable:d,identity:await _F(t,l,u,p,a)}}async function _F(e,t,n,r,o){return await Fn("context7-installation",[Nn({manager:e.family,package_root:$n(t),package_executable:$n(n),shim:$n(r),package:o})])}function wv(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function wF(e,t,n){let r=e.PATH;if(r===void 0)return;let o=t==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((i)=>i.length>0).map((i)=>`ctx7${i.toLowerCase()}`):["ctx7"];for(let i of r.split(t==="win32"?";":":")){if(i.length===0)continue;for(let a of o){let s=nn(t).join(i,a);try{return await n.access(s),s}catch{}}}return}function Lz(e,t,n){if(n==="win32")return nn(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?nn(n).join(e,"bin","ctx7"):nn(n).join(e,"ctx7")}async function Dz(e,t){try{return await e.realpath(t)}catch{return t}}function cs(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function vF(e){return typeof e.bin==="string"?e.bin:vv(e.bin)&&typeof e.bin.ctx7==="string"?e.bin.ctx7:void 0}function is(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function qz(e){return vv(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(is(e))}function $z(e){return/(?:no package\.json(?: was)? found|couldn['\u2019]?t find (?:a )?package\.json|could not find (?:a )?package\.json|package\.json (?:is )?missing)/iu.test(e)}async function Uz(e,t){let n=await e.run(t.executable,["root","--global"]),r=n.stdout.trim();return n.exitCode===0&&r.length>0?nn(e.platform).join(r,"ctx7"):void 0}async function RF(e,t){let n=await e.run(t.family==="bun"&&qc(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return cs(n.stdout)}function jz(e,t){let n=nn(t),r=n.dirname(e),o=$n(r).endsWith("/usr/bin")?n.resolve(r,"..",".."):n.resolve(r,"..");return n.resolve(o,"cmd","git.exe")}function xd(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function _d(e,t,n){let r=nn(n),o=r.resolve(e),i=r.resolve(t);return n==="win32"?$n(o)===$n(i):o===i}async function Uc(e,t,n){if(_d(t,n,e.platform))return!0;let r=e.files??$c;try{let[o,i]=await Promise.all([r.realpath(t),r.realpath(n)]);return _d(o,i,e.platform)}catch{return!1}}function nn(e){return e==="win32"?Cz:Tz}function $n(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function vv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var as="C:\\Program Files\\Git\\bin\\bash.exe",Er="ctx7@latest",Ez,$c,me;var Ph=b(()=>{ht();Ez=Oz(_z),$c={access:wz,readText:(e)=>vz(e,"utf8"),realpath:Rz};me=class me extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as Mh,rmdir as Cv}from"fs/promises";import{join as Hz}from"path";async function Ev(e={},t=process.env){let n=Cr(e,t),r={};try{await Xa(n.codexHome),await Xa(n.stateRoot),r.paths=ps({state_root:n.stateRoot})}catch(u){r.paths=Mt(["path_symlink"],{error:Un(u)})}let o=await Vi(n).catch((u)=>{r.configuration=Mt(["state_corrupt"],{error:Un(u)});return}),[i,a]=await Promise.all([Ir(n.preparingRecord,o).catch((u)=>{r.transaction=Mt(["state_corrupt"],{path:n.preparingRecord,error:Un(u)});return}),Ir(n.conflictedRecord,o).catch((u)=>{r.transaction=Mt(["state_corrupt"],{path:n.conflictedRecord,error:Un(u)});return})]);if(r.transaction?.status!=="failed"&&(i!==void 0||a!==void 0)){let u=Dh(o,i,a),d=[...new Set(u.map((p)=>{if(p.relation==="stale")return"stale_transaction_state";if(p.relation==="incompatible")return"incompatible_transaction_state";return p.status==="preparing"?"incomplete_install_state":"conflicted_state"}))];r.transaction=Mt(d,{recovery:u.map((p)=>p.recovery).join(","),transactions:u.map((p)=>`${p.status}:${p.relation}:${p.install_id}:${p.digest}`).join(","),active:o===void 0?"absent":`${o.install_id}:${o.digest}`})}if(!r.configuration)if(!o)r.configuration=Mt(["configuration_missing"]);else if(await Bc(o))r.configuration=ps({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=Mt(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await Xz(n,o),r.native_roles=await Qz(n,o.profile,o.tier,o.tooling?.git_bash.status==="healthy"?o.tooling.git_bash.path:void 0,{browserUse:o.capability_state?.browser_use.status==="healthy"&&o.capability_state.browser_use.selected,computerUse:o.capability_state?.computer_use.status==="healthy"&&o.capability_state.computer_use.selected});let u=Object.entries(o.capability_state??{}).find(([d,p])=>d!=="browser_use"&&p.selected&&p.status!=="healthy");if(u)r.capabilities=Mt(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status});if(o.optional_selections.browser_use)r.browser_use={status:"unsupported",reasons:["surface_managed_by_codex_desktop"],details:{selected:!0,owner:"Codex Desktop/runtime",availability:"Available only on Codex surfaces that provide Browser Use.",cli_provisioning:"HolyCodex CLI does not install, configure, or verify Browser."}}}let s=e.runtime??ls(t);try{let u=await us(s,!1);r.git_bash=u.status==="missing"?Mt(["git_bash_missing"]):ps(u.status==="healthy"?{path:u.path}:{})}catch(u){r.git_bash=Mt(["git_bash_unavailable"],{error:Un(u)})}try{let u=await Sv(s,o?.tooling?.context7);r.context7=ps({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:Un(u)}}}try{let u=await je(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&Dc(u)){let d=r.native_roles;r.native_roles={status:"failed",reasons:[...d?.reasons??[],"stale_legacy_root"],details:{...d?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(u){r.native_roles=Mt(["native_role_invalid"],{error:Un(u)})}let c=e.officialPluginManager;if(o&&c?.status){let u=[...new Set([dn,...wc({browser_use:o.optional_selections.browser_use,computer_use:o.optional_selections.computer_use,sites:o.optional_selections.sites},o.official_plugins),...(o.owned_plugins??[]).filter((d)=>d!==ln)])].filter((d)=>d!==ln);try{let d=await c.status(u),p=Object.entries(d).filter(([,m])=>m!=="installed").map(([m])=>m),f=c.getObservedIdentities?.()??{};r.native_plugins=p.length===0?ps({status:d,observed_identities:f}):Mt(["native_plugin_disagreement"],{missing:p,status:d,observed_identities:f})}catch(d){r.native_plugins=Mt(["native_plugin_status_failed"],{error:Un(d)})}}else r.native_plugins=Mt(["native_plugin_status_unavailable"],{reason:"No read-only live official plugin status source is available."});let l=Object.values(r).flatMap((u)=>u.reasons);return{healthy:Object.values(r).every((u)=>u.status!=="failed"),checks:r,reasons:[...new Set(l)]}}async function kv(e={},t=process.env){let n=Cr(e,t);await Xa(n.codexHome),await Xa(n.stateRoot);let r=await Vi(n);if(r!==void 0&&!await Bc(r))throw new T("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Ir(n.preparingRecord,r),Ir(n.conflictedRecord,r)]);Av(r,o,i);let a=IF(r,o,i);if(a===void 0)return[];let s=un(await je(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await Tr(s,a.managed_config,{schema:a.managed_config.schema,installId:a.managed_config.installId});for(let u of[...l.preservedKeys,...l.unresolvedKeys])c.push(await Tv(n.configFile,u,s,"config-key","This managed Codex setting changed after installation."))}if(a.plugin_config!==void 0){let l=await jc(s,a.plugin_config);for(let u of l.preserved){let d=u==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";c.push(await Tv(n.configFile,d,s,"plugin-config","This HolyCodex plugin setting differs from the recorded install state."))}}if(a.provider_config!==void 0){let l=await Hc(s,Nh(a.provider_config),new Set(Iv(a)));for(let u of l.preserved){let d=`plugins.${JSON.stringify(u)}`;c.push(await Tv(n.configFile,d,s,"plugin-config",`The ${u} plugin setting differs from the recorded install state.`))}}return c.push(...await uF(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[oo(l),l])).values()]}async function vd(e={},t=process.env){let n=Cr(e,t);await Xa(n.codexHome),await Xa(n.stateRoot);let r=await Vi(n);if(r&&!await Bc(r))throw new T("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Ir(n.preparingRecord,r),Ir(n.conflictedRecord,r)]);Av(r,o,i);let a=IF(r,o,i);Ah(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(Iv(a)),c=[],l=[],u=[],d=!1,p=()=>(Ah(e,{stage:"removal",status:"completed",message:"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u});if(a===void 0)return Ah(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let f=await kv(e,t),m=await Yz(e,f),y=await je(n.configFile),g=un(y),x=f.filter((w)=>w.key!==void 0&&m.has(oo(w))),P=new Map;for(let w of f){if(w.key!==void 0||!m.has(oo(w)))continue;let A=EF(w);if(A!==void 0)P.set(w.path,A)}await Zz(n,g,x,P);let _=a?.managed_config;if(_){let w=await Tr(g,_,{schema:_.schema,installId:_.installId});if(w.preservedKeys.length>0||w.unresolvedKeys.length>0){let E=[...w.preservedKeys,...w.unresolvedKeys].map((le)=>({path:n.configFile,key:le,action:"remove"}));for(let le of E)if(m.has(oo(le)))g=Rr(g,le.key)}}if(a?.plugin_config){let w=await jc(g,a.plugin_config);if(w.preserved.length>0){let A=w.preserved.map((E)=>({path:n.configFile,key:E==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let E of w.preserved){let le=A.find((He)=>He.key===(E==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(le===void 0||!m.has(oo(le)))continue;g=Rr(g,E==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let w=await Hc(g,Nh(a.provider_config),s);if(w.preserved.length>0){let A=w.preserved.map((E)=>({path:n.configFile,key:`plugins."${E}"`,action:"remove"}));for(let E of w.preserved){let le=A.find((He)=>He.key===`plugins."${E}"`);if(le===void 0||!m.has(oo(le)))continue;g=Rr(g,`plugins."${E}"`)}}}let I,q;if(s.size>0){try{I=e.officialPluginManager??await os.discover({...t,CODEX_HOME:n.codexHome})}catch(w){throw new T("capability_denied","Native Codex plugin removal is unavailable.",w,{operation:"discover Codex",plugins:[...s].join(","),recovery:"Install or expose Codex, then retry."})}if(I===void 0||!I.remove||!I.list)throw new T("capability_denied","Native Codex plugin removal and readback are unavailable.",void 0,{operation:"prepare plugin removal",plugins:[...s].join(",")});try{q=await I.list()}catch(w){throw new T("capability_denied","Codex plugin state could not be read before removing HolyCodex-owned plugins.",w,{operation:"read Codex plugin state",plugins:[...s].join(","),recovery:"Repair or expose Codex, then retry removal."})}}let O,C=a;try{let w=g,A=_;if(A){let E=await Tr(w,A,{schema:A.schema,installId:A.installId}),le=[...E.preservedKeys,...E.unresolvedKeys];if(le.filter((Be)=>!m.has(oo({path:n.configFile,key:Be,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await kr(n,a??ds()),p();if(w=E.document,le.length>0){let Be=new Set(le);A={...E.state,managed:Object.fromEntries(Object.entries(E.state.managed).filter(([gt])=>!Be.has(gt)))}}else A=E.state}if(a?.plugin_config){let E=await jc(w,a.plugin_config,{allowBeforeState:!0});if(E.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await kr(n,a),p();w=E.document}if(a?.provider_config){let E=await Hc(w,Nh(a.provider_config),s,{allowBeforeState:!0});if(E.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await kr(n,a),p();w=E.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)O=A===void 0?{document:w}:{document:w,state:A};if(O!==void 0){if(Object.keys(O.document).length===0&&y===void 0)await TF(n.configFile,y),await Mh(n.configFile,{force:!1});else await TF(n.configFile,y),await qn(n.configFile,Cd(O.document));C={...a,managed_config:O.state},await kr(n,C),d=!0}}catch(w){if(w instanceof T)throw await kr(n,C??ds()),w;return l.push(n.configFile),u.push("managed_config_write_failed"),await kr(n,C??ds()),p()}let N=await Th(n.codexHome,a?.managed_artifacts??[],P);if(c.push(...N.removed),l.push(...N.preserved),N.preserved.length>0)return u.push("managed_artifact_changed"),await kr(n,C??a??ds()),p();c.push(...await Wz(n.roleRoot,a?.managed_artifacts??[]));for(let w of s)try{if(I?.list===void 0||I.remove===void 0||q===void 0)throw new T("capability_denied","Codex plugin state is unavailable for a HolyCodex-owned plugin.",void 0,{operation:"remove Codex plugin",plugin_id:w});let E=eK(q,w);if(E?.entry.installed!==!0)continue;let le=E.entry.pluginId;await I.remove(le);let He=await I.list();if(q=He,no(He,w)?.entry?.installed===!0||[...He.installed,...He.available].some((ot)=>ot.pluginId===w&&ot.installed))throw new T("capability_denied",`Codex still reports ${w} after removal.`);if(O!==void 0)await Vz(n,O.document,w);c.push(w)}catch(A){throw u.push("native_plugin_remove_failed"),await kr(n,C??ds()),new T("capability_denied",`Codex native plugin removal did not converge for ${w}: ${Un(A)}`,A)}try{if(await wd(e.runtime??ls(t),a.tooling?.context7))c.push("ctx7")}catch(w){throw u.push("context7_remove_failed"),await kr(n,C??ds()),new T("capability_denied",`Context7 removal did not converge: ${Un(w)}`,w)}if(r)try{await Mh(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(w){if(!Xe(w,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await kr(n,a??r),p()}if(l.length===0)try{await Mh(n.installOptions,{force:!1}),c.push(n.installOptions)}catch(w){if(!Xe(w,"ENOENT"))l.push(n.installOptions),u.push("state_remove_failed"),await kr(n,a??r??ds())}if(l.length===0)for(let[w,A]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0||d]]){if(!A)continue;try{await tK(w),c.push(w)}catch{l.push(w),u.push("state_remove_failed")}}if(l.length===0)try{await Cv(n.roleRoot),c.push(n.roleRoot)}catch(w){if(!Xe(w,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await Cv(n.stateRoot),c.push(n.stateRoot)}catch(w){if(Xe(w,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return Ah(e,{stage:"removal",status:"completed",message:l.length===0&&u.length===0?"HolyCodex removal complete":"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u}}async function Vz(e,t,n){let r=await je(e.configFile);if(r===void 0)return;let o=un(r,e.configFile),i=o.plugins;if(!Rv(i))return;let a=i[n];if(!Rv(a)||Object.keys(a).length!==1||a.enabled!==!1)return;let s=t.plugins,c=Rv(s)?s[n]:void 0,l={...i};if(c===void 0)delete l[n];else l[n]=c;let u={...o};if(Object.keys(l).length===0)delete u.plugins;else u.plugins=l;await qn(e.configFile,Cd(u))}function Rv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function Wz(e,t){let n=new Set;for(let o of t){let i=o.path.split("/");if(i.length===4&&i[0]==="holycodex"&&i[1]==="agents"&&/^[a-f0-9]{20}$/u.test(i[2]??"")&&i[3]?.endsWith(".toml"))n.add(i[2])}let r=[];for(let o of n){let i=Hz(e,o);try{await Cv(i),r.push(i)}catch(a){if(!Xe(a,"ENOENT")&&!Xe(a,"ENOTEMPTY")&&!Xe(a,"EEXIST"))throw a}}return r}async function zz(e={},t=process.env,n={}){let r=Cr(e,t),o=await Vi(r),[i,a]=await Promise.all([Ir(r.preparingRecord,o),Ir(r.conflictedRecord,o)]);if(o!==void 0&&!await Bc(o))throw new T("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});Pv(o,i,a);let s=kF(o,i,a),c=s??o;if(c===void 0)throw new T("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l=await Lh(r),u=l===void 0?{profile:c.profile,tier:c.tier,optional:{browser_use:c.optional_selections.browser_use,computer_use:c.optional_selections.computer_use,sites:c.optional_selections.sites},officialPlugins:Kz(c)}:Jz(Rd(l)),d=n.options===void 0?u:pn(n.options),p={profile:d.profile??u.profile,tier:d.tier??u.tier,optional:{...u.optional,...d.optional},officialPlugins:d.officialPlugins??u.officialPlugins},f=!Gz(p,u),m;try{m=await fd()}catch(C){throw new T("upgrade_failed","The running HolyCodex version is unavailable.",C)}let y=m.split("-",1)[0]===c.version.split("-",1)[0]&&m.includes("-dev.")!==c.version.includes("-dev."),g=y?0:Uu(m,c.version);if(g<0)throw new T("upgrade_downgrade",`The running HolyCodex version ${m} is older than the installed version ${c.version}.`,void 0,{installed_version:c.version,running_version:m});let x=c.managed_config?.managed["features.context_management"]!==void 0,P=c.managed_config?.managed[Di[0]]!==void 0,_=[];if(n.dryRun===!0){let C=un(await je(r.configFile));if(c.managed_config!==void 0)for(let w of Object.keys(c.managed_config.managed)){if(!Ka(w))continue;if((await Ga(C,c.managed_config,w)).status!=="unchanged")_.push({path:r.configFile,key:w,action:"replace"})}if(c.plugin_config!==void 0){let w=await jc(C,c.plugin_config);for(let A of w.preserved){let E=A==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";_.push({path:r.configFile,key:E,action:"replace"})}}if(c.provider_config!==void 0){let w=await Hc(C,Nh(c.provider_config),new Set(Iv(c)));for(let A of w.preserved)_.push({path:r.configFile,key:`plugins."${A}"`,action:"replace"})}let N=await vh(r.codexHome,c.profile,c.managed_artifacts,c.tier,c.tooling?.git_bash.status==="healthy"?c.tooling.git_bash.path:void 0,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use});for(let w of N)_.push(w)}let I=c.tooling===void 0,q=c.tooling===void 0?["record missing"]:[];try{let C=e.runtime??ls(t);if((await us(C,!1)).status==="missing")q.push("Git Bash unavailable");let w;try{w=await Sv(C,c.tooling?.context7)}catch(E){if(c.tooling?.context7!==void 0||!nK(E))throw E}let A=c.tooling?.context7;if(A?.manager!==w?.manager)q.push("Context7 manager changed");if(A?.version!==w?.version)q.push("Context7 version changed");if(A?.executable===void 0?w?.executable!==void 0:w?.executable===void 0||!await Uc(C,A.executable,w.executable))q.push("Context7 executable changed");I||=q.length>0}catch(C){I=!0;let N=typeof C==="object"&&C!==null&&"code"in C&&typeof C.code==="string"?C.code:C instanceof Error?C.name:"inspection failed";q.push(`inspection failed (${N})`)}let O=[...g>0||y?["version"]:[],...f?["installation options"]:[],...l===void 0?["installation options migration"]:[],...x?["context-management configuration migration"]:[],...P?["auto-compaction configuration cleanup"]:[],...g>0||x||P?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...I?[`shared tooling reconciliation (${q.join(", ")})`]:[],..._.map((C)=>`conflict: ${C.path}${C.key===void 0?"":` (${C.key})`} -> ${C.action}`)];if(O.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:m,changes:[],record:o,preserved:[],warnings:[],conflicts:_};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:m,changes:O,record:o,preserved:[],warnings:[],conflicts:_};try{let C=await fs(p,e,t);return{status:"upgraded",from_version:c.version,to_version:m,changes:O,record:C.record,preserved:C.preserved,warnings:C.warnings}}catch(C){if(C instanceof T)throw C;throw new T("upgrade_failed",`HolyCodex upgrade failed: ${Un(C)}`,C)}}function Kz(e){let t=new Set(wc(e.optional_selections));return(e.official_plugins??[]).filter((n)=>n!==ln&&!CF(n)&&!t.has(n))}function Nh(e){return e.filter((t)=>t.plugin_id!==ln)}function Jz(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!CF(t))}}}function CF(e){let t=e.slice(0,e.lastIndexOf("@"));return Bz.has(t)}function Gz(e,t){let n=e.optional??{},r=t.optional??{},o=[...new Set(e.officialPlugins??[])],i=[...new Set(t.officialPlugins??[])];return e.profile===t.profile&&e.tier===t.tier&&n.browser_use===r.browser_use&&n.computer_use===r.computer_use&&n.sites===r.sites&&o.length===i.length&&o.every((a,s)=>a===i[s])}async function Yz(e,t){let n=new Set;if(e.resolveConflicts!==void 0&&t.length>0){let r=t.map((i)=>({...i,identity:`remove:${i.path}:${i.key??""}`,category:i.key===void 0?"role-asset":"config-key",target:i.key??i.path,explanation:"HolyCodex can remove this managed value after reviewing the change.",validDecisions:["keep","remove","cancel"],defaultDecision:"keep"})),o=await e.resolveConflicts(r);for(let i=0;i<r.length;i+=1){let a=r[i],s=o[a.identity];if(s==="remove")n.add(oo(t[i]));else if(s==="keep")continue;else if(s==="cancel")throw new T("confirmation_required","Conflict resolution was cancelled.",void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});else throw new T("confirmation_required",`The removal conflict at ${a.target} requires a keep, remove, or cancel decision.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key},decision:s??"unavailable"})}return n}for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(oo(r));continue}if(o==="decline")continue;throw new T("confirmation_required",o==="cancel"?"Conflict resolution was cancelled.":"Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:r.path,...r.key===void 0?{}:{key:r.key},action:r.action,resolution:o??"unavailable"})}return n}function oo(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function Tv(e,t,n,r,o){let i=fe(n,t),a=await OF(n,t);return{identity:oo({path:e,key:t,action:"remove"}),category:r,target:t,existing:{present:i!==void 0,digest:a},desired:{present:!1},explanation:o,validDecisions:["keep","remove","cancel"],defaultDecision:"keep",path:e,key:t,action:"remove"}}async function OF(e,t){let n=fe(e,t);return await Fn("holycodex-removal-config-review-v1",[Nn(cn(n===void 0?{present:!1}:{present:!0,value:n}))])}function EF(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}async function Zz(e,t,n,r){for(let i of n){if(i.key===void 0)continue;let a=EF(i);if(a===void 0||await OF(t,i.key)!==a)throw Ov(i.path,i.key)}let o;try{o=await dF(e.codexHome,r)}catch(i){let a=r.keys().next().value;throw new T("confirmation_required","A reviewed HolyCodex file could not be checked safely, so removal did not continue.",i,{operation:"verify removal review",...a===void 0?{}:{path:a},recovery:"Check file access, then run remove again to review current state."})}if(o.length>0)throw Ov(o[0])}function Ov(e,t){return new T("confirmation_required","A reviewed HolyCodex item changed before removal. No reviewed changes were applied; run remove again to review the current state.",void 0,{operation:"remove HolyCodex",path:e,...t===void 0?{}:{key:t},recovery:"Run remove again to review the current state."})}async function TF(e,t){if(await je(e)!==t)throw Ov(e)}async function Xz(e,t){if(!t.managed_config)return Mt(["incomplete_install_state"]);try{let n=un(await je(e.configFile)),r=Od(t.profile,t.tier,{browserUse:t.capability_state?.browser_use.status==="healthy"&&t.capability_state.browser_use.selected,computerUse:t.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security,...t.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:t.tooling.git_bash.path}:{}}),o=[];for(let i of Object.keys(r))if((await Ga(n,t.managed_config,i)).status!=="unchanged")o.push(i);return o.length===0?ps({managed_keys:Object.keys(r).length}):Mt(["changed_holycodex_config"],{keys:o})}catch(n){return Mt(["config_unreadable"],{error:Un(n)})}}async function Qz(e,t,n,r,o={browserUse:!1,computerUse:!1}){try{let i=un(await je(e.configFile)),a=[],s=rs(t,n,{...o,...r===void 0?{}:{windowsGitBashExecutable:r}});for(let l of Vo(t,n)){let u=fe(i,`agents."${l.name}".config_file`),d=Ja(e.configFile,hd(l.name,s)).replaceAll("\\","/");if(typeof u!=="string"||Ja(e.configFile,u).replaceAll("\\","/")!==d){a.push(`${l.name}:registration`);continue}let p=await je(d);if(p===void 0){a.push(`${l.name}:missing`);continue}if(p!==Lc(l,{...o,...r===void 0?{}:{windowsGitBashExecutable:r}})){a.push(`${l.name}:changed`);continue}let f=un(p);if(f.name!==l.name||typeof f.description!=="string"||typeof f.developer_instructions!=="string"||f.model!==l.model||f.model_reasoning_effort!==l.effort||f.model_reasoning_summary!=="none"||f.model_verbosity!=="low"||f.tool_output_token_limit!==void 0||f.service_tier!==(n==="standard"?"default":"fast")||!Ch(l,f)||f.approval_policy!=="never"||f.web_search!==(l.permissions.network?"live":"disabled")||fe(f,"agents.enabled")!==!1||fe(f,"features.multi_agent")!==!1||fe(f,"features.multi_agent_v2")!==!1||fe(f,"features.agent_message_board")!==!1||fe(f,"features.context_management.experimental_mode")!==!0||Object.keys(f.features??{}).some((m)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(m)))a.push(`${l.name}:malformed`)}let c=await je(`${e.codexHome}/agents/root.toml`);if(c!==void 0&&Dc(c))a.push("root:stale");return a.length===0?ps({role_root:e.roleRoot,agent_types:Vo(t,n).map((l)=>l.name)}):Mt(["native_role_disagreement"],{roles:a})}catch(i){return Mt(["native_role_invalid"],{error:Un(i)})}}async function kr(e,t){let n={...t,status:"conflicted",step:"conflicted",managed_config:t.managed_config??{owner:"holycodex",schema:t.schema_epoch,installId:t.install_id,managed:{}},plugin_snapshot:t.plugin_snapshot??[],owned_plugins:t.owned_plugins??[]};if(Ie(ji,n)!==void 0)await ts(e.conflictedRecord,cn(n))}function kF(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||Td(r,e)))}function IF(e,t,n){return kF(e,t,n)??e}function ds(){return{owner:"holycodex",schema_epoch:"state-0.16",install_id:"remove-conflict",version:"0.0.0",digest:"0".repeat(64),profile:"default",tier:"standard",optional_selections:{browser_use:!1,computer_use:!1,sites:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function Iv(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)].filter((o)=>o!==ln);let t=(e?.plugin_snapshot??[]).filter((o)=>o.plugin_id!==ln&&(o.status==="missing"||o.status==="available")).map((o)=>o.plugin_id),n=e?.plugin_config?.before.preference.presence==="absent"&&e.plugin_config.after.preference.presence==="present"?[dn]:[],r=(e?.provider_config??[]).filter((o)=>o.plugin_id!==ln&&o.before.presence==="absent"&&o.after.presence==="present").map((o)=>o.plugin_id);return[...new Set([...t,...n,...r])]}function eK(e,t){let n=no(e,t);if(n!==void 0)return n;let r=[...e.installed,...e.available].find((o)=>o.pluginId===t);return r===void 0?void 0:{entry:r}}function ps(e){return{status:"healthy",reasons:[],details:e}}function Mt(e,t={}){return{status:"failed",reasons:e,details:t}}async function tK(e){await Mh(e,{force:!1}).catch((t)=>{if(!Xe(t,"ENOENT"))throw t})}function nK(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function Un(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function Ah(e,t){try{e.onProgress?.(t)}catch{}}var Bz;var Fh=b(()=>{Ya();ht();Ed();cd();md();Oh();yd();Qa();Za();Nc();Ph();Bz=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{lstat as rK,open as oK,rm as Hh}from"fs/promises";import{dirname as iK}from"path";function pn(e){let t=Ie(Sh,e);if(t===void 0)throw new T("install_failed","The installation options are invalid.");let n=t;return qF(n),n}function qF(e){if(e.officialPlugins?.includes(ln)!==!0)return;throw new T("install_failed","Browser Use is provided by Codex Desktop/runtime and cannot be installed by the HolyCodex CLI. Select the Browser Use capability instead; it is available only on supporting Codex surfaces.",void 0,{plugin_id:ln})}async function Lh(e){let t=await je(e.installOptions);return $F(t,e.installOptions)}function $F(e,t){if(e===void 0)return;let n;try{n=gv(e)}catch(i){throw new T("state_corrupt","The HolyCodex install options are not valid TOML.",i,{path:t})}let r=Ie(pd,n);if(r!==void 0)return r;let o=Ie(J0,n);if(o!==void 0)return{schema_version:1,profile:o.profile,tier:o.tier,capabilities:o.capabilities.filter((i)=>i==="browser_use"||i==="computer_use"||i==="sites").concat(...["browser_use","sites"].filter((i)=>!o.capabilities.includes(i))),additional_plugins:o.additional_plugins};if(r===void 0)throw new T("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}async function UF(e,t){if(Ie(pd,t)===void 0)throw new T("state_corrupt","The HolyCodex install options are invalid.");await qn(e.installOptions,yv(t))}function Rd(e){return{profile:e.profile,tier:e.tier,optional:{browser_use:e.capabilities.includes("browser_use"),computer_use:e.capabilities.includes("computer_use"),sites:e.capabilities.includes("sites")},officialPlugins:e.additional_plugins.filter((t)=>t!==ln)}}async function jF(e={},t=process.env){let n=Cr(e,t),r=await Lh(n);if(r!==void 0)return Rd(r);let o=await Vi(n);if(o===void 0)return{};return{profile:o.profile,tier:o.tier,optional:o.optional_selections,officialPlugins:$v(o)}}function HF(e,t,n,r){let o=["browser_use","computer_use","sites"].filter((i)=>n[i]);return{schema_version:1,profile:e,tier:t,capabilities:o,additional_plugins:[...new Set(r)].filter((i)=>i!==ln)}}function Td(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function Dh(e,t,n){let r=[{status:"conflicted",record:n},{status:"preparing",record:t}].filter((a)=>a.record!==void 0),o=r.length>1,i=o&&r.every(({record:a})=>Td(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?o&&!i?"incompatible":"orphaned":Td(s,e)?o&&!i?"incompatible":"bound":"stale";return{status:a,relation:c,install_id:s.install_id,digest:s.digest,recovery:c==="stale"||c==="incompatible"?"inspect":"reconcile",...e===void 0?{}:{active_install_id:e.install_id,active_digest:e.digest}}})}function Pv(e,t,n){let r=Dh(e,t,n);if(r.filter((i)=>i.relation==="stale"||i.relation==="incompatible").length>0)throw new T("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,BF(r));return r}function Av(e,t,n){let r=Dh(e,t,n);if(e===void 0&&r.some((o)=>o.relation==="incompatible"))throw new T("state_corrupt","HolyCodex has ambiguous transaction state and cannot recover safely.",void 0,BF(r));return r}function BF(e){return{recovery:e.map((t)=>t.recovery).join(","),transactions:e.map((t)=>`${t.status}:${t.relation}:${t.install_id}:${t.digest}`).join(","),active:e[0]?.active_install_id===void 0?"absent":`${e[0].active_install_id}:${e[0].active_digest}`}}async function fs(e={},t={},n=process.env){let r=Ie(dd,e);if(r===void 0)throw new T("install_failed","The installation options are invalid.");qF(r);let o=Cr(t,n),i=await je(o.installOptions),a=await je(o.activeRecord),s=$F(i,o.installOptions),c=s===void 0?void 0:Rd(s);Pr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let l=await Vi(o);if(l!==void 0&&!await Bc(l))throw new T("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:o.activeRecord});let u=await Ir(o.preparingRecord,l),d=await Ir(o.conflictedRecord,l);Pv(l,u,d);let p=[d,u].find((M)=>M!==void 0&&(l===void 0||Td(M,l)));if(p!==void 0){await Promise.resolve().then(() => Fh());let J=await vd(t,n);if(J.preserved.length>0||J.reasons.length>0)throw new T("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:J.preserved.join(","),reasons:J.reasons.join(",")});return await fs({profile:e.profile??c?.profile??p.profile,tier:e.tier??c?.tier??p.tier,optional:{browser_use:e.optional?.browser_use??c?.optional?.browser_use??p.optional_selections.browser_use,computer_use:e.optional?.computer_use??c?.optional?.computer_use??p.optional_selections.computer_use,sites:e.optional?.sites??c?.optional?.sites??p.optional_selections.sites},officialPlugins:e.officialPlugins??c?.officialPlugins??$v(p)},t,n)}let f=PK(e.profile??c?.profile,l?.profile),m=AK(e.tier??c?.tier,l?.tier),y=c?.optional,g=Dv(y,e.optional),x=MK(g,l?.optional_selections),P=Dv(Dv(l?.explicit_optional_selections,y),e.optional),_=e.officialPlugins??c?.officialPlugins??$v(l),I=t.runtime??ls(n),q=await us(I,!1),O=await Ih(I,!1,l?.tooling?.context7).then(()=>!0,()=>!1),C=q,N,w,A=[...new Set(wc(VF(x),_).map((M)=>Sr(M)??M))],E;try{E=t.officialPluginManager??await os.discover({...n,CODEX_HOME:o.codexHome})}catch(M){throw new T("capability_denied","Native Codex plugin installation is unavailable.",M,{recovery:"Install or expose Codex, then retry."})}if(!E.addMarketplace||!E.add||!E.list)throw new T("install_failed","Native Codex plugin installation and verification are unavailable.");let le;try{le=await E.list()}catch(M){throw new T("capability_denied","Native Codex plugin state could not be read safely.",M)}let He=A.filter((M)=>{if(!M.endsWith("@openai-curated"))return!1;let J=Mr(le,M);return!(J?.installed&&J.enabled)});Pr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let Be=l?.install_id??crypto.randomUUID().replaceAll("-",""),gt=await fd(),ot=l!==void 0&&l.version!==gt&&l.owned_plugins?.includes(dn)===!0?new Set([dn]):new Set,Qe=new Set((l?.owned_plugins??[]).filter((M)=>M!==ln)),fn=new Set([dn,...A]),tr=[...Qe].filter((M)=>!fn.has(M));if(tr.length>0&&E.remove===void 0)throw new T("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:tr.join(",")});let hs=(t.now?.()??new Date).toISOString(),nr=Od(f,m,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:Pt.frontend,security:Pt.security,...I.platform==="win32"?{windowsGitBashExecutable:q.status==="healthy"?q.path:as}:{}}),eg=await je(o.configFile),rR;try{rR=un(eg,o.configFile)}catch(M){if(M instanceof T&&M.code==="state_corrupt")await hK(t,M,o.configFile);throw M}let tg=l?.managed_config??fh({schema:Tn,installId:Be}),oR=await Uh(rR,tg),ng=await pK(t,o.configFile,oR.document,['plugins."holycodex@holycodex"',"marketplaces.holycodex",...Object.keys(nr)]),{document:Jc,conflicts:Gc,decisions:gL}=ng,Gi=await qh(Jc),rg=l?.plugin_config?.before??Gi,io=rg,gs=t.resolveConflicts!==void 0,ys=[],Yc=[],Zc=[];if(Yc=["preference","marketplace"].filter((J)=>{let F=Gi[J].digest,Se=Gi[J],et=J==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:Vc},qt=Se.presence==="present"&&JSON.stringify(Se.safe_value)!==JSON.stringify(et),Ve=l?.plugin_config!==void 0&&F!==l.plugin_config.after[J].digest&&F!==l.plugin_config.before[J].digest;return qt||Ve}).map((J)=>{let F=J==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",Se=Gi[J],et=J==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:Vc};return Ar({path:o.configFile,key:F,action:"replace",category:"config-key",target:F,existing:Se.safe_value??{presence:Se.presence},desired:et,explanation:`The existing ${F} entry does not match the HolyCodex plugin configuration.`,...J==="preference"&&AF(Jc,"plugins",Wi)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),gs)ys.push(...Yc);let og=[...new Set([...A,...(l?.provider_config??[]).map((M)=>M.plugin_id),...l?.owned_plugins??[]])].filter((M)=>M!==dn&&M!==ln),Yi=await $h(Jc,og);{let M=new Set(l?.owned_plugins??[]);if(Zc=Yi.filter((F)=>{let Se=l?.provider_config?.find((Ve)=>Ve.plugin_id===F.plugin_id),et=M.has(F.plugin_id)&&Se!==void 0&&F.before.digest!==Se.after.digest&&F.before.digest!==Se.before.digest,qt=A.includes(F.plugin_id)&&F.before.presence==="present"&&F.before.safe_value?.value!==!0;return et||qt}).map((F)=>{let Se=`plugins."${F.plugin_id}"`;return Ar({path:o.configFile,key:Se,action:"replace",category:"config-key",target:Se,existing:F.before.safe_value??{presence:F.before.presence},desired:{kind:"boolean",value:!0},explanation:`The existing provider plugin entry ${F.plugin_id} does not match the selected plugin configuration.`,...A.includes(F.plugin_id)&&AF(Jc,"plugins",F.plugin_id)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),gs)ys.push(...Zc)}let ig=Yi.map((M)=>{let J=l?.provider_config?.find((F)=>F.plugin_id===M.plugin_id);return J===void 0?M:{plugin_id:M.plugin_id,before:J.before,after:J.before}}),Ld=ig,iR=oR.state,aR=await Fv(Jc,iR,l),sR=await Uh(aR.document,aR.state),cR=await Lv(sR.document,sR.state),{document:Nr,state:rr}=cR;bK(Nr,rr);let xs;if(l!==void 0){xs=Od(l.profile,l.tier,{browserUse:l.optional_selections.browser_use,computerUse:l.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security,...l.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:l.tooling.git_bash.path}:{}});let M=qm(l.version.split("-",1)[0]);for(let J of Uo){let F=l.managed_artifacts.find(({path:Se})=>Se.endsWith(`/${J}.toml`));xs[`agents."${J}".config_file`]=F?.path??`holycodex/agents/${J}.toml`}if(Uu(M,sK)<0)xs.model="gpt-6-astra",xs.model_reasoning_effort=l.profile==="low"?"low":l.profile==="default"?"medium":"high";delete xs.developer_instructions}let ag=await SK(Nr,rr,nr,xs),Ss;try{Ss=await Ic(Nr,rr,ag,{schema:Tn,installId:Be})}catch(M){if(M instanceof T)throw M;throw new T("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",M,{recovery:"Converge the conflicting Codex setting, then retry."})}let Xc=[];if(Ss.driftedKeys.length>0)Xc=Ss.driftedKeys.map((M)=>{let J=rr.managed[M],F=fe(Nr,M),Se=nr[M];return Ar({path:o.configFile,key:M,action:"replace",category:"config-key",target:M,existing:F??J?.lastManagedValue,desired:Se,explanation:`The managed Codex setting ${M} changed outside the previous transaction.`})});let Dd=Object.entries(nr).flatMap(([M,J])=>{let F=M;if(rr.managed[F]!==void 0)return[];let Se=fe(Nr,F);if(Se===void 0||JSON.stringify(Se)===JSON.stringify(J))return[];return[Ar({path:o.configFile,key:F,action:"replace",category:"config-key",target:F,existing:Se,desired:J,explanation:`The existing Codex setting ${F} is user-owned and differs from the HolyCodex install value.`,defaultDecision:"keep",validDecisions:["keep","replace","cancel"]})]});if(gs)ys.push(...Dd);if(gs)ys.push(...Xc);let Qc;try{Qc=await vh(o.codexHome,f,l?.managed_artifacts,m,I.platform==="win32"?q.status==="healthy"?q.path:as:void 0,{browserUse:x.browser_use,computerUse:x.computer_use})}catch(M){throw new T("install_failed",Id(M),M)}if(gs)ys.push(...Qc.map(Ar));let qd=[...Gc,...Yc,...Zc,...Dd,...Xc,...Qc.map(Ar)],yL=new Set(Gc.map((M)=>M.identity)),xL=gs?ys:qd.filter((M)=>!yL.has(M.identity)),lR=await Wh(t,xL,!0),ao={...lR,decisions:new Map([...gL,...lR.decisions])},uR=[],el={...ag},$d=rr.managed,dR=async()=>{uR=Qc.map((qt)=>{let Ve=Ar(qt),lt=ao.decisions.get(Ve.identity);return lt===void 0?Ve:{...Ve,decision:lt}});let M=await MF(Nr,Nr,rg,ig,Gi,Yi,Yc,Zc,ao.decisions,A),J=Bh(M.document,Gc,ao.decisions);io=M.pluginConfigBefore,Ld=M.providerConfigBefore;let F={...rr.managed},Se={...ag};for(let qt of[...Dd,...Xc]){let Ve=qt.key;if(Ve===void 0)continue;let lt=Ve,Rt=ao.decisions.get(qt.identity);if(Rt!=="keep"&&Rt!=="replace")throw new T("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:Ve});let co=F[lt],jn=nr[lt];if(jn===void 0)throw new T("state_corrupt","The managed conflict cannot be verified.",void 0,{path:o.configFile,key:Ve});let Zi=fe(Nr,lt);if(Rt==="replace"){if(J=Li(J,lt,jn),co!==void 0)F[lt]={...co,lastManagedValue:await sn(lt,jn)}}else{if(delete Se[lt],co===void 0)continue;if(Zi===void 0){delete F[lt];continue}F[lt]={...co,lastManagedValue:await sn(lt,Zi)}}}if(Ss=await Ic(J,{...rr,managed:F},Se,{schema:Tn,installId:Be}),Ss.driftedKeys.length>0)throw new T("state_corrupt","The accepted managed conflicts did not converge.");el=Se;let et={...rr.managed};for(let qt of[...Dd,...Xc]){let Ve=qt.key;if(Ve===void 0)continue;let lt=fe(Nr,Ve),Rt=et[Ve];if(Rt!==void 0&&lt===void 0)delete et[Ve];else if(Rt!==void 0&&lt!==void 0)et[Ve]={...Rt,lastManagedValue:await sn(Ve,lt)}}$d=et};await dR();let pR=()=>qd.map((M)=>{let J=Ar(M),F=ao.decisions.get(J.identity);return F===void 0?J:{...J,decision:F}}),fR=(M)=>Object.fromEntries(["config-key","invalid-config","native-plugin","role-asset"].flatMap((J)=>{let F=M.filter((Se)=>Se.category===J).length;return F===0?[]:[[J,F]]})),Ud=pR(),mR=fR(Ud),SL=NK(q,O,le,A);if(t.reviewInstall!==void 0)while(!0){let M=await t.reviewInstall({operation:l===void 0?"install":"upgrade",...l===void 0?{}:{fromVersion:l.version},toVersion:gt,profile:f,tier:m,capabilities:{browser_use:x.browser_use,computer_use:x.computer_use,sites:x.sites},additionalPlugins:[..._],conflicts:Ud,conflictCounts:mR,tools:SL});if(M.action==="cancel")throw new T("confirmation_required","Install review was cancelled.");if(M.action==="resolve"){if(qd.length===0)throw new T("confirmation_required","There are no managed conflicts to resolve.");ao=await Wh(t,qd,!0),await dR(),Ud=pR(),mR=fR(Ud);continue}if(M.action==="change"){if(M.request===void 0)throw new T("confirmation_required","Changing install options requires a revised request.");return await fs(M.request,t,n)}if(M.action==="apply")break;throw new T("confirmation_required","Unknown install review action.")}let sg={owner:"holycodex",schema_epoch:Tn,install_id:Be,version:gt,digest:l?.digest??"0".repeat(64),profile:f,tier:m,optional_selections:x,explicit_optional_selections:P,official_plugins:A,capability_state:Vh(x),managed_artifacts:l?.managed_artifacts??[],installed_at:hs,status:"preparing",step:"validated",managed_config:iR,plugin_snapshot:[],plugin_config:{plugin_id:dn,before:io,after:io},provider_config:Ld,owned_plugins:[...Qe],...l?.tooling===void 0?{}:{tooling:l.tooling}};await Mc(o.stateRoot),await er(o.preparingRecord,sg);let tl=[],so,hR=!1,gR=new Set,cg=new Set,jd=new Set,Rn=new Set(Qe),lg=new Set(Qe),ug=new Set,he=sg,yR=!1,Fr,dg,nl=Ss.state,xR=!1,SR=!1;try{try{C=await us(I,!0)}catch(ie){if(ie instanceof me)throw new T("capability_denied",ie.message,ie,ie.details);throw ie}try{N=await Ih(I,!0,l?.tooling?.context7)}catch(ie){w=`Optional ctx7 is unavailable: ${Id(ie)}`}let M=N??l?.tooling?.context7,J={git_bash:C,...M===void 0?{}:{context7:M}},F={...sg,tooling:J};if(he=F,await er(o.preparingRecord,he),E.ensureOfficialMarketplace!==void 0&&He.length>0)try{await E.ensureOfficialMarketplace(He)}catch(ie){throw new T("capability_denied",`The selected official Codex provider marketplace is unavailable: ${Id(ie)}`,ie,{recovery:"Check Codex network and marketplace policy, then retry."})}try{tl=await _K({list:()=>E.list()},[...new Set([dn,...A,...Qe])])}catch(ie){throw new T("capability_denied","Native Codex plugin state could not be read safely.",ie)}F={...F,plugin_snapshot:tl},he=F,await er(o.preparingRecord,he);let Se=un(await je(o.configFile),o.configFile),et=Bh(Se,Gc,ao.decisions);await xK(et,Gi,Yi);let qt=await Fv(et,tg,l),Ve=await Uh(qt.document,qt.state);Fr=(await Lv(Ve.document,Ve.state)).document,await FF(Fr,Nr,{...rr,managed:$d},el),Pr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await Mc(o.roleRoot),so=await lv(o.codexHome,f,l?.managed_artifacts,m,C.status==="healthy"?C.path:void 0,Qc.length===0?t.resolveConflict:void 0,uR,{browserUse:x.browser_use,computerUse:x.computer_use}),he={...F,step:"roles_prepared",managed_artifacts:so.managed_artifacts},await er(o.preparingRecord,he),Pr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),Pr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),yR=!0;let Rt=Fr;if(Rt===void 0)throw new T("state_corrupt","The pre-mutation configuration baseline is missing.");Rt=Wo(Rt,"plugins",Wi,{enabled:!0}),Rt=Wo(Rt,"marketplaces",zc,{source_type:"git",source:Vc});for(let ie of A)Rt=Wo(Rt,"plugins",ie,{enabled:!0});let co=await qh(Rt),Zi=(await $h(Rt,og)).map((ie)=>({plugin_id:ie.plugin_id,before:Yi.find((yt)=>yt.plugin_id===ie.plugin_id)?.before??ie.before,after:ie.before}));if(he={...he,plugin_config:{plugin_id:dn,before:io,after:co},provider_config:Zi},await er(o.preparingRecord,he),eg===void 0)try{dg=await CK(o.configFile);let ie=await je(o.configFile);if(dg===void 0||ie!=="")throw new T("confirmation_required","Codex config.toml appeared during installation; review the latest configuration and retry.",void 0,{operation:"initialize Codex configuration",path:o.configFile})}catch(ie){if(ie instanceof T)throw ie;throw new T("permission_denied","Codex config.toml could not be initialized before plugin setup.",ie,{operation:"initialize Codex configuration",path:o.configFile,recovery:"Check CODEX_HOME permissions, then retry."})}await E.addMarketplace(aK),await EK({list:()=>E.list(),add:(ie)=>E.add(ie)},[dn,...A],ot,async(ie,yt)=>{if(yt==="new")gR.add(ie),Rn.add(ie),lg.add(ie),he={...he,owned_plugins:[...Rn]};else ug.add(ie),Rn.add(ie),lg.add(ie),he={...he,owned_plugins:[...Rn]};await er(o.preparingRecord,he)}),he={...he,step:"plugins_installed"},await er(o.preparingRecord,he),Pr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let _R=await je(o.configFile),bL=un(_R,o.configFile),_L=Bh(bL,Gc,ao.decisions),wR=await Fv(_L,tg,l),vR=await Uh(wR.document,wR.state),wL=await Lv(vR.document,vR.state);if(Fr===void 0)throw new T("state_corrupt","The pre-mutation configuration baseline is missing.");let pg=await MF(wL.document,Fr,rg,ig,Gi,Yi,Yc,Zc,ao.decisions,A),Xi=pg.document;for(let ie of Object.keys($d)){let yt=ie,lo=fe(Fr,yt);Xi=lo===void 0?Rr(Xi,yt):Li(Xi,yt,lo)}io=pg.pluginConfigBefore,Ld=pg.providerConfigBefore;let Hd=await qh(Xi),RR=await $h(Xi,og),TR=RR.map((ie)=>({plugin_id:ie.plugin_id,before:Ld.find((yt)=>yt.plugin_id===ie.plugin_id)?.before??ie.before,after:ie.before})),CR=RR.map((ie)=>({plugin_id:ie.plugin_id,before:Yi.find((yt)=>yt.plugin_id===ie.plugin_id)?.before??ie.before,after:ie.before}));he={...he,plugin_config:{plugin_id:dn,before:io,after:Hd},provider_config:CR};let OR={};for(let[ie,yt]of Object.entries($d)){let lo=ie,IR=fe(Fr,lo);OR[lo]={...yt,...IR===void 0?{}:{lastManagedValue:await sn(lo,IR)}}}let ER={...rr,managed:OR};await FF(Xi,Fr,ER,el);let Bd=await Ic(Xi,ER,el,{schema:Tn,installId:Be});if(Bd.driftedKeys.length>0)throw new T("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Bd.driftedKeys.join(",")});if(Pr(t,{stage:"config",status:"started",message:"Configuring Root"}),nl=Bd.state,he={...he,managed_config:nl,plugin_config:{plugin_id:dn,before:io,after:Hd},provider_config:CR},await je(o.configFile)!==_R)throw new T("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:o.configFile});if(await qn(o.configFile,Cd(Bd.document)),hR=!0,he={...he,step:"config_published"},await er(o.preparingRecord,he),tr.length>0)await kK({list:()=>E.list(),remove:(yt)=>E.remove(yt)},tr,async(yt,lo)=>{if(lo==="removed")cg.add(yt),Rn.delete(yt);else if(lo==="absent")Rn.delete(yt);else jd.add(yt);he={...he,owned_plugins:[...Rn]},await er(o.preparingRecord,he)});Pr(t,{stage:"config",status:"completed",message:"Root configuration published"}),Pr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await vK(o,f,m,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:Pt.frontend,security:Pt.security,...C.status==="healthy"?{windowsGitBashExecutable:C.path}:{}},nl,so.preserved,el),Pr(t,{stage:"verification",status:"completed",message:"Installation verified"});let kR=Vh(x),vL=await zh({owner:"holycodex",install_id:Be,version:gt,profile:f,tier:m,optional_selections:x,explicit_optional_selections:P,official_plugins:A,capability_state:kR,managed_artifacts:so.managed_artifacts,managed_config:nl,plugin_config:{plugin_id:dn,before:io,after:Hd},provider_config:TR,plugin_snapshot:tl,owned_plugins:[...Rn],tooling:J}),fg={owner:"holycodex",schema_epoch:Tn,install_id:Be,version:gt,digest:vL,profile:f,tier:m,optional_selections:x,explicit_optional_selections:P,official_plugins:A,capability_state:kR,managed_artifacts:so.managed_artifacts,installed_at:hs,status:"active",step:"active",managed_config:nl,plugin_snapshot:tl,plugin_config:{plugin_id:dn,before:io,after:Hd},provider_config:TR,owned_plugins:[...Rn],tooling:J};if(Ie(Ac,fg)===void 0)throw new T("state_corrupt","The HolyCodex configuration is invalid.");return xR=!0,await ts(o.activeRecord,cn(fg)),SR=!0,await UF(o,HF(f,m,x,_)),await jh(o.preparingRecord),await jh(o.conflictedRecord),Pr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:fg,optional_plugins:A,preserved:so.preserved,warnings:[...so.preserved.length===0?[]:["modified managed files were preserved"],...w===void 0?[]:[w]]}}catch(M){let J=[];if(xR)try{if(a===void 0)await Hh(o.activeRecord,{force:!1}).catch((F)=>{if(!Xe(F,"ENOENT"))throw F});else await qn(o.activeRecord,a)}catch{J.push("active_record")}if(SR)try{if(i===void 0)await Hh(o.installOptions,{force:!1}).catch((F)=>{if(!Xe(F,"ENOENT"))throw F});else await qn(o.installOptions,i)}catch{J.push("install_options")}if(yR||hR)try{if(Fr!==void 0)await wK(o.configFile,he,Fr,lg)}catch{J.push("config")}if(J.length===0&&eg===void 0)try{if(await je(o.configFile)===""&&await OK(o.configFile,dg))await Hh(o.configFile,{force:!1})}catch{J.push("config_initialization")}if(so!==void 0)try{if((await Rh(so.rollback)).preserved.length>0)J.push("roles")}catch{J.push("roles")}if(ug.size>0)J.push(...[...ug].map((F)=>`plugin:${F}`));for(let F of gR)try{await E.remove?.(F)}catch{J.push(`plugin:${F}`)}for(let F of new Set([...cg,...jd]))try{await IK({list:()=>E.list(),add:(Se)=>E.add(Se)},F,tl.find((Se)=>Se.plugin_id===F)?.status),cg.delete(F),jd.delete(F),Rn.add(F),he={...he,owned_plugins:[...Rn]},await er(o.preparingRecord,he)}catch{Rn.add(F),jd.add(F),he={...he,owned_plugins:[...Rn]},await er(o.preparingRecord,he).catch(()=>{return}),J.push(`plugin:${F}`)}if(N?.ownership==="holycodex"&&l?.tooling?.context7?.ownership!=="holycodex")try{if(!await wd(I,N))J.push("context7")}catch{J.push("context7")}if(J.length>0){try{let Se=un(await je(o.configFile),o.configFile),et=he.plugin_config,qt=await qh(Se),Ve=et===void 0?void 0:{...et,after:{preference:qt.preference.digest===et.before.preference.digest?et.before.preference:et.after.preference,marketplace:qt.marketplace.digest===et.before.marketplace.digest?et.before.marketplace:et.after.marketplace}},lt=he.provider_config,Rt=await $h(Se,lt?.map((jn)=>jn.plugin_id)??[]),co=lt?.map((jn)=>{let Zi=Rt.find((bR)=>bR.plugin_id===jn.plugin_id);return Zi!==void 0&&Zi.before.digest===jn.before.digest?{...jn,after:jn.before}:jn});he={...he,...Ve===void 0?{}:{plugin_config:Ve},...co===void 0?{}:{provider_config:co}}}catch{}let F=!1;try{await er(o.conflictedRecord,{...he,step:"conflicted",status:"conflicted"}),F=!0}catch{}if(F)await jh(o.preparingRecord).catch(()=>{return})}else await jh(o.preparingRecord).catch(()=>{return});if(M instanceof Qn)throw M;if(M instanceof T)throw M;throw new T(M instanceof ro||M instanceof Ko?"capability_denied":"install_failed",Id(M),M,J.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function Vi(e){let t=await rv(e.activeRecord,ld);if(t===void 0)return;let n=t.optional_selections,o=typeof n==="object"&&n!==null&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"work")?void 0:Ie(Ac,t);if(o!==void 0)return o;let i=Ie(G0,t);if(i===void 0)throw new T("state_corrupt","The HolyCodex configuration is invalid.");if(!await WF(i))throw new T("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord});let a="profile"in i&&i.profile!==void 0?i.profile:("plan"in i)?i.plan:void 0;if(a===void 0)throw new T("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=Bm(a)}catch(E){throw new T("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,E,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([E])=>E!=="plan")):i,{optional_selections:l,explicit_optional_selections:u}=i,d={browser_use:l.browser_use??Qt.browser_use,computer_use:l.computer_use,sites:l.sites??Qt.sites,coding:!0},p={...u.computer_use===void 0?{}:{computer_use:u.computer_use},...u.browser_use===void 0?{}:{browser_use:u.browser_use},...u.sites===void 0?{}:{sites:u.sites}},f=i.capability_state===void 0?void 0:Vh(d,new Map([["browser_use","missing"],["sites","missing"]])),m=(i.official_plugins??[]).filter((E)=>!kd(E)),y=i.owned_plugins?.filter((E)=>!kd(E)),g=i.provider_config?.filter((E)=>!kd(E.plugin_id)),x=i.plugin_snapshot?.filter((E)=>!kd(E.plugin_id)),{optional_selections:P,explicit_optional_selections:_,capability_state:I,official_plugins:q,owned_plugins:O,provider_config:C,plugin_snapshot:N,...w}=c,A={...w,profile:s,optional_selections:d,explicit_optional_selections:p,official_plugins:m,...f===void 0?{}:{capability_state:f},...y===void 0?{}:{owned_plugins:y},...g===void 0?{}:{provider_config:g},...x===void 0?{}:{plugin_snapshot:x},digest:await zh({owner:i.owner,install_id:i.install_id,version:i.version,profile:s,tier:i.tier,optional_selections:d,explicit_optional_selections:p,official_plugins:m,capability_state:f??null,managed_artifacts:i.managed_artifacts,...i.managed_config===void 0?{}:{managed_config:i.managed_config},...i.plugin_config===void 0?{}:{plugin_config:i.plugin_config},...g===void 0?{}:{provider_config:g},...x===void 0?{}:{plugin_snapshot:x},...y===void 0?{}:{owned_plugins:y},...i.tooling===void 0?{}:{tooling:i.tooling}})};return DF.set(A,i.digest),A}async function Ir(e,t){let n=await rv(e,ld);if(n===void 0)return;let r=Ie(ji,n);if(r!==void 0)return r;let o=Ie(X0,n);if(o===void 0)throw new T("state_corrupt","The HolyCodex transaction state is invalid.",void 0,{path:e});let i=o,a=i.profile??i.plan;if(typeof a!=="string")throw new T("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e});let s;try{s=Bm(a)}catch(w){throw new T("state_corrupt","The persisted transaction profile requires an explicit replacement.",w,{path:e,profile:a})}let{optional_selections:c,explicit_optional_selections:l}=i,u={browser_use:c.browser_use??Qt.browser_use,computer_use:c.computer_use??!1,sites:c.sites??Qt.sites,coding:!0},d={...l.browser_use===void 0?{}:{browser_use:l.browser_use},...l.computer_use===void 0?{}:{computer_use:l.computer_use},...l.sites===void 0?{}:{sites:l.sites}},f=i.capability_state===void 0?void 0:Vh(u,new Map([["browser_use","missing"],["sites","missing"]])),{plan:m,profile:y,optional_selections:g,explicit_optional_selections:x,capability_state:P,..._}=i,I=typeof _.digest==="string"?_.digest:void 0,q=t===void 0?void 0:DF.get(t),O=t!==void 0&&_.install_id===t.install_id&&(I===t.digest||q!==void 0&&I===q)?t.digest:I,C={..._,profile:s,optional_selections:u,explicit_optional_selections:d,...f===void 0?{}:{capability_state:f},...O===void 0?{}:{digest:O}},N=Ie(ji,C);if(N===void 0)throw new T("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e});return N}function VF(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites}}function un(e,t="config.toml"){if(e===void 0||e.trim().length===0)return{};try{let n=globalThis.Bun,r=n?.TOML?.parse?n.TOML.parse(e):gv(e),o=Ie(za,r);if(o===void 0){let i=qv(r),a=i===void 0?"an unsupported TOML value":`the TOML value ${i}`;throw new T("state_corrupt",`${t} contains ${a} that HolyCodex cannot preserve. Convert it to a string, number, boolean, table, or array, then retry.`,void 0,{path:t,...i===void 0?{}:{key:i},reason:"unsupported_toml_value"})}return o}catch(n){if(n instanceof T)throw n;let r=Id(n),o=fK(e,r),i=o===void 0?`${t} contains invalid TOML: ${r}. Fix the TOML syntax and retry; HolyCodex cannot safely rewrite malformed TOML.`:`${t} contains invalid TOML at line ${o.line}, column ${o.column} (offset ${o.offset}): ${r}. Fix the syntax at that location and retry; HolyCodex cannot safely rewrite malformed TOML.`;throw new T("state_corrupt",i,n,{path:t,parser_message:r,...o===void 0?{}:o,reason:"invalid_toml_syntax"})}}function qv(e,t=[]){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number")return Number.isFinite(e)?void 0:Nv(t);if(Array.isArray(e)){for(let[n,r]of e.entries()){let o=qv(r,[...t,"["+n+"]"]);if(o!==void 0)return o}return}if(typeof e==="object"&&e!==null){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return Nv(t);for(let[r,o]of Object.entries(e)){let i=qv(o,[...t,r]);if(i!==void 0)return i}return}return Nv(t)}function Nv(e){return e.length===0?"<root>":e.join(".")}function lK(e,t){let n=new Map;for(let r of t)for(let o of uK(r)){let i=fe(e,o);if(i!==void 0&&!zi(i))n.set(o,i)}return[...n].map(([r,o])=>({key:r,value:o}))}function uK(e){let t=[],n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r)r=!1;else if(i==="\\")r=!0;else if(i==='"')n=!1;continue}if(i==='"')n=!0;else if(i===".")t.push(e.slice(0,o))}return t}function dK(e,t){let n=JSON.stringify(t.value);return new T("state_corrupt",`${e} has the non-table value ${n} at ${t.key}, but the HolyCodex installer needs that path to be a table. Remove it after review or convert it to a table and retry; replacing it automatically could discard user configuration.`,void 0,{path:e,key:t.key,existing:n,reason:"expected_table"})}async function pK(e,t,n,r){let o=lK(n,r).map((a)=>{let s=dK(t,a);return Ar({identity:`invalid-config:${t}:${a.key}`,category:"invalid-config",target:a.key,existing:a.value,desired:`Remove the conflicting value at ${a.key} so HolyCodex can create the required table.`,explanation:`${s.message} Choose remove to continue or cancel to repair it manually.`,path:t,key:a.key,action:"remove",defaultDecision:"cancel",validDecisions:["remove","cancel"]})});if(o.length===0)return{document:n,conflicts:o,decisions:new Map};let i=await Wh(e,o,!0);return{document:Bh(n,o,i.decisions),conflicts:o,decisions:i.decisions}}function Bh(e,t,n){let r=e;for(let o of t){if(n.get(o.identity)!=="remove"||o.key===void 0)throw new T("confirmation_required",`Invalid configuration at ${o.target} can only be removed after review or cancelled.`,void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},existing:JSON.stringify(o.existing),valid_decisions:o.validDecisions??["remove","cancel"]});let a=fe(r,o.key);if(a===void 0)continue;if(JSON.stringify(a)!==JSON.stringify(o.existing))throw new T("confirmation_required",`Invalid configuration at ${o.key} changed after review; review the current value and retry.`,void 0,{path:o.path,key:o.key,reviewed:JSON.stringify(o.existing),current:JSON.stringify(a)});r=Rr(r,o.key)}return r}function fK(e,t){let n,r=/found \(0x([0-9a-f]{2})\)/iu.exec(t),o=/found '((?:\\.|[^'])*)'/u.exec(t),i=r===null?o?.[1]?.replaceAll("\\'","'").replaceAll("\\\"",'"'):String.fromCharCode(Number.parseInt(r[1],16));if(i!==void 0)n=mK(e,i);else if(/end of file|unterminated/iu.test(t))n=e.length;else if(/missing value after/iu.test(t)){let c=e.lastIndexOf("="),l=c<0?-1:e.indexOf(`
33
+ schema (${r._tag}): ${r}`;return o},LA=(e)=>Ui("Invalid Argument",e),DA=(e)=>Ui("Unsupported key schema",void 0,void 0,e),qA=(e)=>Ui("Unsupported literal",`literal value: ${Hr(e)}`),fb=(e)=>Ui("Duplicate index signature",`${e} index signature`),UA,$A,mb=(e)=>Ui("Duplicate property signature transformation",`Duplicate key ${Hr(e)}`),hb=(e)=>Ui("Duplicate property signature",`Duplicate key ${Hr(e)}`);var gb=w(()=>{st();at();Pu();UA=Ui("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),$A=Ui("Invalid element","A required element cannot follow an optional element. ts(1257)")});var HA,BA,VA,WA,zA,KA,JA;var GA=w(()=>{HA=Symbol.for("effect/SchemaId/DateFromSelf"),BA=Symbol.for("effect/SchemaId/GreaterThan"),VA=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),WA=Symbol.for("effect/SchemaId/Int"),zA=Symbol.for("effect/SchemaId/MinLength"),KA=Symbol.for("effect/SchemaId/MaxLength"),JA=Symbol.for("effect/SchemaId/MinItems")});class wc{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(e,t,n,r={}){this.typeParameters=e,this.decodeUnknown=t,this.encodeUnknown=n,this.annotations=r}toString(){return Ue(Xr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:rt(this.annotations)}}}class Ya{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Ue(Xr(this),()=>Hr(this.literal))}toJSON(){return{_tag:this._tag,literal:li(this.literal)?String(this.literal):this.literal,annotations:rt(this.annotations)}}}class Nm{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Ue(Xr(this),()=>Hr(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:rt(this.annotations)}}}class cM{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class lM{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class uM{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class dM{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class pM{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class mM{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class gM{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class xM{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class bM{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class wM{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class vM{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return _r(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class _c{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:rt(this.annotations)}}toString(){return String(this.type)}}class Nu{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(e,t,n,r={}){this.elements=e,this.rest=t,this.isReadonly=n,this.annotations=r;let o=!1,i=!1;for(let a of e)if(a.isOptional)o=!0;else if(o){i=!0;break}if(i||o&&t.length>1)throw Error($A)}toString(){return Ue(Xr(this),()=>qH(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:rt(this.annotations)}}}class vc{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,TM(e))this.parameter=e;else throw Error(UA)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class Qr{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(e,t,n={}){this.annotations=n;let r={};for(let i=0;i<e.length;i++){let a=e[i].name;if(Object.prototype.hasOwnProperty.call(r,a))throw Error(hb(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=Jb(t[i].parameter);if(Dm(a)){if(o.string)throw Error(fb("string"));o.string=!0}else if(_M(a)){if(o.symbol)throw Error(fb("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Ue(Xr(this),()=>UH(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:rt(this.annotations)}}}class on{types;annotations;static make=(e,t)=>qm(e)?new on(e,t):e.length===1?e[0]:Lm;static unify=(e,t)=>on.make(HH(CM(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Ue(Xr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:rt(this.annotations)}}}class Um{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=Iu(e)}toString(){return Xr(this).pipe(ur(()=>pr(gT(this.f)(),(e)=>Xr(e))),Ue(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=yb.get(e);if(t)return t;return yb.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:rt(this.annotations)},yb.set(e,t),t}}class Fu{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return Au(this).pipe(Ue(()=>pt(PM(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Lu(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:rt(this.annotations)}}}class Bb{from;to;transformation;annotations;_tag="Transformation";constructor(e,t,n,r={}){this.from=e,this.to=t,this.transformation=n,this.annotations=r}toString(){return Ue(Xr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:rt(this.annotations)}}}class Vb{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class Wb{propertySignatureTransformations;_tag="TypeLiteralTransformation";constructor(e){this.propertySignatureTransformations=e;let t={},n={};for(let r of e){let o=r.from;if(t[o])throw Error(mb(o));t[o]=!0;let i=r.to;if(n[i])throw Error(mb(i));n[i]=!0}}}function Yn(e,t){let n=!1,r=wa(e.length);for(let o=0;o<e.length;o++){let i=e[o],a=t(i);if(a!==i)n=!0;r[o]=a}return n?r:e}function KH(e){return pt(Nb(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Hr(n)}>`).join("")})}var ZA,Sb,XA,bb,Im,Pm,xn,Am,jo,wb,_b,vb,Rb,Tb,Cb,QA,Ob,kb,Eb,Ib,Pb,Ab,Mb,Qt,Nb,eM,tM,Fb,Lb,Au,Db,nM,rM,oM,iM,aM,qb,PH,Ub=(e)=>ST(PH(e),(t)=>t===!0),$b,AH,MH=(e)=>ur(AH(e),()=>Au(e)),Mu=(e)=>(t)=>t._tag===e,Mm,sM,Fm,NH,Lm,jb,fM,hM,Dm,yM,SM,FH,LH,_M,DH,$i,RM=(e)=>e.map((t)=>t.type),qH=(e)=>{let t=e.elements.map(String).join(", ");return _T(e.rest,{onEmpty:()=>`readonly [${t}]`,onNonEmpty:(n,r)=>{let o=String(n),i=o.includes(" | ")?`(${o})`:o;if(r.length>0){let a=r.map(String).join(", ");if(e.elements.length>0)return`readonly [${t}, ...${i}[], ${a}]`;else return`readonly [...${i}[], ${a}]`}else if(e.elements.length>0)return`readonly [${t}, ...${i}[]]`;else return`ReadonlyArray<${o}>`}})},kt,TM=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return TM(e.from)}return!1},YA=(e)=>e.map(String).join("; "),UH=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${YA(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${YA(e.indexSignatures)} }`;else return"{}"},$H,jH,CM=(e)=>Il(e,(t)=>Hb(t)?CM(t.types):[t]),HH=(e)=>{let t=$H(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[fM];case"UnknownKeyword":return[jb];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!r[i._tag])r[i._tag]=i,n.push(i);break}case"Literal":{let a=typeof i.literal;switch(a){case"string":case"number":case"bigint":case"boolean":{let s=jH[a];if(!r[s]&&!o.includes(i.literal))o.push(i.literal),n.push(i);break}case"object":{if(!o.includes(i.literal))o.push(i.literal),n.push(i);break}}break}case"UniqueSymbol":{if(!r.SymbolKeyword&&!o.includes(i.symbol))o.push(i.symbol),n.push(i);break}case"TupleType":{if(!r.ObjectKeyword)n.push(i);break}case"TypeLiteral":{if(i.propertySignatures.length===0&&i.indexSignatures.length===0){if(!r["{}"])r["{}"]=i,n.push(i)}else if(!r.ObjectKeyword)n.push(i);break}default:n.push(i)}return n},OM=(e,t)=>e.map(t),qm=(e)=>e.length>1,Hb,yb,Lu,$m,Du=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[Pm];let o={...r,...t},i=qb(e);if($e(i))o[Ab]=Du(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},BH="[\\s\\S]*?",VH="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",kM=(e,t)=>{switch(e._tag){case"Literal":return dc(String(e.literal));case"StringKeyword":return BH;case"NumberKeyword":return VH;case"TemplateLiteral":return EM(e,t,!1);case"Union":return e.types.map((n)=>kM(n,t)).join("|")}},WH=(e,t,n,r)=>{if(Hb(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},EM=(e,t,n)=>{let r="";if(e.head!==""){let o=dc(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=kM(o.type,t);if(r+=WH(o.type,i,t,n),o.literal!==""){let a=dc(o.literal);r+=t&&n?`(${a})`:a}}return r},IM=(e)=>new RegExp(`^${EM(e,!1,!0)}$`),zb=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new vc(i,t,!0));break;case"Literal":if(Ut(i.literal)||kn(i.literal))n.push(new kt(i.literal,t,!1,!0));else throw Error(qA(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new kt(s,t,!1,!0));break}case"UniqueSymbol":n.push(new kt(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(DA(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},Kb=(e)=>(t)=>{let n=void 0;for(let r of e)if(Object.prototype.hasOwnProperty.call(t.annotations,r)){if(n===void 0)n={};n[r]=t.annotations[r]}return n},zH,_t=(e)=>{switch(e._tag){case"Declaration":{let t=Yn(e.typeParameters,_t);return t===e.typeParameters?e:new wc(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Yn(e.elements,(o)=>{let i=_t(o.type);return i===o.type?o:new $i(i,o.isOptional)}),n=RM(e.rest),r=Yn(n,_t);return t===e.elements&&r===n?e:new Nu(t,r.map((o)=>new _c(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Yn(e.propertySignatures,(r)=>{let o=_t(r.type);return o===r.type?r:new kt(r.name,o,r.isOptional,r.isReadonly)}),n=Yn(e.indexSignatures,(r)=>{let o=_t(r.type);return o===r.type?r:new vc(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new Qr(t,n,e.annotations)}case"Union":{let t=Yn(e.types,_t);return t===e.types?e:on.make(t,e.annotations)}case"Suspend":return new Um(()=>_t(e.f()),e.annotations);case"Refinement":{let t=_t(e.from);return t===e.from?e:new Fu(t,e.filter,e.annotations)}case"Transformation":{let t=zH(e);return _t(t!==void 0?Du(e.to,t):e.to)}}return e},xb=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return xb(e.from);case"Suspend":return xb(e.f())}},Zr=(e,t)=>{switch(e._tag){case"Declaration":{let n=Yn(e.typeParameters,(r)=>Zr(r,t));return n===e.typeParameters?e:new wc(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=Yn(e.elements,(i)=>{let a=Zr(i.type,t);return a===i.type?i:new $i(a,i.isOptional)}),r=RM(e.rest),o=Yn(r,(i)=>Zr(i,t));return n===e.elements&&o===r?e:new Nu(n,o.map((i)=>new _c(i)),e.isReadonly)}case"TypeLiteral":{let n=Yn(e.propertySignatures,(o)=>{let i=Zr(o.type,t);return i===o.type?o:new kt(o.name,i,o.isOptional,o.isReadonly)}),r=Yn(e.indexSignatures,(o)=>{let i=Zr(o.type,t);return i===o.type?o:new vc(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new Qr(n,r)}case"Union":{let n=Yn(e.types,(r)=>Zr(r,t));return n===e.types?e:on.make(n)}case"Suspend":{let n=void 0,r=MH(e);if($e(r)){let o=t?"Bound":"";n={[$b]:`${r.value}Encoded${o}`}}return new Um(()=>Zr(e.f(),t),n)}case"Refinement":{let n=Zr(e.from,t);if(t){if(n===e.from)return e;if(xb(e.from)===void 0&&Ub(e))return new Fu(n,e.filter,e.annotations);return n}else return n}case"Transformation":return Zr(e.from,t)}return e},jm=(e)=>Zr(e,!1),rt=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},Jb=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return Jb(e.from)}},_r=(e)=>Ue(Xr(e),()=>e._tag),PM=(e)=>Fb(e).pipe(ur(()=>Db(e)),ur(()=>Lb(e)),dr((t)=>t+KH(e))),Xr=(e)=>ur(Au(e),()=>PM(e));var Gb=w(()=>{st();ne();at();gb();Pu();hu();ft();yp();Ie();rS();ZA=Symbol.for("effect/annotation/TypeConstructor"),Sb=Symbol.for("effect/annotation/Brand"),XA=Symbol.for("effect/annotation/SchemaId"),bb=Symbol.for("effect/annotation/Message"),Im=Symbol.for("effect/annotation/MissingMessage"),Pm=Symbol.for("effect/annotation/Identifier"),xn=Symbol.for("effect/annotation/Title"),Am=Symbol.for("effect/annotation/AutoTitle"),jo=Symbol.for("effect/annotation/Description"),wb=Symbol.for("effect/annotation/Examples"),_b=Symbol.for("effect/annotation/Default"),vb=Symbol.for("effect/annotation/JSONSchema"),Rb=Symbol.for("effect/annotation/Arbitrary"),Tb=Symbol.for("effect/annotation/Pretty"),Cb=Symbol.for("effect/annotation/Equivalence"),QA=Symbol.for("effect/annotation/Documentation"),Ob=Symbol.for("effect/annotation/Concurrency"),kb=Symbol.for("effect/annotation/Batching"),Eb=Symbol.for("effect/annotation/ParseIssueTitle"),Ib=Symbol.for("effect/annotation/ParseOptions"),Pb=Symbol.for("effect/annotation/DecodingFallback"),Ab=Symbol.for("effect/annotation/Surrogate"),Mb=Symbol.for("effect/annotation/StableFilter"),Qt=h(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?Y(e.annotations[t]):B()),Nb=Qt(Sb),eM=Qt(bb),tM=Qt(Im),Fb=Qt(xn),Lb=Qt(Am),Au=Qt(Pm),Db=Qt(jo),nM=Qt(Ob),rM=Qt(kb),oM=Qt(Eb),iM=Qt(Ib),aM=Qt(Pb),qb=Qt(Ab),PH=Qt(Mb),$b=Symbol.for("effect/annotation/JSONIdentifier"),AH=Qt($b);Mm=Mu("Literal"),sM=new Ya(null);Fm=new cM({[xn]:"undefined"});NH=new lM({[xn]:"void"});Lm=new uM({[xn]:"never"});jb=new dM({[xn]:"unknown"});fM=new pM({[xn]:"any"});hM=new mM({[xn]:"string",[jo]:"a string"}),Dm=Mu("StringKeyword");yM=new gM({[xn]:"number",[jo]:"a number"});SM=new xM({[xn]:"boolean",[jo]:"a boolean"});FH=new bM({[xn]:"bigint",[jo]:"a bigint"});LH=new wM({[xn]:"symbol",[jo]:"a symbol"}),_M=Mu("SymbolKeyword");DH=new vM({[xn]:"object",[jo]:"an object in the TypeScript meaning, i.e. the `object` type"});$i=class $i extends _c{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:rt(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};kt=class kt extends $i{name;isReadonly;constructor(e,t,n,r,o){super(t,n,o);this.name=e,this.isReadonly=r}toString(){return(this.isReadonly?"readonly ":"")+String(this.name)+(this.isOptional?"?":"")+": "+this.type}toJSON(){return{name:String(this.name),type:this.type.toJSON(),isOptional:this.isOptional,isReadonly:this.isReadonly,annotations:rt(this.annotations)}}};$H=Ro(gp(Yr,(e)=>{switch(e._tag){case"AnyKeyword":return 0;case"UnknownKeyword":return 1;case"ObjectKeyword":return 2;case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":return 3}return 4})),jH={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};Hb=Mu("Union"),yb=re(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Lu=Mu("Refinement"),$m={};zH=Kb([wb,_b,vb,Rb,Tb,Cb])});class Et{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class Xb{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class Rc{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class ot{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class Bm{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Vm{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Zn{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class Qb{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function vr(e){return e.sort(XH).map((t)=>t[1])}function o1(e){return Db(e).pipe(ur(()=>Fb(e)),ur(()=>Lb(e)),ur(()=>Au(e)),Ue(()=>`{ ${e.from} | filter }`))}function i1(e){if(e.message!==void 0)return e.message;return`Expected ${Lu(e.ast)?o1(e.ast):String(e.ast)}, actual ${Hr(e.actual)}`}var MM,LM,tw=(e)=>new LM({issue:e}),DM,qM,bn,Ho,Rr,Wm,UM,nw=(e,t)=>{if(t===void 0||kn(t))return e;if(e===void 0)return t;return{...e,...t}},$M=(e,t,n)=>{let r=Bt(e,t);return(o,i)=>r(o,nw(n,i))},JH=(e,t,n)=>{let r=$M(e,t,n);return(o,i)=>Kg(r(o,i),tw)},jM=(e,t)=>$M(e.ast,!0,t),Hu=(e,t)=>JH(_t(e.ast),!0,t),zm=(e,t)=>{let n=Bt(_t(e.ast),!0);return(r,o)=>Tt(n(r,{exact:!0,...nw(t,o)}))},GH,YH,Bt=(e,t)=>{let n=t?GH:YH,r=n.get(e);if(r)return r;let o=ZH(e,t),i=iM(e),a=$e(i)?(l,u)=>o(l,nw(u,i.value)):o,s=aM(e),c=t&&$e(s)?(l,u)=>Uu(UM(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},Yb=(e)=>gn(nM(e)),Zb=(e)=>gn(rM(e)),ZH=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=Bt(e.from,!0);return(r,o)=>{o=o??$m;let i=o?.errors==="all",a=Ho(UM(n(r,o),(s)=>{let c=new Bm(e,r,"From",s);if(i&&Ub(e)&&zM(s))return pt(e.filter(r,o,e),{onNone:()=>ce(c),onSome:(l)=>ce(new ot(e,r,[c,new Bm(e,r,"Predicate",l)]))});return ce(c)}),(s)=>pt(e.filter(s,o,e),{onNone:()=>ue(s),onSome:(c)=>ce(new Bm(e,r,"Predicate",c))}));return Uu(a,e,r,o)}}else{let n=Bt(_t(e),!0),r=Bt(BM(e.from),!1);return(o,i)=>Uu(Ho(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=QH(e.transformation,t),r=t?Bt(e.from,!0):Bt(e.to,!1),o=t?Bt(e.to,!0):Bt(e.from,!1);return(i,a)=>Uu(Ho(Wm(r(i,a),(s)=>new Vm(e,i,t?"Encoded":"Type",s)),(s)=>Ho(Wm(n(s,a??$m,e,i),(c)=>new Vm(e,i,"Transformation",c)),(c)=>Wm(o(c,a),(l)=>new Vm(e,i,t?"Type":"Encoded",l)))),e,i,a)}case"Declaration":{let n=t?e.decodeUnknown(...e.typeParameters):e.encodeUnknown(...e.typeParameters);return(r,o)=>Uu(n(r,o??$m,e),e,r,o)}case"Literal":return Sn(e,(n)=>n===e.literal);case"UniqueSymbol":return Sn(e,(n)=>n===e.symbol);case"UndefinedKeyword":return Sn(e,$R);case"NeverKeyword":return Sn(e,jR);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return ue;case"StringKeyword":return Sn(e,Ut);case"NumberKeyword":return Sn(e,kn);case"BooleanKeyword":return Sn(e,pa);case"BigIntKeyword":return Sn(e,li);case"SymbolKeyword":return Sn(e,fa);case"ObjectKeyword":return Sn(e,rn);case"Enums":return Sn(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>Dm(r.type)))return Sn(e,(r)=>{if(!Ut(r)||!r.startsWith(e.head))return!1;let o=e.head.length;for(let a=0;a<e.spans.length-1;a++){let s=e.spans[a].literal,c=r.indexOf(s,o);if(c===-1)return!1;o=c+s.length}let i=e.spans[e.spans.length-1].literal;return r.endsWith(i)&&r.length-i.length>=o});let n=IM(e);return Sn(e,(r)=>Ut(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>Bt(l.type,t)),r=e.rest.map((l)=>Bt(l.type,t)),o=e.elements.filter((l)=>!l.isOptional);if(e.rest.length>0)o=o.concat(e.rest.slice(1));let i=o.length,a=e.elements.length>0?e.elements.map((l,u)=>u).join(" | "):"never",s=Yb(e),c=Zb(e);return(l,u)=>{if(!ey(l))return ce(new Zn(e,l));let d=u?.errors==="all",p=[],m=0,f=[],x=l.length;for(let C=x;C<=i-1;C++){let M=new Et(C,l,new Rc(o[C-x]));if(d){p.push([m++,M]);continue}else return ce(new ot(e,l,M,f))}if(e.rest.length===0)for(let C=e.elements.length;C<=x-1;C++){let M=new Et(C,l,new Xb(l[C],`is unexpected, expected: ${a}`));if(d){p.push([m++,M]);continue}else return ce(new ot(e,l,M,f))}let g=0,y=void 0;for(;g<n.length;g++)if(x<g+1){if(e.elements[g].isOptional)continue}else{let C=n[g],M=C(l[g],u);if(bn(M)){if(qe(M)){let N=new Et(g,l,M.left);if(d){p.push([m++,N]);continue}else return ce(new ot(e,l,N,vr(f)))}f.push([m++,M.right])}else{let N=m++,O=g;if(!y)y=[];y.push(({es:E,output:I})=>wr(Ga(M),(S)=>{if(qe(S)){let D=new Et(O,l,S.left);if(d)return E.push([N,D]),Nn;else return ce(new ot(e,l,D,vr(I)))}return I.push([N,S.right]),Nn}))}}if(Fe(r)){let[C,...M]=r;for(;g<x-M.length;g++){let N=C(l[g],u);if(bn(N))if(qe(N)){let O=new Et(g,l,N.left);if(d){p.push([m++,O]);continue}else return ce(new ot(e,l,O,vr(f)))}else f.push([m++,N.right]);else{let O=m++,E=g;if(!y)y=[];y.push(({es:I,output:S})=>wr(Ga(N),(D)=>{if(qe(D)){let A=new Et(E,l,D.left);if(d)return I.push([O,A]),Nn;else return ce(new ot(e,l,A,vr(S)))}else return S.push([O,D.right]),Nn}))}}for(let N=0;N<M.length;N++){let O=g+N;if(x<O+1)continue;else{let E=M[N](l[O],u);if(bn(E)){if(qe(E)){let I=new Et(O,l,E.left);if(d){p.push([m++,I]);continue}else return ce(new ot(e,l,I,vr(f)))}f.push([m++,E.right])}else{let I=m++;if(!y)y=[];y.push(({es:S,output:D})=>wr(Ga(E),(A)=>{if(qe(A)){let pe=new Et(O,l,A.left);if(d)return S.push([I,pe]),Nn;else return ce(new ot(e,l,pe,vr(D)))}return D.push([I,A.right]),Nn}))}}}}let v=({es:C,output:M})=>mi(C)?ce(new ot(e,l,vr(C),vr(M))):ue(vr(M));if(y&&y.length>0){let C=y;return Eu(()=>{let M={es:qs(p),output:qs(f)};return wr(ku(C,(N)=>N(M),{concurrency:s,batching:c,discard:!0}),()=>v(M))})}return v({output:f,es:p})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Sn(e,HR);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([Bt(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Bt(u.parameter,t),Bt(u.type,t),u.parameter]),a=on.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>fa(u)?new Nm(u):new Ya(u)))),s=Bt(a,t),c=Yb(e),l=Zb(e);return(u,d)=>{if(!Ig(u))return ce(new Zn(e,u));let p=d?.errors==="all",m=[],f=0,x=d?.onExcessProperty==="error",g=d?.onExcessProperty==="preserve",y={},v;if(x||g){v=Reflect.ownKeys(u);for(let O of v){let E=s(O,d);if(bn(E)&&qe(E))if(x){let I=new Et(O,u,new Xb(u[O],`is unexpected, expected: ${String(a)}`));if(p){m.push([f++,I]);continue}else return ce(new ot(e,u,I,y))}else y[O]=u[O]}}let C=void 0,M=d?.exact===!0;for(let O=0;O<n.length;O++){let E=n[O][1],I=E.name,S=Object.prototype.hasOwnProperty.call(u,I);if(!S){if(E.isOptional)continue;else if(M){let pe=new Et(I,u,new Rc(E));if(p){m.push([f++,pe]);continue}else return ce(new ot(e,u,pe,y))}}let D=n[O][0],A=D(u[I],d);if(bn(A)){if(qe(A)){let pe=new Et(I,u,S?A.left:new Rc(E));if(p){m.push([f++,pe]);continue}else return ce(new ot(e,u,pe,y))}y[I]=A.right}else{let pe=f++,De=I;if(!C)C=[];C.push(({es:vt,output:Rt})=>wr(Ga(A),(et)=>{if(qe(et)){let Je=new Et(De,u,S?et.left:new Rc(E));if(p)return vt.push([pe,Je]),Nn;else return ce(new ot(e,u,Je,Rt))}return Rt[De]=et.right,Nn}))}}for(let O=0;O<i.length;O++){let E=i[O],I=E[0],S=E[1],D=db(u,E[2]);for(let A of D){let pe=I(A,d);if(bn(pe)&&Tt(pe)){let De=S(u[A],d);if(bn(De)){if(qe(De)){let vt=new Et(A,u,De.left);if(p){m.push([f++,vt]);continue}else return ce(new ot(e,u,vt,y))}else if(!Object.prototype.hasOwnProperty.call(r,A))y[A]=De.right}else{let vt=f++,Rt=A;if(!C)C=[];C.push(({es:et,output:Je})=>wr(Ga(De),(it)=>{if(qe(it)){let sr=new Et(Rt,u,it.left);if(p)return et.push([vt,sr]),Nn;else return ce(new ot(e,u,sr,Je))}else{if(!Object.prototype.hasOwnProperty.call(r,A))Je[A]=it.right;return Nn}}))}}}}let N=({es:O,output:E})=>{if(mi(O))return ce(new ot(e,u,vr(O),E));if(d?.propertyOrder==="original"){let I=v||Reflect.ownKeys(u);for(let D of o)if(I.indexOf(D)===-1)I.push(D);let S={};for(let D of I)if(Object.prototype.hasOwnProperty.call(E,D))S[D]=E[D];return ue(S)}return ue(E)};if(C&&C.length>0){let O=C;return Eu(()=>{let E={es:qs(m),output:Object.assign({},y)};return wr(ku(O,(I)=>I(E),{concurrency:c,batching:l,discard:!0}),()=>N(E))})}return N({es:m,output:y})}}case"Union":{let n=HM(e.types,t),r=Reflect.ownKeys(n.keys),o=r.length,i=e.types.length,a=new Map;for(let l=0;l<i;l++)a.set(e.types[l],Bt(e.types[l],t));let s=Yb(e)??1,c=Zb(e);return(l,u)=>{let d=[],p=0,m=[];if(o>0)if(xl(l))for(let g=0;g<o;g++){let y=r[g],v=n.keys[y].buckets;if(Object.prototype.hasOwnProperty.call(l,y)){let C=String(l[y]);if(Object.prototype.hasOwnProperty.call(v,C))m=m.concat(v[C]);else{let{candidates:M,literals:N}=n.keys[y],O=on.make(N),E=M.length===i?new Qr([new kt(y,O,!1,!0)],[]):on.make(M);d.push([p++,new ot(E,l,new Et(y,l,new Zn(O,l[y])))])}}else{let{candidates:C,literals:M}=n.keys[y],N=new kt(y,on.make(M),!1,!0),O=C.length===i?new Qr([N],[]):on.make(C);d.push([p++,new ot(O,l,new Et(y,l,new Rc(N)))])}}else{let g=n.candidates.length===i?e:on.make(n.candidates);d.push([p++,new Zn(g,l)])}if(n.otherwise.length>0)m=m.concat(n.otherwise);let f=void 0;for(let g=0;g<m.length;g++){let y=m[g],v=a.get(y)(l,u);if(bn(v)&&(!f||f.length===0))if(Tt(v))return v;else d.push([p++,v.left]);else{let C=p++;if(!f)f=[];f.push((M)=>Eu(()=>{if("finalResult"in M)return Nn;else return wr(Ga(v),(N)=>{if(Tt(N))M.finalResult=N;else M.es.push([C,N.left]);return Nn})}))}}let x=(g)=>mi(g)?g.length===1&&g[0][1]._tag==="Type"?ce(g[0][1]):ce(new ot(e,l,vr(g))):ce(new Zn(e,l));if(f&&f.length>0){let g=f;return Eu(()=>{let y={es:qs(d)};return wr(ku(g,(v)=>v(y),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in y)return y.finalResult;return x(y.es)})})}return x(d)}}case"Suspend":{let n=Iu(()=>Bt(e.f(),t));return(r,o)=>n()(r,o)}}},Sn=(e,t)=>(n)=>t(n)?ue(n):ce(new Zn(e,n)),qu=(e,t)=>{switch(e._tag){case"Declaration":{let n=qb(e);if($e(n))return qu(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?jm(o.type):_t(o.type);if(Mm(i)&&!o.isOptional)n.push([o.name,i])}return n}case"TupleType":{let n=[];for(let r=0;r<e.elements.length;r++){let o=e.elements[r],i=t?jm(o.type):_t(o.type);if(Mm(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return qu(e.from,t);case"Suspend":return qu(e.f(),t);case"Transformation":return qu(t?e.from:e.to,t)}return[]},HM=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=qu(a,t);if(s.length>0){o.push(a);for(let c=0;c<s.length;c++){let[l,u]=s[c],d=String(u.literal);n[l]=n[l]||{buckets:{},literals:[],candidates:[]};let p=n[l].buckets;if(Object.prototype.hasOwnProperty.call(p,d)){if(c<s.length-1)continue;p[d].push(a),n[l].literals.push(u),n[l].candidates.push(a)}else{p[d]=[a],n[l].literals.push(u),n[l].candidates.push(a);break}}}else r.push(a)}return{keys:n,otherwise:r,candidates:o}},BM=(e)=>Lu(e)?BM(e.from):e,Uu=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(bn(e))return e;let o=new Su,i=PA(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(EI(a))return ue(a.value);let s=a.cause;if(wk(s))return ce(s.error);return ce(new Qb(t,n,_k(s)))}return ce(new Qb(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},XH=([e],[t])=>e>t?1:e<t?-1:0,QH=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return ue;case"TypeLiteralTransformation":return(n)=>{let r=ue(n);for(let o of e.propertySignatureTransformations){let[i,a]=t?[o.from,o.to]:[o.to,o.from],s=t?o.decode:o.encode;r=Rr(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?Y(l[i]):B());if(delete l[i],$e(u))l[a]=u.value;return l})}return r}}},an=(e,t=[])=>({value:e,forest:t}),$u,e1=(e)=>e.value+VM(`
34
+ `,e.forest),VM=(e,t)=>{let n="",r=t.length,o;for(let i=0;i<r;i++){o=t[i];let a=i===r-1;n+=e+(a?"\u2514":"\u251C")+"\u2500 "+o.value,n+=VM(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},t1=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},n1=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},WM=(e)=>("ast"in e)?Y(e.ast):B(),ew,r1=(e)=>WM(e).pipe(pr(eM),pt({onNone:()=>ew,onSome:(t)=>{let n=t(e);if(Ut(n))return ue({message:n,override:!1});if(kA(n))return Om(n,(r)=>({message:r,override:!1}));if(Ut(n.message))return ue({message:n.message,override:n.override});return Om(n.message,(r)=>({message:r,override:n.override}))}})),rw=(e)=>(t)=>t._tag===e,zM,NM,FM,ju=(e)=>Ho(r1(e),(t)=>{if(t!==void 0)return!t.override&&(zM(e)||NM(e)&&e.kind==="From"||FM(e)&&e.kind!=="Transformation")?FM(e)||NM(e)?ju(e.issue):ew:ue(t.message);return ew}),KM=(e)=>WM(e).pipe(pr(oM),yT((t)=>t(e)),gn),a1=(e)=>Rr(ju(e),(t)=>t??KM(e)??i1(e)),Hm=(e)=>KM(e)??String(e.ast),s1=(e)=>e.message??"is forbidden",c1=(e)=>e.message??"is unexpected",l1=(e)=>{let t=tM(e.ast);if($e(t)){let n=t.value();return Ut(n)?ue(n):n}return ue(e.message??"is missing")},Tc=(e)=>{switch(e._tag){case"Type":return Rr(a1(e),an);case"Forbidden":return ue(an(Hm(e),[an(s1(e))]));case"Unexpected":return ue(an(c1(e)));case"Missing":return Rr(l1(e),an);case"Transformation":return Ho(ju(e),(t)=>{if(t!==void 0)return ue(an(t));return Rr(Tc(e.issue),(n)=>an(Hm(e),[an(t1(e.kind),[n])]))});case"Refinement":return Ho(ju(e),(t)=>{if(t!==void 0)return ue(an(t));return Rr(Tc(e.issue),(n)=>an(Hm(e),[an(n1(e.kind),[n])]))});case"Pointer":return Rr(Tc(e.issue),(t)=>an(km(e.path),[t]));case"Composite":return Ho(ju(e),(t)=>{if(t!==void 0)return ue(an(t));let n=Hm(e);return pb(e.issues)?Rr(ku(e.issues,Tc),(r)=>an(n,r)):Rr(Tc(e.issues),(r)=>an(n,[r]))})}};var ow=w(()=>{st();vk();fE();MA();hn();II();ne();at();Pu();ft();Ie();dm();Gb();MM=Symbol.for("effect/Schema/ParseErrorTypeId");LM=class LM extends pE("ParseError"){[MM]=MM;get message(){return this.toString()}toString(){return $u.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[me](){return this.toJSON()}};DM=ue,qM=ce,bn=zg,Ho=h(2,(e,t)=>bn(e)?El(e,{onLeft:ce,onRight:t}):wr(e,t)),Rr=h(2,(e,t)=>bn(e)?uT(e,t):Om(e,t)),Wm=h(2,(e,t)=>bn(e)?hp(e,t):IA(e,t)),UM=h(2,(e,t)=>bn(e)?El(e,{onLeft:t,onRight:ue}):EA(e,t)),GH=re(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),YH=re(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);$u={formatIssue:(e)=>Rr(Tc(e),e1),formatIssueSync:(e)=>{let t=$u.formatIssue(e);return bn(t)?pT(t):AA(t)},formatError:(e)=>$u.formatIssue(e.issue),formatErrorSync:(e)=>$u.formatIssueSync(e.issue)},ew=ue(void 0),zM=rw("Composite"),NM=rw("Refinement"),FM=rw("Transformation")});var JM,GM;var YM=w(()=>{ne();Ie();JM=h((e)=>rn(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),GM=h((e)=>rn(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function Vt(e){return class{[Bu]=ZM;static ast=e;static annotations(n){return Vt(eo(this.ast,n))}static pipe(){return F(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Bu]=ZM}}function p1(e){return qm(e)?on.make(OM(e,(t)=>new Ya(t))):new Ya(e[0])}function oN(e,t=p1(e)){return class extends Vt(t){static annotations(r){return oN(this.literals,eo(this.ast,r))}static literals=[...e]}}function k(...e){return Fe(e)?oN(e):sw}function aw(e,t){return class extends Vt(t){static annotations(r){return aw(this.typeParameters,eo(this.ast,r))}static typeParameters=[...e]}}function aN(e,t=h1(e)){return class extends Vt(t){static annotations(r){return aN(this.members,eo(this.ast,r))}static members=[...e]}}function xe(...e){return qm(e)?aN(e):Fe(e)?e[0]:sw}function Km(e,t,n=y1(e,t)){return class extends Vt(n){static annotations(o){return Km(this.elements,this.rest,eo(this.ast,o))}static elements=[...e];static rest=[...t]}}function sN(...e){return Array.isArray(e[0])?Km(e[0],e.slice(1)):Km(e,[])}function cN(e,t){return class extends Km([],[e],t){static annotations(r){return cN(this.value,eo(this.ast,r))}static value=e}}class uN{from;to;decode;encode;_tag="PropertySignatureTransformation";constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}toString(){return`PropertySignature<${iw(this.to.isOptional)}, ${this.to.type}, ${x1(this.from.fromKey)}, ${iw(this.from.isOptional)}, ${this.from.type}>`}}function pw(e,t,n=b1(e,t)){return class extends Vt(n){static annotations(o){return pw(this.fields,this.records,eo(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=w1(e,{...o});return gw(i)?a:Hu(this)(a)};static pick(...o){return T(JM(e,...o))}static omit(...o){return T(GM(e,...o))}}}function T(e,...t){return pw(e,t)}function mN(e,t,n){return class extends pw({},[{key:e,value:t}],n){static annotations(o){return mN(e,t,eo(this.ast,o))}static key=e;static value=t}}function hN(e,t){return class extends Vt(t){static annotations(r){return hN(this.from,eo(this.ast,r))}static make=(r,o)=>gw(o)?r:Hu(this)(r);static from=e}}function gN(e,t,n){return class extends Vt(n){static annotations(o){return gN(this.from,this.filter,eo(this.ast,o))}static[_1]=e;static from=e;static filter=t;static make=(o,i)=>gw(i)?o:Hu(this)(o)}}function Ze(e,t){return(n)=>{function r(i,a,s){return v1(e(i,a,s),s,i)}let o=new Fu(n.ast,r,Za(t));return gN(n,r,o)}}function gw(e){return pa(e)?e:e?.disableValidation??!1}var Bu,ZM,XM,Za=(e)=>{if(!e)return{};let t={...e};for(let n in XM)if(n in e){let r=XM[n];t[r]=e[n],delete t[n]}return t},eo=(e,t)=>Du(e,Za(t)),Vu=(e,t)=>{let n=jM(e,t);return(r,o)=>hp(n(r,o),tw)},QM=(e)=>H(e,Bu)&&rn(e[Bu]),f1=(e,t,n)=>aw(e,new wc(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(Vt)),(...r)=>t.encode(...r.map(Vt)),Za(n))),m1=(e,t)=>{let n=()=>(o,i,a)=>e(o)?DM(o):qM(new Zn(a,o));return aw([],new wc([],n,n,Za(t)))},ee=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return f1(n,r,o)}let e=arguments[0],t=arguments[1];return m1(e,t)},iN,It,sw,cw,q,wn,V,h1=(e)=>on.make(e.map((t)=>t.ast)),g1=(e)=>xe(e,iN),y1=(e,t)=>new Nu(e.map((n)=>QM(n)?new $i(n.ast,!1):n.ast),t.map((n)=>QM(n)?new _c(n.ast):n.ast),!0),K=(e)=>cN(e),iw=(e)=>e?'"?:"':'":"',lw,lN,x1=(e)=>{if(e===void 0)return"never";if(Ut(e))return JSON.stringify(e);return String(e)},dN=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new lw(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new uN(e.from,new lN(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},pN,fN=(e)=>H(e,pN),uw,dw,R=(e)=>{let t=e.ast===Fm||e.ast===Lm?Fm:g1(e).ast;return new dw(new lw(t,!0,!0,{},void 0),e)},S1,b1=(e,t)=>{let n=Reflect.ownKeys(e),r=[];if(n.length>0){let i=[],a=[],s=[];for(let c=0;c<n.length;c++){let l=n[c],u=e[l];if(fN(u)){let d=u.ast;switch(d._tag){case"PropertySignatureDeclaration":{let{type:p,isOptional:m,annotations:f}=d;i.push(new kt(l,p,m,!0,S1(d))),a.push(new kt(l,_t(p),m,!0,f)),r.push(new kt(l,p,m,!0,f));break}case"PropertySignatureTransformation":{let p=d.from.fromKey??l;i.push(new kt(p,d.from.type,d.from.isOptional,!0,d.from.annotations)),a.push(new kt(l,d.to.type,d.to.isOptional,!0,d.to.annotations)),s.push(new Vb(p,l,d.decode,d.encode));break}}}else i.push(new kt(l,u.ast,!1,!0)),a.push(new kt(l,_t(u.ast),!1,!0)),r.push(new kt(l,u.ast,!1,!0))}if(Fe(s)){let c=[],l=[];for(let u of t){let{indexSignatures:d,propertySignatures:p}=zb(u.key.ast,u.value.ast);p.forEach((m)=>{i.push(m),a.push(new kt(m.name,_t(m.type),m.isOptional,m.isReadonly,m.annotations))}),d.forEach((m)=>{c.push(m),l.push(new vc(m.parameter,_t(m.type),m.isReadonly))})}return new Bb(new Qr(i,c,{[Am]:"Struct (Encoded side)"}),new Qr(a,l,{[Am]:"Struct (Type side)"}),new Wb(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=zb(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new Qr(r,o)},w1=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&fN(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},Jm=(e)=>mN(e.key,e.value),Wu=(e,t)=>(n)=>{let r=pt(Nb(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=Du(n.ast,Za({[Sb]:r,...t}));return hN(n,o)},_1,eN=(e,t,n)=>{if(pa(e))return e?B():Y(new Zn(t,n));if(Ut(e))return Y(new Zn(t,n,e));if(e!==void 0){if("_tag"in e)return Y(e);let r=new Zn(t,n,e.message);return Y(Fe(e.path)?new Et(e.path,n,r):r)}return B()},v1=(e,t,n)=>{if(FA(e))return eN(e,t,n);if(Fe(e)){let r=Sp(e,(o)=>eN(o,t,n));if(Fe(r))return Y(r.length===1?r[0]:new ot(t,n,r))}return B()},R1,fw=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length<=e,{schemaId:R1,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),T1,Cc=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length>=e,{schemaId:T1,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),tN,we=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ze((o)=>(e.lastIndex=0,e.test(o)),{schemaId:tN,[tN]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},C1,nN,O1,k1,mw=(e,t)=>(n)=>n.pipe(Ze((r)=>r>e,{schemaId:k1,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),E1,yN=(e,t)=>(n)=>n.pipe(Ze((r)=>r>=e,{schemaId:E1,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),I1,Gm=(e)=>(t)=>t.pipe(Ze((n)=>Number.isSafeInteger(n),{schemaId:I1,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),hw=(e)=>mw(0,{title:"positive",...e}),Ym,P1,to=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(LA(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ze((o)=>o.length>=r,{schemaId:P1,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[Mb]:!0,...t}))},rN,A1;var Dt=w(()=>{st();hn();gl();gb();GA();Pu();ft();ow();Ne();Ie();Gb();YM();ow();Bu=Symbol.for("effect/Schema");ZM={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},XM={typeConstructor:ZA,schemaId:XA,message:bb,missingMessage:Im,identifier:Pm,title:xn,description:jo,examples:wb,default:_b,documentation:QA,jsonSchema:vb,arbitrary:Rb,pretty:Tb,equivalence:Cb,concurrency:Ob,batching:kb,parseIssueTitle:Eb,parseOptions:Ib,decodingFallback:Pb};iN=class iN extends Vt(Fm){};It=class It extends Vt(sM){};sw=class sw extends Vt(Lm){};cw=class cw extends Vt(jb){};q=class q extends Vt(hM){};wn=class wn extends Vt(yM){};V=class V extends Vt(SM){};lw=class lw extends $i{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=iw(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};lN=class lN extends $i{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};pN=Symbol.for("effect/PropertySignature");uw=class uw{ast;[Bu];[pN]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return F(this,arguments)}annotations(e){return new uw(dN(this.ast,Za(e)))}toString(){return String(this.ast)}};dw=class dw extends uw{from;constructor(e,t){super(e);this.from=t}annotations(e){return new dw(dN(this.ast,Za(e)),this.from)}};S1=Kb([Im]);_1=Symbol.for("effect/SchemaId/Refine");R1=KA,T1=zA,tN=Symbol.for("effect/SchemaId/Pattern"),C1=Symbol.for("effect/SchemaId/UUID"),nN=/^[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}$/i;O1=class O1 extends q.pipe(we(nN,{schemaId:C1,identifier:"UUID",jsonSchema:{format:"uuid",pattern:nN.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};k1=BA,E1=VA,I1=WA;Ym=class Ym extends wn.pipe(Gm({identifier:"Int"})){};P1=JA,rN=HA;A1=class A1 extends ee(ip,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:rN,[rN]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>qR}){}});function Xn(e,t){return Vu(e,M1)(t)}var M1;var Oc=w(()=>{Dt();M1={onExcessProperty:"error"}});function _N(e){let t=Vu(kc)(e);return Tt(t)?t.right:void 0}function yw(e){return _N(e)!==void 0}function vN(e){return yw(e)&&!e.includes("-")}function xN(e){if(e===void 0||e.length===0||e[0]==="0")return!1;for(let t of e)if(t<"0"||t>"9")return!1;return!0}function N1(e){let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!vN(t))return!1;let[o,i,a,s]=n.split(".");return o==="dev"&&s===void 0&&xN(i)&&xN(a)}function Zm(e){let t=_N(e);if(t===void 0)throw Error(`The canonical version ${e} is invalid.`);let n=t.split("-",1)[0];if(n===void 0)throw Error(`The canonical version ${e} has no base version.`);return n}function Ku(e,t){let n=SN(e),r=SN(t),o=zu(n.minor,r.minor);if(o!==0)return o;let i=zu(n.patch,r.patch);if(i!==0)return i;return F1(n.suffix,r.suffix)}function Sw(e,t){let n=Zm(t);if(e!=="patch"&&e!=="minor"){if(!yw(e))throw Error("The version target is invalid.");return e}let[,r,o]=n.split(".");if(r===void 0||o===void 0)throw Error(`The canonical version ${t} has an invalid base version.`);let i=BigInt(r),a=BigInt(o);return e==="minor"?`0.${i+1n}.0`:`0.${i}.${a+1n}`}function SN(e){let[t,n]=e.split("-",2),r=t?.split("."),o=r?.[1],i=r?.[2];if(o===void 0||i===void 0)throw Error(`The release version ${e} has an invalid base version.`);if(n===void 0)return{minor:o,patch:i,suffix:{kind:"base"}};if(n.startsWith("dev.")){let[,a,s]=n.split(".");if(a===void 0||s===void 0)throw Error(`The development version ${e} has an invalid release suffix.`);return{minor:o,patch:i,suffix:{kind:"development",runNumber:a,runAttempt:s}}}return{minor:o,patch:i,suffix:{kind:"numeric",value:n}}}function zu(e,t){let n=BigInt(e),r=BigInt(t);if(n<r)return-1;if(n>r)return 1;return 0}function F1(e,t){let n=bN(e),r=bN(t);if(n<r)return-1;if(n>r)return 1;if(e.kind==="numeric"&&t.kind==="numeric")return zu(e.value,t.value);if(e.kind==="development"&&t.kind==="development"){let o=zu(e.runNumber,t.runNumber);return o===0?zu(e.runAttempt,t.runAttempt):o}return 0}function bN(e){if(e.kind==="development")return 0;if(e.kind==="base")return 1;return 2}var wN,kc,xw,RN,Ec;var TN=w(()=>{hn();Dt();wN=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,kc=q.pipe(we(wN));xw=q.pipe(Ze(vN));RN=q.pipe(Ze(N1)),Ec=xe(kc,RN)});function _w(e,t){if(typeof t!=="string")return;let n=e.lastIndexOf("@");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(r==="sites"&&o==="openai-curated-remote"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:"sites@openai-bundled"};if(ww.includes(r)&&o==="openai-bundled"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:e};if(!kN(r)||!ON(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function Tr(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(n==="sites"&&r==="openai-curated-remote")return"sites@openai-bundled";if(kN(n)&&ON(r))return`${n}@openai-curated`;if(ww.includes(n)&&r==="openai-bundled")return`${n}@openai-bundled`;return}function Ic(e){let t=Tr(e);if(t===void 0)return[];if(t==="sites@openai-bundled")return Object.freeze([t,"sites@openai-curated-remote"]);if(t.endsWith("@openai-bundled"))return Object.freeze([t]);let n=t.slice(0,t.lastIndexOf("@"));return Object.freeze([t,`${n}@openai-curated-remote`])}function ON(e){return CN.includes(e)}function kN(e){return Xm.includes(e)}function vw(e,t){let n=t??en;return{browser_use:e?.browser_use??n.browser_use,computer_use:e?.computer_use??n.computer_use,sites:e?.sites??n.sites}}function Pc(e,t=[]){let n=[...IN],r=new Set(n);for(let o of EN){if(!e[o])continue;for(let i of Bo[o].pluginIds)if(!r.has(i))r.add(i),n.push(i)}for(let o of t){if(o==="browser@openai-bundled")continue;if(!r.has(o))r.add(o),n.push(o)}return n}var Ju,bw,L1,D1,CN,Xm,ww,Pt,ji,q1,U1,Bo,EN,$1,IN,j1,en;var Rw=w(()=>{Dt();Ju=k("browser_use","computer_use","frontend","security","sites"),bw=k("browser_use","computer_use","sites"),L1=k("installed","disabled","missing","uncertain"),D1=k("healthy","missing","disabled","uncertain"),CN=Object.freeze(["openai-curated","openai-curated-remote"]),Xm=Object.freeze(["build-web-apps","codex-security"]),ww=Object.freeze(["browser","computer-use","sites"]);Pt=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),ji=Object.freeze({frontend:Object.freeze([{skillId:"build-web-apps:frontend-app-builder",appliesWhen:"a new visually-driven UI or meaningful redesign"},{skillId:"build-web-apps:frontend-testing-debugging",appliesWhen:"a rendered UI or interaction defect"},{skillId:"build-web-apps:react-best-practices",appliesWhen:"a relevant React or Next implementation or review"}]),security:Object.freeze([]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([])}),q1=ji.frontend,U1={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Pt.frontend,semanticSkillIds:Object.freeze(ji.frontend.map(({skillId:e})=>e)),applicability:ji.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Pt.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:ji.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Pt.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:ji.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:Pt.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:ji.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:Pt.sites,migrationKey:"sites",semanticSkillIds:[],applicability:ji.sites,ownership:"shared-preserve"}},Bo=Object.freeze(U1),EN=Object.freeze(["browser_use","computer_use","sites"]),$1=Object.freeze(["frontend","security"]),IN=Object.freeze([...Bo.frontend.pluginIds,...Bo.security.pluginIds]),j1=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),en=Object.freeze({browser_use:Pt.browser_use,computer_use:Pt.computer_use,sites:Pt.sites})});function no(e){return T({identifier:k(e),label:q,requiresRootApproval:V})}function PN(e){let t=e.map((r)=>r.label),n=t.at(-1);if(n===void 0)return"";if(t.length===1)return n;return`${t.slice(0,-1).join(", ")}, and ${n}`}function AN(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var MN,H1,B1,Tw,V1,NN,W1,z1,K1;var FN=w(()=>{Dt();MN=k("local.repository.edit","local.repository.check","local.repository.lint","local.repository.format","local.repository.commit","external.read","specialist.dispatch","vcs.server.mutation","vcs.server.ci-trigger","unknown.effect"),H1=T({identifier:MN,label:q,requiresRootApproval:V});B1=T({localRepositoryEdit:no("local.repository.edit"),localRepositoryCheck:no("local.repository.check"),localRepositoryLint:no("local.repository.lint"),localRepositoryFormat:no("local.repository.format"),localRepositoryCommit:no("local.repository.commit"),externalRead:no("external.read"),specialistDispatch:no("specialist.dispatch"),versionControlServerMutation:no("vcs.server.mutation"),versionControlServerCiTrigger:no("vcs.server.ci-trigger"),unknownEffect:no("unknown.effect")}),Tw={localRepositoryEdit:{identifier:"local.repository.edit",label:"local repository edit",requiresRootApproval:!1},localRepositoryCheck:{identifier:"local.repository.check",label:"local repository check",requiresRootApproval:!1},localRepositoryLint:{identifier:"local.repository.lint",label:"local repository lint",requiresRootApproval:!1},localRepositoryFormat:{identifier:"local.repository.format",label:"local repository format",requiresRootApproval:!1},localRepositoryCommit:{identifier:"local.repository.commit",label:"local repository commit",requiresRootApproval:!1},externalRead:{identifier:"external.read",label:"external read",requiresRootApproval:!1},specialistDispatch:{identifier:"specialist.dispatch",label:"specialist dispatch",requiresRootApproval:!1},versionControlServerMutation:{identifier:"vcs.server.mutation",label:"version-control-server mutation",requiresRootApproval:!0},versionControlServerCiTrigger:{identifier:"vcs.server.ci-trigger",label:"version-control-server CI triggering",requiresRootApproval:!0},unknownEffect:{identifier:"unknown.effect",label:"unclassified effect",requiresRootApproval:!0}};jr(Tw);V1=k("never","root"),NN=Object.values(Tw);W1=NN.filter((e)=>!e.requiresRootApproval),z1=NN.filter((e)=>e.requiresRootApproval),K1=Object.freeze({noRootApproval:`${AN(PN(W1))} actions do not require Root approval.`,rootApproval:`${AN(PN(z1))} require Root approval.`})});function Qm(e){let t=Xn(J1,e);if(qe(t))return da(ul("sha256 digest",t.left));return ks(t.right)}var Cr,Cw,jZ,HZ,BZ,J1,G1,Y1,Z1,X1;var eh=w(()=>{hn();Dt();Es();Oc();Cr=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Cw=q.pipe(we(/^[0-9a-f]{64}$/u)),jZ=Cr.pipe(Wu("RunId")),HZ=Cr.pipe(Wu("ProjectId")),BZ=Cr.pipe(Wu("TrustId")),J1=Cw.pipe(Wu("Sha256Digest"));G1=T({run_id:Cr,objective_lineage:Cr,parent_run_id:R(xe(Cr,It))}),Y1=T({project_id:Cr,trust_id:Cr,trust_digest:Cw}),Z1=T({project_id:Cr,project_digest:Cw}),X1=q.pipe(we(/^state-[0-9]+\.[0-9]+$/u))});function nh(e){switch(e){case"go":case"Go":throw Error(`Legacy profile ${e} was removed and requires an explicit replacement.`);case"plus-low":return"low";case"plus":return"default";case"plus-high":return"high";case"pro-5x":case"pro-20x":throw Error(`Legacy profile ${e} was removed and requires an explicit replacement.`);default:return e}}function UN(e){return typeof e==="string"&&rB.has(e)}function iB(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!UN(t)||typeof n!=="string")return!1;return Gu.get(t)?.tasks.some((r)=>r.name===n)===!0}function oh(e,t){return typeof t==="string"&&Gu.get(e)?.tasks.some((n)=>n.name===t)===!0}function $N(e){return typeof e==="string"&&oB.has(e)}function Iw(e){let t=`${e.role}.${e.task}`;if(!kw.has(t))throw Error("Unknown native specialist agent type.");return t}function Pw(e){let t=Gu.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return e.role==="Librarian"?`${eB} ${t.instruction}`:t.instruction}function Aw(e){let t=Gu.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function HN(e){let t=Gu.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function Mw(e){let n=HN(e.role).tasks.find((o)=>o.name===e.task);if(n===void 0)throw Error("Unknown specialist task policy.");let r=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":n.permissions.network?"current_sources":"disabled";return Object.freeze({network:n.permissions.network,filesystem:n.permissions.filesystem,sourceMutation:n.permissions.sourceMutation,networkScope:r})}var ro,LN,Or,Vo,Q1,rh="Satisfy the complete requested outcome correctly, elegantly, and mergeably; never weaken or reinterpret it to shrink the patch. Then make the smallest coherent patch within the authorized boundary. Prefer simple, cohesive, idiomatic solutions with appropriate abstraction and minimal accidental complexity. Avoid unrelated code, prose, configuration, documentation, instructions, tests, restructuring, formatting churn, files, and operations. Preserve unrelated work; return material scope expansion to Root.",Hi="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",eB="For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or web search. Return the typed context7 evidence state with version/source evidence. Use web search only when Context7 is unavailable, lacks relevant coverage or the required version, fails for authentication or quota, or a conflict remains after checking authoritative first-party documentation.",tB,DN,nB,Wo,Gu,rB,Ow,oB,qN,kw,Ew,aB,sB,cB,lB,Yu,Xa,jN,zo,uB,ih,BN,th,dB,pB,fB,Nw,Zu,mB,Fn,hB,gB,W;var Xu=w(()=>{Dt();ro=k("low","default","high"),LN=k("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),Or=xe(ro,LN);Vo=k("standard","fast","fast-all"),Q1=k("low","medium","high","xhigh","max"),tB=k("none"),DN=Object.freeze(["implementation","review","validation","integration","vcs"]),nB=k("read-only","workspace-write"),Wo=[{role:"Explorer",tasks:[{name:"map",description:"Bounded repository structure mapping specialist.",instruction:`Map the assigned repository area: locate its relevant packages, entry points, ownership boundaries, and nearby tests or docs. Return a compact path map and identify where a follow-up lookup or trace should start; do not trace runtime behavior or resolve an unrelated fact. ${Hi}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"lookup",description:"Repository fact lookup specialist.",instruction:`Find the specific requested repository fact and cite its exact path or symbol; keep the search narrower than a structure map or execution trace. ${Hi}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:`Follow the assigned execution or reference path across callers, boundaries, and tests; explain the evidence-backed flow and stop at the assigned boundary. ${Hi}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:`Answer the specific external fact with its current authoritative source. ${Hi}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:`Compare and synthesize the assigned current sources with citations, noting conflicts and uncertainty. ${Hi}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply the exact already-decided transformation within the assigned files and verify it.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Design and implement the assigned behavior within its bounded seam, then verify the changed behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Connect already-decided component seams, resolve interface mismatches within the assigned boundary, and verify their combined behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Use babysit-ci to observe the assigned CI or release gate for the Root-supplied exact ref or SHA until terminal; report the matching result and failure evidence. ${Hi}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`Independently exercise the assigned local behavior with the smallest relevant checks, classify failures, and report reproducible evidence; generated proof state is allowed, but do not repair the implementation or substitute for code review. ${Hi}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Use the debugging skill to repair the assigned defect within its bounded seam.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-assignment",authority:"Concrete task permissions govern observation, proof writes, or source repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",tasks:[{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. Batch relevant evidence, then follow up on concrete uncertainty. Check correctness, safety, compatibility, test quality, generated-artifact hygiene, and the canonical patch-quality rule.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Inspect the assigned produced artifact against its requested content, usability, and delivery constraints; repair concrete defects within the artifact boundary and repeat inspection until no actionable findings remain.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-review",authority:"Concrete task permissions govern observational review or bounded repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}];jr(Wo);Gu=new Map(Wo.map((e)=>[e.role,e])),rB=new Set(Wo.map((e)=>e.role)),Ow=Wo.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),oB=new Set(Ow),qN=Ow.map((e)=>e.replace(":",".")),kw=new Set(qN);Ew=ee(UN),aB=ee((e)=>oh("Explorer",e)),sB=ee((e)=>oh("Librarian",e)),cB=ee((e)=>oh("Worker",e)),lB=ee((e)=>oh("Reviewer",e)),Yu=ee(iB),Xa=Object.freeze(Ow.filter((e)=>$N(e))),jN=ee($N),zo=Object.freeze(qN.filter((e)=>kw.has(e))),uB=ee((e)=>typeof e==="string"&&kw.has(e)),ih=Object.freeze(["worker","explorer","reviewer","librarian"]);BN=T({profile:ro,service_tier:R(Vo)}),th=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),dB=k(...th),pB=k("delegated","root_direct","unavailable"),fB=k(...th),Nw=k("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),Zu=Object.freeze({rule:"Use the smallest meaningful proof proportionate to changed behavior, scope, and risk, plus repository-required gates. Reuse current evidence; broaden or repeat checks only after relevant changes, failures, or unresolved concerns. Avoid tests that mirror implementation for reversible low-impact changes.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),mB=Object.freeze({requiredFor:Object.freeze(["library","framework","sdk","api","cli","cloud_service"]),resolveIdentityBeforeQuery:!0,queryNarrowly:!0,evidenceStates:Object.freeze(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),webFallbackEvidenceStates:Object.freeze(["no_coverage","unavailable","auth_or_quota_failure"]),missingRequiredVersionAllowsFallback:!0,successfulEvidenceAloneAllowsFallback:!1,checkFirstPartyDocsBeforeFallbackForConflict:!0,unresolvedConflictAfterFirstPartyAllowsFallback:!0,materialDecisionsRemainRootOwned:!0}),Fn=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnImplementationAndInteractionProof:!0,specialistVisualImplementationInstruction:"When an Assignment changes visual output, inspect and visually judge the current render, repair actionable defects, and recheck before returning; this local loop supplements Root's higher-level visual acceptance. If assigned capabilities provide no way to judge the render, report that blocker.",rootOwnsVisualJudgment:!0,rootOwnsSharedDevServer:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["specialist_implements","specialist_inspects_judges_and_repairs_current_render","specialist_renders_and_interacts","root_judges_current_render","root_assigns_discrepancies","specialist_repairs","root_rerenders_and_retests"])}),hB=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),gB=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),W=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:zo,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:ih,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","browser_use","computer_use","review","ci_release_observation"]),directExecutionExceptions:th,rootOwnedAuthority:th,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","ambiguity_or_missing_material_input"]),surgicalMutationRule:rh,phaseOrder:DN,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,collectiveWaits:!0,evidenceReusedAcrossPhases:!0}),atomicLifecycleTransitions:Object.freeze({relatedAssignmentAndIntentWrites:!0,oneLockOneCommit:!0,staleRevisionChecksRetained:!0,repositoryDriftChecksRetained:!0}),supersession:Object.freeze({explicitOnly:!0,unfinishedPredecessorOnly:!0,validatedRelatedReplacement:!0,reasonAndProvenanceRequired:!0,supersededExcludedFromCompletionBlockers:!0}),specialistTerminalResultPersistence:Object.freeze({ownActiveInvocationCapabilityRequired:!0,ownAssignmentOnly:!0,terminalOutcomeOnly:!0,rootOwnedIntentLifecycle:!0,rootOwnedAcceptanceReviewAndCiGates:!0,rootOwnedVcsAndExternalEffects:!0,sharedRuntimeCallerIdentityUnavailable:!0,legacyResultCompatibilityPreserved:!0}),normalSpawnForkTurns:"none",normalSpawnRequiresExplicitForkTurns:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,semanticStateBoundary:"Use holycodex-agent semantic operations for Intent and Assignment state. Do not edit TOON state. Resume the current Intent or create one for new work; record verification, acceptance, and readiness, and complete only when holycodex-agent confirms every completion predicate. There is no HolyCodex planning workflow or automatic Plan approval gate; preserve existing Plan state when resuming work that uses it.",routeConfigurationBeforeDispatch:"Use the active profile's registered Role.task configuration, including model, effort, tier, permissions, shell, and capabilities. Verify the registration once per configuration generation; recheck after configuration changes or when resuming an unverified thread. Pass fields required by the dispatch tool; registered settings need not be copied into Assignment prose. Never inherit Root settings, substitute a generic route, or override the selected route. Report a missing or incompatible route before dispatch.",assignmentInvocationLifecycle:"Before each specialist spawn, persist the bounded Assignment and call holycodex-agent assignment start. Keep the returned active_invocation_id and capability in Root; give the specialist only the bounded Assignment, never the capability. After a terminal report, record the result with that invocation ID and capability. Recover an interrupted invocation only after confirming it stopped, using the matching Root-held capability; never share that capability.",assignmentContextIsTaskSpecificOnly:!0,configuredRouteModelAndEffortPreserved:!0,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["significant_findings_or_decisions","consequential_blockers_or_input_needs","release_milestones"]),outOfBoundaryRequiresNewAssignment:!0,routineWaitTool:"collaboration.wait_agent",routineWaitMaximumTimeoutMs:600000,routineWaitUsesMaximumRuntimeTimeout:!0,earlySpecialistCompletionWakesWait:!0,collectiveMailboxIncludesRelevantAgents:!0,idleTimeoutRepeatsMaximumWait:!0,shortRoutineWaitsForbidden:!0,longestPracticalEventWait:!0,busyPollingForbidden:!0,statusOnlyCoordinationLoopsForbidden:!0,batchIndependentLifecycleActions:!0,releaseLeavesAfterAcceptedOutcome:!0,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),evidenceFirstConciseStructuredReports:!0,specialistReportFields:Object.freeze(["changed paths","checks","observable evidence","blockers","Root decisions needed","remaining risk"]),rootLargeReadsOnlyFor:Object.freeze(["material decisions","conflicts","failures","findings"]),stableFactsReused:!0,duplicatePolicyForbidden:!0,stableBoundedComponentScopesAreCanonical:!0,lifecycleWorkerOwnsDeterministicApi:!0,materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,routineSafeReversibleInScopeDecisionsProceedAutonomously:!0,userInstructionsOverrideSkillGuidelinesExceptHardInvariants:!0,authorizedWorkContinuesThroughRequestedTerminalState:!0,testingPolicy:Zu,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function tn(e,t){return new dt("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function Fw(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw tn(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw tn(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw tn(t,"invalid number");return r}case"undefined":throw tn(t,"undefined is not JSON");case"bigint":throw tn(t,"bigint is not JSON");case"function":throw tn(t,"function is not JSON");case"symbol":throw tn(t,"symbol is not JSON");case"object":break}if(n.has(e))throw tn(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw tn(t,`symbol property ${String(s)}`);let i=e,a=[];for(let s=0;s<i.length;s+=1){let c=Object.getOwnPropertyDescriptor(i,String(s));if(!c||!c.enumerable||!("value"in c))throw tn(`${t}[${s}]`,"sparse or accessor array item");a.push(Fw(c.value,`${t}[${s}]`,n))}for(let s of Object.getOwnPropertyNames(i)){if(s==="length")continue;let c=Number(s);if(!Number.isInteger(c)||c<0||c>=i.length||String(c)!==s)throw tn(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw tn(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw tn(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw tn(t,`symbol property ${String(i)}`);for(let i of Object.getOwnPropertyNames(e)){let a=Object.getOwnPropertyDescriptor(e,i);if(!a||!a.enumerable||!("value"in a))throw tn(`${t}.${i}`,"non-enumerable or accessor property")}let o=[];for(let i of Object.keys(e).sort()){let a=Object.getOwnPropertyDescriptor(e,i);if(!a||!("value"in a))throw tn(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${Fw(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function Ln(e){return Fw(e,"$",new Set)}function Dn(e){return new TextEncoder().encode(Ln(e))}function VN(e,t){if(e.length===0||e.includes("\x00"))throw new dt("invalid_digest_domain","Digest domains must be non-empty and NUL-free.",{field:"domain"});let n=new TextEncoder().encode("holycodex-sha256\x00"),r=new TextEncoder().encode(e),o=n.byteLength+8+r.byteLength;for(let c of t){if(c.byteLength>4294967295||o>4294967291-c.byteLength)throw new dt("invalid_digest_domain","Digest input is too large.");o+=4+c.byteLength}let i=new Uint8Array(o),a=new DataView(i.buffer);i.set(n,0);let s=n.byteLength;a.setUint32(s,r.byteLength,!1),s+=4,i.set(r,s),s+=r.byteLength,a.setUint32(s,t.length,!1),s+=4;for(let c of t)a.setUint32(s,c.byteLength,!1),s+=4,i.set(c,s),s+=c.byteLength;return i}function xB(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function qn(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new dt("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",SB(VN(e,t)));return xB(new Uint8Array(r))}function SB(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var Lw=w(()=>{Es();eh()});function KN(e){try{return Ln(e)!==void 0}catch{return!1}}function sh(e){let t=Xn(e0,e);if(qe(t))return da(ul("CLI envelope",t.left));return ks(t.right)}var WN,zN,JN,bB,wB,Dw="holycodex-specialist-outcome-2",zt,Ac,Qu,_B,vB,RB,TB,CB,OB,ah,kB,EB,IB,PB,AB,GN,YN,ZN,MB,XN,QN,e0;var qw=w(()=>{hn();Dt();Lw();Rw();Es();eh();Xu();Oc();WN=k("blocked","completed","failed","partial"),zN=xe(k("high","max","xhigh"),It);JN=ee((e)=>KN(e)),bB=ee((e)=>Cg(e)&&!Array.isArray(e)&&KN(e)),wB=T({blocked:V,changed_files:K(q),confidence:wn,context_owner:xe(q,It),material_findings:K(q),needs_more_context:V,needs_root_decision:V,needs_verification:V,relevant_files:K(q),remaining_risk:K(q),reuse_recommended:V,status:WN,suggested_followup:xe(q,It),suggested_luna_effort:zN,suggested_specialist:xe(Ew,It),verification:K(q),verification_passed:V}),zt=q.pipe(Cc(1)),Ac=T({state:Nw,evidence:K(zt).pipe(to(1)),library:R(zt),version:R(zt)}),Qu={protocol_version:k(Dw),route:Yu,evidence:K(zt),context7:R(Ac)},_B=T(Qu),vB=T({...Qu,status:k("completed"),summary:zt}),RB=T({...Qu,status:k("blocked"),reason:zt,needs_root_decision:V}),TB=T({...Qu,status:k("partial"),summary:zt,completed:K(zt),remaining:K(zt),needs_root_decision:V}),CB=T({...Qu,status:k("failed"),error:zt}),OB=xe(vB,RB,TB,CB),ah={protocol_version:k(Dw),capability:Ju,route:xe(Yu,It),evidence:K(zt),context7:R(Ac),data:JN},kB=T({...ah,status:k("completed"),summary:zt}),EB=T({...ah,status:k("blocked"),reason:zt,needs_root_decision:V}),IB=T({...ah,status:k("partial"),summary:zt,completed:K(zt),remaining:K(zt),needs_root_decision:V}),PB=T({...ah,status:k("failed"),error:zt}),AB=xe(kB,EB,IB,PB),GN=K(q),YN=q.pipe(we(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),ZN=k(yo),MB=T({code:Cr,message:q,details:bB}),XN=T({schema_version:ZN,ok:k(!0),command:YN,data:JN,warnings:GN}),QN=T({schema_version:ZN,ok:k(!1),command:YN,error:MB,warnings:GN}),e0=xe(XN,QN)});function NB(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:ed,effort:n}}function DB(e){let t=LB.get(e);if(t===void 0)throw new dt("catalog_invalid","A profile has no route effort policy.",{profile:e});return Wo.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new dt("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return NB(n.role,r.name,i)}))}function Uw(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:ed,defaultServiceTier:"standard",routes:DB(e.name)}}function qB(e){let t=["low","default","high"];if(e.length!==t.length)throw new dt("catalog_invalid","The profile catalog has an invalid size.");for(let n=0;n<t.length;n+=1){let r=e[n],o=t[n];if(!r||r.name!==o)throw new dt("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=ch,a=o==="low"?"low":o==="default"?"medium":"high";if(r.root.model!==i||r.root.effort!==a||r.specialistModel!==ed)throw new dt("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==Xa.length)throw new dt("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let c of r.routes){if(s.has(c.key)||!FB.has(c.key)||c.model!==ed||`${c.role}:${c.task}`!==c.key)throw new dt("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(c.key)}if(s.size!==Xa.length)throw new dt("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<Xa.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||t0[i.effort]<r)throw new dt("catalog_invalid","Profile route effort is not monotonic.",{route:Xa[n]??"unknown"});r=t0[i.effort]}}}function oo(e){let t=Xn(ro,e);if(qe(t))return da(new dt("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=r0.get(t.right);if(!n)return da(new dt("invalid_profile","Unknown profile selection.",{profile:t.right}));return ks(n)}var ch="gpt-6.1-sol",ed="gpt-6-luna",FB,t0,$w,LB,jw,n0,r0,UB;var o0=w(()=>{hn();Es();Xu();Oc();FB=new Set(Xa),t0={low:0,medium:1,high:2,xhigh:3,max:4},$w=[{profile:"low",rationale:"The low profile keeps bounded specialist work economical.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"high","Worker:implementation":"high","Worker:integration":"max","Worker:operations":"high","Worker:validation":"medium","Worker:debugging":"high","Reviewer:code":"max","Reviewer:artifact":"high"}},{profile:"default",rationale:"The default profile is the recommended balanced route.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"xhigh","Librarian:lookup":"medium","Librarian:research":"xhigh","Worker:mechanical":"high","Worker:implementation":"xhigh","Worker:integration":"max","Worker:operations":"high","Worker:validation":"high","Worker:debugging":"xhigh","Reviewer:code":"max","Reviewer:artifact":"xhigh"}},{profile:"high",rationale:"The high profile maximizes specialist reasoning where specified.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"max","Librarian:lookup":"medium","Librarian:research":"max","Worker:mechanical":"xhigh","Worker:implementation":"max","Worker:integration":"max","Worker:operations":"xhigh","Worker:validation":"xhigh","Worker:debugging":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];jr($w);LB=new Map($w.map((e)=>[e.profile,e]));jw=[Uw({name:"low",rootModel:ch,rootEffort:"low"}),Uw({name:"default",rootModel:ch,rootEffort:"medium"}),Uw({name:"high",rootModel:ch,rootEffort:"high"})];qB(jw);jr(jw);n0=jw,r0=new Map,UB=new Map;for(let e of n0){r0.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);UB.set(e.name,t)}});import{execFile as jB}from"child_process";import{promisify as HB}from"util";var a0="holycodex-intent-1",s0="holycodex-plan-1",c0="holycodex-assignment-1",lh="toon-4",te,kr,uh,l0,Mc,Qn,ht,mX,Hw,Qa,Bw,Vw,BB,i0,VB,WB,Ww,u0,d0,Nc,zw,zB,KB,hX,JB="holycodex-work-state-transaction-1",gX,yX,GB,YB,ZB,XB,QB,eV,tV,nV,xX,rV,SX;var p0=w(()=>{Dt();qw();Xu();Oc();te=q.pipe(Ze((e)=>e.trim().length>0)),kr=q.pipe(we(/^[a-z0-9][a-z0-9-]{0,95}$/u)),uh=q.pipe(we(/^[a-f0-9]{64}$/u)),l0=q.pipe(we(/^[a-f0-9]{40}$/u)),Mc=Ym.pipe(yN(1)),Qn=q.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),ht=K(te),mX=T({pid:Ym.pipe(mw(0)),token:te}),Hw=T({role:k("Explorer","Librarian","Worker","Reviewer"),task:te}).pipe(Ze((e)=>Wo.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),Qa=T({kind:k("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:te,result:R(k("passed","failed","observed","unknown"))}),Bw=T({root:te,git_common_dir:te,initial_head:te,expected_head:te,expected_changes:ht,expected_status_digest:uh,integrated_commit:R(l0),updated_at:Qn}),Vw=k("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),BB=k("scoping","ready","executing","verifying","reviewing"),i0=T({required:V,status:k("not_required","missing","passed","failed","accepted","rejected"),evidence:K(Qa)}),VB=T({schema_version:k(a0),toon_compatibility:k(lh),id:kr,slug:kr,title:te,goal:te,acceptance_criteria:ht,state:Vw,revision:Mc,plan_required:V,active_plan_revision:R(Mc),active_plan_digest:R(uh),blockers:ht,resume_state:R(BB),verification:i0,review:i0,acceptance_met:V,root_readiness:V,evidence:K(Qa),baseline:Bw,created_at:Qn,updated_at:Qn}),WB=T({schema_version:k(s0),toon_compatibility:k(lh),intent_id:kr,revision:Mc,predecessor_digest:R(uh),approach:te,scope:ht,exclusions:ht,assignments:ht,dependencies:ht,architecture:ht,risks:ht,assumptions:ht,open_questions:ht,verification:ht,recovery:ht,updated_at:Qn}),Ww=k("completed","blocked","needs_root_input","failed"),u0=k("pending","executing","completed","blocked","needs_root_input","failed","superseded"),d0=T({id:kr,outcome:Ww,started_at:Qn,finished_at:Qn,summary:te,evidence:K(Qa),context7:R(Ac),blocker:R(te),remaining_risk:ht}),Nc=uh,zw={schema_version:k(c0),toon_compatibility:k(lh),intent_id:kr,id:kr,objective:te,owner:xe(Hw,T({role:k("Reviewer"),task:k("plan")})),scope:ht,constraints:ht,exclusions:ht,dependencies:ht,acceptance_criteria:ht,status:u0,revision:Mc,invocations:K(d0),active_invocation_id:R(te),active_started_at:R(Qn),supersedes:R(kr),superseded_by:R(kr),supersession_reason:R(te),supersession_provenance:R(te),evidence:K(Qa),blocker:R(te),remaining_risk:ht,created_at:Qn,updated_at:Qn},zB=T(zw),KB=T({...zw,capability:Nc}),hX=T({...zw,active_invocation_capability_verifier:R(Nc),active_invocation_capability:R(Nc)}),gX=T({schema_version:k(JB),state:k("prepared","committed"),files:K(T({path:te,previous:q,next:q})).pipe(to(1))}),yX=T({schema_version:k("holycodex-intent-0"),id:kr,slug:kr,title:te,goal:te,acceptance_criteria:ht,state:Vw,revision:Mc,baseline:Bw,created_at:Qn,updated_at:Qn}),GB=T({title:te,goal:te,acceptanceCriteria:K(te).pipe(to(1)),planRequired:R(V),verificationRequired:R(V),reviewRequired:R(V)}),YB=T({approach:te,scope:R(K(te)),exclusions:R(K(te)),assignments:R(K(te)),dependencies:R(K(te)),architecture:R(K(te)),risks:R(K(te)),assumptions:R(K(te)),openQuestions:R(K(te)),verification:R(K(te)),recovery:R(K(te))}),ZB=T({id:R(te),objective:te,owner:Hw,scope:K(te).pipe(to(1)),constraints:R(K(te)),exclusions:R(K(te)),dependencies:R(K(te)),acceptanceCriteria:K(te).pipe(to(1))}),XB=T({scope:K(te).pipe(to(1))}),QB=T({scope:R(K(te).pipe(to(1)))}),eV=T({replacementId:kr,replacementRevision:R(Mc),reason:te,provenance:te}),tV=T({commit:l0}),nV=T({invocationId:R(te),capability:R(Nc),outcome:Ww,startedAt:R(te),summary:te,scope:R(K(te).pipe(to(1))),evidence:R(K(Qa)),context7:R(Ac),blocker:R(te),remainingRisk:R(K(te))}),xX=T({invocationId:te,startedAt:Qn,capability:Nc,interruptionReason:te}),rV=T({evidence:R(K(Qa)),verification:R(k("passed","failed")),review:R(k("accepted","rejected")),acceptanceMet:R(V),rootReadiness:R(V),clearBlockers:R(V)}),SX=HB(jB)});var gt=w(()=>{DR();Es();Oc();TN();Rw();FN();eh();Xu();qw();o0();Lw();p0()});function de(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Xe(e){try{return Ln(e),!0}catch{return!1}}function aV(e){switch(e){case"invalid_external_data":case"manifest_invalid":case"empty_output_directory":return"validation";case"discovery_failed":return"identity";case"protocol_mismatch":case"method_unsupported":case"server_request_unsupported":case"unexpected_response":return"protocol";case"invalid_transport_line":case"transport_closed":case"transport_failure":return"transport";case"approval_required":case"permission_denied":return"approval";case"cancellation":return"interruption";case"timeout":return"timeout";case"turn_failed":return"turn";case"closed":return"closed";case"server_error":return"server"}}function m0(e){return{ok:!1,error:e}}function h0(e){return{ok:!0,value:e}}function Un(e,t=512){let n="";for(let r of e){let o=r.codePointAt(0)??0;n+=o<=8||o===11||o===12||o>=14&&o<=31||o===127?" ":r}return n.replace(/\s+/gu," ").trim().slice(0,t)}function es(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return Un(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>es(n,t+1));if(de(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=Un(r,96);if(i.length>0)n[i]=es(o,t+1)}return n}return"[redacted]"}function g0(e){let t=es(e);return de(t)?t:{value:t}}function Qe(e,t,n){return new ie("invalid_external_data",`Invalid ${e}.`,{field:e,received:es(t)},n===void 0?void 0:{cause:n})}function Ve(e,t,n){let r=Xn(e,t);if(qe(r))throw Qe(n,t,String(r.left));return r.right}function y0(e,t){try{return Ve(e,t,"value"),!0}catch{return!1}}var Kw,td=1048576,Jw=65536,$n,Bi,dQ,Ko,iV,ie;var io=w(()=>{gt();hn();Dt();Kw=yo;$n=ee((e)=>Xe(e)),Bi=ee((e)=>de(e)&&Xe(e)),dQ=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Ko=q.pipe(Ze((e)=>e.length>0&&e.length<=4096)),iV=wn.pipe(Ze((e)=>Number.isFinite(e)&&e>=0));ie=class ie extends Error{code;kind;details;retryable;constructor(e,t,n={},r){super(t,r?.cause===void 0?void 0:{cause:r.cause});this.name="CodexError",this.code=e,this.kind=aV(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var Gw,nd,rd,Yw,Zw,Xw,Qw="turn/completed";var dh=w(()=>{Gw=["initialize","thread/start","thread/resume","thread/read","thread/list","thread/fork","thread/unsubscribe","turn/start","turn/steer","turn/interrupt","model/list","modelProvider/capabilities/read","config/read","permissionProfile/list"],nd=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],rd=["item/permissions/requestApproval"],Yw=["mcpServer/elicitation/request"],Zw=["item/tool/call"],Xw={method:"initialized"}});class fh{transport;maxLineBytes;requestTimeoutMs;signal;notificationListeners=new Set;serverRequestHandlers=new Set;pending=new Map;serverRequestWork=new Set;serverRequestTasks=new Set;nextRequestId=1;readerPromise;initializePromise;transportClosePromise;initializeAttempted=!1;initialized=!1;closed=!1;constructor(e,t={}){if(this.transport=e,this.maxLineBytes=t.maxLineBytes??td,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new ie("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new ie("invalid_external_data","The request timeout is invalid.");if(t.onNotification)this.notificationListeners.add(t.onNotification);if(t.onServerRequest)this.serverRequestHandlers.add(t.onServerRequest);if(this.signal?.aborted)this.close();else if(this.signal)this.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get isInitialized(){return this.initialized}onNotification(e){return this.notificationListeners.add(e),()=>this.notificationListeners.delete(e)}onServerRequest(e){return this.serverRequestHandlers.add(e),()=>this.serverRequestHandlers.delete(e)}async initialize(e=sV){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new ie("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Ve(ph,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",u_,e,ad)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",d_,t,o_)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",p_,t,c_)}async listThreads(e={}){return this.action("thread/list",m_,e,l_)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",f_,t,i_)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",a_,t,s_)}async startTurn(e){return this.action("turn/start",h_,e,y_)}async steerTurn(e){return this.action("turn/steer",g_,e,x_)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",S_,n,b_)}async listModels(e={}){return this.action("model/list",__,e,v_)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",R_,e,T_)}async readConfig(e={}){return this.action("config/read",C_,e,O_)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",k_,e,E_)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Ve(ph,t,"initialize parameters"));return Ve($n,r,"initialize result")}let n=Ve(id,{id:1,method:e,params:t},"App Server method");if(!cV.has(n.method))throw new ie("method_unsupported",`Unsupported App Server method: ${e}.`,{method:e});return this.request(n.method,n.params===void 0?{}:n.params)}async close(){await this.closeWithError(new ie("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Ve($n,e,"initialize parameters")),n=Ve(n_,t,"initialize result"),r=Ve(r_,Xw,"initialized notification");return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(t){let n=t instanceof ie?t:new ie("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(n),n}}async action(e,t,n,r){let o=Ve(t,n,`${e} parameters`),i=Ve($n,o,`${e} parameters`),a=await this.request(e,i);return Ve(r,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new ie("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=Ve(id,{id:n,method:e,params:t},`${e} request`);return new Promise((o,i)=>{let a=!1,s,c,l=(d)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(d)};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new ie("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let d=()=>l(new ie("cancellation",`The ${e} request was cancelled.`,{method:e}));this.signal.addEventListener("abort",d,{once:!0}),c=()=>this.signal?.removeEventListener("abort",d)}let u={method:e,resolve:(d)=>{if(a)return;if(a=!0,s!==void 0)clearTimeout(s);c?.(),o(d)},reject:l,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,u),this.transport.writeLine(JSON.stringify(r)).catch((d)=>{l(d instanceof ie?d:new ie("transport_failure","The App Server request could not be written.",{},{cause:d}))})})}startReader(){if(!this.readerPromise)this.readerPromise=this.readLoop().catch((e)=>this.handleReaderFailure(e)).catch(()=>{return})}async readLoop(){while(!this.closed){let e=await this.transport.readLine();if(e===null){if(!this.closed)throw new ie("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new ie("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof ie?e:new ie("transport_failure","The App Server transport failed.",{},{cause:e});await this.closeWithError(t)}handleLine(e){let t;try{t=JSON.parse(e)}catch(i){throw new ie("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let n=this.tryDecode(od,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(id,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(t_,t);if(o!==void 0){this.handleNotification(o);return}throw Qe("JSON-RPC message",t)}tryDecode(e,t){try{return Ve(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new ie("unexpected_response","The App Server returned an unknown request id.",{id:e.id});if(this.pending.delete(e.id),"error"in e){let n=e.error.code===-32001,r=uV(t.method);t.reject(new ie(r,`The App Server rejected ${t.method}: ${Un(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:es(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Ve(I_,{...e,params:t,category:x0(e.method)},"server request");this.emitNotification({kind:"server_request",method:e.method,params:t});let r=[...this.serverRequestHandlers];if(r.length===0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let o=r[0];if(o===void 0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let i={active:!0};this.serverRequestWork.add(i);let a;try{a=o(n)}catch(s){this.completeServerRequest(i,()=>this.writeServerError(e.id,-32000,Un(String(s))));return}if(a instanceof Promise){this.trackServerRequestTask(a.then((s)=>this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,s)),(s)=>this.completeServerRequest(i,()=>this.writeServerError(e.id,-32000,Un(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Ve(P_,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,Un(String(n)))}}completeServerRequest(e,t){if(!e.active)return;e.active=!1,this.serverRequestWork.delete(e);try{this.trackServerRequestTask(t())}catch{}}trackServerRequestTask(e){let t=e.catch(()=>{return});this.serverRequestTasks.add(t),t.then(()=>this.serverRequestTasks.delete(t),()=>this.serverRequestTasks.delete(t))}async writeServerResult(e,t){let n=Ve(od,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Ve(od,{id:e,error:{code:t,message:lV(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===Qw){let n=Ve(w_,t,"turn/completed notification");this.emitNotification({kind:"turn_completed",method:e.method,params:n});return}if(e.method.includes("agent")||e.method.includes("subagent")){this.emitNotification({kind:"multi_agent",method:e.method,...t===void 0?{}:{params:t}});return}this.emitNotification({kind:"unknown",method:e.method,metadata:g0({params:es(t)})})}emitNotification(e){for(let t of this.notificationListeners)try{t(e)}catch{}}rejectPending(e){for(let t of this.pending.values())t.reject(e);this.pending.clear()}async closeWithError(e){if(this.transportClosePromise!==void 0){await this.transportClosePromise;return}this.closed=!0,this.rejectPending(e);for(let t of this.serverRequestWork)t.active=!1;this.serverRequestWork.clear(),this.serverRequestTasks.clear(),this.transportClosePromise=Promise.resolve().then(()=>this.transport.close()).catch(()=>{return}),await this.transportClosePromise}ensureOpen(){if(this.closed)throw new ie("closed","The App Server client is closed.")}}function lV(e){let t=Un(e);return t.length>0?t:"server request failed"}function uV(e){if(rd.some((t)=>t===e))return"permission_denied";if(nd.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var sV,cV;var e_=w(()=>{io();dh();A_();sV={clientInfo:{name:"holycodex",title:null,version:Kw},capabilities:null},cV=new Set(Gw)});import{isAbsolute as dV}from"path";function Vi(e=process.env){let t=["PATH","HOME","USER","CODEX_HOME","TMPDIR","TEMP","TMP","LANG","LC_ALL"],n={};for(let r of t){let o=e[r];if(o!==void 0&&o.length>0)n[r]=o}return n}function M_(e=process.env){return Object.freeze(Vi(e))}async function mh(e,t){let n=e.getReader(),r=[],o=0;try{while(!0){let s=await n.read();if(s.done)break;if(o+=s.value.byteLength,o>t)throw new ie("invalid_transport_line","A subprocess stream exceeded its limit.");r.push(s.value)}}finally{n.releaseLock()}let i=new Uint8Array(o),a=0;for(let s of r)i.set(s,a),a+=s.byteLength;return i}function hh(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ie("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}}function Wi(e){return Un(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}function sd(e){return e.split(/\r?\n/u).map((t)=>Wi(t)).filter((t)=>t.length>0).slice(0,128)}class gh{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!dV(e.executablePath))throw new ie("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??td,this.maxDiagnosticBytes=e.maxDiagnosticBytes??Jw,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new ie("invalid_external_data","The transport bounds are invalid.");if(this.process=Bun.spawn([e.executablePath,"app-server"],{...e.cwd===void 0?{}:{cwd:e.cwd},env:Vi(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new ie("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new ie("transport_failure","The Codex App Server did not expose stdin.");if(this.stdin=this.process.stdin,this.stdoutReader=this.process.stdout,this.stderrStream=this.process.stderr,this.stderrPromise=this.collectStderr(),e.signal)if(e.signal.aborted)this.close();else e.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get diagnostics(){return[...this.stderrDiagnostics]}async readLine(){if(this.closed&&this.stdoutBuffer.byteLength===0)return null;let e=this.stdoutReader.getReader();try{while(!0){let t=this.stdoutBuffer.indexOf(10);if(t>=0){if(t>this.maxLineBytes)throw await this.close(),new ie("invalid_transport_line","The App Server emitted an overlong line.");let o=this.stdoutBuffer.slice(0,t);this.stdoutBuffer=this.stdoutBuffer.slice(t+1);let i=o.at(-1)===13?o.slice(0,-1):o;return this.lineDecoder.decode(i)}if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new ie("invalid_transport_line","The App Server emitted an overlong line.");let n=await e.read();if(n.done){if(this.stdoutBuffer.byteLength===0)return null;if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new ie("invalid_transport_line","The App Server emitted an overlong line.");let o=this.stdoutBuffer;return this.stdoutBuffer=new Uint8Array(0),this.lineDecoder.decode(o)}let r=new Uint8Array(this.stdoutBuffer.byteLength+n.value.byteLength);r.set(this.stdoutBuffer,0),r.set(n.value,this.stdoutBuffer.byteLength),this.stdoutBuffer=r}}catch(t){if(t instanceof ie)throw t;throw new ie("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new ie("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new ie("invalid_transport_line","The App Server request exceeded the line limit.");try{await this.stdin.write(`${e}
35
+ `),await this.stdin.flush()}catch(t){throw new ie("transport_failure","The App Server stdin could not be written.",{},{cause:t})}}async close(){if(this.closed)return;this.closed=!0;try{await Promise.resolve(this.stdin.end())}catch{}try{this.process.kill()}catch{}await Promise.race([this.process.exited,new Promise((e)=>setTimeout(()=>e(-1),1000))]),await this.stderrPromise.catch(()=>{return})}async collectStderr(){try{let e=await mh(this.stderrStream,this.maxDiagnosticBytes),t=hh(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=Wi(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var yh=w(()=>{io()});import{spawn as pV}from"child_process";import{lstat as Go,mkdir as fV,mkdtemp as mV,readFile as hV,readdir as gV,realpath as F_,rename as yV,rm as xV,stat as vQ}from"fs/promises";import{dirname as b0,isAbsolute as $_,join as Ki,relative as w0,resolve as xh,sep as _0}from"path";async function R0(e){let t=W_(e.selectedPluginIds);if(t.length===0)return;if(k0(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new he("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>V_(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&bh(r,t))return r;let o=e.initializeRuntime??(()=>MV(e)),i,a;try{i=await o()}catch(s){a=se("marketplace_unavailable","Codex runtime initialization could not start the official marketplace sync. Check that Codex is available and its network/policy settings permit the official marketplace.",s)}if(a===void 0)try{let s=e.timeoutMs??B_,c=e.pollIntervalMs??bV,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new he("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&bh(u,t))return u;let d=s-(Date.now()-l);if(d<=0)break;await(e.sleep??E0)(Math.min(c,d))}a=se("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired. Check network access and Codex marketplace policy, then retry.")}catch(s){if(s instanceof he&&s.code==="cancelled")throw s;a=s instanceof he?s:se("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await T0({codexHome:e.codexHome,selectedPluginIds:e.selectedPluginIds,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.signal===void 0?{}:{signal:e.signal},...e.gitFallback===void 0?{}:e.gitFallback})}catch(s){if(s instanceof he)throw s;throw se("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??se("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function T0(e){let t=W_(e.selectedPluginIds);if(t.length===0)throw se("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(k0(e.timeoutMs,void 0),!$_(e.codexHome))throw se("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new he("cancelled","Official Codex marketplace fallback was cancelled.");let n=Vi(e.environment),r=e.gitRunner??A0("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??B_,i;try{i=await CV(r,o,e.signal)}catch(u){if(u instanceof he)throw u;throw se("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Ki(e.codexHome,"plugins"),s=Ki(a,H_[1]);if(await kV(a,e.codexHome),await Go(s).catch((u)=>{if(Fc(u))return;throw se("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await mV(Ki(a,".openai-plugins-stage-"));try{if(await D_(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(ns,l)}catch(f){if(NV(f))throw se("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",f);throw f}else{let f=await r.run(["-c","core.longpaths=true","clone","--depth=1","--no-tags",ns,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(f.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",f.stderr)}await Sh(l);let u=await C0(l,e.codexHome,t);if(u===void 0||!bh(u,t))throw se("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await OV(r,l,o,e.signal)!==i)throw se("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Go(s).catch((f)=>{if(Fc(f))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",f)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await RV(l,s,e.renameSnapshot??yV);let m=await V_(e.codexHome,e.selectedPluginIds);if(m===void 0||!bh(m,t))throw se("marketplace_invalid","The published official marketplace failed validation.");return m}catch(u){if(u instanceof he)throw u;throw se("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await xV(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function RV(e,t,n){for(let r=0;;r+=1)try{await n(e,t);return}catch(o){let i=wV[r];if(process.platform!=="win32"||i===void 0||!TV(o))throw o;if(await Go(t).catch((s)=>{if(Fc(s))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before retrying publication.",s)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during publication; refusing to overwrite it.");await E0(i)}}function TV(e){return e!==null&&typeof e==="object"&&"code"in e&&(e.code==="EPERM"||e.code==="EBUSY")}async function CV(e,t,n){let r=await e.run(["ls-remote",ns,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",r.stderr);let o=r.stdout.trim().split(/\r?\n/u).map((a)=>a.trim()).filter((a)=>a.length>0),i=o.length===1?/^([0-9a-f]{40}|[0-9a-f]{64})\s+HEAD$/iu.exec(o[0]??""):null;if(i?.[1]===void 0)throw se("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function OV(e,t,n,r){let o=await e.run(["rev-parse","HEAD"],{timeoutMs:n,cwd:t,...r===void 0?{}:{signal:r}}),i=o.stdout.trim().toLowerCase();if(o.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(i))throw se("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function kV(e,t){await L_(t,e),await fV(e,{recursive:!0}),await L_(t,e)}async function L_(e,t){let n=xh(e),r=xh(t);while(!0){if((await Go(r).catch((a)=>{if(Fc(a))return;throw a}))?.isSymbolicLink())throw se("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=b0(r);if(i===r||i!==n&&!EV(n,i))throw se("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function EV(e,t){let n=w0(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${_0}`)&&!$_(n)}async function Sh(e){let t=await Go(e);if(t.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw se("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await gV(e,{withFileTypes:!0});for(let r of n){let o=Ki(e,r.name),i=await Go(o);if(i.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await Sh(o)}}async function V_(e,t=[]){return await C0(Ki(e,...H_),e,W_(t))}async function C0(e,t,n=[]){if(t!==void 0)await L_(t,e);let r=await Go(e).catch((l)=>{if(Fc(l))return;throw se("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",l)});if(r===void 0)return;if(r.isSymbolicLink()||!r.isDirectory())throw se("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await D_(t,e);else await Sh(e);if(t!==void 0)await Sh(e);let o=await F_(e),i=[Ki(o,".agents","plugins","marketplace.json"),Ki(o,".codex-plugin","marketplace.json"),Ki(o,"marketplace.json")],a,s;for(let l of i){let u=await Go(l).catch((d)=>{if(Fc(d))return;throw se("marketplace_invalid","The official marketplace manifest could not be read safely.",d)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw se("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await D_(o,l),a!==void 0)throw se("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await hV(l))}catch(d){throw se("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",d)}}if(a===void 0||s===void 0)return;let c;try{c=JSON.parse(s)}catch(l){throw se("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return O0(c,o,a,n)}function O0(e,t=`${H_.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!de(e)||e.name!==ld)throw se("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");IV(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw se("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!de(s)||typeof s.name!=="string"){if(r.length>0)continue;throw se("marketplace_invalid","The official marketplace contains a malformed plugin entry.")}let c=s.name;if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(c)){if(r.length>0)continue;throw se("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw se("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=PV(s);if(!AV(l))throw se("marketplace_invalid",`The official marketplace source for ${c} is unsafe.`);i.push({name:c,source:l})}if(r.some((s)=>!i.some((c)=>c.name===s)))throw se("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:ld,source:ns,rootPath:t,manifestPath:n,plugins:i}}function IV(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:de(n)&&typeof n.url==="string"?n.url:void 0)!==ns)throw se("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function PV(e){let t=e.source;if(typeof t==="string")return t;if(de(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function AV(e){if(e===void 0||e.length===0||$_(e))return!1;if(/^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(t))return!1;return t.split("/").every((n)=>n.length===0||n==="."||n!=="..")}function W_(e){let t=[],n=new Set;for(let r of e){let o=r.lastIndexOf("@");if(o<1)continue;let i=r.slice(o+1);if(i!==ld&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw se("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!I0(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function bh(e,t){return t.every((n)=>{let r=e.plugins.find((i)=>i.name===n);if(r===void 0)return!1;return r.source.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)===n})}async function MV(e){let t=Vi(e.environment),n;try{n=new gh({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new fh(n,{requestTimeoutMs:Math.min(e.timeoutMs??B_,1e4),...e.signal===void 0?{}:{signal:e.signal}});return await r.initialize(),async()=>{await r.close()}}catch(r){throw await n?.close().catch(()=>{return}),r}}function k0(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw se("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw se("marketplace_invalid","The official marketplace poll interval is invalid.")}async function D_(e,t){let n=await F_(e),r=await F_(t),o=w0(n,r);if(o===""||o===".."||o.startsWith(`..${_0}`))throw se("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=xh(e),a=xh(t);while(!0){if((await Go(a)).isSymbolicLink())throw se("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=b0(a);if(c===a)throw se("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Fc(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function NV(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function E0(e){await new Promise((t)=>setTimeout(t,e))}function se(e,t,n){return new he(e,t,n instanceof Error?{cause:Wi(n.message)}:{})}function ao(e,t){let n=Tr(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=_w(i.pluginId,i.marketplaceName);return a?.canonicalPluginId===n?[{identity:a,entry:i}]:[]});return o.find((i)=>i.entry.pluginId===n&&i.entry.installed)??o.find((i)=>i.entry.installed)??o.find((i)=>i.entry.pluginId===n)??o[0]}function I0(e){return Xm.includes(e)}function P0(e){if(!y0(U_,e))return m0(Qe("live official plugin list",e));return h0(Ve(U_,e,"live official plugin list"))}function wh(e){let t=e.runner??A0(e.executable,{environment:e.environment??Vi(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=async()=>{let o=await t.run(["plugin","list","--json"]);if(o.exitCode!==0)throw zi("list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new he("command_failed","Codex returned invalid plugin data.")}let a=P0(i);if(!a.ok)throw new he("command_failed","Codex returned an invalid official plugin list.");return a.value},r=async()=>{let o=await t.run(["plugin","marketplace","list","--json"]);if(o.exitCode!==0)throw zi("marketplace list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new he("command_failed","Codex returned invalid marketplace data.")}if(!de(i)||!Array.isArray(i.marketplaces))throw new he("command_failed","Codex returned an invalid marketplace list.");return i.marketplaces.map((a)=>{if(!de(a)||typeof a.name!=="string"||typeof a.root!=="string")throw new he("command_failed","Codex returned an invalid marketplace entry.");let s=a.marketplaceSource;if(s===void 0)return{name:a.name,root:a.root};if(!de(s)||typeof s.sourceType!=="string"||typeof s.source!=="string")throw new he("command_failed",`Codex returned an invalid source for marketplace ${a.name}.`);return{name:a.name,root:a.root,marketplaceSource:{sourceType:s.sourceType,source:s.source}}})};return{list:n,ensureOfficialMarketplace:async(o)=>{if(e.codexHome===void 0)throw new he("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await R0({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:o,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(o,i)=>{let a=Ve(ts,o,"plugin marketplace source");if(a===ld||a===ns)throw new he("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.");if(a!==j_)throw new he("marketplace_invalid",`Unsupported managed marketplace source: ${a}.`);let s,c=!1;try{s=await r()}catch(y){if(!DV(y))throw y;e.onMarketplaceConflict?.("The registered HolyCodex marketplace cache is incomplete; Codex will rebuild it from the canonical source.");let v=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(v.exitCode!==0)throw zi("marketplace add",v,a);s=await r(),c=!0}let l=N_(s,Jo),u=qV(s,Jo);if(l!==void 0&&u.length>0){e.onMarketplaceConflict?.(`${l} HolyCodex will remove the conflicting registration and restore its required source.`);for(let y of u){let v=await t.run(["plugin","marketplace","remove",y],i===void 0?void 0:{signal:i});if(v.exitCode!==0)throw zi("marketplace remove",v,y)}}let d=u.length===0?s:await r(),p=N_(d,Jo);if(p!==void 0)throw new he("marketplace_invalid",p);if(d.find((y)=>y.name===Jo)===void 0){let y=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(y.exitCode!==0)throw zi("marketplace add",y,a)}else if(!c){let y=await t.run(["plugin","marketplace","upgrade",Jo],i===void 0?void 0:{signal:i});if(y.exitCode!==0)throw zi("marketplace upgrade",y,Jo)}let f=await r(),x=N_(f,Jo);if(x!==void 0)throw new he("marketplace_invalid",x);let g=f.find((y)=>y.name===Jo);if(g===void 0||!ud(g.marketplaceSource))throw new he("readback_mismatch","Codex did not report the canonical HolyCodex marketplace after installation or refresh.")},add:async(o,i)=>{let a=Ve(ts,o,"official plugin id"),s=Ic(a),c=s.includes(a)?[a,...s.filter((x)=>x!==a)]:[a],l=!1;for(let[x,g]of c.entries()){let y=await t.run(["plugin","add",g,"--json"],i===void 0?void 0:{signal:i});if(y.exitCode===0){l=!0;break}if(x<c.length-1&&LV(y.stderr))continue;throw zi("add",y,g)}if(!l)throw new he("command_failed",`Codex could not install ${a} from its recognized marketplace sources.`);let u=await n(),d=ao(u,a),p=Tr(a),m=[...u.installed,...u.available].filter((x)=>x.pluginId===a&&(p===void 0||x.marketplaceName==null)),f=d?.entry??m.find((x)=>x.installed)??m[0];if(!f)throw new he("readback_mismatch",`Codex did not report ${a} after installation.`,{plugin_id:a});if(!f.installed)throw new he("plugin_missing",`Codex reported ${a} as unavailable after installation.`,{plugin_id:a});if(!f.enabled)throw new he("plugin_disabled",`Codex installed ${a} but it is disabled; enable it in Codex and retry.`,{plugin_id:a})},remove:async(o,i)=>{let a=Ve(ts,o,"official plugin id"),s=a;if(Tr(a)===a){let d=await n(),p=ao(d,a);if(p?.entry.installed)s=p.entry.pluginId}let c=await t.run(["plugin","remove",s,"--json"],i===void 0?void 0:{signal:i});if(c.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(c.stderr))throw zi("remove",c,s);let l=await n(),u=[...l.installed,...l.available].find((d)=>d.pluginId===s);if(u?.installed)throw new he("readback_mismatch",`Codex still reports ${a} after removal.`,{plugin_id:a,observed_plugin_id:u.pluginId})}}}function zi(e,t,n){let r=Wi(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new he("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function LV(e){return/plugin\b.+\bnot found in marketplace\b/iu.test(Wi(e))}function DV(e){if(!(e instanceof he)||e.code!=="command_failed")return!1;return/(?:^|[\n:])\s*-\s*`([^`]+)`\s+at\s+[^\r\n]*:\s*marketplace root does not contain a supported manifest/iu.exec(e.message)?.[1]===Jo}function N_(e,t){let n=e.filter((o)=>o.name===t);if(n.length>1)return`Multiple Codex marketplaces use the reserved name ${t}; resolve the duplicate configuration before installing HolyCodex.`;if(n[0]!==void 0&&!ud(n[0].marketplaceSource)){let o=n[0].marketplaceSource?.source??"an unknown source";return`Codex marketplace ${t} points to ${o}, not the canonical HolyCodex source ${j_}; resolve the conflict before installing.`}let r=e.find((o)=>o.name!==t&&ud(o.marketplaceSource));if(r!==void 0)return`The canonical HolyCodex source is already registered as Codex marketplace ${r.name}; resolve the noncanonical marketplace name before installing.`;return}function qV(e,t){let r=e.filter((o)=>o.name===t).length>1;return[...new Set(e.filter((o)=>o.name===t&&(r||!ud(o.marketplaceSource))||o.name!==t&&ud(o.marketplaceSource)).map((o)=>o.name))]}function ud(e){if(e?.sourceType!=="git")return!1;return _h(e.source)}function _h(e){return SV.some((t)=>t===e)}function A0(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>UV(e,i,{...t.environment===void 0?{}:{environment:t.environment},timeoutMs:a?.timeoutMs??n,stdoutLimit:r,stderrLimit:o,...a?.cwd===void 0?{}:{cwd:a.cwd},...a?.signal===void 0?{}:{signal:a.signal}})}}async function UV(e,t,n){if(n.signal?.aborted)throw new he("cancelled","The Codex plugin command was cancelled.");let r=pV(e,[...t],{env:n.environment===void 0?void 0:{...n.environment},...n.cwd===void 0?{}:{cwd:n.cwd},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=S0(r.stdout,n.stdoutLimit),i=S0(r.stderr,n.stderrLimit),a=new Promise((d,p)=>{r.once("error",p),r.once("close",(m)=>d(m??-1))}),s,c,l=new Promise((d,p)=>{c=()=>{try{r.kill()}catch{}p(new he("cancelled","The Codex plugin command was cancelled."))},n.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((d,p)=>{s=setTimeout(()=>{try{r.kill()}catch{}p(new he("timeout","The Codex plugin command timed out."))},n.timeoutMs)});try{let[d,p,m]=await Promise.race([Promise.all([o,i,a]),l,u]);return{stdout:d,stderr:p,exitCode:m}}catch(d){try{r.kill()}catch{}if(d instanceof he)throw d;throw new he("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function S0(e,t){if(e===null)return Promise.reject(new he("command_failed","Codex plugin command output is unavailable."));return new Promise((n,r)=>{let o=[],i=0;e.on("data",(a)=>{let s=typeof a==="string"?new TextEncoder().encode(a):a instanceof Uint8Array?a:void 0;if(s===void 0){r(new he("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new he("output_limit","Codex plugin output exceeded its limit."));return}o.push(s)}),e.once("end",()=>{let a=new Uint8Array(i),s=0;for(let c of o)a.set(c,s),s+=c.byteLength;try{n(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(c){r(c)}}),e.once("error",(a)=>r(a))})}var ld="openai-curated",ns="https://github.com/openai/plugins.git",Jo="holycodex",j_="davidbasilefilho/holycodex",SV,H_,B_=30000,bV=100,wV,v0,_V,cd,ts,vV,FV,q_,U_,he;var vh=w(()=>{gt();Dt();e_();io();yh();SV=[j_,"https://github.com/davidbasilefilho/holycodex.git","https://github.com/davidbasilefilho/holycodex","https://github.com/davidbasilefilho/holycodex.git/","https://github.com/davidbasilefilho/holycodex/","git@github.com:davidbasilefilho/holycodex.git","git@github.com:davidbasilefilho/holycodex","ssh://git@github.com/davidbasilefilho/holycodex.git","ssh://git@github.com/davidbasilefilho/holycodex"],H_=["plugins","openai-plugins"],wV=[25,50,100,200],v0=q.pipe(we(/^[a-z][a-z0-9._-]{1,63}$/u)),_V=q.pipe(we(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),cd=K(q),ts=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),vV=T({name:v0,version:_V,description:Ko,author:R($n),license:R(Ko),homepage:R(Ko),repository:R(Ko),keywords:R(cd),skills:R(cd),commands:R(cd),hooks:R(cd),assets:R(cd),official:R(V)});FV=T({id:v0,selected:k(!0)}),q_=T({pluginId:ts,installed:V,enabled:V,name:R(xe(q,It)),marketplaceName:R(xe(q,It)),version:R(xe(q,It))},Jm({key:q,value:cw})),U_=T({installed:K(q_),available:K(q_)});he=class he extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});function Lc(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object")return!1;if(t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>Lc(n,t));return de(e)&&Object.values(e).every((n)=>Lc(n,t))}finally{t.delete(e)}}function Er(e){return de(e)&&Lc(e)}function K_(e){let t=[],n=0,r=!1,o=!1;for(let i=0;i<=e.length;i+=1){let a=e[i];if(i===e.length||a==="."&&!r){let s=e.slice(n,i),c=s.startsWith('"')?jV(s):s,l=s.startsWith('"'),u=l&&t.length===1&&t[0]==="plugins"&&zm(ts)(c),d=l&&t.length===1&&t[0]==="agents"&&z_.includes(c);if(l?!u&&!d:!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!z_.includes(c))throw Qe("TOML key path",e);if(c==="__proto__"||(c==="constructor"||c==="prototype")&&!u)throw Qe("TOML key path",e);t.push(c),n=i+1;continue}if(r){if(o)o=!1;else if(a==="\\")o=!0;else if(a==='"')r=!1}else if(a==='"')r=!0}if(r||o||t.length===0)throw Qe("TOML key path",e);return t}function jV(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Qe("TOML quoted key",e)}function fe(e,t){if(!Er(e))throw Qe("TOML document",e);let n=e,r=K_(t);for(let o=0;o<r.length;o+=1){let i=r[o];if(!Er(n)||!Object.prototype.hasOwnProperty.call(n,i))return;if(n=n[i],o===1&&r[0]==="features"&&i==="context_management"&&typeof n==="boolean"&&r[2]==="experimental_mode")return n}return n}function Rh(e){if(Array.isArray(e))return e.map(Rh);if(de(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Rh(n)]));return e}function Th(e){return Rh(e)}function so(e,t,n){if(!Er(e)||!Lc(n))throw Qe("TOML write",{keyPath:t});let r=K_(t),o={...Th(e)},i=o;for(let a of r.slice(0,-1)){let s=Object.prototype.hasOwnProperty.call(i,a)?i[a]:void 0;if(s!==void 0&&!Er(s)){if(a!=="context_management"||typeof s!=="boolean"||i!==o.features)throw Qe("TOML table path",t);if(r.at(-1)==="experimental_mode"&&s===n)return o;i[a]={experimental_mode:s}}let c=s===void 0?{}:Er(i[a])?{...i[a]}:{};i[a]=c,i=c}return i[r.at(-1)]=Rh(n),o}function er(e,t){if(!Er(e))throw Qe("TOML document",e);let n=K_(t),r={...Th(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!Er(c))return r;let l={...c};o.push({table:i,key:s}),i[s]=l,i=l}let a=n.at(-1);if(!Object.prototype.hasOwnProperty.call(i,a))return r;delete i[a];for(let s=o.length-1;s>=0;s-=1){let c=o[s],l=c.table[c.key];if(Er(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function os(e){if(typeof e!=="string")return!1;if(N0.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return z_.some((t)=>e===`agents."${t}".config_file`)}function Ch(e){return os(e)||Yi.includes(e)}function Ji(e){return typeof e==="string"&&BV.test(e)}function J_(e){return e==="gpt-6-astra"||e==="gpt-6.1-sol"||e==="gpt-6-sol"||e==="gpt-6-luna"||e==="gpt-5.6-terra"||e==="gpt-5.6-sol"||e==="gpt-5.6-luna"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"||e==="default"||e==="fast"||e==="live"||e==="cached"||e==="indexed"||e==="disabled"}function VV(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function G_(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function Y_(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function Z_(e){if(!de(e)||!Y_(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return J_(e.value);case"number":return G_(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&Eh(e.value);case"digest":return VV(e.value);default:return!1}}function M0(e,t){switch(Q_(e)){case"number":return t.kind==="number";case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"digest":return t.kind==="digest";case"enum":if(t.kind!=="enum")return!1;if(e==="model")return t.value==="gpt-6-astra"||t.value==="gpt-6.1-sol"||t.value==="gpt-6-sol"||t.value==="gpt-6-luna"||t.value==="gpt-5.6-terra"||t.value==="gpt-5.6-sol"||t.value==="gpt-5.6-luna";if(e==="model_reasoning_effort")return t.value==="low"||t.value==="medium"||t.value==="high"||t.value==="xhigh"||t.value==="max";if(e==="service_tier")return t.value==="default"||t.value==="fast";if(e==="web_search")return t.value==="live"||t.value==="cached"||t.value==="indexed"||t.value==="disabled";return t.value==="low"||t.value==="medium"||t.value==="high"}}function q0(e){return de(e)&&e.kind==="absent"?Object.keys(e).length===1:Z_(e)}function U0(e){return de(e)&&Y_(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Ji(e.schema)&&Ji(e.installId)&&Ch(e.keyPath)&&q0(e.originalValue)&&Z_(e.lastManagedValue)&&M0(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||M0(e.keyPath,e.originalValue))}function Gi(e){if(!de(e)||!Y_(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Ji(e.schema)||!Ji(e.installId)||!de(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>Ch(t)&&U0(n)&&n.keyPath===t)}function kh(e){if(!Ji(e.schema)||!Ji(e.installId))throw Qe("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Eh(e){if(e.length===0||e.includes("\x00")||/^[\\/]|^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/").split("/");return t.some((n)=>n!==".")&&t.every((n)=>n.length>0&&n!=="..")}function X_(e){if(!Eh(e))throw Qe("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function is(e,t){let n=X_(t),r=e.replaceAll("\\","/").split("/");r.pop();let o=[...r,...n.split("/")].join("/"),i=[];for(let c of o.split("/")){if(c.length===0||c===".")continue;if(c==="..")i.pop();else i.push(c)}let a=e.replaceAll("\\","/");return`${a.startsWith("//")?"//":a.startsWith("/")?"/":""}${i.join("/")}`}function Q_(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="agents.max_concurrent_threads_per_session")return"number";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="features.multi_agent"||e==="features.default_mode_request_user_input"||e==="features.multi_agent_v2"||e==="features.agent_message_board"||e==="features.context_management.experimental_mode"||Yi.includes(e)||e==="sandbox_workspace_write.network_access")return"boolean";return"enum"}function WV(e,t){let n=Q_(e);if(n==="number")return G_(t);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&Eh(t);if(n==="digest")return typeof t==="string";if(e==="model")return t==="gpt-6-astra"||t==="gpt-6.1-sol"||t==="gpt-6-luna";return typeof t==="string"&&J_(t)}async function _n(e,t){if(!Ch(e)||!Lc(t))throw Qe("managed config value",{keyPath:e});let n=Q_(e);if(n==="number"&&G_(t))return{kind:n,value:t};if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&Eh(t))return{kind:n,value:X_(t)};if(n==="enum"&&typeof t==="string"&&J_(t))return{kind:n,value:t};return{kind:"digest",value:await qn("holycodex-managed-config-value",[Dn({keyPath:e,value:t})])}}function zV(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function Dc(e,t,n,r){if(!Er(e)||!Gi(t)||!Ji(r.schema)||!Ji(r.installId))throw Qe("managed runtime config",{});let o={...t.managed},i=Th(e),a=[];for(let[c,l]of Object.entries(n)){if(!os(c)||typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Qe("managed config key",c);let u=c,d=t.managed[u],p=fe(i,u);if(d&&(d.schema!==r.schema||d.installId!==r.installId)){a.push(u);continue}if(d&&d.owner==="holycodex"){let f=p===void 0?void 0:await _n(u,p);if(f===void 0||JSON.stringify(f)!==JSON.stringify(d.lastManagedValue)){a.push(u);continue}}let m=d?.originalValue??(p===void 0?{kind:"absent"}:await _n(u,p));if(!WV(u,l))throw Qe("managed config value",{keyPath:u});i=so(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:m,lastManagedValue:await _n(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!Gi(s))throw Qe("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Ir(e,t,n){if(!Er(e)||!Gi(t))throw Qe("managed runtime config",{});let r=Th(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!Ch(c))throw Qe("managed config key",c);let u=c;if(l.owner!=="holycodex"||l.schema!==n.schema||l.installId!==n.installId){if(l.schema!==n.schema||l.installId!==n.installId)s.push(u);continue}let d=fe(r,u);if(!(d!==void 0&&JSON.stringify(await _n(u,d))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=er(r,u),i.push(u),delete o[u];else{let m=zV(l.originalValue);if(m===void 0){s.push(u),a.push(u);continue}r=so(r,u,m),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function as(e,t,n){if(!os(n)||!Gi(t))throw Qe("managed config key",n);let r=t.managed[n],o=fe(e,n),i=o===void 0?void 0:await _n(n,o);if(!r)return i===void 0?{keyPath:n,status:"unmanaged"}:{keyPath:n,status:"unmanaged",current:i};return{keyPath:n,status:i!==void 0&&JSON.stringify(i)===JSON.stringify(r.lastManagedValue)?"unchanged":"drifted",expected:r.lastManagedValue,...i===void 0?{}:{current:i}}}var z_,$V,rs,N0,Yi,HV,F0,L0,D0,Oh,BV;var Ih=w(()=>{gt();gt();Dt();io();vh();z_=[...zo,"Reviewer.plan"];$V=ee((e)=>Lc(e)),rs=ee((e)=>Er(e));N0=["model","model_reasoning_effort","service_tier","agents.max_concurrent_threads_per_session","web_search","sandbox_workspace_write.network_access","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.multi_agent","features.default_mode_request_user_input","features.multi_agent_v2","features.agent_message_board","features.context_management.experimental_mode"],Yi=["model_auto_compact_token_limit","features.context_management"],HV=ee((e)=>os(e));F0=ee((e)=>Z_(e)),L0=ee((e)=>q0(e)),D0=ee((e)=>U0(e)),Oh=ee((e)=>Gi(e)),BV=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function JV(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function $0(e,t,n){let r=new Set([...t,n]),o=Object.keys(e);if(Object.keys(e).some((i)=>!r.has(i)))return!1;return o.length>0&&o.every((i)=>JV(e[i]))}function B0(e){if(!de(e)||!Xe(e))return!1;return $0(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||$0(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function Ph(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function V0(e){return de(e)&&Xe(e)&&Ph(e.thread)}function ZV(e){return de(e)&&Xe(e)&&typeof e.id==="string"}function Zi(e){return de(e)&&Xe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function W0(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||B0(e.usage))}function XV(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>de(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>de(t)&&typeof t.id==="string"))&&(e.defaultServiceTier===void 0||e.defaultServiceTier===null||typeof e.defaultServiceTier==="string")&&(e.multiAgentVersion===void 0||e.multiAgentVersion===null||e.multiAgentVersion==="disabled"||e.multiAgentVersion==="v1"||e.multiAgentVersion==="v2")}function x0(e){if(rd.some((t)=>t===e))return"permissions";if(nd.some((t)=>t===e))return"approval";if(Yw.some((t)=>t===e))return"elicitation";if(Zw.some((t)=>t===e))return"dynamic_tool";return"other"}var j0,dd,H0,od,KV,t_,id,GV,ph,n_,r_,YV,ad,o_,i_,a_,s_,c_,l_,u_,d_,p_,f_,m_,h_,g_,y_,x_,S_,b_,w_,__,v_,R_,T_,C_,O_,k_,E_,I_,P_,qQ,QV,UQ;var A_=w(()=>{Dt();io();dh();Ih();j0=q.pipe(we(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),dd=xe(q.pipe(Cc(1)),wn.pipe(Ze((e)=>Number.isSafeInteger(e)))),H0=T({code:wn.pipe(Ze((e)=>Number.isSafeInteger(e))),message:q,data:R($n)}),od=xe(T({id:dd,result:$n}),T({id:dd,error:H0})),KV=T({id:dd,error:H0}),t_=T({method:j0,params:R($n)}),id=T({id:dd,method:j0,params:R($n),trace:R($n)});GV=ee(B0),ph=T({clientInfo:T({name:Ko,version:Ko,title:xe(Ko,It)}),capabilities:xe(T({experimentalApi:V,requestAttestation:V,mcpServerOpenaiFormElicitation:R(V),optOutNotificationMethods:R(xe(K(q),It)),extensions:R(Bi)}),It)}),n_=ee((e)=>de(e)&&Xe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),r_=T({method:k("initialized")});YV=ee(Ph);ad=ee((e)=>V0(e)||ZV(e)),o_=ad,i_=ad,a_=ee(Zi),s_=ee((e)=>de(e)&&Xe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),c_=ee((e)=>V0(e)),l_=ee((e)=>{if(!de(e)||!Xe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>Ph(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>Ph(r));return t&&e.threads===void 0||n&&e.data===void 0}),u_=ee((e)=>de(e)&&Xe(e));d_=ee(Zi),p_=ee(Zi),f_=ee(Zi),m_=ee((e)=>de(e)&&Xe(e));h_=ee((e)=>Zi(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Xe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),g_=ee((e)=>Zi(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Xe(t))),y_=ee((e)=>de(e)&&Xe(e)&&(e.turn!==void 0&&W0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),x_=ee((e)=>de(e)&&Xe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),S_=ee((e)=>Zi(e)&&typeof e.turnId==="string"&&e.turnId.length>0),b_=ee((e)=>de(e)&&Xe(e)),w_=ee((e)=>Zi(e)&&(e.turn!==void 0&&W0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),__=ee((e)=>de(e)&&Xe(e));v_=ee((e)=>de(e)&&Xe(e)&&Array.isArray(e.data)&&e.data.every((t)=>XV(t))),R_=Bi,T_=Bi,C_=T({includeLayers:R(V),cwd:R(xe(q,It))}),O_=T({config:rs,origins:Bi,layers:xe(K(Bi),It)}),k_=Bi,E_=Bi,I_=ee((e)=>de(e)&&Xe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&de(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),P_=$n,qQ=ee((e)=>de(e)&&Xe(e)&&typeof e.kind==="string"&&typeof e.method==="string");QV=xe(k("stable","experimental","disabled"),V),UQ=Jm({key:q,value:QV})});import{lstat as HQ,mkdir as BQ,readFile as eW,readdir as VQ,realpath as tW,stat as nW}from"fs/promises";import{delimiter as rW,isAbsolute as zQ,join as KQ,relative as JQ,resolve as z0}from"path";async function iW(e){let t=[];if(e.executablePath!==void 0)t.push(z0(e.cwd??process.cwd(),e.executablePath));else{let n=e.pathValue??e.environment?.PATH??process.env.PATH??"",r=process.platform==="win32"?["codex.exe","codex.cmd","codex"]:["codex"];for(let o of n.split(rW).filter((i)=>i.length>0))for(let i of r)t.push(z0(o,i))}for(let n of t)try{let r=await nW(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await tW(n)}catch{if(e.executablePath!==void 0)throw new ie("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new ie("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function aW(e,t){let n=Bun.spawn([e,"--version"],{env:t,stdin:"ignore",stdout:"pipe",stderr:"pipe"});if(!(n.stdout instanceof ReadableStream)||!(n.stderr instanceof ReadableStream))throw new ie("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await cW(Promise.all([mh(n.stdout,16384),mh(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=Un(hh(r,"Codex version output"));if(i!==0||a.length===0){let s=Wi(hh(o,"Codex version diagnostics"));throw new ie("discovery_failed","The Codex executable did not provide a version.",{exitCode:i,diagnostics:s})}return a}catch(r){try{n.kill()}catch{}if(r instanceof ie)throw r;throw new ie("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function sW(e){let t=await eW(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=Qm(r);if(!o.ok)throw new ie("discovery_failed","The Codex executable digest was invalid.");return o.value}async function ev(e={}){let t=await iW(e),n=Vi(e.environment),r=e.versionRunner?Un(await e.versionRunner(t,n)):await aW(t,n);if(r.length===0)throw new ie("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await sW(t)}}async function cW(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new ie("timeout",n))},oW)})])}finally{if(r!==void 0)clearTimeout(r)}}var oW=30000,XQ;var K0=w(()=>{gt();Dt();io();yh();XQ=T({exitCode:wn.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:q.pipe(fw(1048576)),stderr:q.pipe(fw(1048576))})});var lW="packages/codex/generated",uW,dW,tv,nee,ree;var J0=w(()=>{gt();Dt();io();uW=/^codex-cli \d+\.\d+\.\d+$/u,dW=/^codex-app-server-\d+\.\d+\.\d+$/u,tv=q.pipe(we(/^[a-f0-9]{64}$/u)),nee=T({schema_version:k("holycodex-generated-v2"),artifact_root:k(lW),codex_cli_version:q.pipe(we(uW)),codex_cli_digest:tv,protocol_epoch:q.pipe(we(dW)),generator:T({command:sN(k("app-server"),k("generate-ts")),supported_surface:k("codex app-server generators")}),typescript_root:k("typescript"),files:T({count:wn.pipe(Gm(),hw()),digest:tv})}),ree=T({path:q.pipe(Cc(1)),size:wn.pipe(Gm(),hw()),sha256:tv})});var pW;var G0=w(()=>{Dt();Ih();pW=T({owner:k("holycodex"),schema:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});var ss=w(()=>{io();io();dh();A_();e_();yh();K0();J0();G0();Ih();vh();vh()});function sn(e){if(!qc(e))throw Error("The value is not JSON serializable.");return Ln(e),e}function qc(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object"||t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>qc(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>qc(n,t))}finally{t.delete(e)}}var hd=w(()=>{gt()});function Pe(e,t){let n=Xn(e,t);return Tt(n)?n.right:void 0}function iF(e){return Pe(gd,e)!==void 0}var gd,Jee,_W,vW,yd,RW,Qi,TW,CW,OW,X0,xd,Nh,Q0,Sd,eF,nn,iv,kW,EW,IW,PW,AW,MW,NW,FW,LW,Mh,DW,Z0,qW,Fh,Uc,UW,av,$W,sv,jW,tF,cv,lv,ea,nF,HW,rF,BW,oF;var cs=w(()=>{ss();gt();hn();Dt();hd();gd=ee((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&qc(e)),Jee=ee(qc),_W=Ec,vW=q.pipe(we(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),yd=q.pipe(we(/^[0-9a-f]{64}$/u)),RW=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Qi=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),TW=q.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),CW=T({path:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:yd}),OW=T({browser_use:V,computer_use:V,sites:V,coding:k(!0)}),X0=T({browser_use:R(V),computer_use:R(V),sites:R(V)}),xd=T({profile:R(ro),tier:R(Vo),optional:R(X0),officialPlugins:R(K(Qi))}),Nh=xd,Q0=k("keep","remove","replace","cancel"),Sd=T({schema_version:k(1),profile:ro,tier:Vo,capabilities:K(bw),additional_plugins:K(Qi)}),eF=T({schema_version:k(1),profile:ro,tier:Vo,capabilities:K(Ju),additional_plugins:K(Qi)}),nn=T({selected:V,status:k("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:K(Qi),reason:R(q)}),iv=T({browser_use:nn,computer_use:nn,frontend:nn,security:nn,sites:nn}),kW=T({browser_use:R(V),computer_use:V,frontend:V,security:V,sites:R(V),coding:k(!0),work:V}),EW=T({browser_use:R(V),computer_use:R(V),frontend:R(V),security:R(V),sites:R(V),work:R(V)}),IW=T({browser_use:R(nn),computer_use:nn,frontend:nn,security:nn,sites:R(nn),work:nn}),PW=T({computer_use:V,frontend:V,security:V,coding:k(!0)}),AW=T({computer_use:R(V),frontend:R(V),security:R(V)}),MW=T({computer_use:nn,frontend:nn,security:nn}),NW=xe(T({status:k("not_applicable")}),T({status:k("missing")}),T({status:k("healthy"),path:q,installed:V})),FW=T({manager:k("bun","npm","pnpm"),launcher:k("bunx","npx","pnpm dlx"),version:vW,executable:q,ownership:k("user","holycodex"),identity:R(yd)}),LW=T({git_bash:R(NW),context7:R(FW)}),Mh=T({presence:k("absent","present"),digest:yd,safe_value:R(xe(T({kind:k("boolean"),value:V}),T({kind:k("marketplace"),source_type:k("git"),source:k("https://github.com/davidbasilefilho/holycodex.git")})))}),DW=T({plugin_id:k("holycodex@holycodex"),before:T({preference:Mh,marketplace:Mh}),after:T({preference:Mh,marketplace:Mh})}),Z0=T({presence:k("absent","present"),digest:yd,safe_value:R(T({kind:k("boolean"),value:V}))}),qW=T({plugin_id:Qi,before:Z0,after:Z0}),Fh={owner:k("holycodex"),schema_epoch:k(On),install_id:RW,version:_W,digest:yd,profile:ro,tier:Vo,optional_selections:OW,explicit_optional_selections:X0,official_plugins:R(K(Qi)),capability_state:R(iv),managed_artifacts:K(CW),installed_at:TW,status:R(k("active")),step:R(k("active")),managed_config:R(Oh),plugin_snapshot:R(K(T({plugin_id:Qi,status:k("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:R(DW),provider_config:R(K(qW)),owned_plugins:R(K(Qi)),tooling:R(LW)},Uc=T(Fh),UW=(({profile:e,...t})=>t)(Fh),av={...Fh,optional_selections:kW,explicit_optional_selections:EW,capability_state:R(IW)},$W=(({profile:e,...t})=>t)(av),sv={...Fh,optional_selections:PW,explicit_optional_selections:AW,capability_state:R(MW)},jW=(({profile:e,...t})=>t)(sv),tF=xe(T({...av,profile:Or}),T({...$W,plan:Or}),T({...UW,plan:Or}),T({...sv,profile:Or}),T({...jW,plan:Or})),cv=k("preparing","conflicted"),lv=k("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),ea=T({...Uc.fields,status:cv,step:lv}),nF={...av,status:cv,step:lv},HW=(({profile:e,...t})=>t)(nF),rF={...sv,status:cv,step:lv},BW=(({profile:e,...t})=>t)(rF),oF=xe(ea,T({...nF,profile:Or}),T({...HW,plan:Or}),T({...rF,profile:Or}),T({...BW,plan:Or}))});import{lstat as VW,mkdir as WW}from"fs/promises";import{homedir as zW}from"os";import{dirname as KW,join as ta,posix as aF,resolve as JW,sep as sF,win32 as cF}from"path";function Pr(e={},t=process.env){let n=zW(),r=e.paths?.codexHome??t.CODEX_HOME??ta(n,".codex"),o=dv(r,"CODEX_HOME"),i=ta(o,GW);return{codexHome:o,stateRoot:i,activeRecord:ta(i,YW),preparingRecord:ta(i,ZW),conflictedRecord:ta(i,XW),installOptions:ta(i,QW),roleRoot:ta(i,"agents"),configFile:ta(o,"config.toml")}}function dv(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||tz(e))throw new tr("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?cF:aF,o=uv(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new tr("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":sF).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new tr("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new tr("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function tz(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function $c(e){dv(e,"owned path"),await Yo(e),await WW(e,{recursive:!0}),await Yo(e)}async function Yo(e){let n=JW(e);while(!0){try{if((await VW(n)).isSymbolicLink())throw new tr("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof tr)throw o;if(!Ke(o,"ENOENT"))throw o}let r=KW(n);if(r===n)break;n=r}}async function ls(e){await Yo(e)}function Ar(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?cF:aF,o=r.resolve(uv(e,n)),i=r.resolve(uv(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":sF}`)&&a!==".."&&!r.isAbsolute(a)}function uv(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function Ke(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var GW="holycodex",YW="active.json",ZW="preparing.json",XW="conflicted.json",QW="install.toml",ez,tr;var us=w(()=>{gt();ez=On;tr=class tr extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as lF,open as nz,readFile as uF,rename as rz,unlink as oz,writeFile as iz}from"fs/promises";import{dirname as az}from"path";async function dF(e){let t;try{t=await nz(e,"r"),await t.sync()}catch(n){if(!pF(n))throw n}finally{await t?.close().catch(()=>{return})}}async function cz(e){await dF(e).catch((t)=>{if(!pF(t))throw t})}async function ps(e,t){await At(e,`${Ln(t)}
36
+ `)}async function At(e,t){let n=az(e);await $c(n),await Yo(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await iz(r,t,{encoding:"utf8",mode:384}),await dF(r),await rz(r,e),await cz(n)}catch(o){throw await oz(r).catch(()=>{return}),o}}async function lz(e,t){let n=await lF(e);if(!n.isFile()||n.isSymbolicLink())throw new ds("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await uF(e,"utf8"))}catch(i){throw new ds("state_corrupt","A persisted file is not valid JSON.",i)}let o=Pe(t,r);if(o===void 0)throw new ds("state_corrupt","A persisted file failed schema validation.");return o}async function be(e){try{let t=await lF(e);if(!t.isFile()||t.isSymbolicLink())throw new ds("state_corrupt","A persisted file is not a regular file.");return await uF(e,"utf8")}catch(t){if(Ke(t,"ENOENT"))return;throw t}}async function pv(e,t){try{return await lz(e,t)}catch(n){if(Ke(n,"ENOENT"))return;throw n}}function pF(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return sz.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var sz,ds;var jc=w(()=>{gt();us();cs();sz=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);ds=class ds extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as uz}from"fs/promises";import{dirname as dz,resolve as pz}from"path";import{fileURLToPath as fz}from"url";async function fF(e=fs){let t=JSON.parse(await uz(e,"utf8")),n=Pe(mz,t);if(n===void 0)throw new Zo("manifest_invalid","The public package manifest is invalid.");return n}async function Hc(e=fs){let t=(await fF(e)).version,n=Pe(Ec,t);if(n===void 0)throw new Zo("manifest_invalid","The public package manifest version is invalid.");return n}async function mF(e=fs){let t=await Hc(e),n=Pe(kc,t);if(n===void 0)throw new Zo("manifest_invalid","The public package manifest must use a canonical stable release version.");return n}async function hz(e=fs){let n=(await Hc(e)).split("-",1)[0],r=Pe(xw,n);if(r===void 0)throw new Zo("manifest_invalid","The public package manifest must use a canonical release base version.");return r}async function bd(e=fs){return await Hc(e)}async function fv(e,t,n=fs){let r=await fF(n),o=await mF(n),i=gz(e,o);if(!t)await ps(n,{...r,version:i});return{previous:o,next:i}}function gz(e,t){if(e!=="patch"&&e!=="minor"){if(Pe(kc,e)===void 0)throw new Zo("version_invalid","The version target is invalid.");return e}try{return Sw(e,t)}catch(n){throw new Zo("version_invalid",n instanceof Error?n.message:"The current version is invalid.")}}var mz,fs,Zo;var wd=w(()=>{gt();Dt();cs();jc();mz=ee((e)=>iF(e)&&e.name==="holycodex"&&Pe(Ec,e.version)!==void 0),fs=pz(dz(fz(import.meta.url)),"../package.json");Zo=class Zo extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as yz}from"crypto";import{lstat as mv,readFile as hv,rm as Lh}from"fs/promises";import{join as Mt,relative as hF}from"path";async function qh(e,t,n=[],r="standard",o={}){let i=ms(t,r,o),a=Mt(e,"holycodex","agents",i),s=Xo(t,r).map((u)=>({path:Mt(a,`${u.name}.toml`),contents:Bc(u,o)})),c=new Map(n.map((u)=>[Mt(e,u.path),u])),l=[];for(let u of s){let d=await na(u.path),p=c.get(u.path),m=d===void 0?void 0:await wF(u,d,p);if(m!==void 0)l.push(m)}return l}async function yF(e,t){let n=Mt(e,"agents"),r=Mt(e,"holycodex","agents"),o=[];for(let i of t){let a=Mt(e,i.path);if(!Ar(e,a)||!Ar(n,a)&&!Ar(r,a)&&a!==Mt(e,"config.toml"))continue;let s=await na(a);if(s!==void 0&&await jn(s)!==i.digest)o.push({...bF(a,"remove",{present:!0,digest:await jn(s)},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}return o}async function xF(e,t){let n=Mt(e,"agents"),r=Mt(e,"holycodex","agents"),o=[];for(let[i,a]of t){if(!Ar(e,i)||!Ar(n,i)&&!Ar(r,i)){o.push(i);continue}let s=await na(i);if(s!==void 0&&await jn(s)!==a)o.push(i)}return o}function Xo(e,t="standard"){let n=oo(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:Iw(o),description:Aw(o),taskInstruction:Pw(o),permissions:Mw(o),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function ms(e,t="standard",n={}){let r=Xo(e,t).map((o)=>`${o.name}\x00${Bc(o,n)}`).join("\x00");return yz("sha256").update(r).digest("hex").slice(0,20)}function _d(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function gv(e,t="standard"){let n=oo(e);if(!n.ok)throw Error("Unknown profile.");return{name:"root",description:"Root-directed HolyCodex control agent.",model:n.value.root.model,effort:n.value.root.effort,serviceTier:t==="fast-all"?"fast":"default"}}function yv(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!W.requiresDelegation||!W.assignmentStartAndDispatchPrecedeDelegableExecution||!W.trivialWorkRequiresDelegation||!W.preparatoryAndExploratoryWorkRequiresDelegation||W.genericDirectWorkFallback||W.directExecutionExceptions!==W.rootOwnedAuthority||!W.codeReviewRequiredForImplementation||!W.codeReviewRequiredBeforeVcs||!W.externalVerificationMustBeTerminal||!W.concreteSpecialistDispatchRequired||!W.roleFamiliesAreLabelsOnly||!W.missingConcreteRouteIsBlocker||!W.normalSpawnRequiresExplicitForkTurns||W.normalSpawnForkTurns!=="none"||!W.normalSpawnUsesConcreteRegisteredAgentType||!W.assignmentContextIsTaskSpecificOnly||!W.configuredRouteModelAndEffortPreserved||W.normalProgressMessages||W.normalHeartbeatMessages||W.normalIntermediateEvidence||!W.userUpdatesUsefulOrImportantOnly||!W.routinePerToolOrSubagentNarrationForbidden||!W.routineStatusOnlyChatterForbidden||!W.fixedCadenceUserUpdatesForbidden||!W.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!W.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!W.materialUserUpdateKinds.includes("release_milestones")||!W.outOfBoundaryRequiresNewAssignment||!W.longestPracticalEventWait||!W.busyPollingForbidden||!W.statusOnlyCoordinationLoopsForbidden||!W.batchIndependentLifecycleActions||!W.releaseLeavesAfterAcceptedOutcome||W.routineWaitTool!=="collaboration.wait_agent"||!Number.isSafeInteger(W.routineWaitMaximumTimeoutMs)||W.routineWaitMaximumTimeoutMs<=0||!W.routineWaitUsesMaximumRuntimeTimeout||!W.earlySpecialistCompletionWakesWait||!W.collectiveMailboxIncludesRelevantAgents||!W.idleTimeoutRepeatsMaximumWait||!W.shortRoutineWaitsForbidden||!W.evidenceFirstConciseStructuredReports||W.specialistReportFields.length===0||W.rootLargeReadsOnlyFor.length===0||!W.stableFactsReused||!W.duplicatePolicyForbidden||!W.stableBoundedComponentScopesAreCanonical||!W.lifecycleWorkerOwnsDeterministicApi||W.registeredSpecialistAgentTypes!==zo||W.forbiddenGenericAgentTypes!==ih)throw Error("The Root orchestration policy is incomplete.");let n=[`You are the HolyCodex Root/session orchestrator. Never perform delegable work yourself unless the user explicitly requests direct execution or forbids delegation. Root owns ${W.rootOwnedAuthority.map((r)=>Sz[r]).join("; ")}, within authorization and capability boundaries.`,`Delegate ${W.delegableActions.map((r)=>bz[r]).join("; ")} through bounded Assignments. Bundle related trivial and preparatory steps into a coherent Assignment rather than spawning per action.`,W.routeConfigurationBeforeDispatch,W.assignmentInvocationLifecycle,`For normal specialist spawns, set fork_turns: "${W.normalSpawnForkTurns}". Give each specialist a self-contained Assignment with objective, bounded scope, constraints, dependencies, acceptance criteria, and evidence needed for acceptance.`,`Dispatch each Assignment to its exact concrete registered Role.task agent_type. Registered targets: ${W.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are labels only; generic built-in agent_type values ${W.forbiddenGenericAgentTypes.join(", ")} are forbidden.`,W.semanticStateBoundary,"User instructions take precedence over skill guidelines. Treat later user steering as current when it changes scope, ownership, or delegation; do not carry forward earlier conflicting constraints. Infer intent from the request and session; carry authorized work through its requested terminal state. Routine omissions get safe defaults. For a blocking material user decision, Root alone uses grill-me, which must ask through request_user_input; ask only what remains unresolved, never turn clarification into planning. Specialists return material input needs to Root as needs_root_input and never ask the user. Dispatch immediately when no decision blocks the next step, and continue independent work while an answer is pending. Check existing authorization before asking again; prepare the concrete reviewable result before requesting approval for a consequential effect. Credential entry remains user-owned.","Dispatch independent non-conflicting Assignments concurrently as soon as their inputs are ready, including across workflow phases. Give each overlapping write or shared-mutable seam one specialist owner and send follow-ups to that owner instead of spawning competing writers; start dependent review or validation once its source is stable. Reuse accepted findings instead of repeating discovery. Batch independent tool reads and lifecycle work where supported; keep revisions and dependent writes ordered. Resolve material contradictions before acceptance.","Delegate ordinary browser and computer execution. For visual tasks, Root uses visual-loop to inspect the current render and judge it, then assigns repairs; use dev-server when a shared background server is needed. Use only selected capabilities available in the active surface and honor its tool precedence. Report a capability blocker without inventing a provider or widening authority.",vz(t),"Use writing-instructions for model-facing contracts. Keep each meaning with one authoritative owner and add only the missing semantic delta for the receiver.","Give the user useful updates for significant findings, decisions, blockers, input needs, and release milestones; avoid per-tool, status-only, heartbeat, or fixed-cadence messages.",_z,`${Zu.rule} ${wz}`,"After integration, Root owns approved VCS writes. For PR or release gates use babysit-ci and dispatch Worker.operations for exact-ref terminal evidence. Pending gates are not complete."];if(t.frontend??!0)n.push(Rz());if(t.security??!0)n.push("For security-sensitive changes, use the relevant security review skills before VCS. Validate supported findings; repair introduced or worsened vulnerabilities before VCS unless explicitly risk-accepted. Keep security review current after relevant repairs.");return n.join(`
37
+ `)}function vz(e){return`For Root visual judgment, use ${[...e.browserUse?["the in-app browser (IAB)"]:[],...e.computerUse?["Computer Use"]:[],"other available rendered evidence such as screenshots or image tools"].join("; if unavailable, use ")}. Unselected capabilities are not fallbacks. Honor higher-priority active-surface tool rules.`}function Rz(){if(!Fn.repositoryAndUserRequirementsPrecedePluginDefaults||!Fn.specialistsOwnImplementationAndInteractionProof||Fn.specialistVisualImplementationInstruction.length===0||!Fn.rootOwnsVisualJudgment||!Fn.rootOwnsSharedDevServer||!Fn.rootAcceptsTerminalVisualEvidence||!Fn.sourceChangesInvalidateRenderEvidence||!Fn.specialistReportsIncludeObservableRenderedEvidence||Fn.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`For frontend work, ${Bo.frontend.applicability.map(({skillId:n,appliesWhen:r})=>`${r} uses ${n}`).join("; ")}. Follow the repository stack, design system, and user requirements. ${Fn.specialistVisualImplementationInstruction} Specialists prove interactions; Root judges current renders with visual-loop and assigns discrepancies. Refresh affected visual evidence after relevant changes. Logic-only changes do not require a visual loop. Check responsive layout, accessibility, and interactions in proportion to the change.`}async function xv(e,t,n=[],r="standard",o,i=[],a={}){let s=ms(t,r,a),c=Mt(e,"holycodex","agents",s),l=[],u=[],d=Xo(t,r).map((v)=>({path:Mt(c,`${v.name}.toml`),contents:Bc(v,a)})),p=new Map(n.map((v)=>[Mt(e,v.path),v])),m=new Map,f=new Set,x=new Set,g=new Map;for(let v of d){let C=await na(v.path);m.set(v.path,C);let M=i.find((O)=>O.path===v.path&&O.action==="replace"&&O.key===void 0);if(M!==void 0){let O=gF(M);if(O===void 0||C===void 0||await jn(C)!==O)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,O),M.decision==="keep")x.add(v.path);else f.add(v.path)}let N=p.get(v.path);if(C!==void 0&&M===void 0){let O=await wF(v,C,N);if(O!==void 0){let E=await o?.(O);if(E==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${v.path}`);if(E===void 0)x.add(v.path);else{let I=gF(O),S=await na(v.path);if(I===void 0||S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,I),E==="accept")f.add(v.path);else x.add(v.path)}}}}let y=[];try{for(let N of d){let O=m.get(N.path),E=p.get(N.path),I=g.get(N.path);if(I!==void 0){let S=await na(N.path);if(S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${N.path}`)}if(x.has(N.path)){if(l.push(N.path),E!==void 0)y.push(E);continue}if(O!==void 0&&E!==void 0){if(await jn(O)!==E.digest&&O!==N.contents&&!f.has(N.path)){l.push(N.path),y.push({path:hF(e,N.path).replaceAll("\\","/"),digest:E.digest});continue}}if(O===void 0||O!==N.contents)await At(N.path,N.contents),u.push({path:N.path,previous:O,installedDigest:await jn(N.contents)});y.push({path:hF(e,N.path).replaceAll("\\","/"),digest:await jn(N.contents)})}let v=Mt(e,"agents","root.toml"),C=await na(v),M=await SF(v);if(M==="preserved")l.push(v);if(M==="removed"&&C!==void 0)u.push({path:v,previous:C,installedDigest:void 0});for(let N of n){let O=Mt(e,N.path);if(!d.some((E)=>E.path===O))y.push(N)}return{managed_artifacts:y,preserved:l,rollback:u}}catch(v){throw await Uh(u).catch(()=>{return}),v}}async function Uh(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await na(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await jn(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await Lh(r.path,{force:!1}).catch((a)=>{if(!Ke(a,"ENOENT"))throw a}),t.push(r.path);else await At(r.path,r.previous)}return{removed:t,preserved:n}}async function $h(e,t,n=new Map){let r=[],o=[],i=Mt(e,"agents"),a=Mt(e,"holycodex","agents");for(let l of t){let u=Mt(e,l.path);if(!Ar(e,u)||!Ar(i,u)&&!Ar(a,u)&&u!==Mt(e,"config.toml")){o.push(u);continue}try{await Yo(u);let d=await mv(u);if(d.isSymbolicLink()||!d.isFile()){o.push(u);continue}let p=await hv(u),m=await jn(p);if(m!==l.digest){let f=n.get(u);if(f!==void 0&&m===f){await Lh(u,{force:!1}),r.push(u);continue}o.push(u);continue}await Lh(u,{force:!1}),r.push(u)}catch(d){if(!Ke(d,"ENOENT"))o.push(u)}}let s=Mt(e,"agents","root.toml"),c=await SF(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);return{removed:r,preserved:o}}function Bc(e,t={}){let n=[xz,e.taskInstruction,...e.permissions.sourceMutation?[`Patch quality: ${rh}`]:[],...t.browserUse?["Use Browser Use only for this Assignment and only when the capability is actually available in the current Codex surface/runtime. Never assume support or substitute another provider; report unavailability as a blocker. Tool availability does not grant authority, and consequential external effects remain Root-owned."]:[],...t.computerUse?["Use Computer Use only for this Assignment and only when the capability is actually available in the current Codex surface/runtime. Its platform restrictions and ability to cause external actions require explicit task authority. Never assume support or substitute another provider; report unavailability as a blocker. Tool availability does not grant authority. Credential entry and submission remain user-owned; never request, enter, retrieve, expose, or store credentials."]:[]].join(`
38
+ `);return[`name = ${JSON.stringify(e.name)}`,`description = ${JSON.stringify(e.description)}`,`model = ${JSON.stringify(e.model)}`,`model_reasoning_effort = ${JSON.stringify(e.effort)}`,`service_tier = ${JSON.stringify(e.serviceTier)}`,'model_reasoning_summary = "none"','model_verbosity = "low"',`sandbox_mode = ${JSON.stringify(Dh(e))}`,'approval_policy = "never"','web_search = "live"',`developer_instructions = ${JSON.stringify(n)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent = false","multi_agent_v2 = false","agent_message_board = false","[features.context_management]","experimental_mode = true","",...Dh(e)==="workspace-write"?["[sandbox_workspace_write]","network_access = true"]:[],""].join(`
39
+ `)}function Dh(e){return e.permissions.filesystem}function jh(e,t){return t.sandbox_mode===Dh(e)&&t.default_permissions===void 0&&(Dh(e)==="workspace-write"?fe(t,"sandbox_workspace_write.network_access")===!0:fe(t,"sandbox_workspace_write.network_access")===void 0)}function Tz(e,t,n){return['name = "root"','description = "Root-directed HolyCodex control agent."',`model = ${JSON.stringify(e)}`,`model_reasoning_effort = ${JSON.stringify(t)}`,`service_tier = ${JSON.stringify(n)}`,'model_verbosity = "low"',""].join(`
40
+ `)}function Vc(e){return Cz.has(e)}async function SF(e){try{await Yo(e);let t=await mv(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await hv(e,"utf8");if(!Vc(n))return"preserved";return await Lh(e,{force:!1}),"removed"}catch(t){if(Ke(t,"ENOENT"))return"absent";throw t}}async function na(e){try{await Yo(e);let t=await mv(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await hv(e))}catch(t){if(Ke(t,"ENOENT"))return;throw t}}async function jn(e){let t=typeof e==="string"?new TextEncoder().encode(e):e,n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),(r)=>r.toString(16).padStart(2,"0")).join("")}function bF(e,t,n,r,o){return{identity:`role-asset:${e}:${t}`,category:"role-asset",target:e,existing:n,desired:r,defaultDecision:"replace",validDecisions:["keep","replace","cancel"],explanation:o,path:e,action:t}}async function wF(e,t,n){if(t===e.contents)return;let r=await jn(t);if(n!==void 0&&r===n.digest)return;return{...bF(e.path,"replace",{present:!0,digest:r},{present:!0,digest:await jn(e.contents)},n===void 0?"A pre-existing generated native role file is not recorded as managed by this installation.":"The managed native role file changed outside the previous HolyCodex transaction."),validDecisions:["replace","cancel"]}}function gF(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var xz,Sz,bz,wz="Before acceptance or VCS writes, require a Reviewer.code fixed point and current relevant validation. Review and validation may overlap on non-conflicting scopes; serialize repairs against checks of the same source. Reuse worker proof and assign Worker.validation only for independent proof or an evidence gap. Repairs invalidate only affected evidence.",_z,Cz;var Hh=w(()=>{ss();gt();us();jc();xz=[`Execute the bounded Assignment through its acceptance criteria; make routine in-scope choices without asking. ${Zu.rule} Return material decisions, scope expansion, or required user input to Root; never ask the user. Do not message Root or peers during execution, delegate, change Intent lifecycle, or perform external effects. Read-only Git/VCS, CI, and PR-comment inspection is allowed when relevant and within the Assignment; Git/VCS writes remain Root-only. Source mutation requires permission from the concrete task; proof and cache writes do not grant it. Preserve others' work in the shared tree and adapt to their changes. Root owns the shared background dev server and higher-level visual acceptance. ${Fn.specialistVisualImplementationInstruction} Do not run dev-server or visual-loop.`,"Do not recover an Assignment or mutate another Assignment's lifecycle. Root keeps active invocation capabilities and records terminal results; never request or use those capabilities.",`Return only one compact, evidence-first terminal outcome (${W.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${W.specialistReportFields.join(", ")}.`].join(" "),Sz={user_interaction:"user interaction",intent:"Intent",material_decisions:"material decisions",orchestration_lifecycle:"orchestration and lifecycle",integration_acceptance:"integration acceptance",completion:"completion",git_vcs:"Git/VCS writes",external_effects:"external effects",visual_judgment:"visual judgment and its browser inspection",dev_server:"the shared background dev server"},bz={repository_discovery:"repository discovery",file_source_test_doc_inspection:"file, source, test, and documentation inspection",fact_finding:"fact finding",research:"research",implementation:"implementation",debugging:"debugging",testing:"testing",validation:"validation",frontend_work:"frontend work",security_work:"security work",browser_use:"authorized Browser Use",computer_use:"authorized Computer Use",review:"review",ci_release_observation:"CI or release observation"},_z=`Wait collectively for specialist results with ${W.routineWaitTool} at timeout_ms=${W.routineWaitMaximumTimeoutMs}, subject to mandatory active tool/runtime limits. Routine 60-second waits waste requests and tokens; use ten-minute collective event waits, which wake when specialists finish. On timeout, inspect only for actionable failures, blockers, or stalls; continue useful independent work or wait again only while relevant specialist results remain a live dependency. Do not poll status or send routine progress messages. Release specialist leaves after accepting their terminal outcomes.`;Cz=new Set([{model:"gpt-5.6-terra",effort:"high"},{model:"gpt-5.6-sol",effort:"low"},{model:"gpt-5.6-sol",effort:"medium"},{model:"gpt-5.6-sol",effort:"high"}].flatMap(({model:e,effort:t})=>["default","fast"].map((n)=>Tz(e,t,n))))});import{access as Oz,readFile as kz,readdir as Ez}from"fs/promises";import{join as Sv}from"path";class Qo{adapter;observedIdentities={};constructor(e){if("run"in e){let t=wh({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await ev({environment:e}),n=wh({executable:t.path,environment:M_(e),onMarketplaceConflict:(r)=>{console.warn(`HolyCodex warning: ${r}`)},...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new Qo(n)}async list(){try{return await this.adapter.list()}catch(e){throw vd("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw vd("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw vd("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw vd("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw vd("add",t,e)}}async status(e){let t=await this.list(),n={},r=new Map;for(let i of[...t.installed,...t.available])if(!r.has(i.pluginId)||i.installed)r.set(i.pluginId,i);let o=Object.fromEntries(await Promise.all(e.map(async(i)=>{let a=ao(t,i),s=Tr(i),c=r.get(i),l=a?.entry??(s===void 0||c?.marketplaceName==null?c:void 0),u=a;if(l!==void 0)n[i]=u?.entry.pluginId??l.pluginId;let d=l===void 0?"missing":l.installed&&l.enabled?"installed":l.installed?"disabled":"missing";return[i,d]})));return this.observedIdentities=Object.freeze(n),o}getObservedIdentities(){return this.observedIdentities}}class Bh{codexHome;observedIdentities={};constructor(e){this.codexHome=e}async status(e){let t;try{t=await kz(Sv(this.codexHome,"config.toml"),"utf8")}catch(c){if(bv(c))return this.observedIdentities=Object.freeze({}),Object.fromEntries(e.map((l)=>[l,"missing"]));throw c}let n=globalThis.Bun;if(!n?.TOML?.parse)throw Error("A TOML parser is unavailable.");let r=Pe(rs,n.TOML.parse(t));if(r===void 0)throw Error("Codex configuration is invalid.");let o=r.plugins,i=typeof o==="object"&&o!==null&&!Array.isArray(o)?o:void 0,a={},s=Object.fromEntries(await Promise.all(e.map(async(c)=>{let l=Ic(c),d=(l.length>0?l:[c]).flatMap((g)=>{if(i===void 0||!Object.hasOwn(i,g))return[];let y=i?.[g],v=typeof y==="object"&&y!==null&&!Array.isArray(y)?y.enabled:void 0;return[{id:g,enabled:v}]});if(d.length===0)return[c,"missing"];let p=d.filter((g)=>g.enabled===!0),f=(await Promise.all(p.map(async(g)=>{let y=Ic(g.id),v=[g.id,...y.filter((C)=>C!==g.id)];return{...g,cachedIdentity:await Iz(this.codexHome,v)}}))).find((g)=>g.cachedIdentity!==void 0),x=f?.cachedIdentity??p[0]?.id??d[0]?.id;if(x!==void 0)a[c]=x;if(f!==void 0)return[c,"installed"];if(p.length>0)return[c,"missing"];if(d.every((g)=>g.enabled===!1))return[c,"disabled"];return[c,"unknown"]})));return this.observedIdentities=Object.freeze(a),s}getObservedIdentities(){return this.observedIdentities}}async function Iz(e,t){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let o=Sv(e,"plugins","cache",n.slice(r+1),n.slice(0,r));try{let i=await Ez(o,{withFileTypes:!0,encoding:"utf8"});for(let a of i){if(!a.isDirectory())continue;try{return await Oz(Sv(o,a.name,".codex-plugin","plugin.json")),n}catch(s){if(!bv(s))throw s}}}catch(i){if(bv(i))continue;throw i}}return}function bv(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function vd(e,t,n){if(t instanceof co)return t;let o=(t instanceof he?t:void 0)?.code,i=o==="timeout"||o==="output_limit"||o==="cancelled"||o==="readback_mismatch"||o==="plugin_disabled"||o==="plugin_missing"||o==="marketplace_invalid"||o==="marketplace_timeout"||o==="marketplace_unavailable"?o:o==="command_failed"?e==="list"?"list_failed":e==="remove"?"remove_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed":e==="list"?"list_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed",a=t instanceof Error?t.message:e==="list"?"Codex could not list official plugins.":e==="remove"?`Codex could not remove ${n??"the selected official plugin"}.`:e==="bootstrap"?"Codex could not initialize the official marketplace.":`Codex could not add ${n??"the selected official plugin"}.`;return new co(i,a,t,n===void 0?{}:{plugin_id:n})}var co;var Rd=w(()=>{ss();gt();cs();co=class co extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t);this.name="OfficialPluginManagerError",this.code=e,this.causeValue=n,this.details=r}}});function vv(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=Az(r).trim();if(o.length===0)continue;if(o.startsWith("[[")||o.endsWith("]]"))throw Error("Array-of-tables are not supported by the validated fallback.");if(o.startsWith("[")&&o.endsWith("]")){n=wv(o.slice(1,-1).trim()),Pz(t,n);continue}let i=TF(o);if(i<1)throw Error("TOML assignment is invalid.");let a=wv(o.slice(0,i).trim()),s=Vh(o.slice(i+1).trim());RF(t,[...n,...a],s)}return t}function Rv(e){let t=[];return vF(e,[],t),t.join(`
41
+ `)}function vF(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(Tv(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(_F).join(".")}]`)}for(let[i,a]of r)n.push(`${_F(i)} = ${CF(a)}`);for(let[i,a]of o)vF(a,[...t,i],n)}function Vh(e){if(e.length===0)throw Error("TOML value is missing.");if(e.startsWith('"')){let t=JSON.parse(e);if(typeof t!=="string")throw Error("TOML string is invalid.");return t}if(e.startsWith("'")){if(!e.endsWith("'")||e.length<2)throw Error("TOML string is invalid.");return e.slice(1,-1)}if(e==="true")return!0;if(e==="false")return!1;if(e.startsWith("[")){if(!e.endsWith("]"))throw Error("TOML array is invalid.");let t=e.slice(1,-1).trim();return t.length===0?[]:_v(t,",").map((n)=>Vh(n.trim()))}if(e.startsWith("{")){if(!e.endsWith("}"))throw Error("TOML inline table is invalid.");let t=e.slice(1,-1).trim(),n={};if(t.length===0)return n;for(let r of _v(t,",")){let o=TF(r);if(o<1)throw Error("TOML inline table entry is invalid.");RF(n,wv(r.slice(0,o).trim()),Vh(r.slice(o+1).trim()))}return n}if(/^[+-]?(?:0|[1-9]\d*)(?:\.\d+)?$/u.test(e)){let t=Number(e);if(Number.isFinite(t))return t}throw Error("TOML value is unsupported.")}function wv(e){let t=_v(e,".").map((n)=>n.trim());if(t.length===0||t.some((n)=>!/^(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(n)||n==="__proto__"||n==="constructor"||n==="prototype"))throw Error("TOML key is invalid.");return t.map((n)=>n.startsWith('"')||n.startsWith("'")?Vh(n):n)}function RF(e,t,n){if(t.length===0)throw Error("TOML key is missing.");let r=e;for(let i of t.slice(0,-1)){let a=r[i];if(a===void 0){let s={};r[i]=s,r=s}else if(Tv(a))r=a;else throw Error("TOML key conflicts with a scalar.")}let o=t.at(-1);if(Object.prototype.hasOwnProperty.call(r,o))throw Error("TOML key is duplicated.");r[o]=n}function Pz(e,t){let n=e;for(let r of t){let o=n[r];if(o===void 0){let i={};n[r]=i,n=i}else if(Tv(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function _v(e,t){let n=[],r=0,o=0,i,a=!1;for(let s=0;s<e.length;s+=1){let c=e[s];if(i!==void 0){if(i==='"'&&a)a=!1;else if(i==='"'&&c==="\\")a=!0;else if(c===i)i=void 0;continue}if(c==='"'||c==="'")i=c;else if(c==="["||c==="{")o+=1;else if(c==="]"||c==="}")o-=1;else if(c===t&&o===0)n.push(e.slice(r,s)),r=s+1}if(i!==void 0||o!==0)throw Error("TOML value is unbalanced.");return n.push(e.slice(r)),n}function TF(e){let t,n=!1,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&i==="\\")n=!0;else if(i===t)t=void 0}else if(i==='"'||i==="'")t=i;else if(i==="["||i==="{")r+=1;else if(i==="]"||i==="}")r-=1;else if(i==="="&&r===0)return o}return-1}function Az(e){let t,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&o==="\\")n=!0;else if(o===t)t=void 0}else if(o==='"'||o==="'")t=o;else if(o==="#")return e.slice(0,r)}return e}function Tv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function _F(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function CF(e){if(typeof e==="string")return JSON.stringify(e);if(typeof e==="boolean"||typeof e==="number"){if(typeof e==="number"&&!Number.isFinite(e))throw Error("TOML number is invalid.");return String(e)}if(Array.isArray(e))return`[${e.map(CF).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{execFile as Mz}from"child_process";import{access as Nz,readFile as Fz,realpath as Lz}from"fs/promises";import{posix as Dz,win32 as qz}from"path";import{promisify as Uz}from"util";function xs(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:zc,run:async(t,n)=>{try{let r=await $z(t,[...n],{encoding:"utf8",windowsHide:!0,env:{...process.env,...e},timeout:120000,maxBuffer:4194304});return{exitCode:0,stdout:r.stdout,stderr:r.stderr}}catch(r){let o=r;return{exitCode:typeof o.code==="number"?o.code:1,stdout:typeof o.stdout==="string"?o.stdout:"",stderr:typeof o.stderr==="string"?o.stderr:r instanceof Error?r.message:"process failed"}}}}}function gs(e){let t=rr(e.npm_execpath??""),n=(e.npm_command??"").toLowerCase(),r=(e.npm_config_user_agent??"").toLowerCase();if(t.includes("yarn")||t.includes("corepack")||r.startsWith("yarn/"))return;if(Td(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(Td(t,"bunx")||Td(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(Td(t,"npx")||t.endsWith("/npx-cli.js")||Td(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function Wh(e,t,n){let r=await Ov(e);if(r!==void 0){let o=gs(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},i=n?.ownership==="holycodex"&&typeof n.identity==="string"&&await Kc(e,n.executable,r.executable);return{manager:o.family,launcher:o.launcher,version:r.version,executable:r.executable,ownership:i?"holycodex":"user",...i?{identity:n.identity}:{}}}if(Wc(e))return Vz(e,t,n);return Bz(e,t,n)}async function Cv(e,t){let n=await Ov(e);if(n!==void 0){let i=gs(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&await Kc(e,t.executable,n.executable);return{manager:i.family,launcher:i.launcher,version:n.version,executable:n.executable,ownership:a?"holycodex":"user",...a?{identity:t.identity}:{}}}let r=Wc(e)?{launcher:"bunx",family:"bun",executable:"bun"}:gs(e.environment);if(r===void 0)throw new Se("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let o=r.family==="bun"&&Wc(e)?await Cd(e):await Od(e,r);if(o===void 0)throw new Se("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:o.version,executable:o.executable,ownership:kv(t,r,o),identity:o.identity}}async function Ov(e){let t=await EF(e.environment,e.platform,e.files??zc);if(t===void 0)return;let n=await e.run(t,["--version"]),r=n.exitCode===0?ys(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}}async function jz(e){if(await Ov(e)!==void 0)return;if(Wc(e)){await Hz(e);return}let t=gs(e.environment);if(t===void 0)throw new Se("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let n=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0)throw new Se("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})}async function Hz(e){let t=e.files??zc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if(Zz(n.stderr))return;throw new Se("context7_unavailable","Bun's managed global installation could not be located before managed changes.",{stderr:n.stderr.slice(0,512)})}let r=cn(e.platform),o=n.stdout.trim(),i=r.join(r.dirname(o),"install","global"),a=r.join(i,"node_modules","ctx7"),s=r.join(a,"package.json"),c=r.join(o,e.platform==="win32"?"ctx7.exe":"ctx7");try{await t.access(o),await t.access(i)}catch(g){throw new Se("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:hs(g)})}let l;try{await t.access(a)}catch(g){if(Yz(g))return;throw new Se("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:hs(g)})}try{l=await t.readText(s)}catch(g){throw new Se("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:hs(g)})}let u;try{u=JSON.parse(l)}catch(g){throw new Se("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:hs(g)})}if(typeof u.version!=="string"||ys(u.version)!==u.version)throw new Se("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let d=IF(u);if(d===void 0)throw new Se("context7_unavailable","Bun's managed ctx7 package does not declare its executable before managed changes.");let p=r.resolve(a,d),m,f;try{await t.access(p),m=await t.realpath(a),f=await t.realpath(p)}catch(g){throw new Se("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:hs(g)})}if(!kd(m,a,e.platform)||!rr(f).startsWith(`${rr(m)}/`))throw new Se("context7_unavailable","Bun's managed ctx7 executable is outside its package before managed changes.");try{await t.access(c),await t.realpath(c)}catch(g){throw new Se("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:hs(g)})}let x=await e.run(c,["--version"]);if(x.exitCode!==0||ys(x.stdout)!==u.version)throw new Se("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:x.stderr.slice(0,512)})}async function Bz(e,t,n){let r=gs(e.environment);if(r===void 0)throw new Se("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await Od(e,r),i=await PF(e,r);if(i===void 0)throw new Se("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=kv(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=r.family==="bun"?{executable:"bun",args:zh(e,"add",nr)}:OF(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new Se("context7_install_failed",`${r.family} could not install ${nr}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new Se("context7_unavailable",`${nr} is not owned by the ${r.family} global installation.`);let s=await Od(e,r);if(s===void 0)throw new Se("context7_verification_failed",`${nr} could not be verified in the ${r.family} global installation.`);if(s.version!==i)throw new Se("context7_outdated",`The ${r.family} global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:r.family,launcher:r.launcher,version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Vz(e,t,n){let r={launcher:"bunx",family:"bun",executable:"bun"},o=await Cd(e),i=await PF(e,r);if(i===void 0)throw new Se("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=kv(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=await e.run(e.processPath,zh(e,"add",nr));if(l.exitCode!==0)throw new Se("context7_install_failed",`Bun could not install ${nr} in its global installation.`,{stderr:l.stderr.slice(0,512)})}else if(o===void 0)throw new Se("context7_unavailable",`${nr} is not present in Bun's exact global installation.`);let s=await Cd(e);if(s===void 0)throw new Se("context7_verification_failed",`${nr} could not be verified in Bun's exact global installation.`);if(s.version!==i)throw new Se("context7_outdated",`Bun's global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:"bun",launcher:"bunx",version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Cd(e){let t=e.files??zc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0)return;let r=n.stdout.trim();if(r.length===0)return;let o=cn(e.platform),i=o.join(o.dirname(r),"install","global","node_modules","ctx7"),a;try{a=JSON.parse(await t.readText(o.join(i,"package.json")))}catch{return}if(typeof a.version!=="string"||ys(a.version)!==a.version)return;let s=IF(a);if(s===void 0)return;let c=o.resolve(i,s),l=o.join(r,e.platform==="win32"?"ctx7.exe":"ctx7"),u,d,p;try{await t.access(i),await t.access(c),await t.access(l),u=await t.realpath(i),d=await t.realpath(c),p=await t.realpath(l)}catch{return}if(!kd(u,i,e.platform)||!rr(d).startsWith(`${rr(u)}/`))return;let m=await e.run(l,["--version"]);if(m.exitCode!==0||ys(m.stdout)!==a.version)return;return{version:a.version,executable:l,identity:await kF({launcher:"bunx",family:"bun",executable:"bun"},u,d,p,a)}}function Wc(e){let t=cn(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function kv(e,t,n){if(n===void 0)return"holycodex";if(e?.ownership!=="holycodex")return"user";if(e.manager!==t.family)return"user";let r=e.identity;if(!Ev(r)||r!==n.identity)return"user";return"holycodex"}async function Ed(e,t){if(Wc(e))return Wz(e,t);return zz(e,t)}async function Wz(e,t){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n;try{n=await Cd(e)}catch{return!1}if(n===void 0||n.version!==t.version||!await Kc(e,n.executable,t.executable)||!Ev(t.identity)||n.identity!==t.identity)return!1;let r=await e.run(e.processPath,zh(e,"remove","ctx7"));if(r.exitCode!==0)throw new Se("context7_remove_failed","Bun could not remove ctx7.",{stderr:r.stderr.slice(0,512)});if(await Cd(e)!==void 0)throw new Se("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0}async function zz(e,t){if(t?.ownership!=="holycodex")return!1;let n=gs(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await Od(e,n)}catch(a){if(a instanceof Se&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!await Kc(e,r.executable,t.executable)||!Ev(t.identity)||r.identity!==t.identity)return!1;let o=n.family==="bun"?{executable:"bun",args:zh(e,"remove","ctx7")}:Kz(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new Se("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await Od(e,n)!==void 0)throw new Se("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof Se&&a.code==="context7_remove_failed")throw a;throw new Se("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function OF(e){switch(e){case"bun":return{executable:"bun",args:["add","--global",nr]};case"npm":return{executable:"npm",args:["install","--global",nr]};case"pnpm":return{executable:"pnpm",args:["add","--global",nr]}}}function zh(e,t,n){let r=cn(e.platform),o=r.dirname(e.processPath),i=r.isAbsolute(o)?o:e.platform==="win32"?"C:\\":"/";return[t,"--global",`--cwd=${i}`,n]}function Kz(e){switch(e){case"bun":return{executable:"bun",args:["remove","--global","ctx7"]};case"npm":return{executable:"npm",args:["uninstall","--global","ctx7"]};case"pnpm":return{executable:"pnpm",args:["remove","--global","ctx7"]}}}async function Od(e,t){let n=e.files??zc,r=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(r.exitCode!==0)return;let o=r.stdout.trim();if(o.length===0)return;let i=t.family==="npm"?cn(e.platform).join(o,"node_modules","ctx7"):t.family==="pnpm"?await Xz(e,t):cn(e.platform).join(cn(e.platform).dirname(o),"install","global","node_modules","ctx7");if(i===void 0)return;let a;try{a=JSON.parse(await n.readText(cn(e.platform).join(i,"package.json")))}catch{return}if(typeof a.version!=="string")return;let s=typeof a.bin==="string"?a.bin:Iv(a.bin)&&typeof a.bin.ctx7==="string"?a.bin.ctx7:void 0;if(s===void 0)return;let c=cn(e.platform).resolve(i,s),l,u;try{if(await n.access(c),l=await n.realpath(i),u=await n.realpath(c),!rr(u).startsWith(`${rr(l)}/`))return}catch{return}let d=Jz(o,t.family,e.platform),p;try{await n.access(d),p=await n.realpath(d)}catch{return}let m=await EF(e.environment,e.platform,n);if(m!==void 0&&!kd(await Gz(n,m),p,e.platform))throw new Se("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:m,expected:d});let f=await e.run(d,["--version"]);if(f.exitCode!==0||ys(f.stdout)!==a.version)return;return{version:a.version,executable:d,identity:await kF(t,l,u,p,a)}}async function kF(e,t,n,r,o){return await qn("context7-installation",[Dn({manager:e.family,package_root:rr(t),package_executable:rr(n),shim:rr(r),package:o})])}function Ev(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function EF(e,t,n){let r=e.PATH;if(r===void 0)return;let o=t==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((i)=>i.length>0).map((i)=>`ctx7${i.toLowerCase()}`):["ctx7"];for(let i of r.split(t==="win32"?";":":")){if(i.length===0)continue;for(let a of o){let s=cn(t).join(i,a);try{return await n.access(s),s}catch{}}}return}function Jz(e,t,n){if(n==="win32")return cn(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?cn(n).join(e,"bin","ctx7"):cn(n).join(e,"ctx7")}async function Gz(e,t){try{return await e.realpath(t)}catch{return t}}function ys(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function IF(e){return typeof e.bin==="string"?e.bin:Iv(e.bin)&&typeof e.bin.ctx7==="string"?e.bin.ctx7:void 0}function hs(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function Yz(e){return Iv(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(hs(e))}function Zz(e){return/(?:no package\.json(?: was)? found|couldn['\u2019]?t find (?:a )?package\.json|could not find (?:a )?package\.json|package\.json (?:is )?missing)/iu.test(e)}async function Xz(e,t){let n=await e.run(t.executable,["root","--global"]),r=n.stdout.trim();return n.exitCode===0&&r.length>0?cn(e.platform).join(r,"ctx7"):void 0}async function PF(e,t){let n=await e.run(t.family==="bun"&&Wc(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return ys(n.stdout)}function Td(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function kd(e,t,n){let r=cn(n),o=r.resolve(e),i=r.resolve(t);return n==="win32"?rr(o)===rr(i):o===i}async function Kc(e,t,n){if(kd(t,n,e.platform))return!0;let r=e.files??zc;try{let[o,i]=await Promise.all([r.realpath(t),r.realpath(n)]);return kd(o,i,e.platform)}catch{return!1}}function cn(e){return e==="win32"?qz:Dz}function rr(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function Iv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var nr="ctx7@latest",$z,zc,Se;var Kh=w(()=>{gt();$z=Uz(Mz),zc={access:Nz,readText:(e)=>Fz(e,"utf8"),realpath:Lz};Se=class Se extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as Gh,rmdir as Mv}from"fs/promises";import{join as Qz}from"path";async function Fv(e={},t=process.env){let n=Pr(e,t),r={};try{await ls(n.codexHome),await ls(n.stateRoot),r.paths=Jc({state_root:n.stateRoot})}catch(u){r.paths=Kt(["path_symlink"],{error:or(u)})}let o=await ra(n).catch((u)=>{r.configuration=Kt(["state_corrupt"],{error:or(u)});return}),[i,a]=await Promise.all([Nr(n.preparingRecord,o).catch((u)=>{r.transaction=Kt(["state_corrupt"],{path:n.preparingRecord,error:or(u)});return}),Nr(n.conflictedRecord,o).catch((u)=>{r.transaction=Kt(["state_corrupt"],{path:n.conflictedRecord,error:or(u)});return})]);if(r.transaction?.status!=="failed"&&(i!==void 0||a!==void 0)){let u=Qh(o,i,a),d=[...new Set(u.map((p)=>{if(p.relation==="stale")return"stale_transaction_state";if(p.relation==="incompatible")return"incompatible_transaction_state";return p.status==="preparing"?"incomplete_install_state":"conflicted_state"}))];r.transaction=Kt(d,{recovery:u.map((p)=>p.recovery).join(","),transactions:u.map((p)=>`${p.status}:${p.relation}:${p.install_id}:${p.digest}`).join(","),active:o===void 0?"absent":`${o.install_id}:${o.digest}`})}if(!r.configuration)if(!o)r.configuration=Kt(["configuration_missing"]);else if(await Zc(o))r.configuration=Jc({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=Kt(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await lK(n,o),r.native_roles=await uK(n,o.profile,o.tier,{browserUse:o.capability_state?.browser_use.status==="healthy"&&o.capability_state.browser_use.selected,computerUse:o.capability_state?.computer_use.status==="healthy"&&o.capability_state.computer_use.selected});let u=Object.entries(o.capability_state??{}).find(([d,p])=>d!=="browser_use"&&p.selected&&p.status!=="healthy");if(u)r.capabilities=Kt(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status});if(o.optional_selections.browser_use)r.browser_use={status:"unsupported",reasons:["surface_managed_by_codex_desktop"],details:{selected:!0,owner:"Codex Desktop/runtime",availability:"Available only on Codex surfaces that provide Browser Use.",cli_provisioning:"HolyCodex CLI does not install, configure, or verify Browser."}}}let s=e.runtime??xs(t);try{let u=await Cv(s,o?.tooling?.context7);r.context7=Jc({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:or(u)}}}try{let u=await be(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&Vc(u)){let d=r.native_roles;r.native_roles={status:"failed",reasons:[...d?.reasons??[],"stale_legacy_root"],details:{...d?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(u){r.native_roles=Kt(["native_role_invalid"],{error:or(u)})}let c=e.officialPluginManager;if(o&&c?.status){let u=[...new Set([un,...Pc({browser_use:o.optional_selections.browser_use,computer_use:o.optional_selections.computer_use,sites:o.optional_selections.sites},o.official_plugins),...(o.owned_plugins??[]).filter((d)=>d!==ln)])].filter((d)=>d!==ln);try{let d=await c.status(u),p=Object.entries(d).filter(([,f])=>f!=="installed").map(([f])=>f),m=c.getObservedIdentities?.()??{};r.native_plugins=p.length===0?Jc({status:d,observed_identities:m}):Kt(["native_plugin_disagreement"],{missing:p,status:d,observed_identities:m})}catch(d){r.native_plugins=Kt(["native_plugin_status_failed"],{error:or(d)})}}else r.native_plugins=Kt(["native_plugin_status_unavailable"],{reason:"No read-only live official plugin status source is available."});let l=Object.values(r).flatMap((u)=>u.reasons);return{healthy:Object.values(r).every((u)=>u.status!=="failed"),checks:r,reasons:[...new Set(l)]}}async function Lv(e={},t=process.env){let n=Pr(e,t);await ls(n.codexHome),await ls(n.stateRoot);let r=await ra(n);if(r!==void 0&&!await Zc(r))throw new _("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Nr(n.preparingRecord,r),Nr(n.conflictedRecord,r)]);Uv(r,o,i);let a=DF(r,o,i);if(a===void 0)return[];let s=Jt(await be(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await Ir(s,a.managed_config,{schema:a.managed_config.schema,installId:a.managed_config.installId});for(let u of[...l.preservedKeys,...l.unresolvedKeys])c.push(await Av(n.configFile,u,s,"config-key","This managed Codex setting changed after installation."))}if(a.plugin_config!==void 0){let l=await Gc(s,a.plugin_config,{allowBeforeState:!0});for(let u of l.preserved){let d=u==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";c.push(await Av(n.configFile,d,s,"plugin-config","This HolyCodex plugin setting differs from the recorded install state."))}}if(a.provider_config!==void 0){let l=await Yc(s,Yh(a.provider_config),new Set(Dv(a)),{allowBeforeState:!0});for(let u of l.preserved){let d=`plugins.${JSON.stringify(u)}`;c.push(await Av(n.configFile,d,s,"plugin-config",`The ${u} plugin setting differs from the recorded install state.`))}}return c.push(...await yF(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[lo(l),l])).values()]}async function Id(e={},t=process.env){let n=Pr(e,t);await ls(n.codexHome),await ls(n.stateRoot);let r=await ra(n);if(r&&!await Zc(r))throw new _("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Nr(n.preparingRecord,r),Nr(n.conflictedRecord,r)]);Uv(r,o,i);let a=DF(r,o,i);Jh(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(Dv(a)),c=[],l=[],u=[],d=!1,p=()=>(Jh(e,{stage:"removal",status:"completed",message:"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u});if(a===void 0)return Jh(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let m=await Lv(e,t),f=await sK(e,m),x=await be(n.configFile),g=Jt(x),y=m.filter((S)=>S.key!==void 0&&f.has(lo(S))),v=new Map;for(let S of m){if(S.key!==void 0||!f.has(lo(S)))continue;let D=FF(S);if(D!==void 0)v.set(S.path,D)}await cK(n,g,y,v);let C=a?.managed_config;if(C){let S=await Ir(g,C,{schema:C.schema,installId:C.installId});if(S.preservedKeys.length>0||S.unresolvedKeys.length>0){let A=[...S.preservedKeys,...S.unresolvedKeys].map((pe)=>({path:n.configFile,key:pe,action:"remove"}));for(let pe of A)if(f.has(lo(pe)))g=er(g,pe.key)}}if(a?.plugin_config){let S=await Gc(g,a.plugin_config,{allowBeforeState:!0});if(S.preserved.length>0){let D=S.preserved.map((A)=>({path:n.configFile,key:A==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let A of S.preserved){let pe=D.find((De)=>De.key===(A==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(pe===void 0||!f.has(lo(pe)))continue;g=er(g,A==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let S=await Yc(g,Yh(a.provider_config),s,{allowBeforeState:!0});if(S.preserved.length>0){let D=S.preserved.map((A)=>({path:n.configFile,key:`plugins."${A}"`,action:"remove"}));for(let A of S.preserved){let pe=D.find((De)=>De.key===`plugins."${A}"`);if(pe===void 0||!f.has(lo(pe)))continue;g=er(g,`plugins."${A}"`)}}}let M,N;if(s.size>0){try{M=e.officialPluginManager??await Qo.discover({...t,CODEX_HOME:n.codexHome})}catch(S){throw new _("capability_denied","Native Codex plugin removal is unavailable.",S,{operation:"discover Codex",plugins:[...s].join(","),recovery:"Install or expose Codex, then retry."})}if(M===void 0||!M.remove||!M.list)throw new _("capability_denied","Native Codex plugin removal and readback are unavailable.",void 0,{operation:"prepare plugin removal",plugins:[...s].join(",")});try{N=await M.list()}catch(S){throw new _("capability_denied","Codex plugin state could not be read before removing HolyCodex-owned plugins.",S,{operation:"read Codex plugin state",plugins:[...s].join(","),recovery:"Repair or expose Codex, then retry removal."})}}let O,E=a;try{let S=g,D=C;if(D){let A=await Ir(S,D,{schema:D.schema,installId:D.installId}),pe=[...A.preservedKeys,...A.unresolvedKeys];if(pe.filter((vt)=>!f.has(lo({path:n.configFile,key:vt,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Mr(n,a??Ss()),p();if(S=A.document,pe.length>0){let vt=new Set(pe);D={...A.state,managed:Object.fromEntries(Object.entries(A.state.managed).filter(([Rt])=>!vt.has(Rt)))}}else D=A.state}if(a?.plugin_config){let A=await Gc(S,a.plugin_config,{allowBeforeState:!0});if(A.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Mr(n,a),p();S=A.document}if(a?.provider_config){let A=await Yc(S,Yh(a.provider_config),s,{allowBeforeState:!0});if(A.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Mr(n,a),p();S=A.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)O=D===void 0?{document:S}:{document:S,state:D};if(O!==void 0){if(Object.keys(O.document).length===0&&x===void 0)await AF(n.configFile,x),await Gh(n.configFile,{force:!1});else await AF(n.configFile,x),await At(n.configFile,uo(O.document));E={...a,managed_config:O.state},await Mr(n,E),d=!0}}catch(S){if(S instanceof _)throw await Mr(n,E??Ss()),S;return l.push(n.configFile),u.push("managed_config_write_failed"),await Mr(n,E??Ss()),p()}let I=await $h(n.codexHome,a?.managed_artifacts??[],v);if(c.push(...I.removed),l.push(...I.preserved),I.preserved.length>0)return u.push("managed_artifact_changed"),await Mr(n,E??a??Ss()),p();c.push(...await nK(n.roleRoot,a?.managed_artifacts??[]));for(let S of s)try{if(M?.list===void 0||M.remove===void 0||N===void 0)throw new _("capability_denied","Codex plugin state is unavailable for a HolyCodex-owned plugin.",void 0,{operation:"remove Codex plugin",plugin_id:S});let A=dK(N,S);if(A?.entry.installed!==!0)continue;let pe=A.entry.pluginId;await M.remove(pe);let De=await M.list();if(N=De,ao(De,S)?.entry?.installed===!0||[...De.installed,...De.available].some((et)=>et.pluginId===S&&et.installed))throw new _("capability_denied",`Codex still reports ${S} after removal.`);if(O!==void 0)await tK(n,O.document,S);c.push(S)}catch(D){throw u.push("native_plugin_remove_failed"),await Mr(n,E??Ss()),new _("capability_denied",`Codex native plugin removal did not converge for ${S}: ${or(D)}`,D)}try{if(await Ed(e.runtime??xs(t),a.tooling?.context7))c.push("ctx7")}catch(S){throw u.push("context7_remove_failed"),await Mr(n,E??Ss()),new _("capability_denied",`Context7 removal did not converge: ${or(S)}`,S)}if(r)try{await Gh(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(S){if(!Ke(S,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await Mr(n,a??r),p()}if(l.length===0)try{await Gh(n.installOptions,{force:!1}),c.push(n.installOptions)}catch(S){if(!Ke(S,"ENOENT"))l.push(n.installOptions),u.push("state_remove_failed"),await Mr(n,a??r??Ss())}if(l.length===0)for(let[S,D]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0||d]]){if(!D)continue;try{await pK(S),c.push(S)}catch{l.push(S),u.push("state_remove_failed")}}if(l.length===0)try{await Mv(n.roleRoot),c.push(n.roleRoot)}catch(S){if(!Ke(S,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await Mv(n.stateRoot),c.push(n.stateRoot)}catch(S){if(Ke(S,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return Jh(e,{stage:"removal",status:"completed",message:l.length===0&&u.length===0?"HolyCodex removal complete":"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u}}async function tK(e,t,n){let r=await be(e.configFile);if(r===void 0)return;let o=Jt(r,e.configFile),i=o.plugins;if(!Pv(i))return;let a=i[n];if(!Pv(a)||Object.keys(a).length!==1||a.enabled!==!1)return;let s=t.plugins,c=Pv(s)?s[n]:void 0,l={...i};if(c===void 0)delete l[n];else l[n]=c;let u={...o};if(Object.keys(l).length===0)delete u.plugins;else u.plugins=l;await At(e.configFile,uo(u))}function Pv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function nK(e,t){let n=new Set;for(let o of t){let i=o.path.split("/");if(i.length===4&&i[0]==="holycodex"&&i[1]==="agents"&&/^[a-f0-9]{20}$/u.test(i[2]??"")&&i[3]?.endsWith(".toml"))n.add(i[2])}let r=[];for(let o of n){let i=Qz(e,o);try{await Mv(i),r.push(i)}catch(a){if(!Ke(a,"ENOENT")&&!Ke(a,"ENOTEMPTY")&&!Ke(a,"EEXIST"))throw a}}return r}async function rK(e={},t=process.env,n={}){let r=Pr(e,t),o=await ra(r),[i,a]=await Promise.all([Nr(r.preparingRecord,o),Nr(r.conflictedRecord,o)]);if(o!==void 0&&!await Zc(o))throw new _("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});qv(o,i,a);let s=LF(o,i,a),c=s??o;if(c===void 0)throw new _("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l=await Xh(r),u=l===void 0?{profile:c.profile,tier:c.tier,optional:{browser_use:c.optional_selections.browser_use,computer_use:c.optional_selections.computer_use,sites:c.optional_selections.sites},officialPlugins:oK(c)}:iK(Pd(l)),d=n.options===void 0?u:dn(n.options),p={profile:d.profile??u.profile,tier:d.tier??u.tier,optional:{...u.optional,...d.optional},officialPlugins:d.officialPlugins??u.officialPlugins},m=!aK(p,u),f;try{f=await bd()}catch(E){throw new _("upgrade_failed","The running HolyCodex version is unavailable.",E)}let x=f.split("-",1)[0]===c.version.split("-",1)[0]&&f.includes("-dev.")!==c.version.includes("-dev."),g=x?0:Ku(f,c.version);if(g<0)throw new _("upgrade_downgrade",`The running HolyCodex version ${f} is older than the installed version ${c.version}.`,void 0,{installed_version:c.version,running_version:f});let y=c.managed_config?.managed["features.context_management"]!==void 0,v=c.managed_config?.managed[Yi[0]]!==void 0,C=[];if(n.dryRun===!0){let E=Jt(await be(r.configFile));if(c.managed_config!==void 0)for(let S of Object.keys(c.managed_config.managed)){if(!os(S))continue;if((await as(E,c.managed_config,S)).status!=="unchanged")C.push({path:r.configFile,key:S,action:"replace"})}if(c.plugin_config!==void 0){let S=await Gc(E,c.plugin_config);for(let D of S.preserved){let A=D==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";C.push({path:r.configFile,key:A,action:"replace"})}}if(c.provider_config!==void 0){let S=await Yc(E,Yh(c.provider_config),new Set(Dv(c)));for(let D of S.preserved)C.push({path:r.configFile,key:`plugins."${D}"`,action:"replace"})}let I=await qh(r.codexHome,c.profile,c.managed_artifacts,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use});for(let S of I)C.push(S)}let M=!1,N=[];try{let E=e.runtime??xs(t),I;try{I=await Cv(E,c.tooling?.context7)}catch(D){if(c.tooling?.context7!==void 0||!fK(D))throw D}let S=c.tooling?.context7;if(S?.manager!==I?.manager)N.push("Context7 manager changed");if(S?.version!==I?.version)N.push("Context7 version changed");if(S?.executable===void 0?I?.executable!==void 0:I?.executable===void 0||!await Kc(E,S.executable,I.executable))N.push("Context7 executable changed");M||=N.length>0}catch(E){M=!0;let I=typeof E==="object"&&E!==null&&"code"in E&&typeof E.code==="string"?E.code:E instanceof Error?E.name:"inspection failed";N.push(`inspection failed (${I})`)}let O=[...g>0||x?["version"]:[],...m?["installation options"]:[],...l===void 0?["installation options migration"]:[],...y?["context-management configuration migration"]:[],...v?["auto-compaction configuration cleanup"]:[],...g>0||y||v?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...M?[`shared tooling reconciliation (${N.join(", ")})`]:[],...C.map((E)=>`conflict: ${E.path}${E.key===void 0?"":` (${E.key})`} -> ${E.action}`)];if(O.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:f,changes:[],record:o,preserved:[],warnings:[],conflicts:C};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:f,changes:O,record:o,preserved:[],warnings:[],conflicts:C};try{let E=await bs(p,e,t);return{status:"upgraded",from_version:c.version,to_version:f,changes:O,record:E.record,preserved:E.preserved,warnings:E.warnings}}catch(E){if(E instanceof _)throw E;throw new _("upgrade_failed",`HolyCodex upgrade failed: ${or(E)}`,E)}}function oK(e){let t=new Set(Pc(e.optional_selections));return(e.official_plugins??[]).filter((n)=>n!==ln&&!MF(n)&&!t.has(n))}function Yh(e){return e.filter((t)=>t.plugin_id!==ln)}function iK(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!MF(t))}}}function MF(e){let t=e.slice(0,e.lastIndexOf("@"));return eK.has(t)}function aK(e,t){let n=e.optional??{},r=t.optional??{},o=[...new Set(e.officialPlugins??[])],i=[...new Set(t.officialPlugins??[])];return e.profile===t.profile&&e.tier===t.tier&&n.browser_use===r.browser_use&&n.computer_use===r.computer_use&&n.sites===r.sites&&o.length===i.length&&o.every((a,s)=>a===i[s])}async function sK(e,t){let n=new Set;if(e.resolveConflicts!==void 0&&t.length>0){let r=t.map((i)=>({...i,identity:`remove:${i.path}:${i.key??""}`,category:i.key===void 0?"role-asset":"config-key",target:i.key??i.path,explanation:"HolyCodex can remove this managed value after reviewing the change.",validDecisions:["keep","remove","cancel"],defaultDecision:"keep"})),o=await e.resolveConflicts(r);for(let i=0;i<r.length;i+=1){let a=r[i],s=o[a.identity];if(s==="remove")n.add(lo(t[i]));else if(s==="keep")continue;else if(s==="cancel")throw new _("confirmation_required","Conflict resolution was cancelled.",void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});else throw new _("confirmation_required",`The removal conflict at ${a.target} requires a keep, remove, or cancel decision.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key},decision:s??"unavailable"})}return n}for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(lo(r));continue}if(o==="decline")continue;throw new _("confirmation_required",o==="cancel"?"Conflict resolution was cancelled.":"Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:r.path,...r.key===void 0?{}:{key:r.key},action:r.action,resolution:o??"unavailable"})}return n}function lo(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function Av(e,t,n,r,o){let i=fe(n,t),a=await NF(n,t);return{identity:lo({path:e,key:t,action:"remove"}),category:r,target:t,existing:{present:i!==void 0,digest:a},desired:{present:!1},explanation:o,validDecisions:["keep","remove","cancel"],defaultDecision:"keep",path:e,key:t,action:"remove"}}async function NF(e,t){let n=fe(e,t);return await qn("holycodex-removal-config-review-v1",[Dn(sn(n===void 0?{present:!1}:{present:!0,value:n}))])}function FF(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}async function cK(e,t,n,r){for(let i of n){if(i.key===void 0)continue;let a=FF(i);if(a===void 0||await NF(t,i.key)!==a)throw Nv(i.path,i.key)}let o;try{o=await xF(e.codexHome,r)}catch(i){let a=r.keys().next().value;throw new _("confirmation_required","A reviewed HolyCodex file could not be checked safely, so removal did not continue.",i,{operation:"verify removal review",...a===void 0?{}:{path:a},recovery:"Check file access, then run remove again to review current state."})}if(o.length>0)throw Nv(o[0])}function Nv(e,t){return new _("confirmation_required","A reviewed HolyCodex item changed before removal. No reviewed changes were applied; run remove again to review the current state.",void 0,{operation:"remove HolyCodex",path:e,...t===void 0?{}:{key:t},recovery:"Run remove again to review the current state."})}async function AF(e,t){if(await be(e)!==t)throw Nv(e)}async function lK(e,t){if(!t.managed_config)return Kt(["incomplete_install_state"]);try{let n=Jt(await be(e.configFile)),r=Md(t.profile,t.tier,{browserUse:t.capability_state?.browser_use.status==="healthy"&&t.capability_state.browser_use.selected,computerUse:t.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security}),o=[];for(let i of Object.keys(r))if((await as(n,t.managed_config,i)).status!=="unchanged")o.push(i);return o.length===0?Jc({managed_keys:Object.keys(r).length}):Kt(["changed_holycodex_config"],{keys:o})}catch(n){return Kt(["config_unreadable"],{error:or(n)})}}async function uK(e,t,n,r={browserUse:!1,computerUse:!1}){try{let o=Jt(await be(e.configFile)),i=[],a=ms(t,n,r);for(let c of Xo(t,n)){let l=fe(o,`agents."${c.name}".config_file`),u=is(e.configFile,_d(c.name,a)).replaceAll("\\","/");if(typeof l!=="string"||is(e.configFile,l).replaceAll("\\","/")!==u){i.push(`${c.name}:registration`);continue}let d=await be(u);if(d===void 0){i.push(`${c.name}:missing`);continue}if(d!==Bc(c,r)){i.push(`${c.name}:changed`);continue}let p=Jt(d);if(p.name!==c.name||typeof p.description!=="string"||typeof p.developer_instructions!=="string"||p.model!==c.model||p.model_reasoning_effort!==c.effort||p.model_reasoning_summary!=="none"||p.model_verbosity!=="low"||p.tool_output_token_limit!==void 0||p.service_tier!==(n==="standard"?"default":"fast")||!jh(c,p)||p.approval_policy!=="never"||p.web_search!==(c.permissions.network?"live":"disabled")||fe(p,"agents.enabled")!==!1||fe(p,"features.multi_agent")!==!1||fe(p,"features.multi_agent_v2")!==!1||fe(p,"features.agent_message_board")!==!1||fe(p,"features.context_management.experimental_mode")!==!0||Object.keys(p.features??{}).some((m)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(m)))i.push(`${c.name}:malformed`)}let s=await be(`${e.codexHome}/agents/root.toml`);if(s!==void 0&&Vc(s))i.push("root:stale");return i.length===0?Jc({role_root:e.roleRoot,agent_types:Xo(t,n).map((c)=>c.name)}):Kt(["native_role_disagreement"],{roles:i})}catch(o){return Kt(["native_role_invalid"],{error:or(o)})}}async function Mr(e,t){let n={...t,status:"conflicted",step:"conflicted",managed_config:t.managed_config??{owner:"holycodex",schema:t.schema_epoch,installId:t.install_id,managed:{}},plugin_snapshot:t.plugin_snapshot??[],owned_plugins:t.owned_plugins??[]};if(Pe(ea,n)!==void 0)await ps(e.conflictedRecord,sn(n))}function LF(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||Ad(r,e)))}function DF(e,t,n){return LF(e,t,n)??e}function Ss(){return{owner:"holycodex",schema_epoch:"state-0.16",install_id:"remove-conflict",version:"0.0.0",digest:"0".repeat(64),profile:"default",tier:"standard",optional_selections:{browser_use:!1,computer_use:!1,sites:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function Dv(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)].filter((o)=>o!==ln);let t=(e?.plugin_snapshot??[]).filter((o)=>o.plugin_id!==ln&&(o.status==="missing"||o.status==="available")).map((o)=>o.plugin_id),n=e?.plugin_config?.before.preference.presence==="absent"&&e.plugin_config.after.preference.presence==="present"?[un]:[],r=(e?.provider_config??[]).filter((o)=>o.plugin_id!==ln&&o.before.presence==="absent"&&o.after.presence==="present").map((o)=>o.plugin_id);return[...new Set([...t,...n,...r])]}function dK(e,t){let n=ao(e,t);if(n!==void 0)return n;let r=[...e.installed,...e.available].find((o)=>o.pluginId===t);return r===void 0?void 0:{entry:r}}function Jc(e){return{status:"healthy",reasons:[],details:e}}function Kt(e,t={}){return{status:"failed",reasons:e,details:t}}async function pK(e){await Gh(e,{force:!1}).catch((t)=>{if(!Ke(t,"ENOENT"))throw t})}function fK(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function or(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function Jh(e,t){try{e.onProgress?.(t)}catch{}}var eK;var Zh=w(()=>{ss();gt();Nd();hd();wd();Hh();Rd();us();cs();jc();Kh();eK=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{lstat as VF,open as mK,rm as Dd}from"fs/promises";import{dirname as hK}from"path";function dn(e){let t=Pe(Nh,e);if(t===void 0)throw new _("install_failed","The installation options are invalid.");let n=t;return zF(n),n}function zF(e){if(e.officialPlugins?.includes(ln)!==!0)return;throw new _("install_failed","Browser Use is provided by Codex Desktop/runtime and cannot be installed by the HolyCodex CLI. Select the Browser Use capability instead; it is available only on supporting Codex surfaces.",void 0,{plugin_id:ln})}async function Xh(e){let t=await be(e.installOptions);return KF(t,e.installOptions)}function KF(e,t){if(e===void 0)return;let n;try{n=vv(e)}catch(i){throw new _("state_corrupt","The HolyCodex install options are not valid TOML.",i,{path:t})}let r=Pe(Sd,n);if(r!==void 0)return r;let o=Pe(eF,n);if(o!==void 0)return{schema_version:1,profile:o.profile,tier:o.tier,capabilities:o.capabilities.filter((i)=>i==="browser_use"||i==="computer_use"||i==="sites").concat(...["browser_use","sites"].filter((i)=>!o.capabilities.includes(i))),additional_plugins:o.additional_plugins};if(r===void 0)throw new _("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}async function JF(e,t){if(Pe(Sd,t)===void 0)throw new _("state_corrupt","The HolyCodex install options are invalid.");await At(e.installOptions,Rv(t))}function Pd(e){return{profile:e.profile,tier:e.tier,optional:{browser_use:e.capabilities.includes("browser_use"),computer_use:e.capabilities.includes("computer_use"),sites:e.capabilities.includes("sites")},officialPlugins:e.additional_plugins.filter((t)=>t!==ln)}}async function GF(e={},t=process.env){let n=Pr(e,t),r=await Xh(n);if(r!==void 0)return Pd(r);let o=await ra(n);if(o===void 0)return{};return{profile:o.profile,tier:o.tier,optional:o.optional_selections,officialPlugins:Kv(o)}}function YF(e,t,n,r){let o=["browser_use","computer_use","sites"].filter((i)=>n[i]);return{schema_version:1,profile:e,tier:t,capabilities:o,additional_plugins:[...new Set(r)].filter((i)=>i!==ln)}}function Ad(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function Qh(e,t,n){let r=[{status:"conflicted",record:n},{status:"preparing",record:t}].filter((a)=>a.record!==void 0),o=r.length>1,i=o&&r.every(({record:a})=>Ad(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?o&&!i?"incompatible":"orphaned":Ad(s,e)?o&&!i?"incompatible":"bound":"stale";return{status:a,relation:c,install_id:s.install_id,digest:s.digest,recovery:c==="stale"||c==="incompatible"?"inspect":"reconcile",...e===void 0?{}:{active_install_id:e.install_id,active_digest:e.digest}}})}function qv(e,t,n){let r=Qh(e,t,n);if(r.filter((i)=>i.relation==="stale"||i.relation==="incompatible").length>0)throw new _("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,ZF(r));return r}function Uv(e,t,n){let r=Qh(e,t,n);if(e===void 0&&r.some((o)=>o.relation==="incompatible"))throw new _("state_corrupt","HolyCodex has ambiguous transaction state and cannot recover safely.",void 0,ZF(r));return r}function ZF(e){return{recovery:e.map((t)=>t.recovery).join(","),transactions:e.map((t)=>`${t.status}:${t.relation}:${t.install_id}:${t.digest}`).join(","),active:e[0]?.active_install_id===void 0?"absent":`${e[0].active_install_id}:${e[0].active_digest}`}}async function bs(e={},t={},n=process.env){let r=Pe(xd,e);if(r===void 0)throw new _("install_failed","The installation options are invalid.");zF(r);let o=Pr(t,n),i=await be(o.installOptions),a=await be(o.activeRecord),s=KF(i,o.installOptions),c=s===void 0?void 0:Pd(s);Fr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let l=await ra(o);if(l!==void 0&&!await Zc(l))throw new _("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:o.activeRecord});let u=await Nr(o.preparingRecord,l),d=await Nr(o.conflictedRecord,l);qv(l,u,d);let p=[d,u].find((P)=>P!==void 0&&(l===void 0||Ad(P,l)));if(p!==void 0){await Promise.resolve().then(() => Zh());let L=await Id(t,n);if(L.preserved.length>0||L.reasons.length>0)throw new _("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:L.preserved.join(","),reasons:L.reasons.join(",")});return await bs({profile:e.profile??c?.profile??p.profile,tier:e.tier??c?.tier??p.tier,optional:{browser_use:e.optional?.browser_use??c?.optional?.browser_use??p.optional_selections.browser_use,computer_use:e.optional?.computer_use??c?.optional?.computer_use??p.optional_selections.computer_use,sites:e.optional?.sites??c?.optional?.sites??p.optional_selections.sites},officialPlugins:e.officialPlugins??c?.officialPlugins??Kv(p)},t,n)}let m=jK(e.profile??c?.profile,l?.profile),f=HK(e.tier??c?.tier,l?.tier),x=c?.optional,g=Wv(x,e.optional),y=BK(g,l?.optional_selections),v=Wv(Wv(l?.explicit_optional_selections,x),e.optional),C=e.officialPlugins??c?.officialPlugins??Kv(l),M=t.runtime??xs(n),N=await Wh(M,!1,l?.tooling?.context7).then(()=>!0,()=>!1),O,E,I=[...new Set(Pc(XF(y),C).map((P)=>Tr(P)??P))],S;try{S=t.officialPluginManager??await Qo.discover({...n,CODEX_HOME:o.codexHome})}catch(P){throw new _("capability_denied","Native Codex plugin installation is unavailable.",P,{recovery:"Install or expose Codex, then retry."})}if(!S.addMarketplace||!S.add||!S.list)throw new _("install_failed","Native Codex plugin installation and verification are unavailable.");let D=l?.install_id??crypto.randomUUID().replaceAll("-",""),A=await bd(),pe=l!==void 0&&l.version!==A&&l.owned_plugins?.includes(un)===!0?new Set([un]):new Set,De=new Set((l?.owned_plugins??[]).filter((P)=>P!==ln)),vt=new Set([un,...I]),Rt=[...De].filter((P)=>!vt.has(P));if(Rt.length>0&&S.remove===void 0)throw new _("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:Rt.join(",")});let et=(t.now?.()??new Date).toISOString(),Je=Md(m,f,{browserUse:y.browser_use,computerUse:y.computer_use,frontend:Pt.frontend,security:Pt.security}),it=await be(o.configFile),sr;try{sr=Jt(it,o.configFile)}catch(P){if(P instanceof _&&P.code==="state_corrupt")await TK(t,P,o.configFile);throw P}let aa=l?.managed_config??kh({schema:On,installId:D}),ii=await ng(sr,aa),pg=await wK(t,o.configFile,ii.document,['plugins."holycodex@holycodex"',"marketplaces.holycodex",...Object.keys(Je)]),{document:tl,conflicts:Hn,decisions:zd}=pg,fg=Hn.length===0?sr:Xc(sr,Hn,zd),Rn;if(Hn.length>0){if(await be(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed after the invalid-table review; review the latest configuration and retry.",void 0,{path:o.configFile});Rn=uo(fg),await At(o.configFile,Rn)}let Kd,dR=!1,Jd,pR=new Map;try{Kd=await S.list()}catch(P){if(Rn!==void 0)await Hv(o.configFile,it,Rn),Rn=void 0;if(!VK(P))throw new _("capability_denied","Native Codex plugin state could not be read safely.",P);if(await be(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed before the required marketplace repair; review the current marketplace source and retry.",P,{path:o.configFile,key:"marketplaces.holycodex"});let L=fe(tl,"marketplaces.holycodex"),G=Hn.some((Be)=>Be.key==="marketplaces"&&zd.get(Be.identity)==="remove");if(L===void 0&&!G)throw new _("confirmation_required","Codex reported an incomplete marketplace named holycodex, but config.toml does not contain a reviewable marketplace source. Review the source before retrying; no automatic replacement was attempted.",P,{path:o.configFile,key:"marketplaces.holycodex"});if(L!==void 0&&!WK(L))Jd=ar({path:o.configFile,key:"marketplaces.holycodex",action:"replace",category:"config-key",target:"marketplaces.holycodex",existing:L,desired:{source_type:"git",source:ei},explanation:"The existing HolyCodex marketplace source must be reviewed before rebuilding its incomplete cache from the required canonical source.",defaultDecision:"replace",validDecisions:["replace","cancel"]}),pR=(await qd(t,[Jd],!0)).decisions;if(!(ri(L)&&Object.keys(L).length===2&&L.source_type==="git"&&L.source===ei)){if(await be(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed before marketplace repair; review the current source and retry.",P,{path:o.configFile,key:"marketplaces.holycodex"});let Be=po(tl,"marketplaces",_s,{source_type:"git",source:ei});Rn=uo(Be),await At(o.configFile,Rn)}if(S.addMarketplace===void 0)throw new _("capability_denied","Native Codex plugin state could not be read safely.",P);try{await S.addMarketplace(qF),Kd=await S.list(),dR=!0}catch(Be){if(Rn!==void 0)try{await Hv(o.configFile,it,Rn),Rn=void 0}catch(We){throw new _("confirmation_required","The marketplace repair failed and the reviewed temporary Codex configuration could not be restored safely; review config.toml before retrying.",We,{path:o.configFile,key:"marketplaces.holycodex"})}throw new _("capability_denied","The required HolyCodex marketplace could not be repaired before plugin validation.",Be)}}if(Rn!==void 0)await Hv(o.configFile,it,Rn),Rn=void 0;let fR=I.filter((P)=>{if(!P.endsWith("@openai-curated"))return!1;let L=Lr(Kd,P);return!(L?.installed&&L.enabled)});Fr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let sa=await eg(tl),mg=l?.plugin_config?.before??sa,fo=mg,Ts=t.resolveConflicts!==void 0,Cs=[],nl=[],rl=[];if(nl=["preference","marketplace"].filter((L)=>{let G=sa[L].digest,Z=sa[L],Be=L==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ei},We=Z.presence==="present"&&JSON.stringify(Z.safe_value)!==JSON.stringify(Be),ut=l?.plugin_config!==void 0&&G!==l.plugin_config.after[L].digest&&G!==l.plugin_config.before[L].digest;return We||ut}).map((L)=>{let G=L==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",Z=sa[L],Be=L==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ei};return ar({path:o.configFile,key:G,action:"replace",category:"config-key",target:G,existing:Z.safe_value??{presence:Z.presence},desired:Be,explanation:`The existing ${G} entry does not match the HolyCodex plugin configuration.`,validDecisions:["replace","cancel"],defaultDecision:"replace"})}),Ts)Cs.push(...nl);let hg=[...new Set([...I,...(l?.provider_config??[]).map((P)=>P.plugin_id),...l?.owned_plugins??[]])].filter((P)=>P!==un&&P!==ln),ca=await tg(tl,hg);{let P=new Set(l?.owned_plugins??[]);if(rl=ca.filter((G)=>{let Z=l?.provider_config?.find((ut)=>ut.plugin_id===G.plugin_id),Be=P.has(G.plugin_id)&&Z!==void 0&&G.before.digest!==Z.after.digest&&G.before.digest!==Z.before.digest,We=I.includes(G.plugin_id)&&G.before.presence==="present"&&G.before.safe_value?.value!==!0;return Be||We}).map((G)=>{let Z=`plugins."${G.plugin_id}"`;return ar({path:o.configFile,key:Z,action:"replace",category:"config-key",target:Z,existing:G.before.safe_value??{presence:G.before.presence},desired:{kind:"boolean",value:!0},explanation:`The existing provider plugin entry ${G.plugin_id} does not match the selected plugin configuration.`,...I.includes(G.plugin_id)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),Ts)Cs.push(...rl)}let gg=ca.map((P)=>{let L=l?.provider_config?.find((G)=>G.plugin_id===P.plugin_id);return L===void 0?P:{plugin_id:P.plugin_id,before:L.before,after:L.before}}),Gd=gg,mR=ii.state,hR=await Bv(tl,mR,l),gR=await ng(hR.document,hR.state),yR=await Vv(gR.document,gR.state),{document:Dr,state:cr}=yR;IK(Dr,cr);let Os;if(l!==void 0){Os=Md(l.profile,l.tier,{browserUse:l.optional_selections.browser_use,computerUse:l.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security});let P=Zm(l.version.split("-",1)[0]);for(let L of zo){let G=l.managed_artifacts.find(({path:Z})=>Z.endsWith(`/${L}.toml`));Os[`agents."${L}".config_file`]=G?.path??`holycodex/agents/${L}.toml`}if(Ku(P,gK)<=0)Os.model="gpt-6-astra",Os.model_reasoning_effort=l.profile==="low"?"low":l.profile==="default"?"medium":"high";delete Os.developer_instructions}let yg=await EK(Dr,cr,Je,Os),mo;try{mo=await Dc(Dr,cr,yg,{schema:On,installId:D})}catch(P){if(P instanceof _)throw P;throw new _("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",P,{recovery:"Converge the conflicting Codex setting, then retry."})}let ai=[];if(mo.driftedKeys.length>0)ai=mo.driftedKeys.map((P)=>{let L=cr.managed[P],G=fe(Dr,P),Z=Je[P];return ar({path:o.configFile,key:P,action:"replace",category:"config-key",target:P,existing:G??L?.lastManagedValue,desired:Z,explanation:`The managed Codex setting ${P} changed outside the previous transaction.`})});let la=Object.entries(Je).flatMap(([P,L])=>{let G=P;if(cr.managed[G]!==void 0)return[];let Z=fe(Dr,G);if(Z===void 0||JSON.stringify(Z)===JSON.stringify(L))return[];return[ar({path:o.configFile,key:G,action:"replace",category:"config-key",target:G,existing:Z,desired:L,explanation:`The existing Codex setting ${G} is user-owned and differs from the HolyCodex install value.`,defaultDecision:"replace",validDecisions:["keep","replace","cancel"]})]});if(Ts)Cs.push(...la);if(Ts)Cs.push(...ai);let ol;try{ol=await qh(o.codexHome,m,l?.managed_artifacts,f,{browserUse:y.browser_use,computerUse:y.computer_use})}catch(P){throw new _("install_failed",Ld(P),P)}if(Ts)Cs.push(...ol.map(ar));let Yd=[...Hn,...nl,...rl,...la,...ai,...ol.map(ar)],vL={...mo.state.managed},RL=new Set([...Hn.map((P)=>P.identity),...Jd===void 0?[]:[Jd.identity]]),TL=(Ts?Cs:Yd).filter((P)=>!RL.has(P.identity)),xR=await qd(t,TL,!0),qr={...xR,decisions:new Map([...zd,...pR,...xR.decisions])},SR=[],il={...yg},al=cr.managed,bR=async()=>{SR=ol.map((We)=>{let ut=ar(We),tt=qr.decisions.get(ut.identity);return tt===void 0?ut:{...ut,decision:tt}});let P=await $F(Dr,Dr,mg,gg,sa,ca,nl,rl,qr.decisions,I),L=Xc(P.document,Hn,qr.decisions);fo=P.pluginConfigBefore,Gd=P.providerConfigBefore;let G={...cr.managed},Z={...yg};for(let We of[...la,...ai]){let ut=We.key;if(ut===void 0)continue;let tt=ut,ua=qr.decisions.get(We.identity);if(ua!=="keep"&&ua!=="replace")throw new _("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:ut});let qt=G[tt],si=Je[tt];if(si===void 0)throw new _("state_corrupt","The managed conflict cannot be verified.",void 0,{path:o.configFile,key:ut});let lr=fe(Dr,tt);if(ua==="replace")if(L=so(L,tt,si),qt!==void 0)G[tt]={...qt,lastManagedValue:await _n(tt,si)};else{let $r=vL[tt];if($r!==void 0)G[tt]=$r}else{if(delete Z[tt],qt===void 0)continue;if(lr===void 0){delete G[tt];continue}let $r={...qt,lastManagedValue:await _n(tt,lr)},Qd={...cr,managed:{...G,[tt]:$r}};if(Gi(Qd))G[tt]=$r;else delete G[tt]}}if(mo=await Dc(L,{...cr,managed:G},Z,{schema:On,installId:D}),mo.driftedKeys.length>0)throw new _("state_corrupt","The accepted managed conflicts did not converge.");il=Z;let Be={...cr.managed};for(let We of[...la,...ai]){let ut=We.key;if(ut===void 0)continue;delete Be[ut]}al=Be};await bR();let wR=()=>Yd.map((P)=>{let L=ar(P),G=qr.decisions.get(L.identity);return G===void 0?L:{...L,decision:G}}),_R=(P)=>Object.fromEntries(["config-key","invalid-config","native-plugin","role-asset"].flatMap((L)=>{let G=P.filter((Z)=>Z.category===L).length;return G===0?[]:[[L,G]]})),Zd=wR(),vR=_R(Zd),CL=zK(N,Kd,I);if(t.reviewInstall!==void 0)while(!0){let P=await t.reviewInstall({operation:l===void 0?"install":"upgrade",...l===void 0?{}:{fromVersion:l.version},toVersion:A,profile:m,tier:f,capabilities:{browser_use:y.browser_use,computer_use:y.computer_use,sites:y.sites},additionalPlugins:[...C],conflicts:Zd,conflictCounts:vR,tools:CL});if(P.action==="cancel")throw new _("confirmation_required","Install review was cancelled.");if(P.action==="resolve"){if(Yd.length===0)throw new _("confirmation_required","There are no managed conflicts to resolve.");qr=await qd(t,Yd,!0),await bR(),Zd=wR(),vR=_R(Zd);continue}if(P.action==="change"){if(P.request===void 0)throw new _("confirmation_required","Changing install options requires a revised request.");return await bs(P.request,t,n)}if(P.action==="apply")break;throw new _("confirmation_required","Unknown install review action.")}let xg={owner:"holycodex",schema_epoch:On,install_id:D,version:A,digest:l?.digest??"0".repeat(64),profile:m,tier:f,optional_selections:y,explicit_optional_selections:v,official_plugins:I,capability_state:og(y),managed_artifacts:l?.managed_artifacts??[],installed_at:et,status:"preparing",step:"validated",managed_config:mR,plugin_snapshot:[],plugin_config:{plugin_id:un,before:fo,after:fo},provider_config:Gd,owned_plugins:[...De],...l?.tooling?.context7===void 0?{}:{tooling:{context7:l.tooling.context7}}};await $c(o.stateRoot),await ir(o.preparingRecord,xg);let sl=[],ho,Sg=!1,RR=!1,TR=new Set,bg=new Set,Xd=new Set,Tn=new Set(De),wg=new Set([...De,...I]),_g=new Set,ge=xg,CR=!1,Ur,vg,cl=mo.state,OR=!1,kR=!1;try{if(Hn.length>0){let X=await be(o.configFile);if(fg=Xc(Jt(X,o.configFile),Hn,zd),await be(o.configFile)!==X)throw new _("confirmation_required","Codex configuration changed during conflict resolution; review the latest configuration and retry.",void 0,{path:o.configFile});await At(o.configFile,uo(fg)),RR=!0}try{O=await Wh(M,!0,l?.tooling?.context7)}catch(X){E=`Optional ctx7 is unavailable: ${Ld(X)}`}let P=O??l?.tooling?.context7,L=P===void 0?void 0:{context7:P},G={...xg,...L===void 0?{}:{tooling:L}};if(ge=G,await ir(o.preparingRecord,ge),S.ensureOfficialMarketplace!==void 0&&fR.length>0)try{await S.ensureOfficialMarketplace(fR)}catch(X){throw new _("capability_denied",`The selected official Codex provider marketplace is unavailable: ${Ld(X)}`,X,{recovery:"Check Codex network and marketplace policy, then retry."})}try{sl=await PK({list:()=>S.list()},[...new Set([un,...I,...De])])}catch(X){throw new _("capability_denied","Native Codex plugin state could not be read safely.",X)}G={...G,plugin_snapshot:sl},ge=G,await ir(o.preparingRecord,ge);let Z=await be(o.configFile),Be=Jt(Z,o.configFile),We=Xc(Be,Hn,qr.decisions);await kK(We,sa,ca);let ut=await Bv(We,aa,l),tt=await ng(ut.document,ut.state);Ur=(await Vv(tt.document,tt.state)).document,await HF(Ur,Dr,{...cr,managed:al},il),Fr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await $c(o.roleRoot),ho=await xv(o.codexHome,m,l?.managed_artifacts,f,ol.length===0?t.resolveConflict:void 0,SR,{browserUse:y.browser_use,computerUse:y.computer_use}),ge={...G,step:"roles_prepared",managed_artifacts:ho.managed_artifacts},await ir(o.preparingRecord,ge),Fr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),Fr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),CR=!0;let qt=Ur;if(qt===void 0)throw new _("state_corrupt","The pre-mutation configuration baseline is missing.");qt=po(qt,"plugins",ws,{enabled:!0}),qt=po(qt,"marketplaces",_s,{source_type:"git",source:ei});for(let X of I)qt=po(qt,"plugins",X,{enabled:!0});let si=await eg(qt),$r=(await tg(qt,hg)).map((X)=>({plugin_id:X.plugin_id,before:ca.find((Ae)=>Ae.plugin_id===X.plugin_id)?.before??X.before,after:X.before}));if(ge={...ge,plugin_config:{plugin_id:un,before:fo,after:si},provider_config:$r},await ir(o.preparingRecord,ge),it===void 0)try{vg=await LK(o.configFile);let X=await be(o.configFile);if(vg===void 0||X!=="")throw new _("confirmation_required","Codex config.toml appeared during installation; review the latest configuration and retry.",void 0,{operation:"initialize Codex configuration",path:o.configFile});Z=""}catch(X){if(X instanceof _)throw X;throw new _("permission_denied","Codex config.toml could not be initialized before plugin setup.",X,{operation:"initialize Codex configuration",path:o.configFile,recovery:"Check CODEX_HOME permissions, then retry."})}if(await be(o.configFile)!==Z)throw new _("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:o.configFile});if(await At(o.configFile,uo(qt)),Sg=!0,!dR)await S.addMarketplace(qF);await qK({list:()=>S.list(),add:(X)=>S.add(X)},[un,...I],pe,async(X,Ae)=>{if(Ae==="new")TR.add(X),Tn.add(X),wg.add(X),ge={...ge,owned_plugins:[...Tn]};else _g.add(X),Tn.add(X),wg.add(X),ge={...ge,owned_plugins:[...Tn]};await ir(o.preparingRecord,ge)}),ge={...ge,step:"plugins_installed"},await ir(o.preparingRecord,ge),Fr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let ER=await be(o.configFile),OL=Jt(ER,o.configFile),kL=Xc(OL,Hn,qr.decisions),IR=await Bv(kL,aa,l),PR=await ng(IR.document,IR.state),EL=await Vv(PR.document,PR.state);if(Ur===void 0)throw new _("state_corrupt","The pre-mutation configuration baseline is missing.");let Rg=await $F(EL.document,Ur,mg,gg,sa,ca,nl,rl,qr.decisions,I),go=Rg.document;for(let X of Object.keys(al)){let Ae=X,Cn=fe(Ur,Ae);go=Cn===void 0?er(go,Ae):so(go,Ae,Cn)}fo=Rg.pluginConfigBefore,Gd=Rg.providerConfigBefore;let ep=await eg(go),AR=await tg(go,hg),MR=AR.map((X)=>({plugin_id:X.plugin_id,before:Gd.find((Ae)=>Ae.plugin_id===X.plugin_id)?.before??X.before,after:X.before})),NR=AR.map((X)=>({plugin_id:X.plugin_id,before:ca.find((Ae)=>Ae.plugin_id===X.plugin_id)?.before??X.before,after:X.before}));ge={...ge,plugin_config:{plugin_id:un,before:fo,after:ep},provider_config:NR};let IL=new Set([...la,...ai].flatMap((X)=>X.key===void 0?[]:[X.key])),tp={...al};for(let X of[...la,...ai]){let Ae=X.key;if(Ae===void 0)continue;let Cn=mo.state.managed[Ae];if(Cn!==void 0)tp[Ae]=Cn}for(let[X,Ae]of Object.entries(tp)){if(IL.has(X))continue;let Cn=X,ll=fe(Ur,Cn);tp[Cn]={...Ae,...ll===void 0?{}:{lastManagedValue:await _n(Cn,ll)}}}let FR={...mo.state,managed:tp};await HF(go,Ur,{...FR,managed:al},il);for(let X of[...la,...ai]){let Ae=X.key;if(Ae===void 0)continue;let ll=qr.decisions.get(X.identity)==="replace"?Je[Ae]:fe(Dr,Ae);if(ll!==void 0)go=so(go,Ae,ll)}let np=await Dc(go,FR,il,{schema:On,installId:D});if(np.driftedKeys.length>0)throw new _("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:np.driftedKeys.join(",")});if(Fr(t,{stage:"config",status:"started",message:"Configuring Root"}),cl=np.state,ge={...ge,managed_config:cl,plugin_config:{plugin_id:un,before:fo,after:ep},provider_config:NR},await be(o.configFile)!==ER)throw new _("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:o.configFile});if(await At(o.configFile,uo(np.document)),Sg=!0,ge={...ge,step:"config_published"},await ir(o.preparingRecord,ge),Rt.length>0)await UK({list:()=>S.list(),remove:(Ae)=>S.remove(Ae)},Rt,async(Ae,Cn)=>{if(Cn==="removed")bg.add(Ae),Tn.delete(Ae);else if(Cn==="absent")Tn.delete(Ae);else Xd.add(Ae);ge={...ge,owned_plugins:[...Tn]},await ir(o.preparingRecord,ge)});Fr(t,{stage:"config",status:"completed",message:"Root configuration published"}),Fr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await MK(o,m,f,{browserUse:y.browser_use,computerUse:y.computer_use,frontend:Pt.frontend,security:Pt.security},cl,ho.preserved,il),Fr(t,{stage:"verification",status:"completed",message:"Installation verified"});let LR=og(y),PL=await ig({owner:"holycodex",install_id:D,version:A,profile:m,tier:f,optional_selections:y,explicit_optional_selections:v,official_plugins:I,capability_state:LR,managed_artifacts:ho.managed_artifacts,managed_config:cl,plugin_config:{plugin_id:un,before:fo,after:ep},provider_config:MR,plugin_snapshot:sl,owned_plugins:[...Tn],...L===void 0?{}:{tooling:L}}),Tg={owner:"holycodex",schema_epoch:On,install_id:D,version:A,digest:PL,profile:m,tier:f,optional_selections:y,explicit_optional_selections:v,official_plugins:I,capability_state:LR,managed_artifacts:ho.managed_artifacts,installed_at:et,status:"active",step:"active",managed_config:cl,plugin_snapshot:sl,plugin_config:{plugin_id:un,before:fo,after:ep},provider_config:MR,owned_plugins:[...Tn],...L===void 0?{}:{tooling:L}};if(Pe(Uc,Tg)===void 0)throw new _("state_corrupt","The HolyCodex configuration is invalid.");return OR=!0,await ps(o.activeRecord,sn(Tg)),kR=!0,await JF(o,YF(m,f,y,C)),await rg(o.preparingRecord),await rg(o.conflictedRecord),Fr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Tg,optional_plugins:I,preserved:ho.preserved,warnings:[...ho.preserved.length===0?[]:["modified managed files were preserved"],...E===void 0?[]:[E]]}}catch(P){let L=[],G;if(OR)try{if(a===void 0)await Dd(o.activeRecord,{force:!1}).catch((Z)=>{if(!Ke(Z,"ENOENT"))throw Z});else await At(o.activeRecord,a)}catch{L.push("active_record")}if(kR)try{if(i===void 0)await Dd(o.installOptions,{force:!1}).catch((Z)=>{if(!Ke(Z,"ENOENT"))throw Z});else await At(o.installOptions,i)}catch{L.push("install_options")}if(CR||Sg)try{if(Ur!==void 0)G=await AK(o.configFile,ge,Ur,wg)}catch{L.push("config")}if(RR)try{await _K(o.configFile,Hn)}catch{L.push("invalid_config")}if(ho!==void 0)try{if((await Uh(ho.rollback)).preserved.length>0)L.push("roles")}catch{L.push("roles")}if(_g.size>0)L.push(...[..._g].map((Z)=>`plugin:${Z}`));for(let Z of TR)try{await S.remove?.(Z)}catch{L.push(`plugin:${Z}`)}for(let Z of new Set([...bg,...Xd]))try{await $K({list:()=>S.list(),add:(Be)=>S.add(Be)},Z,sl.find((Be)=>Be.plugin_id===Z)?.status),bg.delete(Z),Xd.delete(Z),Tn.add(Z),ge={...ge,owned_plugins:[...Tn]},await ir(o.preparingRecord,ge)}catch{Tn.add(Z),Xd.add(Z),ge={...ge,owned_plugins:[...Tn]},await ir(o.preparingRecord,ge).catch(()=>{return}),L.push(`plugin:${Z}`)}if(O?.ownership==="holycodex"&&l?.tooling?.context7?.ownership!=="holycodex")try{if(!await Ed(M,O))L.push("context7")}catch{L.push("context7")}if(L.length===0&&it===void 0)try{if((await be(o.configFile))?.trim().length===0&&await DK(o.configFile,G??vg))await Dd(o.configFile,{force:!1})}catch{L.push("config_initialization")}if(L.length>0){try{let Be=Jt(await be(o.configFile),o.configFile),We=ge.plugin_config,ut=await eg(Be),tt=We===void 0?void 0:{...We,after:{preference:ut.preference.digest===We.before.preference.digest?We.before.preference:We.after.preference,marketplace:ut.marketplace.digest===We.before.marketplace.digest?We.before.marketplace:We.after.marketplace}},ua=ge.provider_config,qt=await tg(Be,ua?.map((lr)=>lr.plugin_id)??[]),si=ua?.map((lr)=>{let $r=qt.find((Qd)=>Qd.plugin_id===lr.plugin_id);return $r!==void 0&&$r.before.digest===lr.before.digest?{...lr,after:lr.before}:lr});ge={...ge,...tt===void 0?{}:{plugin_config:tt},...si===void 0?{}:{provider_config:si}}}catch{}let Z=!1;try{await ir(o.conflictedRecord,{...ge,step:"conflicted",status:"conflicted"}),Z=!0}catch{}if(Z)await rg(o.preparingRecord).catch(()=>{return})}else await rg(o.preparingRecord).catch(()=>{return});if(P instanceof tr)throw P;if(P instanceof _)throw P;throw new _(P instanceof co||P instanceof ni?"capability_denied":"install_failed",Ld(P),P,L.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function ra(e){let t=await pv(e.activeRecord,gd);if(t===void 0)return;let n=t.optional_selections,o=typeof n==="object"&&n!==null&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"work")?void 0:Pe(Uc,t);if(o!==void 0)return o;let i=Pe(tF,t);if(i===void 0)throw new _("state_corrupt","The HolyCodex configuration is invalid.");if(!await QF(i))throw new _("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord});let a="profile"in i&&i.profile!==void 0?i.profile:("plan"in i)?i.plan:void 0;if(a===void 0)throw new _("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=nh(a)}catch(A){throw new _("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,A,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([A])=>A!=="plan")):i,{optional_selections:l,explicit_optional_selections:u}=i,d={browser_use:l.browser_use??en.browser_use,computer_use:l.computer_use,sites:l.sites??en.sites,coding:!0},p={...u.computer_use===void 0?{}:{computer_use:u.computer_use},...u.browser_use===void 0?{}:{browser_use:u.browser_use},...u.sites===void 0?{}:{sites:u.sites}},m=i.capability_state===void 0?void 0:og(d,new Map([["browser_use","missing"],["sites","missing"]])),f=(i.official_plugins??[]).filter((A)=>!Fd(A)),x=i.owned_plugins?.filter((A)=>!Fd(A)),g=i.provider_config?.filter((A)=>!Fd(A.plugin_id)),y=i.plugin_snapshot?.filter((A)=>!Fd(A.plugin_id)),{optional_selections:v,explicit_optional_selections:C,capability_state:M,official_plugins:N,owned_plugins:O,provider_config:E,plugin_snapshot:I,...S}=c,D={...S,profile:s,optional_selections:d,explicit_optional_selections:p,official_plugins:f,...m===void 0?{}:{capability_state:m},...x===void 0?{}:{owned_plugins:x},...g===void 0?{}:{provider_config:g},...y===void 0?{}:{plugin_snapshot:y},digest:await ig({owner:i.owner,install_id:i.install_id,version:i.version,profile:s,tier:i.tier,optional_selections:d,explicit_optional_selections:p,official_plugins:f,capability_state:m??null,managed_artifacts:i.managed_artifacts,...i.managed_config===void 0?{}:{managed_config:i.managed_config},...i.plugin_config===void 0?{}:{plugin_config:i.plugin_config},...g===void 0?{}:{provider_config:g},...y===void 0?{}:{plugin_snapshot:y},...x===void 0?{}:{owned_plugins:x},...i.tooling===void 0?{}:{tooling:i.tooling}})};return WF.set(D,i.digest),D}async function Nr(e,t){let n=await pv(e,gd);if(n===void 0)return;let r=Pe(ea,n);if(r!==void 0)return r;let o=Pe(oF,n);if(o===void 0)throw new _("state_corrupt","The HolyCodex transaction state is invalid.",void 0,{path:e});let i=o,a=i.profile??i.plan;if(typeof a!=="string")throw new _("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e});let s;try{s=nh(a)}catch(S){throw new _("state_corrupt","The persisted transaction profile requires an explicit replacement.",S,{path:e,profile:a})}let{optional_selections:c,explicit_optional_selections:l}=i,u={browser_use:c.browser_use??en.browser_use,computer_use:c.computer_use??!1,sites:c.sites??en.sites,coding:!0},d={...l.browser_use===void 0?{}:{browser_use:l.browser_use},...l.computer_use===void 0?{}:{computer_use:l.computer_use},...l.sites===void 0?{}:{sites:l.sites}},m=i.capability_state===void 0?void 0:og(u,new Map([["browser_use","missing"],["sites","missing"]])),{plan:f,profile:x,optional_selections:g,explicit_optional_selections:y,capability_state:v,...C}=i,M=typeof C.digest==="string"?C.digest:void 0,N=t===void 0?void 0:WF.get(t),O=t!==void 0&&C.install_id===t.install_id&&(M===t.digest||N!==void 0&&M===N)?t.digest:M,E={...C,profile:s,optional_selections:u,explicit_optional_selections:d,...m===void 0?{}:{capability_state:m},...O===void 0?{}:{digest:O}},I=Pe(ea,E);if(I===void 0)throw new _("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e});return I}function XF(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites}}function Jt(e,t="config.toml"){if(e===void 0||e.trim().length===0)return{};try{let n=globalThis.Bun,r=n?.TOML?.parse?n.TOML.parse(e):vv(e),o=Pe(rs,r);if(o===void 0){let i=zv(r),a=i===void 0?"an unsupported TOML value":`the TOML value ${i}`;throw new _("state_corrupt",`${t} contains ${a} that HolyCodex cannot preserve. Convert it to a string, number, boolean, table, or array, then retry.`,void 0,{path:t,...i===void 0?{}:{key:i},reason:"unsupported_toml_value"})}return o}catch(n){if(n instanceof _)throw n;let r=Ld(n),o=vK(e,r),i=o===void 0?`${t} contains invalid TOML: ${r}. Fix the TOML syntax and retry; HolyCodex cannot safely rewrite malformed TOML.`:`${t} contains invalid TOML at line ${o.line}, column ${o.column} (offset ${o.offset}): ${r}. Fix the syntax at that location and retry; HolyCodex cannot safely rewrite malformed TOML.`;throw new _("state_corrupt",i,n,{path:t,parser_message:r,...o===void 0?{}:o,reason:"invalid_toml_syntax"})}}function zv(e,t=[]){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number")return Number.isFinite(e)?void 0:jv(t);if(Array.isArray(e)){for(let[n,r]of e.entries()){let o=zv(r,[...t,"["+n+"]"]);if(o!==void 0)return o}return}if(typeof e==="object"&&e!==null){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return jv(t);for(let[r,o]of Object.entries(e)){let i=zv(o,[...t,r]);if(i!==void 0)return i}return}return jv(t)}function jv(e){return e.length===0?"<root>":e.join(".")}function xK(e,t){let n=new Map;for(let r of t)for(let o of SK(r)){let i=fe(e,o);if(i!==void 0&&!ri(i))n.set(o,i)}return[...n].map(([r,o])=>({key:r,value:o}))}function SK(e){let t=[],n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r)r=!1;else if(i==="\\")r=!0;else if(i==='"')n=!1;continue}if(i==='"')n=!0;else if(i===".")t.push(e.slice(0,o))}return t}function bK(e,t){let n=JSON.stringify(t.value);return new _("state_corrupt",`${e} has the non-table value ${n} at ${t.key}, but the HolyCodex installer needs that path to be a table. Remove it after review or convert it to a table and retry; replacing it automatically could discard user configuration.`,void 0,{path:e,key:t.key,existing:n,reason:"expected_table"})}async function wK(e,t,n,r){let o=xK(n,r).map((a)=>{let s=bK(t,a);return ar({identity:`invalid-config:${t}:${a.key}`,category:"invalid-config",target:a.key,existing:a.value,desired:`Remove the conflicting value at ${a.key} so HolyCodex can create the required table.`,explanation:`${s.message} Choose remove to continue or cancel to repair it manually.`,path:t,key:a.key,action:"remove",defaultDecision:"remove",validDecisions:["remove","cancel"]})});if(o.length===0)return{document:n,conflicts:o,decisions:new Map};let i=await qd(e,o,!0);return{document:Xc(n,o,i.decisions),conflicts:o,decisions:i.decisions}}function Xc(e,t,n){let r=e;for(let o of t){if(n.get(o.identity)!=="remove"||o.key===void 0)throw new _("confirmation_required",`Invalid configuration at ${o.target} can only be removed after review or cancelled.`,void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},existing:JSON.stringify(o.existing),valid_decisions:o.validDecisions??["remove","cancel"]});let a=fe(r,o.key);if(a===void 0)continue;if(JSON.stringify(a)!==JSON.stringify(o.existing))throw new _("confirmation_required",`Invalid configuration at ${o.key} changed after review; review the current value and retry.`,void 0,{path:o.path,key:o.key,reviewed:JSON.stringify(o.existing),current:JSON.stringify(a)});r=er(r,o.key)}return r}async function Hv(e,t,n){if(await be(e)!==n)throw new _("confirmation_required","Codex configuration changed during preflight validation; review the latest configuration and retry.",void 0,{path:e});if(t===void 0){await Dd(e,{force:!1}).catch((r)=>{if(!Ke(r,"ENOENT"))throw r});return}await At(e,t)}async function _K(e,t){let n=await be(e),r=Jt(n,e),o=r;for(let i of t){if(i.key===void 0||i.existing===void 0)continue;let a=fe(o,i.key);if(a!==void 0){if(JSON.stringify(a)===JSON.stringify(i.existing))continue;if(!(typeof a==="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0))throw new _("confirmation_required",`Codex configuration at ${i.key} changed during rollback; preserve it and review the current value.`,void 0,{path:e,key:i.key});o=er(o,i.key)}o=so(o,i.key,i.existing)}if(o===r)return;if(await be(e)!==n)throw new _("confirmation_required","Codex configuration changed during rollback; preserve it and review the current value.",void 0,{path:e});await At(e,uo(o))}function vK(e,t){let n,r=/found \(0x([0-9a-f]{2})\)/iu.exec(t),o=/found '((?:\\.|[^'])*)'/u.exec(t),i=r===null?o?.[1]?.replaceAll("\\'","'").replaceAll("\\\"",'"'):String.fromCharCode(Number.parseInt(r[1],16));if(i!==void 0)n=RK(e,i);else if(/end of file|unterminated/iu.test(t))n=e.length;else if(/missing value after/iu.test(t)){let c=e.lastIndexOf("="),l=c<0?-1:e.indexOf(`
42
42
  `,c+1);n=l<0?e.length:l}if(n===void 0)return;let a=e.slice(0,n).split(`
43
43
  `).length,s=e.lastIndexOf(`
44
- `,Math.max(0,n-1));return{offset:n,line:a,column:n-s}}function mK(e,t){let n,r=!1,o=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(o){if(a===`
45
- `)o=!1;continue}if(n!==void 0){if(n==='"'&&r)r=!1;else if(n==='"'&&a==="\\")r=!0;else if(a===n)n=void 0;continue}if(a==="#"){o=!0;continue}if(e.startsWith(t,i))return i;if(a==='"'||a==="'")n=a}return}async function hK(e,t,n){let r=typeof t.details.key==="string"?t.details.key:void 0,o=typeof t.details.offset==="number"?String(t.details.offset):void 0,i=Ar({identity:"invalid-config:"+n+":"+(o??r??"unsupported"),category:"invalid-config",target:r===void 0?n+" syntax":n+" value "+r,existing:t.details,desired:"Repair the TOML value before installing HolyCodex.",explanation:t.message,path:n,...r===void 0?{}:{key:r},action:"replace",defaultDecision:"cancel",validDecisions:["cancel"]});try{await Wh(e,[i],!0)}catch{}}function Cd(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):yv(e)).trimEnd()}
46
- `}catch(t){throw new T("install_failed","The merged Codex configuration is not writable.",t)}}async function qh(e){return{preference:await ms(e,"plugins",Wi),marketplace:await ms(e,"marketplaces",zc)}}async function $h(e,t){return await Promise.all(t.map(async(n)=>{let r=await ms(e,"plugins",n),o={presence:r.presence,digest:r.digest,...r.safe_value?.kind==="boolean"?{safe_value:r.safe_value}:{}};return{plugin_id:n,before:o,after:o}}))}async function jc(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",Wi],["marketplace","marketplaces",zc]]){let u=t.before[s],d=t.after[s],p=await ms(e,c,l);if(n.allowBeforeState===!0&&p.digest===u.digest)continue;if(p.digest!==d.digest){a.push(s);continue}if(u.presence==="absent"){if(p.presence==="present")r=Uv(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=Wo(r,c,l,yK(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function Hc(e,t,n,r={}){let o=e,i=[],a=[],s=[];for(let c of t){if(!n.has(c.plugin_id))continue;let{before:l,after:u}=c,d=await ms(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&d.digest===l.digest)continue;if(d.digest!==u.digest){s.push(c.plugin_id);continue}if(l.presence==="absent"){if(d.presence==="present")o=Uv(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=Wo(o,"plugins",c.plugin_id,{enabled:l.safe_value.value}),i.push(c.plugin_id)}return{document:o,restored:i,removed:a,preserved:s}}async function PF(e,t,n,r,o,i){if(o.presence!=="present"||o.safe_value!==void 0)return{document:e,restored:!1};let a=await ms(e,n,r);if(a.digest===o.digest||a.digest!==i.digest)return{document:e,restored:!1};let s=Wc(t,n,r);if(s===void 0)return{document:e,restored:!1};return{document:Wo(e,n,r,s),restored:!0}}async function ms(e,t,n){let r=Wc(e,t,n),o=await Fn("holycodex-plugin-config",[Nn(cn({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=gK(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function Wc(e,t,n){let r=e[t];if(!zi(r)||!Object.hasOwn(r,n))return;return r[n]}function AF(e,t,n){let r=Wc(e,t,n);return zi(r)&&r.enabled===!1}function gK(e,t){if(!zi(t))return;let n=Object.keys(t);if(e==="plugins"){if(n.length!==1||n[0]!=="enabled"||typeof t.enabled!=="boolean")return;return{kind:"boolean",value:t.enabled}}if(n.length!==2||!n.includes("source_type")||!n.includes("source")||t.source_type!=="git"||t.source!==Vc)return;return{kind:"marketplace",source_type:"git",source:Vc}}function yK(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function Wo(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!zi(i))throw new T("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function Uv(e,t,n){let r=e[t];if(!zi(r)||!Object.prototype.hasOwnProperty.call(r,n))return e;let o={...e},i={...r};if(delete i[n],Object.keys(i).length===0)delete o[t];else o[t]=i;return o}function zi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function xK(e,t,n){let r=[{parent:"plugins",key:Wi,expected:t.preference},{parent:"marketplaces",key:zc,expected:t.marketplace},...n.map(({plugin_id:o,before:i})=>({parent:"plugins",key:o,expected:i}))];for(let{parent:o,key:i,expected:a}of r)if((await ms(e,o,i)).digest!==a.digest)throw new T("confirmation_required","Plugin configuration changed after preflight; review the latest configuration and retry.",void 0,{key:`${o}.${i}`})}async function MF(e,t,n,r,o,i,a,s,c,l){let u=e,d=n,p=r;for(let f of a){let m=f.identity;if(m===void 0)throw new T("state_corrupt","A plugin configuration conflict has no identity.");let y=c.get(m);if(y!=="keep"&&y!=="replace")throw new T("confirmation_required",`Plugin configuration conflict resolution is incomplete for ${f.key??m}.`);let g=f.key==='plugins."holycodex@holycodex"'?"preference":"marketplace",x=o[g];if(y==="keep"){let P=Wc(t,"plugins",Wi);if(g==="preference"&&zi(P)&&P.enabled===!1)throw new T("confirmation_required","Keeping disabled HolyCodex config would disable the selected plugin.");u=NF(u,t,f.key),d={...d,[g]:x};continue}u=Wo(u,g==="preference"?"plugins":"marketplaces",g==="preference"?Wi:zc,g==="preference"?{enabled:!0}:{source_type:"git",source:Vc})}for(let f of s){let{identity:m,key:y}=f;if(m===void 0||y===void 0)throw new T("state_corrupt","A provider configuration conflict has no identity.");let g=y.startsWith('plugins."')&&y.endsWith('"')?y.slice(9,-1):void 0;if(g===void 0)throw new T("state_corrupt",`The provider configuration conflict key ${y} is invalid.`);let x=c.get(m);if(x!=="keep"&&x!=="replace")throw new T("confirmation_required",`Provider configuration conflict resolution is incomplete for ${y}.`);let P=i.find((_)=>_.plugin_id===g);if(P===void 0)throw new T("state_corrupt",`The provider configuration entry ${g} is missing.`);if(x==="keep"){let _=Wc(t,"plugins",g);if(l.includes(g)&&zi(_)&&_.enabled===!1)throw new T("confirmation_required",`Keeping disabled config would disable selected plugin ${g}.`);u=NF(u,t,y),p=p.map((I)=>I.plugin_id===g?{plugin_id:g,before:P.before,after:P.before}:I);continue}u=Wo(u,"plugins",g,{enabled:!0})}return{document:u,pluginConfigBefore:d,providerConfigBefore:p}}function NF(e,t,n){if(n===void 0)throw new T("state_corrupt","A configuration conflict has no key.");if(n.startsWith('plugins."')&&n.endsWith('"')){let o=n.slice(9,-1),i=Wc(t,"plugins",o);return i===void 0?Uv(e,"plugins",o):Wo(e,"plugins",o,i)}let r=fe(t,n);return r===void 0?Rr(e,n):Li(e,n,r)}async function SK(e,t,n,r){let o={...n};if(r===void 0)return o;for(let i of Object.keys(n)){let a=i,s=t.managed[a],c=r[a];if(s===void 0||c===void 0)continue;let l=await sn(a,c);if(JSON.stringify(l)===JSON.stringify(s.lastManagedValue))continue;let u=fe(e,a);if(typeof u!=="string"&&typeof u!=="number"&&typeof u!=="boolean")continue;let d=await sn(a,u);if(JSON.stringify(d)===JSON.stringify(s.lastManagedValue))delete o[a]}return o}function Od(e,t,n=!1){let r=sv(e,t),o=typeof n==="boolean"?{}:n,i={browserUse:o.browserUse??Qt.browser_use,computerUse:typeof n==="boolean"?n:o.computerUse??Qt.computer_use,...o.windowsGitBashExecutable===void 0?{}:{windowsGitBashExecutable:o.windowsGitBashExecutable}},a=rs(e,t,i),s={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,"agents.max_concurrent_threads_per_session":21,web_search:"live","sandbox_workspace_write.network_access":!0,model_verbosity:"low",developer_instructions:cv({...typeof n==="boolean"?{computerUse:n}:n,rootModel:r.model}),suppress_unstable_features_warning:!0,"features.multi_agent":!0,"features.default_mode_request_user_input":!0,"features.multi_agent_v2":!1,"features.agent_message_board":!1,"features.context_management.experimental_mode":!0};for(let c of Uo)s[`agents."${c}".config_file`]=hd(c,a);return s}async function FF(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await Ga(e,n,a)).status==="drifted")o.push(a);continue}let c=fe(t,a),l=fe(e,a),u=cn(c===void 0?null:c),d=cn(l===void 0?null:l);if(Mn(u)!==Mn(d))o.push(a)}if(o.length>0)throw new T("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function Fv(e,t,n){let r=["agents.explorer.config_file","agents.librarian.config_file","agents.worker.config_file","agents.reviewer.config_file"],o=Object.fromEntries(r.flatMap((c)=>{let l=t.managed[c];return l===void 0?[]:[[c,l]]})),i=e,a=t;if(Object.keys(o).length>0){let c=await Tr(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new T("state_corrupt","Legacy HolyCodex agent registrations changed and cannot be migrated safely.",void 0,{keys:[...new Set([...c.preservedKeys,...c.unresolvedKeys])].join(",")});i=c.document,a={...t,managed:Object.fromEntries(Object.entries(t.managed).filter(([l])=>!r.includes(l)))}}if(!n)return{document:i,state:a};let s=n.managed_artifacts.map((c)=>c.path);for(let c of["explorer","librarian","worker","reviewer"]){if(!s.some((f)=>f.startsWith(`agents/${c[0]?.toUpperCase()}${c.slice(1)}.`)||f===`holycodex/agents/${c}.toml`))continue;let u=`agents.${c}.config_file`,d=fe(i,u);if(typeof d!=="string")continue;let p=d.replaceAll("\\","/").replace(/^\.\//u,"");if(p===`agents/${c}.toml`||p===`holycodex/agents/${c}.toml`)i=Rr(i,u)}return{document:i,state:a}}async function Lv(e,t){let n=t.managed[Mv];if(n===void 0)return{document:e,state:t};let r=await Tr(e,{...t,managed:{[Mv]:n}},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>i!==Mv));return{document:r.document,state:{...t,managed:o}}}async function Uh(e,t){let n=Object.fromEntries(Object.entries(t.managed).filter(([i])=>Di.includes(i)));if(Object.keys(n).length===0)return{document:e,state:t};let r=await Tr(e,{...t,managed:n},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>!(i in n)));return{document:r.document,state:{...t,managed:o}}}function bK(e,t){if(fe(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new T("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function _K(e,t){let n=await e.list();return t.map((r)=>{let o=Mr(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function er(e,t){if(Ie(ji,t)===void 0)throw new T("state_corrupt","The HolyCodex transaction state is invalid.");await ts(e,cn(t))}async function jh(e){await Hh(e,{force:!1}).catch((t)=>{if(!Xe(t,"ENOENT"))throw t})}async function wK(e,t,n,r){let o=await je(e);if(o===void 0)return;let i=un(o,e),a={},s=0;for(let[p,f]of Object.entries(t.managed_config.managed)){let m=p,y=fe(n,m),g=y===void 0?void 0:await sn(m,y);if(JSON.stringify(g??null)===JSON.stringify(f.lastManagedValue))continue;if(y!==void 0&&g?.kind==="digest"){let x=fe(i,m);if(x!==void 0&&JSON.stringify(await sn(m,x))===JSON.stringify(f.lastManagedValue))i=Li(i,m,y),s+=1;continue}a[p]={...f,originalValue:g??{kind:"absent"}}}let c=await Tr(i,{...t.managed_config,managed:a},{schema:Tn,installId:t.install_id});i=c.document;let l=t.plugin_config===void 0?void 0:await jc(i,t.plugin_config,{allowBeforeState:!0});if(l!==void 0)i=l.document;let u=t.provider_config===void 0?void 0:await Hc(i,t.provider_config,r,{allowBeforeState:!0});if(u!==void 0)i=u.document;if(t.plugin_config!==void 0)for(let[p,f,m]of[["preference","plugins",Wi],["marketplace","marketplaces",zc]]){let y=await PF(i,n,f,m,t.plugin_config.before[p],t.plugin_config.after[p]);if(i=y.document,y.restored)s+=1}if(t.provider_config!==void 0)for(let p of t.provider_config){if(!r.has(p.plugin_id))continue;let f=await PF(i,n,"plugins",p.plugin_id,p.before,p.after);if(i=f.document,f.restored)s+=1}if(!(c.restoredKeys.length>0||l!==void 0&&(l.restored.length>0||l.removed.length>0)||u!==void 0&&(u.restored.length>0||u.removed.length>0)||s>0))return;await qn(e,Cd(i))}async function vK(e,t,n,r,o,i=[],a=Od(t,n,r)){let s=await je(e.configFile),c=un(s,e.configFile),l=a;for(let[m,y]of Object.entries(l)){let g=fe(c,m);if(m==="developer_instructions"){if(typeof g!=="string"||g!==y||await RK(m,g)!==o.managed[m]?.lastManagedValue.value)throw new T("install_failed","The effective Root instructions did not converge.")}else if(g!==y)throw new T("install_failed",`The effective Codex setting ${m} did not converge.`)}let u={browserUse:r.browserUse??Qt.browser_use,computerUse:r.computerUse,...r.windowsGitBashExecutable===void 0?{}:{windowsGitBashExecutable:r.windowsGitBashExecutable}},d=rs(t,n,u),p=Vo(t,n);for(let m of p){let y=`agents."${m.name}".config_file`,g=fe(c,y);if(typeof g!=="string")throw new T("install_failed",`The ${m.name} registration is missing.`);let x=hd(m.name,d),P=Ja(e.configFile,x),_=P.replaceAll("\\","/");if(Ja(e.configFile,g).replaceAll("\\","/")!==_)throw new T("install_failed",`The ${m.name} registration is stale (expected ${x}; received ${g}).`);let q=await je(P);if(q===void 0)throw new T("install_failed",`The ${m.name} role file is missing.`);if(i.some((C)=>C.replaceAll("\\","/")===_))throw new T("install_failed",`The ${m.name} role file was kept after a conflict and cannot be activated.`);let O=un(q,P);if(O.name!==m.name||typeof O.description!=="string"||typeof O.model!=="string"||typeof O.model_reasoning_effort!=="string"||typeof O.service_tier!=="string"||typeof O.developer_instructions!=="string"||!Ch(m,O)||O.approval_policy!=="never"||O.web_search!==(m.permissions.network?"live":"disabled")||O.tool_output_token_limit!==void 0||fe(O,"agents.enabled")!==!1||fe(O,"features.multi_agent")!==!1||fe(O,"features.multi_agent_v2")!==!1||fe(O,"features.agent_message_board")!==!1||fe(O,"features.context_management.experimental_mode")!==!0||Object.keys(O.features??{}).some((C)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(C)))throw new T("install_failed",`The ${m.name} role file is malformed.`)}let f=await je(`${e.codexHome}/agents/root.toml`);if(f!==void 0&&Dc(f))throw new T("install_failed","A stale HolyCodex Root role remains installed.")}async function RK(e,t){return await Fn("holycodex-managed-config-value",[Nn({keyPath:e,value:t})])}function Dv(e,t){let n={};for(let r of["browser_use","computer_use","sites"]){let o=t?.[r]??e?.[r];if(o!==void 0)n[r]=o}return n}function TK(e){return["browser_use","computer_use","sites"].find((t)=>Do[t].pluginIds.includes(e))}function $v(e){return(e?.official_plugins??[]).filter((t)=>{if(t===ln)return!1;if(kd(t))return!1;let n=TK(t);return n===void 0||e?.optional_selections[n]!==!0})}async function CK(e){await Mc(iK(e));let t;try{t=await oK(e,"wx",384)}catch(n){if(Xe(n,"EEXIST"))return;throw n}try{let n=await t.stat();return await t.sync(),{dev:n.dev,ino:n.ino}}finally{await t.close()}}async function OK(e,t){if(t===void 0)return!1;try{let n=await rK(e);return n.isFile()&&!n.isSymbolicLink()&&n.dev===t.dev&&n.ino===t.ino}catch(n){if(Xe(n,"ENOENT"))return!1;throw n}}function kd(e){let t=e.slice(0,e.lastIndexOf("@"));return cK.has(t)}async function EK(e,t,n=new Set,r){for(let o of t){let i=n.has(o),a;try{a=Mr(await e.list(),o)}catch(l){throw zo("list",l,o)}if(a?.installed&&!a.enabled)throw new Ko("uncertain",`${o} is disabled`);let s=i||!(a?.installed&&a.enabled);if(s)try{await e.add(o)}catch(l){try{let u=Mr(await e.list(),o);if(i||!LF(a,u))await r?.(o,"uncertain")}catch{await r?.(o,"uncertain")}throw zo("add",l,o)}let c;try{c=Mr(await e.list(),o)}catch(l){if(s)await r?.(o,"uncertain");throw zo("list",l,o)}if(!c?.installed){if(s&&(i||!LF(a,c)))await r?.(o,"uncertain");throw new Ko("missing",`${o} is not installed after add`)}if(s&&c.enabled)await r?.(o,i?"uncertain":"new");if(!c.enabled){if(s)await r?.(o,i?"uncertain":"new");throw new Ko("uncertain",`${o} is disabled after add`)}}}async function kK(e,t,n){for(let r of t){let o;try{o=Mr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),zo("list",a,r)}if(!(o?.installed??!1)){await n?.(r,"absent");continue}try{await e.remove(r)}catch(a){try{if(!(Mr(await e.list(),r)?.installed??!1))await n?.(r,"removed");else await n?.(r,"uncertain")}catch{await n?.(r,"uncertain")}throw zo("remove",a,r)}let i;try{i=Mr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),zo("list",a,r)}if(i?.installed)throw await n?.(r,"uncertain"),new Ko("uncertain",`${r} is still installed after remove`);await n?.(r,"removed")}}async function IK(e,t,n){if(n!=="installed"&&n!=="disabled")throw new Ko("uncertain",`${t} has no proven prior installed state`);let r=n==="installed",o;try{o=Mr(await e.list(),t)}catch(a){throw zo("list",a,t)}if(o?.installed&&o.enabled===r)return;try{await e.add(t)}catch(a){throw zo("add",a,t)}let i;try{i=Mr(await e.list(),t)}catch(a){throw zo("list",a,t)}if(!i?.installed)throw new Ko("missing",`${t} is not installed after restore`);if(i.enabled!==r)throw new Ko("uncertain",`${t} did not regain its prior ${r?"enabled":"disabled"} state`)}function LF(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function zo(e,t,n){if(t instanceof ro)return t;return new ro(e==="list"?"list_failed":e==="remove"?"remove_failed":"add_failed",e==="list"?`Codex could not read the status of ${n}.`:e==="remove"?`Codex could not remove ${n}.`:`Codex could not add ${n}.`,t,{plugin_id:n})}function Mr(e,t){let n=no(e,t);if(n!==void 0)return n.entry;let r=Sr(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function PK(e,t){let n=e??t??"default";if(!eo(n).ok)throw new T("install_failed","Unknown profile.");return n}function AK(e,t){let n=e??t??"standard";if(Ie(qo,n)===void 0)throw new T("install_failed","The tier is not supported.");return n}function MK(e,t){let n=t?VF(t):Qt,r=p_(e,n);return{browser_use:r.browser_use,computer_use:r.computer_use,sites:r.sites,coding:!0}}function Vh(e,t=new Map){return Object.fromEntries(["browser_use","computer_use","frontend","security","sites"].map((r)=>{let o=r==="frontend"||r==="security"?!0:e[r],i=r==="frontend"||r==="security"?void 0:t.get(r),a={selected:o,status:o?i??"healthy":"disabled",plugin_ids:[...Do[r].pluginIds]};return[r,a]}))}async function zh(e){let{profile:t,plan:n,...r}=e,o=n===void 0?{...r,profile:t}:{...r,plan:n};return await Fn("install-record",[Nn(cn(o))])}async function Bc(e){return await WF(e)}async function WF(e){return await zh({owner:e.owner,install_id:e.install_id,version:e.version,...e.profile===void 0?{}:{profile:e.profile},...e.plan===void 0?{}:{plan:e.plan},tier:e.tier,optional_selections:e.optional_selections,explicit_optional_selections:e.explicit_optional_selections,official_plugins:e.official_plugins??[],capability_state:e.capability_state??null,managed_artifacts:e.managed_artifacts,...e.managed_config===void 0?{}:{managed_config:e.managed_config},...e.plugin_config===void 0?{}:{plugin_config:e.plugin_config},...e.provider_config===void 0?{}:{provider_config:e.provider_config},...e.plugin_snapshot===void 0?{}:{plugin_snapshot:e.plugin_snapshot},...e.owned_plugins===void 0?{}:{owned_plugins:e.owned_plugins},...e.tooling===void 0?{}:{tooling:e.tooling}})===e.digest}function Id(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function NK(e,t,n,r){let o=[{name:"git-bash",status:e.status,...e.status==="healthy"?{detail:e.path}:e.status==="missing"?{detail:"Git is required for Bash; install with: winget install Git.Git"}:{}},{name:"context7",status:t?"ready":"unavailable"}];for(let i of r){let a=Mr(n,i),s=a===void 0?"missing":a.installed?a.enabled?"installed":"disabled":"available";o.push({name:`official-plugin:${i}`,status:s,...typeof a?.version==="string"?{detail:a.version}:{}})}return o}function Ar(e){let t=e.category??(e.key===void 0?"role-asset":"config-key"),n=e.target??e.key??e.path,r=e.identity??`${t}:${e.path}:${e.key??""}:${e.action}`,o=e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"],i=e.action==="remove"&&e.validDecisions?.includes("replace")===!0&&e.validDecisions.includes("remove")===!1?o:e.validDecisions??o,a=e.defaultDecision!==void 0&&i.includes(e.defaultDecision)?e.defaultDecision:i.includes(e.action)?e.action:i[0]??e.action;return{...e,identity:r,category:t,target:n,defaultDecision:a,validDecisions:i,explanation:e.explanation??(e.action==="remove"?`HolyCodex can remove the managed ${n} after reviewing this change.`:`HolyCodex can replace the managed ${n} after reviewing this change.`)}}async function Wh(e,t,n=!1){let r=t.map(Ar),o=new Map;if(r.length===0)return{accepted:[],decisions:o};if(e.resolveConflicts!==void 0){let a;try{a=await e.resolveConflicts(r)}catch(s){if(!(s instanceof T)||s.code!=="confirmation_required")throw s;let c=r.map((l)=>{let u=l.category==="invalid-config"&&l.key!==void 0&&l.existing!==void 0?` = ${JSON.stringify(l.existing)}`:"";return`${l.target} at ${l.path}${u}`}).join("; ");throw new T("confirmation_required",`${s.message} Conflicts: ${c}.`,s,{conflicts:c})}for(let s of r){let c=s.identity,l=Ie(K0,a[c]);if(l===void 0||s.validDecisions?.includes(l)===!1){let u=s.validDecisions?.join(", ")??"keep, replace, cancel";throw new T("confirmation_required",`The conflict at ${s.target} requires one of these decisions: ${u}.`,void 0,{identity:c,path:s.path,...s.key===void 0?{}:{key:s.key}})}if(l==="cancel")throw new T("confirmation_required",`Conflict resolution was cancelled for ${s.target} at ${s.path}.`,void 0,{identity:c,path:s.path,...s.key===void 0?{}:{key:s.key}});o.set(c,l)}return{accepted:r.filter((s)=>o.get(s.identity)===(s.action==="remove"?"remove":"replace")),decisions:o}}let i=[];for(let a of r){let s=await e.resolveConflict?.(a);if(s==="accept"){let c=a.action==="remove"?"remove":"replace";if(a.validDecisions?.includes(c)===!1)throw new T("confirmation_required",`The conflict at ${a.target} cannot be ${c}d; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});i.push(a),o.set(a.identity,c);continue}if(s==="decline"&&n){if(a.validDecisions?.includes("keep")===!1)throw new T("confirmation_required",`The conflict at ${a.target} cannot be kept; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});o.set(a.identity,"keep");continue}throw new T("confirmation_required",s==="cancel"?`Conflict resolution was cancelled for ${a.target} at ${a.path}.`:`Conflict resolution is required for ${a.target} at ${a.path}: ${a.explanation}.`,void 0,{path:a.path,...a.key===void 0?{}:{key:a.key},action:a.action,resolution:s??"unavailable"})}return{accepted:i,decisions:o}}function Pr(e,t){try{e.onProgress?.(t)}catch{}}var aK="davidbasilefilho/holycodex",dn="holycodex@holycodex",ln="browser@openai-bundled",sK="0.16.8",DF,Vc="https://github.com/davidbasilefilho/holycodex.git",Wi="holycodex@holycodex",zc="holycodex",cK,Mv,Ko,T;var Ed=b(()=>{Ya();ht();cd();md();Oh();yd();Qa();Za();Nc();Ph();Za();DF=new WeakMap;cK=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]),Mv=Di[0];Ko=class Ko extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};T=class T extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t,n===void 0?void 0:{cause:n});this.name="InstallerError",this.code=e,this.causeValue=n,this.details=r}}});import{createInterface as CJ}from"readline/promises";Ya();ht();ht();ht();var Kw=Object.freeze([{name:"yes",kind:"boolean",usage:"--yes",description:"Confirm installation."},{name:"profile",kind:"value",usage:"--profile <low|default|high>",description:"Select routing (default: default)."},{name:"tier",kind:"value",usage:"--tier <standard|fast|fast-all>",description:"Select service handling (default: standard)."},{name:"sites",kind:"boolean",usage:"--sites / --no-sites",description:"ChatGPT Sites (default: true)."},{name:"browser-use",kind:"boolean",usage:"--browser-use / --no-browser-use",description:"Browser Use (default: true)."},{name:"computer-use",kind:"boolean",usage:"--computer-use / --no-computer-use",description:"Computer Use plugins (default: false)."},{name:"add-plugin",kind:"value",usage:"--add-plugin <id>",description:"Add a Codex plugin; repeatable."},{name:"json",kind:"boolean",usage:"--json",description:"Emit one JSON envelope."}]),V0=new Set(["codex-home","profile","tier","add-plugin"]),eW=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","sites","no-sites","browser-use","no-browser-use"]);class ct extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function yh(e){if(e.length===0)throw new ct("unknown_command","A command is required.");if(e.includes("-h")||e.includes("--help")||e.includes("--help=true"))return{command:"help",positionals:[],options:{}};if(e[0]==="help")return{command:"help",positionals:e.slice(1),options:{}};if(e[0]==="-v"||e[0]==="--version"||e[0]==="--version=true")return yh(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new ct("unknown_command","Unknown command.",{command:t??""});let n=[],r={};for(let o=1;o<e.length;o+=1){let i=e[o];if(i===void 0)continue;if(i==="-"||!i.startsWith("-")){n.push(i);continue}if(!i.startsWith("--")||i==="--")throw new ct("invalid_argument","Short options are not supported.",{option:i});let a=i.slice(2),s=a.indexOf("="),c=s>=0?a.slice(0,s):a,l=s>=0?a.slice(s+1):void 0,u=c.replaceAll("_","-");if(u==="plan")throw new ct("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!V0.has(u)&&!eW.has(u))throw new ct("invalid_argument","Unknown option.",{option:`--${c}`});if(V0.has(u)){let d=l??e[o+1];if(d===void 0||d.length===0||d.startsWith("-"))throw new ct("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(l===void 0)o+=1;if(u==="add-plugin"){let p=r[u];r[u]=Array.isArray(p)?[...p,d]:[d]}else{if(r[u]!==void 0)throw new ct("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=d}continue}if(l!==void 0&&l!=="true"&&l!=="false")throw new ct("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new ct("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return tW(t,n,r),{command:t,positionals:n,options:r}}function tW(e,t,n){let r=rW(e);for(let s of Object.keys(n))if(!r.has(s))throw new ct("invalid_argument",`Option --${s} is not valid for ${e}.`,{option:`--${s}`});let o=e==="version"?{min:0,max:1}:{min:0,max:0};if(t.length<o.min||t.length>o.max)throw new ct("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!eo(i).ok){let s=nW[i];if(s!==void 0)throw new ct("invalid_argument",`Legacy profile ${i} was removed; use --profile ${s}.`,{profile:i,replacement:s});if(i==="go"||i==="Go"||i==="pro-5x"||i==="pro-20x")throw new ct("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new ct("invalid_argument","The profile is not supported.",{profile:i})}let a=n.tier;if(typeof a==="string"&&a!=="standard"&&a!=="fast"&&a!=="fast-all")throw new ct("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["sites","no-sites"],["browser-use","no-browser-use"]])if(n[s]!==void 0&&n[c]!==void 0)throw new ct("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove"].includes(e)&&n.yes===!1)throw new ct("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","sites","no-sites","browser-use","no-browser-use","computer-use","no-computer-use","add-plugin"].includes(s)))throw new ct("invalid_argument",`Installation options are not valid for ${e}.`)}var nW={"plus-low":"low",plus:"default","plus-high":"high"};function rW(e){switch(e){case"install":return new Set([...Kw.map((t)=>t.name),"no-sites","no-browser-use","no-computer-use","codex-home","verbose"]);case"doctor":return new Set(["json","verbose","codex-home"]);case"remove":return new Set(["yes","json","verbose","codex-home"]);case"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var oW=`HolyCodex
44
+ `,Math.max(0,n-1));return{offset:n,line:a,column:n-s}}function RK(e,t){let n,r=!1,o=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(o){if(a===`
45
+ `)o=!1;continue}if(n!==void 0){if(n==='"'&&r)r=!1;else if(n==='"'&&a==="\\")r=!0;else if(a===n)n=void 0;continue}if(a==="#"){o=!0;continue}if(e.startsWith(t,i))return i;if(a==='"'||a==="'")n=a}return}async function TK(e,t,n){let r=typeof t.details.key==="string"?t.details.key:void 0,o=typeof t.details.offset==="number"?String(t.details.offset):void 0,i=ar({identity:"invalid-config:"+n+":"+(o??r??"unsupported"),category:"invalid-config",target:r===void 0?n+" syntax":n+" value "+r,existing:t.details,desired:"Repair the TOML value before installing HolyCodex.",explanation:t.message,path:n,...r===void 0?{}:{key:r},action:"replace",defaultDecision:"cancel",validDecisions:["cancel"]});try{await qd(e,[i],!0)}catch{}}function uo(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):Rv(e)).trimEnd()}
46
+ `}catch(t){throw new _("install_failed","The merged Codex configuration is not writable.",t)}}async function eg(e){return{preference:await vs(e,"plugins",ws),marketplace:await vs(e,"marketplaces",_s)}}async function tg(e,t){return await Promise.all(t.map(async(n)=>{let r=await vs(e,"plugins",n),o={presence:r.presence,digest:r.digest,...r.safe_value?.kind==="boolean"?{safe_value:r.safe_value}:{}};return{plugin_id:n,before:o,after:o}}))}async function Gc(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",ws],["marketplace","marketplaces",_s]]){let u=t.before[s],d=t.after[s],p=await vs(e,c,l);if(n.allowBeforeState===!0&&p.digest===u.digest)continue;if(p.digest!==d.digest){a.push(s);continue}if(u.presence==="absent"){if(p.presence==="present")r=Jv(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=po(r,c,l,OK(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function Yc(e,t,n,r={}){let o=e,i=[],a=[],s=[];for(let c of t){if(!n.has(c.plugin_id))continue;let{before:l,after:u}=c,d=await vs(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&d.digest===l.digest)continue;if(d.digest!==u.digest){s.push(c.plugin_id);continue}if(l.presence==="absent"){if(d.presence==="present")o=Jv(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=po(o,"plugins",c.plugin_id,{enabled:l.safe_value.value}),i.push(c.plugin_id)}return{document:o,restored:i,removed:a,preserved:s}}async function UF(e,t,n,r,o,i){if(o.presence!=="present"||o.safe_value!==void 0)return{document:e,restored:!1};let a=await vs(e,n,r);if(a.digest===o.digest||a.digest!==i.digest)return{document:e,restored:!1};let s=Ud(t,n,r);if(s===void 0)return{document:e,restored:!1};return{document:po(e,n,r,s),restored:!0}}async function vs(e,t,n){let r=Ud(e,t,n),o=await qn("holycodex-plugin-config",[Dn(sn({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=CK(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function Ud(e,t,n){let r=e[t];if(!ri(r)||!Object.hasOwn(r,n))return;return r[n]}function CK(e,t){if(!ri(t))return;let n=Object.keys(t);if(e==="plugins"){if(n.length!==1||n[0]!=="enabled"||typeof t.enabled!=="boolean")return;return{kind:"boolean",value:t.enabled}}if(n.length!==2||!n.includes("source_type")||!n.includes("source")||t.source_type!=="git"||t.source!==ei)return;return{kind:"marketplace",source_type:"git",source:ei}}function OK(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function po(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!ri(i))throw new _("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function Jv(e,t,n){let r=e[t];if(!ri(r)||!Object.prototype.hasOwnProperty.call(r,n))return e;let o={...e},i={...r};if(delete i[n],Object.keys(i).length===0)delete o[t];else o[t]=i;return o}function ri(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function kK(e,t,n){let r=[{parent:"plugins",key:ws,expected:t.preference},{parent:"marketplaces",key:_s,expected:t.marketplace},...n.map(({plugin_id:o,before:i})=>({parent:"plugins",key:o,expected:i}))];for(let{parent:o,key:i,expected:a}of r)if((await vs(e,o,i)).digest!==a.digest)throw new _("confirmation_required","Plugin configuration changed after preflight; review the latest configuration and retry.",void 0,{key:`${o}.${i}`})}async function $F(e,t,n,r,o,i,a,s,c,l){let u=e,d=n,p=r;for(let m of a){let f=m.identity;if(f===void 0)throw new _("state_corrupt","A plugin configuration conflict has no identity.");let x=c.get(f);if(x!=="keep"&&x!=="replace")throw new _("confirmation_required",`Plugin configuration conflict resolution is incomplete for ${m.key??f}.`);let g=m.key==='plugins."holycodex@holycodex"'?"preference":"marketplace",y=o[g];if(x==="keep"){let v=Ud(t,"plugins",ws);if(g==="preference"&&ri(v)&&v.enabled===!1)throw new _("confirmation_required","Keeping disabled HolyCodex config would disable the selected plugin.");u=jF(u,t,m.key),d={...d,[g]:y};continue}u=po(u,g==="preference"?"plugins":"marketplaces",g==="preference"?ws:_s,g==="preference"?{enabled:!0}:{source_type:"git",source:ei})}for(let m of s){let{identity:f,key:x}=m;if(f===void 0||x===void 0)throw new _("state_corrupt","A provider configuration conflict has no identity.");let g=x.startsWith('plugins."')&&x.endsWith('"')?x.slice(9,-1):void 0;if(g===void 0)throw new _("state_corrupt",`The provider configuration conflict key ${x} is invalid.`);let y=c.get(f);if(y!=="keep"&&y!=="replace")throw new _("confirmation_required",`Provider configuration conflict resolution is incomplete for ${x}.`);let v=i.find((C)=>C.plugin_id===g);if(v===void 0)throw new _("state_corrupt",`The provider configuration entry ${g} is missing.`);if(y==="keep"){let C=Ud(t,"plugins",g);if(l.includes(g)&&ri(C)&&C.enabled===!1)throw new _("confirmation_required",`Keeping disabled config would disable selected plugin ${g}.`);u=jF(u,t,x),p=p.map((M)=>M.plugin_id===g?{plugin_id:g,before:v.before,after:v.before}:M);continue}u=po(u,"plugins",g,{enabled:!0})}return{document:u,pluginConfigBefore:d,providerConfigBefore:p}}function jF(e,t,n){if(n===void 0)throw new _("state_corrupt","A configuration conflict has no key.");if(n.startsWith('plugins."')&&n.endsWith('"')){let o=n.slice(9,-1),i=Ud(t,"plugins",o);return i===void 0?Jv(e,"plugins",o):po(e,"plugins",o,i)}let r=fe(t,n);return r===void 0?er(e,n):so(e,n,r)}async function EK(e,t,n,r){let o={...n};if(r===void 0)return o;for(let i of Object.keys(n)){let a=i,s=t.managed[a],c=r[a];if(s===void 0||c===void 0)continue;let l=await _n(a,c);if(JSON.stringify(l)===JSON.stringify(s.lastManagedValue))continue;let u=fe(e,a);if(typeof u!=="string"&&typeof u!=="number"&&typeof u!=="boolean")continue;let d=await _n(a,u);if(JSON.stringify(d)===JSON.stringify(s.lastManagedValue))delete o[a]}return o}function Md(e,t,n=!1){let r=gv(e,t),o=typeof n==="boolean"?{}:n,i={browserUse:o.browserUse??en.browser_use,computerUse:typeof n==="boolean"?n:o.computerUse??en.computer_use},a=ms(e,t,i),s={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,"agents.max_concurrent_threads_per_session":21,web_search:"live","sandbox_workspace_write.network_access":!0,model_verbosity:"low",developer_instructions:yv({...typeof n==="boolean"?{computerUse:n}:n,rootModel:r.model}),suppress_unstable_features_warning:!0,"features.multi_agent":!0,"features.default_mode_request_user_input":!0,"features.multi_agent_v2":!1,"features.agent_message_board":!1,"features.context_management.experimental_mode":!0};for(let c of zo)s[`agents."${c}".config_file`]=_d(c,a);return s}async function HF(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await as(e,n,a)).status==="drifted")o.push(a);continue}let c=fe(t,a),l=fe(e,a),u=sn(c===void 0?null:c),d=sn(l===void 0?null:l);if(Ln(u)!==Ln(d))o.push(a)}if(o.length>0)throw new _("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function Bv(e,t,n){let r=["agents.explorer.config_file","agents.librarian.config_file","agents.worker.config_file","agents.reviewer.config_file"],o=Object.fromEntries(r.flatMap((c)=>{let l=t.managed[c];return l===void 0?[]:[[c,l]]})),i=e,a=t;if(Object.keys(o).length>0){let c=await Ir(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new _("state_corrupt","Legacy HolyCodex agent registrations changed and cannot be migrated safely.",void 0,{keys:[...new Set([...c.preservedKeys,...c.unresolvedKeys])].join(",")});i=c.document,a={...t,managed:Object.fromEntries(Object.entries(t.managed).filter(([l])=>!r.includes(l)))}}if(!n)return{document:i,state:a};let s=n.managed_artifacts.map((c)=>c.path);for(let c of["explorer","librarian","worker","reviewer"]){if(!s.some((m)=>m.startsWith(`agents/${c[0]?.toUpperCase()}${c.slice(1)}.`)||m===`holycodex/agents/${c}.toml`))continue;let u=`agents.${c}.config_file`,d=fe(i,u);if(typeof d!=="string")continue;let p=d.replaceAll("\\","/").replace(/^\.\//u,"");if(p===`agents/${c}.toml`||p===`holycodex/agents/${c}.toml`)i=er(i,u)}return{document:i,state:a}}async function Vv(e,t){let n=t.managed[$v];if(n===void 0)return{document:e,state:t};let r=await Ir(e,{...t,managed:{[$v]:n}},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>i!==$v));return{document:r.document,state:{...t,managed:o}}}async function ng(e,t){let n=Object.fromEntries(Object.entries(t.managed).filter(([i])=>Yi.includes(i)));if(Object.keys(n).length===0)return{document:e,state:t};let r=await Ir(e,{...t,managed:n},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>!(i in n)));return{document:r.document,state:{...t,managed:o}}}function IK(e,t){if(fe(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new _("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function PK(e,t){let n=await e.list();return t.map((r)=>{let o=Lr(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function ir(e,t){if(Pe(ea,t)===void 0)throw new _("state_corrupt","The HolyCodex transaction state is invalid.");await ps(e,sn(t))}async function rg(e){await Dd(e,{force:!1}).catch((t)=>{if(!Ke(t,"ENOENT"))throw t})}async function AK(e,t,n,r){let o=await be(e);if(o===void 0)return;let i=Jt(o,e),a={},s=0;for(let[m,f]of Object.entries(t.managed_config.managed)){let x=m,g=fe(n,x),y=g===void 0?void 0:await _n(x,g);if(JSON.stringify(y??null)===JSON.stringify(f.lastManagedValue))continue;if(g!==void 0&&y?.kind==="digest"){let v=fe(i,x);if(v!==void 0&&JSON.stringify(await _n(x,v))===JSON.stringify(f.lastManagedValue))i=so(i,x,g),s+=1;continue}a[m]={...f,originalValue:y??{kind:"absent"}}}let c=await Ir(i,{...t.managed_config,managed:a},{schema:On,installId:t.install_id});i=c.document;let l=t.plugin_config===void 0?void 0:await Gc(i,t.plugin_config,{allowBeforeState:!0});if(l!==void 0)i=l.document;let u=t.provider_config===void 0?void 0:await Yc(i,t.provider_config,r,{allowBeforeState:!0});if(u!==void 0)i=u.document;if(t.plugin_config!==void 0)for(let[m,f,x]of[["preference","plugins",ws],["marketplace","marketplaces",_s]]){let g=await UF(i,n,f,x,t.plugin_config.before[m],t.plugin_config.after[m]);if(i=g.document,g.restored)s+=1}if(t.provider_config!==void 0)for(let m of t.provider_config){if(!r.has(m.plugin_id))continue;let f=await UF(i,n,"plugins",m.plugin_id,m.before,m.after);if(i=f.document,f.restored)s+=1}if(!(c.restoredKeys.length>0||l!==void 0&&(l.restored.length>0||l.removed.length>0)||u!==void 0&&(u.restored.length>0||u.removed.length>0)||s>0))return;await At(e,uo(i));let p=await VF(e);return p.isFile()&&!p.isSymbolicLink()?{dev:p.dev,ino:p.ino}:void 0}async function MK(e,t,n,r,o,i=[],a=Md(t,n,r)){let s=await be(e.configFile),c=Jt(s,e.configFile),l=a;for(let[f,x]of Object.entries(l)){let g=fe(c,f);if(f==="developer_instructions"){if(typeof g!=="string"||g!==x||await NK(f,g)!==o.managed[f]?.lastManagedValue.value)throw new _("install_failed","The effective Root instructions did not converge.")}else if(g!==x)throw new _("install_failed",`The effective Codex setting ${f} did not converge.`)}let u={browserUse:r.browserUse??en.browser_use,computerUse:r.computerUse},d=ms(t,n,u),p=Xo(t,n);for(let f of p){let x=`agents."${f.name}".config_file`,g=fe(c,x);if(typeof g!=="string")throw new _("install_failed",`The ${f.name} registration is missing.`);let y=_d(f.name,d),v=is(e.configFile,y),C=v.replaceAll("\\","/");if(is(e.configFile,g).replaceAll("\\","/")!==C)throw new _("install_failed",`The ${f.name} registration is stale (expected ${y}; received ${g}).`);let N=await be(v);if(N===void 0)throw new _("install_failed",`The ${f.name} role file is missing.`);if(i.some((E)=>E.replaceAll("\\","/")===C))throw new _("install_failed",`The ${f.name} role file was kept after a conflict and cannot be activated.`);let O=Jt(N,v);if(O.name!==f.name||typeof O.description!=="string"||typeof O.model!=="string"||typeof O.model_reasoning_effort!=="string"||typeof O.service_tier!=="string"||typeof O.developer_instructions!=="string"||!jh(f,O)||O.approval_policy!=="never"||O.web_search!==(f.permissions.network?"live":"disabled")||O.tool_output_token_limit!==void 0||fe(O,"agents.enabled")!==!1||fe(O,"features.multi_agent")!==!1||fe(O,"features.multi_agent_v2")!==!1||fe(O,"features.agent_message_board")!==!1||fe(O,"features.context_management.experimental_mode")!==!0||Object.keys(O.features??{}).some((E)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(E)))throw new _("install_failed",`The ${f.name} role file is malformed.`)}let m=await be(`${e.codexHome}/agents/root.toml`);if(m!==void 0&&Vc(m))throw new _("install_failed","A stale HolyCodex Root role remains installed.")}async function NK(e,t){return await qn("holycodex-managed-config-value",[Dn({keyPath:e,value:t})])}function Wv(e,t){let n={};for(let r of["browser_use","computer_use","sites"]){let o=t?.[r]??e?.[r];if(o!==void 0)n[r]=o}return n}function FK(e){return["browser_use","computer_use","sites"].find((t)=>Bo[t].pluginIds.includes(e))}function Kv(e){return(e?.official_plugins??[]).filter((t)=>{if(t===ln)return!1;if(Fd(t))return!1;let n=FK(t);return n===void 0||e?.optional_selections[n]!==!0})}async function LK(e){await $c(hK(e));let t;try{t=await mK(e,"wx",384)}catch(n){if(Ke(n,"EEXIST"))return;throw n}try{let n=await t.stat();return await t.sync(),{dev:n.dev,ino:n.ino}}finally{await t.close()}}async function DK(e,t){if(t===void 0)return!1;try{let n=await VF(e);return n.isFile()&&!n.isSymbolicLink()&&n.dev===t.dev&&n.ino===t.ino}catch(n){if(Ke(n,"ENOENT"))return!1;throw n}}function Fd(e){let t=e.slice(0,e.lastIndexOf("@"));return yK.has(t)}async function qK(e,t,n=new Set,r){for(let o of t){let i=n.has(o),a;try{a=Lr(await e.list(),o)}catch(l){throw ti("list",l,o)}if(a?.installed&&!a.enabled)throw new ni("uncertain",`${o} is disabled`);let s=i||!(a?.installed&&a.enabled);if(s)try{await e.add(o)}catch(l){try{let u=Lr(await e.list(),o);if(i||!BF(a,u))await r?.(o,"uncertain")}catch{await r?.(o,"uncertain")}throw ti("add",l,o)}let c;try{c=Lr(await e.list(),o)}catch(l){if(s)await r?.(o,"uncertain");throw ti("list",l,o)}if(!c?.installed){if(s&&(i||!BF(a,c)))await r?.(o,"uncertain");throw new ni("missing",`${o} is not installed after add`)}if(s&&c.enabled)await r?.(o,i?"uncertain":"new");if(!c.enabled){if(s)await r?.(o,i?"uncertain":"new");throw new ni("uncertain",`${o} is disabled after add`)}}}async function UK(e,t,n){for(let r of t){let o;try{o=Lr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),ti("list",a,r)}if(!(o?.installed??!1)){await n?.(r,"absent");continue}try{await e.remove(r)}catch(a){try{if(!(Lr(await e.list(),r)?.installed??!1))await n?.(r,"removed");else await n?.(r,"uncertain")}catch{await n?.(r,"uncertain")}throw ti("remove",a,r)}let i;try{i=Lr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),ti("list",a,r)}if(i?.installed)throw await n?.(r,"uncertain"),new ni("uncertain",`${r} is still installed after remove`);await n?.(r,"removed")}}async function $K(e,t,n){if(n!=="installed"&&n!=="disabled")throw new ni("uncertain",`${t} has no proven prior installed state`);let r=n==="installed",o;try{o=Lr(await e.list(),t)}catch(a){throw ti("list",a,t)}if(o?.installed&&o.enabled===r)return;try{await e.add(t)}catch(a){throw ti("add",a,t)}let i;try{i=Lr(await e.list(),t)}catch(a){throw ti("list",a,t)}if(!i?.installed)throw new ni("missing",`${t} is not installed after restore`);if(i.enabled!==r)throw new ni("uncertain",`${t} did not regain its prior ${r?"enabled":"disabled"} state`)}function BF(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function ti(e,t,n){if(t instanceof co)return t;return new co(e==="list"?"list_failed":e==="remove"?"remove_failed":"add_failed",e==="list"?`Codex could not read the status of ${n}.`:e==="remove"?`Codex could not remove ${n}.`:`Codex could not add ${n}.`,t,{plugin_id:n})}function Lr(e,t){let n=ao(e,t);if(n!==void 0)return n.entry;let r=Tr(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function jK(e,t){let n=e??t??"default";if(!oo(n).ok)throw new _("install_failed","Unknown profile.");return n}function HK(e,t){let n=e??t??"standard";if(Pe(Vo,n)===void 0)throw new _("install_failed","The tier is not supported.");return n}function BK(e,t){let n=t?XF(t):en,r=vw(e,n);return{browser_use:r.browser_use,computer_use:r.computer_use,sites:r.sites,coding:!0}}function og(e,t=new Map){return Object.fromEntries(["browser_use","computer_use","frontend","security","sites"].map((r)=>{let o=r==="frontend"||r==="security"?!0:e[r],i=r==="frontend"||r==="security"?void 0:t.get(r),a={selected:o,status:o?i??"healthy":"disabled",plugin_ids:[...Bo[r].pluginIds]};return[r,a]}))}async function ig(e){let{profile:t,plan:n,...r}=e,o=Object.fromEntries(Object.entries(n===void 0?{...r,profile:t}:{...r,plan:n}).filter(([,i])=>i!==void 0));return await qn("install-record",[Dn(sn(o))])}async function Zc(e){return await QF(e)}async function QF(e){return await ig({owner:e.owner,install_id:e.install_id,version:e.version,...e.profile===void 0?{}:{profile:e.profile},...e.plan===void 0?{}:{plan:e.plan},tier:e.tier,optional_selections:e.optional_selections,explicit_optional_selections:e.explicit_optional_selections,official_plugins:e.official_plugins??[],capability_state:e.capability_state??null,managed_artifacts:e.managed_artifacts,...e.managed_config===void 0?{}:{managed_config:e.managed_config},...e.plugin_config===void 0?{}:{plugin_config:e.plugin_config},...e.provider_config===void 0?{}:{provider_config:e.provider_config},...e.plugin_snapshot===void 0?{}:{plugin_snapshot:e.plugin_snapshot},...e.owned_plugins===void 0?{}:{owned_plugins:e.owned_plugins},...e.tooling===void 0?{}:{tooling:e.tooling}})===e.digest}function Ld(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function VK(e){if(!(e instanceof Error))return!1;return/(?:^|[\n:])\s*-\s*`([^`]+)`\s+at\s+[^\r\n]*:\s*marketplace root does not contain a supported manifest/iu.exec(e.message)?.[1]==="holycodex"}function WK(e){return ri(e)&&Object.keys(e).length===2&&e.source_type==="git"&&typeof e.source==="string"&&_h(e.source)}function zK(e,t,n){let r=[{name:"context7",status:e?"ready":"unavailable"}];for(let o of n){let i=Lr(t,o),a=i===void 0?"missing":i.installed?i.enabled?"installed":"disabled":"available";r.push({name:`official-plugin:${o}`,status:a,...typeof i?.version==="string"?{detail:i.version}:{}})}return r}function ar(e){let t=e.category??(e.key===void 0?"role-asset":"config-key"),n=e.target??e.key??e.path,r=e.identity??`${t}:${e.path}:${e.key??""}:${e.action}`,o=e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"],i=e.action==="remove"&&e.validDecisions?.includes("replace")===!0&&e.validDecisions.includes("remove")===!1?o:e.validDecisions??o,a=e.defaultDecision!==void 0&&i.includes(e.defaultDecision)?e.defaultDecision:i.includes(e.action)?e.action:i[0]??e.action;return{...e,identity:r,category:t,target:n,defaultDecision:a,validDecisions:i,explanation:e.explanation??(e.action==="remove"?`HolyCodex can remove the managed ${n} after reviewing this change.`:`HolyCodex can replace the managed ${n} after reviewing this change.`)}}async function qd(e,t,n=!1){let r=t.map(ar),o=new Map;if(r.length===0)return{accepted:[],decisions:o};if(e.resolveConflicts!==void 0){let a;try{a=await e.resolveConflicts(r)}catch(s){if(!(s instanceof _)||s.code!=="confirmation_required")throw s;let c=r.map((l)=>{let u=l.category==="invalid-config"&&l.key!==void 0&&l.existing!==void 0?` = ${JSON.stringify(l.existing)}`:"";return`${l.target} at ${l.path}${u}`}).join("; ");throw new _("confirmation_required",`${s.message} Conflicts: ${c}.`,s,{conflicts:c})}for(let s of r){let c=s.identity,l=Pe(Q0,a[c]);if(l===void 0||s.validDecisions?.includes(l)===!1){let u=s.validDecisions?.join(", ")??"keep, replace, cancel";throw new _("confirmation_required",`The conflict at ${s.target} requires one of these decisions: ${u}.`,void 0,{identity:c,path:s.path,...s.key===void 0?{}:{key:s.key}})}if(l==="cancel")throw new _("confirmation_required",`Conflict resolution was cancelled for ${s.target} at ${s.path}.`,void 0,{identity:c,path:s.path,...s.key===void 0?{}:{key:s.key}});o.set(c,l)}return{accepted:r.filter((s)=>o.get(s.identity)===(s.action==="remove"?"remove":"replace")),decisions:o}}let i=[];for(let a of r){let s=await e.resolveConflict?.(a);if(s==="accept"){let c=a.action==="remove"?"remove":"replace";if(a.validDecisions?.includes(c)===!1)throw new _("confirmation_required",`The conflict at ${a.target} cannot be ${c}d; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});i.push(a),o.set(a.identity,c);continue}if(s==="decline"&&n){if(a.validDecisions?.includes("keep")===!1)throw new _("confirmation_required",`The conflict at ${a.target} cannot be kept; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});o.set(a.identity,"keep");continue}throw new _("confirmation_required",s==="cancel"?`Conflict resolution was cancelled for ${a.target} at ${a.path}.`:`Conflict resolution is required for ${a.target} at ${a.path}: ${a.explanation}.`,void 0,{path:a.path,...a.key===void 0?{}:{key:a.key},action:a.action,resolution:s??"unavailable"})}return{accepted:i,decisions:o}}function Fr(e,t){try{e.onProgress?.(t)}catch{}}var qF="davidbasilefilho/holycodex",un="holycodex@holycodex",ln="browser@openai-bundled",gK="0.16.8",WF,ei="https://github.com/davidbasilefilho/holycodex.git",ws="holycodex@holycodex",_s="holycodex",yK,$v,ni,_;var Nd=w(()=>{ss();gt();hd();wd();Hh();Rd();us();cs();jc();Kh();cs();WF=new WeakMap;yK=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]),$v=Yi[0];ni=class ni extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};_=class _ extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t,n===void 0?void 0:{cause:n});this.name="InstallerError",this.code=e,this.causeValue=n,this.details=r}}});import{createInterface as HJ}from"readline/promises";ss();gt();gt();gt();var nv=Object.freeze([{name:"yes",kind:"boolean",usage:"--yes",description:"Confirm installation."},{name:"profile",kind:"value",usage:"--profile <low|default|high>",description:"Select routing (default: default)."},{name:"tier",kind:"value",usage:"--tier <standard|fast|fast-all>",description:"Select service handling (default: standard)."},{name:"sites",kind:"boolean",usage:"--sites / --no-sites",description:"ChatGPT Sites (default: true)."},{name:"browser-use",kind:"boolean",usage:"--browser-use / --no-browser-use",description:"Browser Use (default: true)."},{name:"computer-use",kind:"boolean",usage:"--computer-use / --no-computer-use",description:"Computer Use plugins (default: false)."},{name:"add-plugin",kind:"value",usage:"--add-plugin <id>",description:"Add a Codex plugin; repeatable."},{name:"json",kind:"boolean",usage:"--json",description:"Emit one JSON envelope."}]),Y0=new Set(["codex-home","profile","tier","add-plugin"]),fW=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","sites","no-sites","browser-use","no-browser-use"]);class lt extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Ah(e){if(e.length===0)throw new lt("unknown_command","A command is required.");if(e.includes("-h")||e.includes("--help")||e.includes("--help=true"))return{command:"help",positionals:[],options:{}};if(e[0]==="help")return{command:"help",positionals:e.slice(1),options:{}};if(e[0]==="-v"||e[0]==="--version"||e[0]==="--version=true")return Ah(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new lt("unknown_command","Unknown command.",{command:t??""});let n=[],r={};for(let o=1;o<e.length;o+=1){let i=e[o];if(i===void 0)continue;if(i==="-"||!i.startsWith("-")){n.push(i);continue}if(!i.startsWith("--")||i==="--")throw new lt("invalid_argument","Short options are not supported.",{option:i});let a=i.slice(2),s=a.indexOf("="),c=s>=0?a.slice(0,s):a,l=s>=0?a.slice(s+1):void 0,u=c.replaceAll("_","-");if(u==="plan")throw new lt("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!Y0.has(u)&&!fW.has(u))throw new lt("invalid_argument","Unknown option.",{option:`--${c}`});if(Y0.has(u)){let d=l??e[o+1];if(d===void 0||d.length===0||d.startsWith("-"))throw new lt("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(l===void 0)o+=1;if(u==="add-plugin"){let p=r[u];r[u]=Array.isArray(p)?[...p,d]:[d]}else{if(r[u]!==void 0)throw new lt("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=d}continue}if(l!==void 0&&l!=="true"&&l!=="false")throw new lt("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new lt("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return mW(t,n,r),{command:t,positionals:n,options:r}}function mW(e,t,n){let r=gW(e);for(let s of Object.keys(n))if(!r.has(s))throw new lt("invalid_argument",`Option --${s} is not valid for ${e}.`,{option:`--${s}`});let o=e==="version"?{min:0,max:1}:{min:0,max:0};if(t.length<o.min||t.length>o.max)throw new lt("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!oo(i).ok){let s=hW[i];if(s!==void 0)throw new lt("invalid_argument",`Legacy profile ${i} was removed; use --profile ${s}.`,{profile:i,replacement:s});if(i==="go"||i==="Go"||i==="pro-5x"||i==="pro-20x")throw new lt("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new lt("invalid_argument","The profile is not supported.",{profile:i})}let a=n.tier;if(typeof a==="string"&&a!=="standard"&&a!=="fast"&&a!=="fast-all")throw new lt("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["sites","no-sites"],["browser-use","no-browser-use"]])if(n[s]!==void 0&&n[c]!==void 0)throw new lt("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove"].includes(e)&&n.yes===!1)throw new lt("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","sites","no-sites","browser-use","no-browser-use","computer-use","no-computer-use","add-plugin"].includes(s)))throw new lt("invalid_argument",`Installation options are not valid for ${e}.`)}var hW={"plus-low":"low",plus:"default","plus-high":"high"};function gW(e){switch(e){case"install":return new Set([...nv.map((t)=>t.name),"no-sites","no-browser-use","no-computer-use","codex-home","verbose"]);case"doctor":return new Set(["json","verbose","codex-home"]);case"remove":return new Set(["yes","json","verbose","codex-home"]);case"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var yW=`HolyCodex
47
47
 
48
48
  Usage:
49
49
  holycodex install [options]
@@ -57,15 +57,15 @@ Options:
57
57
  --json Emit one validated JSON envelope.
58
58
 
59
59
  Use --json for scripts. Install and remove use native Codex plugin management.
60
- `,iW=`Install HolyCodex through Codex native plugin management.
60
+ `,xW=`Install HolyCodex through Codex native plugin management.
61
61
 
62
62
  Usage:
63
63
  holycodex install [options]
64
64
 
65
65
  Profiles control routing only:
66
- low Root gpt-6.1-sol/medium; specialists use the low route matrix.
67
- default Root gpt-6.1-sol/high; recommended default routing.
68
- high Root gpt-6-astra/high; specialists use the high route matrix.
66
+ low Root gpt-6.1-sol/low; specialists use the low route matrix.
67
+ default Root gpt-6.1-sol/medium; recommended default routing.
68
+ high Root gpt-6.1-sol/high; specialists use the high route matrix.
69
69
  Default profile: default.
70
70
 
71
71
  Tier is independent service handling (CLI values are lowercase only):
@@ -74,7 +74,7 @@ Tier is independent service handling (CLI values are lowercase only):
74
74
  fast-all Fast service handling for Root and leaves.
75
75
 
76
76
  Options:
77
- ${Kw.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
77
+ ${nv.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
78
78
  `)}
79
79
  --no-sites / --no-browser-use / --no-computer-use
80
80
  Disable the corresponding plugin.
@@ -86,47 +86,48 @@ On an interactive TTY, install opens one wizard and final review with Install,
86
86
  Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
87
87
  Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
88
88
  remains repeatable on the command line.
89
- `,aW=`Remove HolyCodex-owned state through Codex native plugin management.
89
+ `,SW=`Remove HolyCodex-owned state through Codex native plugin management.
90
90
 
91
91
  Usage:
92
92
  holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
93
93
 
94
94
  Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
95
95
  configuration are preserved; changed owned files are preserved for review.
96
- `,sW=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
96
+ `,bW=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
97
97
 
98
98
  Usage:
99
99
  holycodex doctor [--json] [--codex-home <absolute-path>]
100
- `,cW=`Read or update the canonical public package version.
100
+ `,wW=`Read or update the canonical public package version.
101
101
 
102
102
  Usage:
103
103
  holycodex version [<0.x.y[-n]|patch|minor>] [--dry-run] [--json]
104
104
  holycodex --version
105
105
  holycodex -v
106
- `;function id(e){switch(e){case"install":return iW;case"remove":return aW;case"doctor":return sW;case"version":return cW;default:return oW}}function Jw(e,t={}){let n=$i({...t,stream:"stdout"});return id(e).split(`
107
- `).map((r)=>{if(r==="HolyCodex")return ze(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return ze(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>ze(o,"option",n)).replace(/<[^>]+>/gu,(o)=>ze(o,"argument",n))}).join(`
108
- `)}function ad(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function sd(e){let t=e.filter((n)=>!n.startsWith("-"));if(t[0]==="help")return t[1];if(t[0]==="--version"||t[0]==="version"||t[0]==="-v")return"version";return t[0]}function $i(e){let t=e.env??{};if(t.NO_COLOR!==void 0||t.TERM==="dumb")return!1;if(t.FORCE_COLOR!==void 0&&t.FORCE_COLOR!=="0")return!0;if(t.CI!==void 0&&t.CI!=="false")return!1;return(e.stream==="stderr"?e.stderrIsTTY:e.stdoutIsTTY)===!0}var Gw={heading:"#7aa2f7",option:"#7dcfff",argument:"#a9b1d6",focus:"#7dcfff",enabled:"#9ece6a",disabled:"#a9b1d6",success:"#73daca",warning:"#e0af68",error:"#f7768e",hint:"#737aa2"};function ze(e,t,n){if(!n)return e;let r=t==="heading"||t==="focus"?"1;":"",o=Gw[t],i=Number.parseInt(o.slice(1,3),16),a=Number.parseInt(o.slice(3,5),16),s=Number.parseInt(o.slice(5,7),16);return`\x1B[${r}38;2;${i};${a};${s}m${e}\x1B[0m`}ht();Ed();var FK=["low","default","high"],LK=["standard","fast","fast-all"],Ki=["sites","browser_use","computer_use"];function Hv(e){return{...e.stdin===void 0?{}:{stdin:e.stdin},...e.stdout===void 0?{}:{stdout:e.stdout},...e.width===void 0?{}:{width:e.width},...e.height===void 0?{}:{height:e.height}}}function Bv(e){let t=e.stdoutIsTTY??(e.stdout===void 0?process.stdout.isTTY===!0:e.stdout.isTTY===!0);return $i({stdoutIsTTY:t,env:e.env??process.env,stream:"stdout"})}function Pd(...e){return e}function Z(e,t){return Pd({text:e,...t===void 0?{}:{tone:t}})}function DK(e,t,n){let r=e.fg(Gw[n])(t);return n==="heading"||n==="focus"?e.bold(r):r}function Jh(e,t,n){let r=[];return t.forEach((o,i)=>{for(let a of o){if(a.text.length===0)continue;if(!n||a.tone===void 0)r.push(...e.stringToStyledText(a.text).chunks);else r.push(DK(e,a.text,a.tone))}if(i<t.length-1)r.push(...e.stringToStyledText(`
106
+ `;function pd(e){switch(e){case"install":return xW;case"remove":return SW;case"doctor":return bW;case"version":return wW;default:return yW}}function rv(e,t={}){let n=Xi({...t,stream:"stdout"});return pd(e).split(`
107
+ `).map((r)=>{if(r==="HolyCodex")return vn(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return vn(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>vn(o,"option",n)).replace(/<[^>]+>/gu,(o)=>vn(o,"argument",n))}).join(`
108
+ `)}function fd(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function md(e){let t=e.filter((n)=>!n.startsWith("-"));if(t[0]==="help")return t[1];if(t[0]==="--version"||t[0]==="version"||t[0]==="-v")return"version";return t[0]}function Xi(e){let t=e.env??{};if(t.NO_COLOR!==void 0||t.TERM==="dumb")return!1;if(t.FORCE_COLOR!==void 0&&t.FORCE_COLOR!=="0")return!0;if(t.CI!==void 0&&t.CI!=="false")return!1;return(e.stream==="stderr"?e.stderrIsTTY:e.stdoutIsTTY)===!0}var ov={heading:"#7aa2f7",option:"#7dcfff",argument:"#a9b1d6",focus:"#7dcfff",enabled:"#9ece6a",disabled:"#a9b1d6",success:"#73daca",warning:"#e0af68",error:"#f7768e",hint:"#737aa2"};function vn(e,t,n){if(!n)return e;let r=t==="heading"||t==="focus"?"1;":"",o=ov[t],i=Number.parseInt(o.slice(1,3),16),a=Number.parseInt(o.slice(3,5),16),s=Number.parseInt(o.slice(5,7),16);return`\x1B[${r}38;2;${i};${a};${s}m${e}\x1B[0m`}gt();Nd();var KK=["low","default","high"],JK=["standard","fast","fast-all"],oa=["sites","browser_use","computer_use"];function Gv(e){return{...e.stdin===void 0?{}:{stdin:e.stdin},...e.stdout===void 0?{}:{stdout:e.stdout},...e.width===void 0?{}:{width:e.width},...e.height===void 0?{}:{height:e.height}}}function Yv(e){let t=e.stdoutIsTTY??(e.stdout===void 0?process.stdout.isTTY===!0:e.stdout.isTTY===!0);return Xi({stdoutIsTTY:t,env:e.env??process.env,stream:"stdout"})}function Rs(...e){return e}function ae(e,t){return Rs({text:e,...t===void 0?{}:{tone:t}})}function GK(e,t,n){let r=e.fg(ov[n])(t);return n==="heading"||n==="focus"?e.bold(r):r}function ag(e,t,n){let r=[];return t.forEach((o,i)=>{for(let a of o){if(a.text.length===0)continue;if(!n||a.tone===void 0)r.push(...e.stringToStyledText(a.text).chunks);else r.push(GK(e,a.text,a.tone))}if(i<t.length-1)r.push(...e.stringToStyledText(`
109
109
  `).chunks)}),r.push(...e.stringToStyledText(`
110
- `).chunks),new e.StyledText(r)}async function Gh(e={},t={}){let n=pn(e),r=await import("@opentui/core"),o=Kv(n),i=await r.createCliRenderer({...Hv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=Bv(t),s=new r.TextRenderable(i,{content:YF(r,o,0,a)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=0,f=!1,m=(P)=>{if(f)return;f=!0,i.keyInput.off("keypress",x),i.destroy(),c(P)},y=(P)=>{if(f)return;f=!0,i.keyInput.off("keypress",x),i.destroy(),l(P)},g=()=>{s.content=d?JK(r,o,p,a):YF(r,o,u,a),i.requestRender()},x=(P)=>{try{let _=P.name.toLowerCase();if(P.ctrl===!0&&_==="c"){m({action:"cancel"});return}if(d){if(_==="escape"){d=!1,g();return}if(_==="up"||_==="k")p=(p+2)%3;else if(_==="down"||_==="j")p=(p+1)%3;else if(_==="return"||_==="enter"||_==="linefeed"){if(p===0)m({action:"install",request:sL(o)});else if(p===1)d=!1,u=0;else m({action:"cancel"});return}g();return}let I=aL(o,u,P);if(u=I.cursor,I.action==="cancel"){m({action:"cancel"});return}if(I.action==="review")d=!0,p=0;g()}catch(_){y(_)}};i.keyInput.on("keypress",x);try{i.start()}catch(P){y(P)}})}function Vv(e,t={}){let n={};for(let r of e){let o=r.identity??`${r.path}:${r.key??""}:${r.action}`,i=Jo(r),a=t[o]??r.defaultDecision??"keep";n[o]=i.includes(a)?a:i.find((s)=>s!=="cancel")??"cancel"}return{conflicts:e,decisions:n}}function eL(e,t,n){let r=n.name,o=r.toLowerCase(),i=n.shift===!0||r.length===1&&r!==r.toLowerCase();if(o==="escape")return{cursor:t,action:"back"};if(n.ctrl===!0&&o==="c")return{cursor:t,action:"cancel"};if(o==="up"||o==="k"&&!i)return{cursor:Math.max(0,t-1),action:"render"};if(o==="down"||o==="j")return{cursor:Math.min(Math.max(0,e.conflicts.length-1),t+1),action:"render"};if(o==="return"||o==="enter"||o==="linefeed")return{cursor:t,action:"continue"};if(o==="a")return jv(e,"replace"),{cursor:t,action:"render"};if(o==="r")return jv(e,"remove"),{cursor:t,action:"render"};if((o==="k"||r==="K")&&n.ctrl!==!0){if(o==="k"&&!i)return{cursor:Math.max(0,t-1),action:"render"};return jv(e,"keep"),{cursor:t,action:"render"}}if(o==="space")return HK(e,t),{cursor:t,action:"render"};if(o==="left"||o==="right")BK(e,t,o==="left"?-1:1);return{cursor:t,action:"render"}}function qK(e,t=Vv(e).decisions,n=0,r={}){let o=$i({...r,stream:"stdout"}),i={conflicts:e,decisions:{...t}},a=[ze("HolyCodex \xB7 resolve conflicts","heading",o),ze(rL(e),"hint",o),ze(oL(e),"hint",o),ze(iL(e),"hint",o),ze("Enter continue Esc back Ctrl-C cancel","hint",o),ze(`Choice ${e.length===0?0:n+1} of ${e.length}`,"focus",o),""],s;if(e.forEach((c,l)=>{let u=c.category??"managed";if(u!==s){if(s!==void 0)a.push("");a.push(ze(zv(u),"heading",o)),s=u}let d=c.identity??`${c.path}:${c.key??""}:${c.action}`,p=i.decisions[d]??"keep",f=c.target??c.key??c.path,m=l===n?"\u276F":" ",y=p==="replace"?"warning":p==="keep"?"disabled":"error";if(a.push(ze(`${m} ${f}`,l===n?"focus":"argument",o)),a.push(` ${ze(`choice: ${p}`,y,o)}`),a.push(` existing: ${Kh(c.existing)}`),c.action==="remove")a.push(` planned: ${uL(c)}`);else a.push(` desired: ${Kh(c.desired)}`);if(a.push(` ${ze(lL(c,p),"hint",o)}`),a.push(` choices: ${nL(c)}`),c.explanation!==void 0)a.push(` ${ze(c.explanation,"hint",o)}`)}),e.length===0)a.push(ze("No conflicts require a decision.","success",o));return`${a.join(`
110
+ `).chunks),new e.StyledText(r)}async function sg(e={},t={}){let n=dn(e),r=await import("@opentui/core"),o=eR(n),i=await r.createCliRenderer({...Gv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=Yv(t),s=new r.TextRenderable(i,{content:sL(r,o,0,a)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=0,m=!1,f=(v)=>{if(m)return;m=!0,i.keyInput.off("keypress",y),i.destroy(),c(v)},x=(v)=>{if(m)return;m=!0,i.keyInput.off("keypress",y),i.destroy(),l(v)},g=()=>{s.content=d?lJ(r,o,p,a):sL(r,o,u,a),i.requestRender()},y=(v)=>{try{let C=v.name.toLowerCase();if(v.ctrl===!0&&C==="c"){f({action:"cancel"});return}if(d){if(C==="escape"){d=!1,g();return}if(C==="up"||C==="k")p=(p+2)%3;else if(C==="down"||C==="j")p=(p+1)%3;else if(C==="return"||C==="enter"||C==="linefeed"){if(p===0)f({action:"install",request:hL(o)});else if(p===1)d=!1,u=0;else f({action:"cancel"});return}g();return}let M=mL(o,u,v);if(u=M.cursor,M.action==="cancel"){f({action:"cancel"});return}if(M.action==="review")d=!0,p=0;g()}catch(C){x(C)}};i.keyInput.on("keypress",y);try{i.start()}catch(v){x(v)}})}function Zv(e,t={}){let n={};for(let r of e){let o=lg(r),i=Qc(r),a=t[o],s=i.includes(a??"cancel")?a:Qv(r,i);n[o]=i.includes(s)?s:i[0]??"cancel"}return{conflicts:e,decisions:n}}function dL(e,t,n){let r=n.name,o=r.toLowerCase(),i=n.shift===!0||r.length===1&&r!==r.toLowerCase();if(o==="escape")return{cursor:t,action:"back"};if(n.ctrl===!0&&o==="c")return{cursor:t,action:"cancel"};if(o==="up"||o==="k"&&!i)return{cursor:Math.max(0,t-1),action:"render"};if(o==="down"||o==="j")return{cursor:Math.min(Math.max(0,e.conflicts.length-1),t+1),action:"render"};if(o==="return"||o==="enter"||o==="linefeed")return{cursor:t,action:e.conflicts.some((a)=>Qc(a).length===0)?"cancel":"continue"};if(o==="a"&&n.ctrl!==!0)return eL(e,"replace"),{cursor:t,action:"render"};if((o==="k"||r==="K")&&n.ctrl!==!0){if(o==="k"&&!i)return{cursor:Math.max(0,t-1),action:"render"};return eL(e,"keep"),{cursor:t,action:"render"}}if(o==="left"||o==="right")eJ(e,t,o==="left"?-1:1);return{cursor:t,action:"render"}}function YK(e,t=Zv(e).decisions,n=0,r={}){let o=Xi({...r,stream:"stdout"}),i=process.stdout.columns??80,a=process.stdout.rows??24;return`${fL(e,t,n,i,a).map((s)=>s.map((c)=>c.tone===void 0?c.text:vn(c.text,c.tone,o)).join("")).join(`
111
111
  `)}
112
- `}async function Yh(e,t={},n={}){let r=await import("@opentui/core"),o=Vv(e,n),i=await r.createCliRenderer({...Hv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=Bv(t),s=new r.TextRenderable(i,{content:XF(r,o.conflicts,o.decisions,0,a)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=(g)=>{if(d)return;d=!0,i.keyInput.off("keypress",y),i.destroy(),c(g)},f=(g)=>{if(d)return;d=!0,i.keyInput.off("keypress",y),i.destroy(),l(g)},m=()=>{s.content=XF(r,o.conflicts,o.decisions,u,a),i.requestRender()},y=(g)=>{try{let x=eL(o,u,g);if(u=x.cursor,x.action==="continue")p({action:"continue",decisions:{...o.decisions}});else if(x.action==="back"||x.action==="cancel")p({action:x.action});else m()}catch(x){f(x)}};i.keyInput.on("keypress",y);try{i.start()}catch(g){f(g)}})}function $K(e){let t=0,n=0;for(let r of e.conflicts)if(r.decision==="keep")t+=1;else if(r.decision==="replace")n+=1;return{keep:t,replace:n}}function UK(e,t){let n=Wv(e.review),r=t.name.toLowerCase();if(r==="escape")return{selected:e.selected,action:"back"};if(t.ctrl===!0&&r==="c")return{selected:e.selected,action:"cancel"};if(r==="up"||r==="k")return{selected:(e.selected+n.length-1)%n.length,action:"render"};if(r==="down"||r==="j")return{selected:(e.selected+1)%n.length,action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return{selected:e.selected,action:"choose"};return{selected:e.selected,action:"render"}}async function tL(e,t={}){let n=await import("@opentui/core"),r={review:e,selected:0},o=await n.createCliRenderer({...Hv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),i=Bv(t),a=new n.TextRenderable(o,{content:QF(n,e,r.selected,i)});return o.root.add(a),await new Promise((s,c)=>{let l=r.selected,u=!1,d=(y)=>{if(u)return;u=!0,o.keyInput.off("keypress",m),o.destroy(),s(y)},p=(y)=>{if(u)return;u=!0,o.keyInput.off("keypress",m),o.destroy(),c(y)},f=()=>{a.content=QF(n,e,l,i),o.requestRender()},m=(y)=>{try{let g=UK({review:e,selected:l},y);if(l=g.selected,g.action==="cancel")d({action:"cancel"});else if(g.action==="back")d({action:"change"});else if(g.action==="choose"){let x=Wv(e)[l];d({action:x})}else f()}catch(g){p(g)}};o.keyInput.on("keypress",m);try{o.start()}catch(y){p(y)}})}function Wv(e){return e.conflicts.length>0?["apply","change","resolve","cancel"]:["apply","change","cancel"]}function jK(e,t){switch(e){case"apply":return t==="upgrade"?"Upgrade":"Install";case"change":return"Change options";case"resolve":return"Resolve conflicts";case"cancel":return"Cancel"}}function jv(e,t){for(let n of e.conflicts){if(!Jo(n).includes(t))continue;e.decisions[n.identity??`${n.path}:${n.key??""}:${n.action}`]=t}}function HK(e,t){let n=e.conflicts[t];if(n===void 0)return;let r=n.identity??`${n.path}:${n.key??""}:${n.action}`,o=Jo(n),i=e.decisions[r]??"keep",a=n.action==="remove"?"remove":"replace",s=i===a?"keep":a;if(o.includes(s))e.decisions[r]=s}function BK(e,t,n){let r=e.conflicts[t];if(r===void 0)return;let o=r.identity??`${r.path}:${r.key??""}:${r.action}`,i=Jo(r);if(i.length===0)return;let a=e.decisions[o]??i[0],s=i.indexOf(a),c=s<0?0:s;e.decisions[o]=i[(c+n+i.length)%i.length]??i[0]}function nL(e){return Jo(e).join(" | ")}function Jo(e){return e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"])}function rL(e){if(e.length===0)return"No conflicts require a decision.";let t=new Set(e.flatMap(Jo)),n=e.filter((i)=>Jo(i).includes("remove")),r=n.length===0?void 0:n.every((i)=>i.action==="remove")?"Remove deletes a selected item":n.every((i)=>i.action!=="remove")?"Remove drops the current value before applying the planned value":"Remove deletes a selected item or drops the current value",o=[t.has("keep")?"Keep preserves current state":void 0,t.has("replace")?"Replace applies the planned value":void 0,r,t.has("cancel")?"Cancel stops this operation":void 0].filter((i)=>i!==void 0);return`${e.length} item${e.length===1?"":"s"} need a choice. ${o.join("; ")}.`}function oL(e){let t=new Set(e.flatMap(Jo));if(e.length>0&&e.every((n)=>n.action==="remove")&&t.has("keep")&&t.has("remove"))return"Keep is selected by default. Choose Remove only for edited items you want deleted.";return"Review each available choice before continuing."}function iL(e){let t=new Set(e.flatMap(Jo));return["\u2191/\u2193 or j/k navigate","\u2190/\u2192 choose",...t.has("replace")||t.has("remove")?["Space toggle"]:[],...t.has("replace")?["A replace all"]:[],...t.has("remove")?["R remove all"]:[],...t.has("keep")?["K keep all"]:[]].join(" ")}function zv(e){return e.split(/[-_]/u).map((t)=>t.length===0?t:`${t[0].toUpperCase()}${t.slice(1)}`).join(" ")}function Kh(e){if(e===void 0)return"(unknown)";if(typeof e==="string")return e;try{return JSON.stringify(e)}catch{return"(unavailable)"}}function aL(e,t,n){let r=n.name.toLowerCase(),o=Ki.length+2;if(r==="escape"||n.ctrl===!0&&r==="c")return{cursor:t,action:"cancel"};if(r==="up"||r==="k")return{cursor:Math.max(0,t-1),action:"render"};if(r==="down"||r==="j")return{cursor:Math.min(o,t+1),action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return e.plugins=cL(e.pluginInput),{cursor:t,action:"review"};if(t===o){if(r==="backspace")JF(e,-1);else if(r==="delete")JF(e,1);else if(r==="left")e.pluginCursor=Math.max(0,e.pluginCursor-1);else if(r==="right")e.pluginCursor=Math.min(e.pluginInput.length,e.pluginCursor+1);else if(r==="home")e.pluginCursor=0;else if(r==="end")e.pluginCursor=e.pluginInput.length;else if(r==="space")KF(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!QK(n.name))KF(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)WK(e,t-2);else if(r==="left")zF(e,t,-1);else if(r==="right")zF(e,t,1);return{cursor:t,action:"render"}}function sL(e){let t={profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]};return pn(t)}function VK(e,t="install",n={}){let r=Kv(pn(e));return zK(r,t==="install"?0:t==="change"?1:2,$i({...n,stream:"stdout"}))}function Kv(e){let t={...Qt,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{browser_use:t.browser_use??Qt.browser_use,computer_use:t.computer_use??Qt.computer_use,sites:t.sites??Qt.sites},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function zF(e,t,n){if(t===0)e.profile=GF(FK,e.profile,n);else if(t===1)e.tier=GF(LK,e.tier,n)}function WK(e,t){let n=Ki[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function KF(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function JF(e,t){if(t===-1){if(e.pluginCursor===0)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor-1)}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor-=1;return}if(e.pluginCursor>=e.pluginInput.length)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${e.pluginInput.slice(e.pluginCursor+1)}`}function GF(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function cL(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return pn({officialPlugins:t}),t}function zK(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[ze("HolyCodex \xB7 review","heading",n),ze("Review configuration","heading",n),ze("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",ze("CAPABILITIES","heading",n),...Ki.map((i)=>` ${Zh(i)}: ${ze(Gv(e.optional[i]),e.optional[i]?"enabled":"disabled",n)}`),...Jv(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((i,a)=>ze(`${a===t?"\u203A":" "} ${i}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
112
+ `}async function cg(e,t={},n={}){let r=await import("@opentui/core"),o=Zv(e,n),i=await r.createCliRenderer({...Gv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=Yv(t),s=new r.TextRenderable(i,{content:lL(r,o.conflicts,o.decisions,0,a,t.width??process.stdout.columns??80,t.height??process.stdout.rows??24)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=(g)=>{if(d)return;d=!0,i.keyInput.off("keypress",x),i.destroy(),c(g)},m=(g)=>{if(d)return;d=!0,i.keyInput.off("keypress",x),i.destroy(),l(g)},f=()=>{s.content=lL(r,o.conflicts,o.decisions,u,a,t.width??process.stdout.columns??80,t.height??process.stdout.rows??24),i.requestRender()},x=(g)=>{try{let y=dL(o,u,g);if(u=y.cursor,y.action==="continue")p({action:"continue",decisions:{...o.decisions}});else if(y.action==="back"||y.action==="cancel")p({action:y.action});else f()}catch(y){m(y)}};i.keyInput.on("keypress",x);try{i.start()}catch(g){m(g)}})}function ZK(e){let t=0,n=0;for(let r of e.conflicts)if(r.decision==="keep")t+=1;else if(r.decision==="replace")n+=1;return{keep:t,replace:n}}function XK(e,t){let n=Xv(e.review),r=t.name.toLowerCase();if(r==="escape")return{selected:e.selected,action:"back"};if(t.ctrl===!0&&r==="c")return{selected:e.selected,action:"cancel"};if(r==="up"||r==="k")return{selected:(e.selected+n.length-1)%n.length,action:"render"};if(r==="down"||r==="j")return{selected:(e.selected+1)%n.length,action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return{selected:e.selected,action:"choose"};return{selected:e.selected,action:"render"}}async function pL(e,t={}){let n=await import("@opentui/core"),r={review:e,selected:0},o=await n.createCliRenderer({...Gv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),i=Yv(t),a=new n.TextRenderable(o,{content:uL(n,e,r.selected,i)});return o.root.add(a),await new Promise((s,c)=>{let l=r.selected,u=!1,d=(x)=>{if(u)return;u=!0,o.keyInput.off("keypress",f),o.destroy(),s(x)},p=(x)=>{if(u)return;u=!0,o.keyInput.off("keypress",f),o.destroy(),c(x)},m=()=>{a.content=uL(n,e,l,i),o.requestRender()},f=(x)=>{try{let g=XK({review:e,selected:l},x);if(l=g.selected,g.action==="cancel")d({action:"cancel"});else if(g.action==="back")d({action:"change"});else if(g.action==="choose"){let y=Xv(e)[l];d({action:y})}else m()}catch(g){p(g)}};o.keyInput.on("keypress",f);try{o.start()}catch(x){p(x)}})}function Xv(e){return e.conflicts.length>0?["apply","change","resolve","cancel"]:["apply","change","cancel"]}function QK(e,t){switch(e){case"apply":return t==="upgrade"?"Upgrade":"Install";case"change":return"Change options";case"resolve":return"Resolve conflicts";case"cancel":return"Cancel"}}function eL(e,t){for(let n of e.conflicts){let r=Qc(n),o=t==="replace"&&n.category==="invalid-config"&&!r.includes("replace")&&r.includes("remove")?"remove":t;if(r.includes(o))e.decisions[lg(n)]=o}}function eJ(e,t,n){let r=e.conflicts[t];if(r===void 0)return;let o=lg(r),i=Qc(r);if(i.length===0)return;let a=e.decisions[o]??Qv(r,i),s=i.indexOf(a),c=s<0?0:s;e.decisions[o]=i[(c+n+i.length)%i.length]??i[0]}function tJ(e){return e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"])}function Qc(e){return tJ(e).filter((t)=>t!=="cancel")}function Qv(e,t){let n=e.category==="invalid-config"?"remove":e.action==="remove"?"keep":"replace";return t.includes(n)?n:t[0]??"cancel"}function tL(e,t){let n=Qc(e),r=t[lg(e)];return n.includes(r??"cancel")?r:Qv(e,n)}function fL(e,t,n,r,o){let i=Math.min(Math.max(n,0),Math.max(0,e.length-1)),a=e.length+11>o,s=[ae("HolyCodex \xB7 resolve conflicts","heading"),ae(`${e.length} conflict${e.length===1?"":"s"}`,"hint"),ae("\u2191/\u2193 navigate \u2190/\u2192 change action A replace all K keep all","hint"),ae("Enter continue Esc back Ctrl-C cancel","hint")];if(!a)s.push(ae(""));if(s.push(ae(" ACTION CONFIG","heading")),e.forEach((m,f)=>{let x=Qc(m),g=tL(m,t),y=f===i?">":" ",v=x.length===0?"blocked":g,C=x.length===0?"error":g==="replace"?"warning":g==="keep"?"disabled":"error",M=$d(m.target??m.key??m.path,r-12);s.push(Rs({text:`${y} ${v.padEnd(7)} `,tone:C},{text:M,tone:f===i?"focus":"argument"}))}),e.length===0)return s.push(ae("No conflicts require a decision.","success")),s;if(!a)s.push(ae(""));let c=e[i],l=tL(c,t),u=$d(nL(c.existing),r-10),d=c.desired===void 0&&c.action==="remove"?oJ(c):nL(c.desired),p=$d(d,r-10);return s.push(ae($d(c.target??c.key??c.path,r),"focus")),s.push(Rs({text:"current ",tone:"hint"},{text:u})),s.push(Rs({text:"install ",tone:"hint"},{text:p})),s.push(ae($d(rJ(c,l),r),"hint")),s}function $d(e,t){let n=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim(),r=Math.max(1,t);return n.length<=r?n:`${n.slice(0,Math.max(0,r-1))}\u2026`}function nJ(e){return e.split(/[-_]/u).map((t)=>t.length===0?t:`${t[0].toUpperCase()}${t.slice(1)}`).join(" ")}function nL(e){if(e===void 0)return"(unknown)";if(typeof e==="string")return e;try{return JSON.stringify(e)}catch{return"(unavailable)"}}function rJ(e,t){if(t==="keep")return"Keep the current value.";if(t==="remove")return e.category==="invalid-config"?"Remove the invalid value so HolyCodex can create the required table.":"Remove the managed item.";if(t==="cancel")return"No available action can continue this operation.";return"Replace the current value with the HolyCodex value."}function oJ(e){return e.category==="invalid-config"?"remove this conflicting user-owned value":"remove this managed item"}function lg(e){return e.identity??`${e.path}:${e.key??""}:${e.action}`}function mL(e,t,n){let r=n.name.toLowerCase(),o=oa.length+2;if(r==="escape"||n.ctrl===!0&&r==="c")return{cursor:t,action:"cancel"};if(r==="up"||r==="k")return{cursor:Math.max(0,t-1),action:"render"};if(r==="down"||r==="j")return{cursor:Math.min(o,t+1),action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return e.plugins=gL(e.pluginInput),{cursor:t,action:"review"};if(t===o){if(r==="backspace")iL(e,-1);else if(r==="delete")iL(e,1);else if(r==="left")e.pluginCursor=Math.max(0,e.pluginCursor-1);else if(r==="right")e.pluginCursor=Math.min(e.pluginInput.length,e.pluginCursor+1);else if(r==="home")e.pluginCursor=0;else if(r==="end")e.pluginCursor=e.pluginInput.length;else if(r==="space")oL(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!fJ(n.name))oL(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)aJ(e,t-2);else if(r==="left")rL(e,t,-1);else if(r==="right")rL(e,t,1);return{cursor:t,action:"render"}}function hL(e){let t={profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]};return dn(t)}function iJ(e,t="install",n={}){let r=eR(dn(e));return sJ(r,t==="install"?0:t==="change"?1:2,Xi({...n,stream:"stdout"}))}function eR(e){let t={...en,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{browser_use:t.browser_use??en.browser_use,computer_use:t.computer_use??en.computer_use,sites:t.sites??en.sites},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function rL(e,t,n){if(t===0)e.profile=aL(KK,e.profile,n);else if(t===1)e.tier=aL(JK,e.tier,n)}function aJ(e,t){let n=oa[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function oL(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function iL(e,t){if(t===-1){if(e.pluginCursor===0)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor-1)}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor-=1;return}if(e.pluginCursor>=e.pluginInput.length)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${e.pluginInput.slice(e.pluginCursor+1)}`}function aL(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function gL(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return dn({officialPlugins:t}),t}function sJ(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[vn("HolyCodex \xB7 review","heading",n),vn("Review configuration","heading",n),vn("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",vn("CAPABILITIES","heading",n),...oa.map((i)=>` ${ug(i)}: ${vn(nR(e.optional[i]),e.optional[i]?"enabled":"disabled",n)}`),...tR(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((i,a)=>vn(`${a===t?"\u203A":" "} ${i}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
113
113
  `)}
114
- `}function YF(e,t,n,r){let o=Ki.length+2,i=n<2?n===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":n<o?XK(Ki[n-2]):"Optional plugin IDs separated by spaces. Enter continues to review.",a=[Z("HolyCodex \xB7 install","heading"),Z("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint"),Z(""),Z("PROFILE","heading"),ZF("Profile",t.profile,n===0),ZF("Service tier",t.tier,n===1),Z(""),Z("OPTIONAL CAPABILITIES","heading"),...Ki.map((s,c)=>KK(s,t.optional[s],n===c+2)),Z(""),Z("ADDITIONAL PLUGINS","heading"),...Jv(`${n===o?"\u276F":" "} ${t.pluginInput||"(none)"}`).map((s)=>Z(s,n===o?"focus":"argument")),Z(""),Z(i,"hint")];return Jh(e,a,r)}function ZF(e,t,n){return Z(`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`,n?"focus":"argument")}function KK(e,t,n){let r=t?"[x] enabled":"[ ] disabled";return Z(`${n?"\u276F":" "} ${Zh(e).padEnd(14)} ${r}`,n?"focus":t?"enabled":"disabled")}function JK(e,t,n,r){let o=["Install","Change options / Redo","Cancel"],i=[Z("HolyCodex \xB7 review","heading"),Z("Review configuration","heading"),Z("\u2191/\u2193 choose Enter confirm Esc back","hint"),Z(""),Z(`Profile: ${t.profile}`),Z(`Service tier: ${t.tier}`),Z(""),Z("CAPABILITIES","heading"),...Ki.map((a)=>Pd({text:` ${Zh(a)}: `},{text:Gv(t.optional[a]),tone:t.optional[a]?"enabled":"disabled"})),...Jv(` Additional plugins: ${t.plugins.length===0?"none":t.plugins.join(" ")}`).map((a)=>Z(a,"argument")),Z(""),...o.map((a,s)=>Z(`${s===n?"\u203A":" "} ${a}`,s===n?"focus":s===0?"success":s===1?"warning":"error"))];return Jh(e,i,r)}function XF(e,t,n,r,o){let i=[Z("HolyCodex \xB7 resolve conflicts","heading"),Z(rL(t),"hint"),Z(oL(t),"hint"),Z(iL(t),"hint"),Z("Enter continue Esc back Ctrl-C cancel","hint"),Z(""),Z(`Decision ${t.length===0?0:r+1} of ${t.length}`,"focus"),Z("")],a;if(t.forEach((s,c)=>{let l=s.category??"managed";if(l!==a)i.push(Z(zv(l),"heading")),a=l;let u=s.identity??`${s.path}:${s.key??""}:${s.action}`,d=n[u]??"keep",p=s.target??s.key??s.path,f=c===r?"\u276F":" ",m=d==="replace"?"warning":d==="keep"?"disabled":"error";i.push(Pd({text:`${f} ${p}`,tone:c===r?"focus":"argument"},{text:" choice: "},{text:d,tone:m},{text:` choices: ${nL(s)}`,tone:"hint"}))}),t.length===0)i.push(Z("No conflicts require a decision.","success"));else{let s=t[Math.min(Math.max(r,0),t.length-1)];if(s!==void 0){let c=s.target??s.key??s.path;if(i.push(Z(`Focused conflict: ${c}`,"focus")),i.push(Z(lL(s,n[GK(s)]??"keep"),"warning")),i.push(Z(` existing: ${Kh(s.existing)}`)),s.action==="remove")i.push(Z(` planned: ${uL(s)}`));else i.push(Z(` desired: ${Kh(s.desired)}`));if(s.explanation!==void 0)i.push(Z(` ${s.explanation}`,"hint"))}}return Jh(e,i,o)}function lL(e,t){if(t==="keep")return e.action==="remove"?"Effect: preserve this edited item in place; removal remains partial until you retry or leave it.":"Effect: preserve the current file or setting and leave this change unapplied.";if(t==="cancel")return"Effect: stop this operation before applying the reviewed changes.";if(t==="remove"){if(e.category==="invalid-config")return"Effect: remove this reviewed user-owned value so HolyCodex can create the required table.";return e.action==="remove"?"Effect: delete this modified HolyCodex-owned item after confirmation.":"Effect: remove the current value and apply the reviewed HolyCodex value."}return e.action==="remove"?"Effect: this removal does not offer Replace; use Remove or Keep.":"Effect: replace the current item with the reviewed HolyCodex version."}function uL(e){return e.category==="invalid-config"?"remove this conflicting user-owned value":"remove this managed item"}function GK(e){return e.identity??`${e.path}:${e.key??""}:${e.action}`}function QF(e,t,n,r){let o=t.operation==="upgrade"?"upgrade":"install",i=t.operation==="upgrade"&&t.fromVersion!==void 0?`${t.fromVersion} \u2192 ${t.toVersion}`:t.toVersion,a=Object.values(t.conflictCounts).reduce((u,d)=>u+d,0),s=$K(t),c=s.keep+s.replace,l=[Z(`HolyCodex \xB7 ${o} review`,"heading"),Z("Review the complete preflight plan before applying changes.","hint"),Z(`Version: ${i}`),Z(`Profile: ${t.profile}`),Z(`Service tier: ${t.tier}`),Z("CAPABILITIES","heading"),...Ki.map((u)=>Pd({text:` ${Zh(u)}: `},{text:Gv(t.capabilities[u]),tone:t.capabilities[u]?"enabled":"disabled"})),Z(` Additional plugins: ${t.additionalPlugins.length===0?"none":t.additionalPlugins.join(" ")}`,"argument"),Z(`CONFLICTS (${a})`,"heading"),...a===0?[Z(" none")]:Object.entries(t.conflictCounts).map(([u,d])=>Z(` ${zv(u)}: ${d}`)),...a===0?[]:[Z(`DECISIONS (${c})`,"heading"),Z(` Keep: ${s.keep}`),Z(` Replace: ${s.replace}`)],Z("PREREQUISITES","heading"),...t.tools.length===0?[Z(" none")]:t.tools.map((u)=>YK(u)),Z("\u2191/\u2193 or j/k choose Enter select Esc back Ctrl-C cancel","hint"),...Wv(t).map((u,d)=>Z(`${d===n?"\u203A":" "} ${jK(u,t.operation)}`,d===n?"focus":u==="apply"?"success":u==="change"||u==="resolve"?"warning":"error"))];return Jh(e,l,r)}function YK(e){let t=e.name.toLowerCase()==="context7",n=t?ZK(e.status):e.status,r=e.status==="ready"||e.status==="healthy"?"success":"warning",o=t||e.detail===void 0?"":` (${e.detail})`;return Pd({text:` ${e.name}: `},{text:n,tone:r},...o.length===0?[]:[{text:o}])}function ZK(e){return e==="ready"?"Use available ctx7":"Attempt optional managed ctx7 install"}function XK(e){switch(e){case"sites":return"ChatGPT Sites may depend on your account, region, workspace policy, or supported Codex surface.";case"browser_use":return"Browser Use depends on the Codex surface and runtime; it may be unavailable where unsupported.";case"computer_use":return"Computer Use has stronger platform and surface restrictions and can take external actions."}}function Jv(e,t=76){if(e.length<=t)return[e];let n=[],r=e;while(r.length>t){let o=r.lastIndexOf(" ",t),i=o>0?o:t;n.push(r.slice(0,i)),r=r.slice(o>0?i+1:i)}if(r.length>0)n.push(r);return n}function Zh(e){switch(e){case"sites":return"ChatGPT Sites";case"browser_use":return"Browser Use";case"computer_use":return"Computer Use"}}function Gv(e){return e?"enabled":"disabled"}function QK(e){let t=e.codePointAt(0)??0;return t<=31||t===127}Ed();cd();Fh();md();yd();Qa();Nc();async function Qv(e,t={}){if(e.length===0||ad(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:sd(e);return{envelope:dL(r===void 0?"help":`${r} help`,{help:id(r)}),exitCode:0}}let n;try{n=yh(e);let r=await pL(n,t);return{envelope:dL(n.command,r),exitCode:mJ(n.command,r)}}catch(r){return fJ(n?.command??yJ(e),r)}}async function pL(e,t){switch(e.command){case"install":return cn(await eJ(e,t));case"doctor":{let n=Fd(e,t),r=Cr(n,t.env);return cn(await Ev({...n,officialPluginManager:n.officialPluginManager??new Eh(r.codexHome)},t.env))}case"remove":return cn(await rJ(e,t));case"version":return cn(await oJ(e,t));case"help":return{help:id(e.positionals[0])};default:throw new Kc("invalid_argument","Unknown command.")}}async function eJ(e,t){let n=nJ(e),r=await tJ(e,t,n);if("cancelled"in r)return r;return await fs(r,Fd(e,t),t.env)}async function tJ(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await jF(Fd(e,t),t.env),a=await(t.io?.installWizard??Gh)({...i,...n,...i.optional===void 0&&n.optional===void 0?{}:{optional:{...i.optional,...n.optional}}});if(a.action==="cancel")return{cancelled:!0};return pn(a.request)}let o=await fL(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new Kc("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return pn(n)}function nJ(e){let t=sJ(e),n=cJ(e),r=aJ(e),o=e.options["add-plugin"]===void 0?void 0:lJ(e,"add-plugin");return pn({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o===void 0?{}:{officialPlugins:o}})}async function rJ(e,t){let n=await fL(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let o=(await kv(Fd(e,t),t.env))[0];if(o!==void 0)throw new T("confirmation_required","Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},action:o.action});throw new Kc("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.")}return await vd(Fd(e,t),t.env)}async function oJ(e,t){let n=e.positionals[0];if(!n)return{version:await Fc()};return await ov(n,e.options["dry-run"]===!0)}async function fL(e,t,n){if(e.options.yes===!0)return"confirmed";if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return"unavailable";return await iJ(t,n)}async function iJ(e,t){if(e.io?.confirm===void 0)return"unavailable";let n=await e.io.confirm(t);if(n==="confirmed"||n==="cancelled"||n==="unavailable")return n;return n?"confirmed":"cancelled"}function aJ(e){let t={};for(let n of["browser_use","computer_use","sites"]){let r=n.replaceAll("_","-");if(e.options[r]===!0)t[n]=!0;else if(e.options[r]===!1)t[n]=!1;else if(e.options[`no-${r}`]===!0)t[n]=!1}return Object.keys(t).length===0?void 0:t}function sJ(e){let t=e.options.profile;if(typeof t!=="string")return;let n=eo(t);return n.ok?n.value.name:void 0}function cJ(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function lJ(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Fd(e,t){let n=t.installer??{},r=e.options.json===!0,o=!r&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0,i=(y)=>{n.onProgress?.(y),t.onProgress?.(y),xJ(t,r,y.message)},a=new Map,s=(y,g)=>{for(let x of y){let P=Xh(x),_=g[P];if(_!==void 0)a.set(P,_)}return g},c=n.resolveConflict??(async(y)=>{if(e.options.yes===!0)return"decline";if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)throw new T("confirmation_required",`Review the modified HolyCodex-owned state at ${y.key===void 0?y.path:`${y.path} (${y.key})`} in an interactive terminal; --yes preserves user changes.`,void 0,{path:y.path,...y.key===void 0?{}:{key:y.key}});let g=Xh(y),x=await Yh([y],{},Object.fromEntries(a));if(x.action==="back")return"decline";if(x.action!=="continue")return"cancel";let P=x.decisions[g];if(P!==void 0)a.set(g,P);if(P==="replace"||P==="remove")return"accept";if(P==="keep")return"decline";return"cancel"}),l=n.resolveConflicts??(e.options.yes===!0?async(y)=>{if(y.length>0){let g=y.map((x)=>`${x.key===void 0?x.path:`${x.path} (${x.key})`}: ${x.explanation??"user-owned state requires review"}`).join("; ");throw new T("confirmation_required",`--yes cannot resolve user-owned configuration without overwriting it. Conflicts: ${g}.`,void 0,{conflicts:g})}return{}}:async(y)=>{if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)throw new T("confirmation_required","Managed conflicts require an interactive review or --yes.");let g=await Yh(y,{},Object.fromEntries(a));if(g.action==="back"){let x=Object.fromEntries(y.map((P)=>{let _=P.validDecisions??(P.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]);return[Xh(P),_.includes("keep")?"keep":"cancel"]}));return s(y,x)}if(g.action==="cancel")throw new T("confirmation_required","Conflict review was cancelled.");if(g.action==="continue")return g.decisions;throw new T("confirmation_required","Conflict review was reopened.")}),u=async(y)=>s(y,await l(y)),p=n.reviewInstall??t.io?.installReview??(e.options.yes===!0?async()=>({action:"apply"}):o?async(y)=>await tL(y):void 0),f=p===void 0?void 0:async(y)=>{let g=dJ(y,a),x=await p(pJ(g));if(x.action!=="change")return x;if(x.request!==void 0)return{action:"change",request:pn(x.request)};if(!o)throw new T("confirmation_required","Changing install options requires an interactive review.");let P=await(t.io?.installWizard??Gh)(uJ(g));if(P.action==="cancel")return{action:"cancel"};return{action:"change",request:pn(P.request)}},m=e.options["codex-home"];if(typeof m!=="string")return{...n,onProgress:i,resolveConflict:c,resolveConflicts:u,...f===void 0?{}:{reviewInstall:f},...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:m},onProgress:i,resolveConflict:c,resolveConflicts:u,...f===void 0?{}:{reviewInstall:f},...t.now?{now:t.now}:{}}}function uJ(e){return pn({profile:e.profile,tier:e.tier,optional:e.capabilities,officialPlugins:e.additionalPlugins})}function Xh(e){return e.identity??e.path}function dJ(e,t){if(t.size===0||e.conflicts.length===0)return e;return{...e,conflicts:e.conflicts.map((n)=>{let r=t.get(Xh(n));return r===void 0?n:{...n,decision:r}})}}function pJ(e){let{fromVersion:t,...n}=e;return{...n,operation:"install"}}function dL(e,t){let n=Jm({schema_version:uo,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new Kc("internal_error","The success envelope failed validation.");return n.value}function fJ(e,t){let n=hJ(t,e),r=Jm({schema_version:uo,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:uo,ok:!1,command:"internal-error",error:{code:"internal_error",message:"The CLI failure envelope was invalid.",details:{}},warnings:[]},exitCode:5};return{envelope:r.value,exitCode:n.exitCode}}function mJ(e,t){if(e==="doctor"&&Go(t)&&t.healthy===!1)return 4;if(e==="remove"&&Go(t)){if(t.cancelled===!0)return 1;if(Ji(t,"preserved").length>0||Ji(t,"reasons").length>0)return 4}return 0}function hJ(e,t){if(e instanceof ct)return{code:e.code,message:Ad(e.message),details:e.details,exitCode:1};if(e instanceof Kc)return{code:e.code,message:Ad(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof Qn)return{code:"trust_boundary_failed",message:Ad(e.message),details:{},exitCode:4};if(e instanceof T){let n=e,r=n.code==="confirmation_required"?1:n.code==="capability_denied"?2:n.code==="state_corrupt"?4:3;return{code:n.code,message:Zv(n.message),details:Yv(n.details,n.causeValue,t),exitCode:r}}if(e instanceof ro){let n=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),r=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:n?"effect_uncertain":r?"capability_denied":"install_failed",message:Zv(e.message),details:Yv(e.details,e.causeValue,t),exitCode:n?4:r?2:3}}if(e instanceof es)return{code:e.code,message:Zv(e.message),details:Yv({},e.causeValue,t),exitCode:4};if(e instanceof Bo)return{code:e.code,message:Ad(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:ed(`${e.name}: ${e.message}`).join(" ").slice(0,512)},exitCode:5};return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:"A non-Error value was thrown."},exitCode:5}}function Yv(e,t,n){let r={...e};if(t!==void 0){if(typeof r.operation!=="string")r.operation=n;r.cause=ed(gJ(t)).join(" ").slice(0,512)}return r}function gJ(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(typeof e==="string")return e;return"The operation failed with a non-Error cause."}function Zv(e){return Ad(ed(e).join(" "))}function yJ(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function Ad(e){return Array.from(e).map((t)=>{let n=t.codePointAt(0)??0;return n<=31||n===127?" ":t}).join("").replace(/\s+/gu," ").trim().slice(0,512)}function Go(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function xJ(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${mL(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
115
- `)}function Qh(e,t={}){let n=$i(t);if(e.envelope.ok){if(e.envelope.command==="version")return SJ(e.envelope.data);if(e.envelope.command==="install")return bJ(e.envelope.data,n);if(e.envelope.command==="remove")return _J(e.envelope.data,n);if(e.envelope.command==="doctor")return wJ(e.envelope.data,n);return`${_e("\u2714","green",n)} ${_e(e.envelope.command,"heading",n)}
116
- ${vJ(e.envelope.data,n)}`}let r=e.envelope.error,o=TJ(r.code,e.envelope.command);return[`${_e("\u2716","red",n)} ${_e(e.envelope.command,"heading",n)}`,` ${_e(r.code,"red",n)}: ${r.message}`,...RJ(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
117
- `)}function mL(e,t={}){return`${_e("\u2022","cyan",$i({...t,stream:"stderr"}))} ${e}`}function SJ(e){if(Go(e)&&typeof e.version==="string")return`holycodex ${e.version}
118
- `;if(Go(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
114
+ `}function sL(e,t,n,r){let o=oa.length+2,i=n<2?n===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":n<o?pJ(oa[n-2]):"Optional plugin IDs separated by spaces. Enter continues to review.",a=[ae("HolyCodex \xB7 install","heading"),ae("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint"),ae(""),ae("PROFILE","heading"),cL("Profile",t.profile,n===0),cL("Service tier",t.tier,n===1),ae(""),ae("OPTIONAL CAPABILITIES","heading"),...oa.map((s,c)=>cJ(s,t.optional[s],n===c+2)),ae(""),ae("ADDITIONAL PLUGINS","heading"),...tR(`${n===o?"\u276F":" "} ${t.pluginInput||"(none)"}`).map((s)=>ae(s,n===o?"focus":"argument")),ae(""),ae(i,"hint")];return ag(e,a,r)}function cL(e,t,n){return ae(`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`,n?"focus":"argument")}function cJ(e,t,n){let r=t?"[x] enabled":"[ ] disabled";return ae(`${n?"\u276F":" "} ${ug(e).padEnd(14)} ${r}`,n?"focus":t?"enabled":"disabled")}function lJ(e,t,n,r){let o=["Install","Change options / Redo","Cancel"],i=[ae("HolyCodex \xB7 review","heading"),ae("Review configuration","heading"),ae("\u2191/\u2193 choose Enter confirm Esc back","hint"),ae(""),ae(`Profile: ${t.profile}`),ae(`Service tier: ${t.tier}`),ae(""),ae("CAPABILITIES","heading"),...oa.map((a)=>Rs({text:` ${ug(a)}: `},{text:nR(t.optional[a]),tone:t.optional[a]?"enabled":"disabled"})),...tR(` Additional plugins: ${t.plugins.length===0?"none":t.plugins.join(" ")}`).map((a)=>ae(a,"argument")),ae(""),...o.map((a,s)=>ae(`${s===n?"\u203A":" "} ${a}`,s===n?"focus":s===0?"success":s===1?"warning":"error"))];return ag(e,i,r)}function lL(e,t,n,r,o,i,a){return ag(e,fL(t,n,r,i,a),o)}function uL(e,t,n,r){let o=t.operation==="upgrade"?"upgrade":"install",i=t.operation==="upgrade"&&t.fromVersion!==void 0?`${t.fromVersion} \u2192 ${t.toVersion}`:t.toVersion,a=Object.values(t.conflictCounts).reduce((u,d)=>u+d,0),s=ZK(t),c=s.keep+s.replace,l=[ae(`HolyCodex \xB7 ${o} review`,"heading"),ae("Review the complete preflight plan before applying changes.","hint"),ae(`Version: ${i}`),ae(`Profile: ${t.profile}`),ae(`Service tier: ${t.tier}`),ae("CAPABILITIES","heading"),...oa.map((u)=>Rs({text:` ${ug(u)}: `},{text:nR(t.capabilities[u]),tone:t.capabilities[u]?"enabled":"disabled"})),ae(` Additional plugins: ${t.additionalPlugins.length===0?"none":t.additionalPlugins.join(" ")}`,"argument"),ae(`CONFLICTS (${a})`,"heading"),...a===0?[ae(" none")]:Object.entries(t.conflictCounts).map(([u,d])=>ae(` ${nJ(u)}: ${d}`)),...a===0?[]:[ae(`DECISIONS (${c})`,"heading"),ae(` Keep: ${s.keep}`),ae(` Replace: ${s.replace}`)],ae("PREREQUISITES","heading"),...t.tools.length===0?[ae(" none")]:t.tools.map((u)=>uJ(u)),ae("\u2191/\u2193 or j/k choose Enter select Esc back Ctrl-C cancel","hint"),...Xv(t).map((u,d)=>ae(`${d===n?"\u203A":" "} ${QK(u,t.operation)}`,d===n?"focus":u==="apply"?"success":u==="change"||u==="resolve"?"warning":"error"))];return ag(e,l,r)}function uJ(e){let t=e.name.toLowerCase()==="context7",n=t?dJ(e.status):e.status,r=e.status==="ready"||e.status==="healthy"?"success":"warning",o=t||e.detail===void 0?"":` (${e.detail})`;return Rs({text:` ${e.name}: `},{text:n,tone:r},...o.length===0?[]:[{text:o}])}function dJ(e){return e==="ready"?"Use available ctx7":"Attempt optional managed ctx7 install"}function pJ(e){switch(e){case"sites":return"ChatGPT Sites may depend on your account, region, workspace policy, or supported Codex surface.";case"browser_use":return"Browser Use depends on the Codex surface and runtime; it may be unavailable where unsupported.";case"computer_use":return"Computer Use has stronger platform and surface restrictions and can take external actions."}}function tR(e,t=76){if(e.length<=t)return[e];let n=[],r=e;while(r.length>t){let o=r.lastIndexOf(" ",t),i=o>0?o:t;n.push(r.slice(0,i)),r=r.slice(o>0?i+1:i)}if(r.length>0)n.push(r);return n}function ug(e){switch(e){case"sites":return"ChatGPT Sites";case"browser_use":return"Browser Use";case"computer_use":return"Computer Use"}}function nR(e){return e?"enabled":"disabled"}function fJ(e){let t=e.codePointAt(0)??0;return t<=31||t===127}Nd();hd();Zh();wd();Rd();us();jc();async function sR(e,t={}){if(e.length===0||fd(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:md(e);return{envelope:xL(r===void 0?"help":`${r} help`,{help:pd(r)}),exitCode:0}}let n;try{n=Ah(e);let r=await SL(n,t);return{envelope:xL(n.command,r),exitCode:IJ(n.command,r)}}catch(r){return EJ(n?.command??MJ(e),r)}}async function SL(e,t){switch(e.command){case"install":return sn(await gJ(e,t));case"doctor":{let n=Wd(e,t),r=Pr(n,t.env);return sn(await Fv({...n,officialPluginManager:n.officialPluginManager??await mJ(r.codexHome,t.env)},t.env))}case"remove":return sn(await SJ(e,t));case"version":return sn(await bJ(e,t));case"help":return{help:pd(e.positionals[0])};default:throw new el("invalid_argument","Unknown command.")}}async function mJ(e,t){try{return await Qo.discover(t)}catch(n){if(hJ(n))return new Bh(e);throw n}}function hJ(e){return e instanceof Error&&"code"in e&&e.code==="discovery_failed"&&e.message.startsWith("No Codex executable was found")}async function gJ(e,t){let n=xJ(e),r=await yJ(e,t,n);if("cancelled"in r)return r;return await bs(r,Wd(e,t),t.env)}async function yJ(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await GF(Wd(e,t),t.env),a=await(t.io?.installWizard??sg)({...i,...n,...i.optional===void 0&&n.optional===void 0?{}:{optional:{...i.optional,...n.optional}}});if(a.action==="cancel")return{cancelled:!0};return dn(a.request)}let o=await bL(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new el("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return dn(n)}function xJ(e){let t=vJ(e),n=RJ(e),r=_J(e),o=e.options["add-plugin"]===void 0?void 0:TJ(e,"add-plugin");return dn({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o===void 0?{}:{officialPlugins:o}})}async function SJ(e,t){let n=await bL(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let o=(await Lv(Wd(e,t),t.env))[0];if(o!==void 0)throw new _("confirmation_required","Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},action:o.action});throw new el("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.")}return await Id(Wd(e,t),t.env)}async function bJ(e,t){let n=e.positionals[0];if(!n)return{version:await Hc()};return await fv(n,e.options["dry-run"]===!0)}async function bL(e,t,n){if(e.options.yes===!0)return"confirmed";if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return"unavailable";return await wJ(t,n)}async function wJ(e,t){if(e.io?.confirm===void 0)return"unavailable";let n=await e.io.confirm(t);if(n==="confirmed"||n==="cancelled"||n==="unavailable")return n;return n?"confirmed":"cancelled"}function _J(e){let t={};for(let n of["browser_use","computer_use","sites"]){let r=n.replaceAll("_","-");if(e.options[r]===!0)t[n]=!0;else if(e.options[r]===!1)t[n]=!1;else if(e.options[`no-${r}`]===!0)t[n]=!1}return Object.keys(t).length===0?void 0:t}function vJ(e){let t=e.options.profile;if(typeof t!=="string")return;let n=oo(t);return n.ok?n.value.name:void 0}function RJ(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function TJ(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Wd(e,t){let n=t.installer??{},r=e.options.json===!0,o=!r&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0,i=(x)=>{n.onProgress?.(x),t.onProgress?.(x),NJ(t,r,x.message)},a=new Map,s=(x,g)=>{for(let y of x){let v=jd(y),C=g[v];if(C!==void 0)a.set(v,C)}return g},c=n.resolveConflict??(async(x)=>{if(e.options.yes===!0){let C=iR(x);return yL(t,[x]),C==="keep"?"decline":C==="cancel"?"cancel":"accept"}if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)throw new _("confirmation_required",`Review the modified HolyCodex-owned state at ${x.key===void 0?x.path:`${x.path} (${x.key})`} in an interactive terminal; --yes preserves user changes.`,void 0,{path:x.path,...x.key===void 0?{}:{key:x.key}});let g=jd(x),y=await cg([x],{},Object.fromEntries(a));if(y.action==="back")return"decline";if(y.action!=="continue")return"cancel";let v=y.decisions[g];if(v!==void 0)a.set(g,v);if(v==="replace"||v==="remove")return"accept";if(v==="keep")return"decline";return"cancel"}),l=n.resolveConflicts??(e.options.yes===!0?async(x)=>{let g=Object.fromEntries(x.map((y)=>[jd(y),iR(y)]));return yL(t,x),g}:async(x)=>{if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)throw new _("confirmation_required","Managed conflicts require an interactive review or --yes.");let g=await cg(x,{},Object.fromEntries(a));if(g.action==="back"){let y=Object.fromEntries(x.map((v)=>{let C=v.validDecisions??(v.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]);return[jd(v),C.includes("keep")?"keep":"cancel"]}));return s(x,y)}if(g.action==="cancel")throw new _("confirmation_required","Conflict review was cancelled.");if(g.action==="continue")return g.decisions;throw new _("confirmation_required","Conflict review was reopened.")}),u=async(x)=>s(x,await l(x)),p=n.reviewInstall??t.io?.installReview??(e.options.yes===!0?async()=>({action:"apply"}):o?async(x)=>await pL(x):void 0),m=p===void 0?void 0:async(x)=>{let g=OJ(x,a),y=await p(kJ(g));if(y.action!=="change")return y;if(y.request!==void 0)return{action:"change",request:dn(y.request)};if(!o)throw new _("confirmation_required","Changing install options requires an interactive review.");let v=await(t.io?.installWizard??sg)(CJ(g));if(v.action==="cancel")return{action:"cancel"};return{action:"change",request:dn(v.request)}},f=e.options["codex-home"];if(typeof f!=="string")return{...n,onProgress:i,resolveConflict:c,resolveConflicts:u,...m===void 0?{}:{reviewInstall:m},...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:f},onProgress:i,resolveConflict:c,resolveConflicts:u,...m===void 0?{}:{reviewInstall:m},...t.now?{now:t.now}:{}}}function iR(e){let t=e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]),n=e.action==="remove"?"remove":"replace",r=t.includes(n)?n:void 0;if(r===void 0)throw new _("confirmation_required",`--yes cannot resolve ${e.target??e.key??e.path}; choose ${t.join(", ")}.`,void 0,{path:e.path,...e.key===void 0?{}:{key:e.key}});return r}function yL(e,t){if(t.length===0)return;let n=t.map((r)=>{let o=iR(r),i=r.key===void 0?r.path:`${r.path} (${r.key})`;return o==="keep"?void 0:`${o} ${i}`}).filter((r)=>r!==void 0);if(n.length===0)return;e.io?.writeStderr?.(`Warning: --yes will apply these conflict decisions: ${n.join("; ")}. This may overwrite existing Codex configuration.
115
+ `)}function CJ(e){return dn({profile:e.profile,tier:e.tier,optional:e.capabilities,officialPlugins:e.additionalPlugins})}function jd(e){return e.identity??e.path}function OJ(e,t){if(t.size===0||e.conflicts.length===0)return e;return{...e,conflicts:e.conflicts.map((n)=>{let r=t.get(jd(n));return r===void 0?n:{...n,decision:r}})}}function kJ(e){let{fromVersion:t,...n}=e;return{...n,operation:"install"}}function xL(e,t){let n=sh({schema_version:yo,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new el("internal_error","The success envelope failed validation.");return n.value}function EJ(e,t){let n=PJ(t,e),r=sh({schema_version:yo,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:yo,ok:!1,command:"internal-error",error:{code:"internal_error",message:"The CLI failure envelope was invalid.",details:{}},warnings:[]},exitCode:5};return{envelope:r.value,exitCode:n.exitCode}}function IJ(e,t){if(e==="doctor"&&oi(t)&&t.healthy===!1)return 4;if(e==="remove"&&oi(t)){if(t.cancelled===!0)return 1;if(ia(t,"preserved").length>0||ia(t,"reasons").length>0)return 4}return 0}function PJ(e,t){if(e instanceof lt)return{code:e.code,message:Hd(e.message),details:e.details,exitCode:1};if(e instanceof el)return{code:e.code,message:Hd(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof tr)return{code:"trust_boundary_failed",message:Hd(e.message),details:{},exitCode:4};if(e instanceof _){let n=e,r=n.code==="confirmation_required"?1:n.code==="capability_denied"?2:n.code==="state_corrupt"?4:3;return{code:n.code,message:oR(n.message),details:rR(n.details,n.causeValue,t),exitCode:r}}if(e instanceof co){let n=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),r=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:n?"effect_uncertain":r?"capability_denied":"install_failed",message:oR(e.message),details:rR(e.details,e.causeValue,t),exitCode:n?4:r?2:3}}if(e instanceof ds)return{code:e.code,message:oR(e.message),details:rR({},e.causeValue,t),exitCode:4};if(e instanceof Zo)return{code:e.code,message:Hd(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:sd(`${e.name}: ${e.message}`).join(" ").slice(0,512)},exitCode:5};return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:"A non-Error value was thrown."},exitCode:5}}function rR(e,t,n){let r={...e};if(t!==void 0){if(typeof r.operation!=="string")r.operation=n;r.cause=sd(AJ(t)).join(" ").slice(0,512)}return r}function AJ(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(typeof e==="string")return e;return"The operation failed with a non-Error cause."}function oR(e){return Hd(sd(e).join(" "))}function MJ(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function Hd(e){return Array.from(e).map((t)=>{let n=t.codePointAt(0)??0;return n<=31||n===127?" ":t}).join("").replace(/\s+/gu," ").trim().slice(0,512)}function oi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function NJ(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${wL(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
116
+ `)}function dg(e,t={}){let n=Xi(t);if(e.envelope.ok){if(e.envelope.command==="version")return FJ(e.envelope.data);if(e.envelope.command==="install")return LJ(e.envelope.data,n);if(e.envelope.command==="remove")return DJ(e.envelope.data,n);if(e.envelope.command==="doctor")return qJ(e.envelope.data,n);return`${_e("\u2714","green",n)} ${_e(e.envelope.command,"heading",n)}
117
+ ${UJ(e.envelope.data,n)}`}let r=e.envelope.error,o=jJ(r.code,e.envelope.command);return[`${_e("\u2716","red",n)} ${_e(e.envelope.command,"heading",n)}`,` ${_e(r.code,"red",n)}: ${r.message}`,...$J(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
118
+ `)}function wL(e,t={}){return`${_e("\u2022","cyan",Xi({...t,stream:"stderr"}))} ${e}`}function FJ(e){if(oi(e)&&typeof e.version==="string")return`holycodex ${e.version}
119
+ `;if(oi(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
119
120
  `}return`holycodex version completed
120
- `}function bJ(e,t){if(eR(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("install","heading",t)} cancelled
121
- `;let n=Md(e,"record"),r=Nd(n,"version")??"unknown",o=Nd(n,"profile")??"unknown",i=Nd(n,"tier")??"unknown",a=Md(n,"capability_state"),s=["frontend","security","sites","browser_use","computer_use"].filter((f)=>Md(a,f)?.selected===!0).map((f)=>{let m=Nd(Md(a,f),"status");return m===void 0||m==="healthy"?f:`${f} (${m})`}),c=Ji(e,"preserved"),l=Ji(e,"warnings"),u=s.length===0?"none":s.join(", "),d=c.length===0?"none":`${c.length} managed item${c.length===1?"":"s"} (review before retrying)`;return`${[`${_e("\u2714","green",t)} ${_e("install","heading",t)}`,` ${_e("version","option",t)}: ${r}`,` ${_e("profile","option",t)}: ${o}`,` ${_e("tier","option",t)}: ${i}`,` ${_e("capabilities","option",t)}: ${u}`,` ${_e("preserved","option",t)}: ${d}`,...l.map((f)=>` ${_e("warning","warning",t)}: ${tR(f)}`)].join(`
121
+ `}function LJ(e,t){if(cR(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("install","heading",t)} cancelled
122
+ `;let n=Bd(e,"record"),r=Vd(n,"version")??"unknown",o=Vd(n,"profile")??"unknown",i=Vd(n,"tier")??"unknown",a=Bd(n,"capability_state"),s=["frontend","security","sites","browser_use","computer_use"].filter((m)=>Bd(a,m)?.selected===!0).map((m)=>{let f=Vd(Bd(a,m),"status");return f===void 0||f==="healthy"?m:`${m} (${f})`}),c=ia(e,"preserved"),l=ia(e,"warnings"),u=s.length===0?"none":s.join(", "),d=c.length===0?"none":`${c.length} managed item${c.length===1?"":"s"} (review before retrying)`;return`${[`${_e("\u2714","green",t)} ${_e("install","heading",t)}`,` ${_e("version","option",t)}: ${r}`,` ${_e("profile","option",t)}: ${o}`,` ${_e("tier","option",t)}: ${i}`,` ${_e("capabilities","option",t)}: ${u}`,` ${_e("preserved","option",t)}: ${d}`,...l.map((m)=>` ${_e("warning","warning",t)}: ${lR(m)}`)].join(`
122
123
  `)}
123
- `}function _J(e,t){if(eR(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("remove","heading",t)} cancelled
124
- `;let n=Ji(e,"removed"),r=Ji(e,"preserved"),o=Ji(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`,a=r.length>0||o.length>0,s=a?"remove incomplete":"remove";return`${[`${_e(a?"!":"\u2714",a?"warning":"green",t)} ${_e(s,a?"warning":"heading",t)}`,` ${_e("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${_e("preserved","option",t)}: ${i}`,...o.map((l)=>` ${_e("reason","option",t)}: ${tR(l)}`)].join(`
124
+ `}function DJ(e,t){if(cR(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("remove","heading",t)} cancelled
125
+ `;let n=ia(e,"removed"),r=ia(e,"preserved"),o=ia(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`,a=r.length>0||o.length>0,s=a?"remove incomplete":"remove";return`${[`${_e(a?"!":"\u2714",a?"warning":"green",t)} ${_e(s,a?"warning":"heading",t)}`,` ${_e("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${_e("preserved","option",t)}: ${i}`,...o.map((l)=>` ${_e("reason","option",t)}: ${lR(l)}`)].join(`
125
126
  `)}
126
- `}function wJ(e,t){let n=eR(e,"healthy")===!0,r=Md(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=Go(l)?l:void 0,d=Nd(u,"status");if(d===void 0||d==="healthy")return[];let p=Ji(u,"reasons");return[` ${_e(c,"option",t)}: ${p.length===0?d:p.map(tR).join(", ")}`]});return`${[`${n?_e("\u2714","green",t):_e("\u2716","red",t)} ${_e("doctor","heading",t)}`,` ${_e("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${_e("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${_e("issues","option",t)}:`,...i]].join(`
127
+ `}function qJ(e,t){let n=cR(e,"healthy")===!0,r=Bd(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=oi(l)?l:void 0,d=Vd(u,"status");if(d===void 0||d==="healthy")return[];let p=ia(u,"reasons");return[` ${_e(c,"option",t)}: ${p.length===0?d:p.map(lR).join(", ")}`]});return`${[`${n?_e("\u2714","green",t):_e("\u2716","red",t)} ${_e("doctor","heading",t)}`,` ${_e("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${_e("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${_e("issues","option",t)}:`,...i]].join(`
127
128
  `)}
128
- `}function Md(e,t){if(!Go(e))return;return Go(e[t])?e[t]:void 0}function eR(e,t){return Go(e)?e[t]:void 0}function Nd(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function Ji(e,t){if(!Go(e)||!Array.isArray(e[t]))return[];return e[t]}function tR(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function vJ(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${_e(Xv(e),"dim",t)}
129
- `;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([o])=>o.length));return`${n.map(([o,i])=>` ${_e(o.padEnd(r),"option",t)}: ${Xv(i)}`).join(`
129
+ `}function Bd(e,t){if(!oi(e))return;return oi(e[t])?e[t]:void 0}function cR(e,t){return oi(e)?e[t]:void 0}function Vd(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function ia(e,t){if(!oi(e)||!Array.isArray(e[t]))return[];return e[t]}function lR(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function UJ(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${_e(aR(e),"dim",t)}
130
+ `;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([o])=>o.length));return`${n.map(([o,i])=>` ${_e(o.padEnd(r),"option",t)}: ${aR(i)}`).join(`
130
131
  `)}
131
- `}function RJ(e,t){return Object.entries(e).map(([n,r])=>` ${_e(n,"option",t)}: ${_e(Xv(r),"dim",t)}`)}function Xv(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function TJ(e,t){if(e==="unknown_command")return"run `holycodex --help` to list supported commands";if(e==="invalid_argument")return`holycodex ${t} --help`;if(e==="non_tty_confirmation_required")return"rerun with --yes or use an interactive terminal";if(e==="capability_denied")return"run `holycodex doctor` to inspect capability availability";return}function _e(e,t,n){return ze(e,{red:"error",green:"success",cyan:"focus",dim:"hint",warning:"warning",heading:"heading",option:"option"}[t],n)}class Kc extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function nR(e=Bun.argv.slice(2),t=OJ()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??EJ(),stdoutIsTTY:t.stdoutIsTTY??process.stdout.isTTY===!0,stderrIsTTY:t.stderrIsTTY??process.stderr.isTTY===!0,...t.confirm===void 0?{}:{confirm:t.confirm},...t.installWizard===void 0?{}:{installWizard:t.installWizard},writeStdout:t.writeStdout,writeStderr:t.writeStderr}},r=await Qv(e,n);if((e.length===0||ad(e)||e[0]==="help")&&!hL(e))n.io?.writeStdout?.(Jw(sd(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(hL(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
132
- `);else if(r.envelope.ok)n.io?.writeStdout?.(Qh(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(Qh(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function OJ(){return{stdoutIsTTY:process.stdout.isTTY===!0,stderrIsTTY:process.stderr.isTTY===!0,writeStdout:(e)=>process.stdout.write(e),writeStderr:(e)=>process.stderr.write(e),confirm:async(e)=>{let t=CJ({input:process.stdin,output:process.stderr});try{let n=await t.question(`${e} [y/N] `);return/^(?:y|yes)$/iu.test(n.trim())}finally{t.close()}}}}function hL(e){let t=!1;for(let n of e)if(n==="--json"||n==="--json=true")t=!0;else if(n==="--json=false")t=!1;return t}async function*EJ(){let e=new TextDecoder;for await(let n of process.stdin)if(typeof n==="string")yield n;else yield e.decode(n,{stream:!0});let t=e.decode();if(t.length>0)yield t}Ed();Fh();md();Qa();yd();Ph();Oh();var gne="holycodex";if(import.meta.main)process.exitCode=await nR();export{ct as ArgumentError,Er as CONTEXT7_SPEC,tn as CapabilityInstallStateSchema,Yw as CapabilityStateRecordSchema,os as CodexOfficialPluginManager,Sh as InstallOptionsSchema,Ac as InstallRecordSchema,dd as InstallRequestSchema,T as InstallerError,ro as OfficialPluginManagerError,Qn as PathBoundaryError,pd as PersistedInstallOptionsSchema,Eh as ReadOnlyCodexPluginStatus,jW as STATE_SCHEMA,me as ToolingError,as as WINDOWS_GIT_BASH,eL as applyConflictScreenKey,aL as applyWizardConfigurationKey,nv as assertRootText,bF as context7InstallCommand,ls as createInstallerRuntime,ss as detectContext7Manager,Ev as doctorHolyCodex,Ih as ensureContext7,us as ensureGitBash,pL as executeCommand,ad as helpRequested,id as helpText,sd as helpTopic,fs as installHolyCodex,lv as installNativeAgents,zh as installRecordDigest,Rd as installRequestFromPersistedOptions,gne as packageName,yh as parseArgv,cL as parsePluginInput,Or as pathWithin,HF as persistedOptionsForInstall,kz as preflightContext7,Vo as projectNativeAgents,sv as projectRootAgent,ns as publicManifestPath,Vi as readActiveInstallRecord,nz as readCanonicalBaseVersion,cF as readCanonicalVersion,Lh as readInstallOptions,fd as readInstallationVersion,Fc as readPublicVersion,vd as removeHolyCodex,Th as removeManagedNativeAgents,wd as removeOwnedContext7,qK as renderConflictScreen,Jw as renderHelp,Qh as renderHuman,VK as renderInstallWizardReview,Lc as renderNativeAgent,mL as renderProgress,Cr as resolveInstallerPaths,Rh as rollbackNativeAgentInstall,cv as rootDeveloperInstructions,nR as runBinary,Qv as runCli,Yh as runOpenTuiConflictResolver,Gh as runOpenTuiInstallWizard,Vv as stateFromConflicts,Kv as stateFromRequest,sL as toInstallOptions,ov as updateCanonicalVersion,zz as upgradeHolyCodex,pn as validateInstallOptions,uv as windowsGitBashShellDirective,UF as writeInstallOptions};
132
+ `}function $J(e,t){return Object.entries(e).map(([n,r])=>` ${_e(n,"option",t)}: ${_e(aR(r),"dim",t)}`)}function aR(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function jJ(e,t){if(e==="unknown_command")return"run `holycodex --help` to list supported commands";if(e==="invalid_argument")return`holycodex ${t} --help`;if(e==="non_tty_confirmation_required")return"rerun with --yes or use an interactive terminal";if(e==="capability_denied")return"run `holycodex doctor` to inspect capability availability";return}function _e(e,t,n){return vn(e,{red:"error",green:"success",cyan:"focus",dim:"hint",warning:"warning",heading:"heading",option:"option"}[t],n)}class el extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function uR(e=Bun.argv.slice(2),t=BJ()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??VJ(),stdoutIsTTY:t.stdoutIsTTY??process.stdout.isTTY===!0,stderrIsTTY:t.stderrIsTTY??process.stderr.isTTY===!0,...t.confirm===void 0?{}:{confirm:t.confirm},...t.installWizard===void 0?{}:{installWizard:t.installWizard},writeStdout:t.writeStdout,writeStderr:t.writeStderr}},r=await sR(e,n);if((e.length===0||fd(e)||e[0]==="help")&&!_L(e))n.io?.writeStdout?.(rv(md(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(_L(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
133
+ `);else if(r.envelope.ok)n.io?.writeStdout?.(dg(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(dg(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function BJ(){return{stdoutIsTTY:process.stdout.isTTY===!0,stderrIsTTY:process.stderr.isTTY===!0,writeStdout:(e)=>process.stdout.write(e),writeStderr:(e)=>process.stderr.write(e),confirm:async(e)=>{let t=HJ({input:process.stdin,output:process.stderr});try{let n=await t.question(`${e} [y/N] `);return/^(?:y|yes)$/iu.test(n.trim())}finally{t.close()}}}}function _L(e){let t=!1;for(let n of e)if(n==="--json"||n==="--json=true")t=!0;else if(n==="--json=false")t=!1;return t}async function*VJ(){let e=new TextDecoder;for await(let n of process.stdin)if(typeof n==="string")yield n;else yield e.decode(n,{stream:!0});let t=e.decode();if(t.length>0)yield t}Nd();Zh();wd();us();Rd();Kh();Hh();var Mne="holycodex";if(import.meta.main)process.exitCode=await uR();export{lt as ArgumentError,nr as CONTEXT7_SPEC,nn as CapabilityInstallStateSchema,iv as CapabilityStateRecordSchema,Qo as CodexOfficialPluginManager,Nh as InstallOptionsSchema,Uc as InstallRecordSchema,xd as InstallRequestSchema,_ as InstallerError,co as OfficialPluginManagerError,tr as PathBoundaryError,Sd as PersistedInstallOptionsSchema,Bh as ReadOnlyCodexPluginStatus,ez as STATE_SCHEMA,Se as ToolingError,dL as applyConflictScreenKey,mL as applyWizardConfigurationKey,dv as assertRootText,OF as context7InstallCommand,xs as createInstallerRuntime,gs as detectContext7Manager,Fv as doctorHolyCodex,Wh as ensureContext7,SL as executeCommand,fd as helpRequested,pd as helpText,md as helpTopic,bs as installHolyCodex,xv as installNativeAgents,ig as installRecordDigest,Pd as installRequestFromPersistedOptions,Mne as packageName,Ah as parseArgv,gL as parsePluginInput,Ar as pathWithin,YF as persistedOptionsForInstall,jz as preflightContext7,Xo as projectNativeAgents,gv as projectRootAgent,fs as publicManifestPath,ra as readActiveInstallRecord,hz as readCanonicalBaseVersion,mF as readCanonicalVersion,Xh as readInstallOptions,bd as readInstallationVersion,Hc as readPublicVersion,Id as removeHolyCodex,$h as removeManagedNativeAgents,Ed as removeOwnedContext7,YK as renderConflictScreen,rv as renderHelp,dg as renderHuman,iJ as renderInstallWizardReview,Bc as renderNativeAgent,wL as renderProgress,Pr as resolveInstallerPaths,Uh as rollbackNativeAgentInstall,yv as rootDeveloperInstructions,uR as runBinary,sR as runCli,cg as runOpenTuiConflictResolver,sg as runOpenTuiInstallWizard,Zv as stateFromConflicts,eR as stateFromRequest,hL as toInstallOptions,fv as updateCanonicalVersion,rK as upgradeHolyCodex,dn as validateInstallOptions,JF as writeInstallOptions};