holycodex 0.16.9-dev.103.1 → 0.16.9-dev.106.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,45 +1,49 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var S=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Cr(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&&Yh(r.value))Cr(r.value,t)}Object.freeze(e)}function Yh(e){return typeof e==="object"&&e!==null}var oo="0.15",Rn="state-0.16";var Qv=()=>{};function ps(e){return{ok:!0,value:e}}function Bi(e){return{ok:!1,error:e}}function Kc(e,t){return new at("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var at;var fs=S(()=>{at=class at extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,Cr(this.details),Object.freeze(this)}}});function x(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 Zh=(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)}}}},xe=(e)=>e,Jc=(e)=>()=>e,Gc,Ho,Fd,Yc;var ee=S(()=>{Gc=Jc(!0),Ho=Jc(!1),Fd=Jc(void 0),Yc=Fd});var Xc=(e)=>(t,n)=>t===n||e(t,n),NF=(e,t)=>e===t,FF=()=>NF,LF,Xh,eR,tR=(e)=>Xc((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 Qc=S(()=>{ee();LF=FF(),Xh=h(2,(e,t)=>Xc((n,r)=>e(t(n),t(r)))),eR=Xh(LF,(e)=>e.getTime())});var el,te=(e,t)=>{if(!el)globalThis["effect/GlobalValue"]??=new Map,el=globalThis["effect/GlobalValue"];if(!el.has(e))el.set(e,t());return el.get(e)};var Lt=(e)=>typeof e==="string",Tn=(e)=>typeof e==="number",Vi=(e)=>typeof e==="boolean",Bo=(e)=>typeof e==="bigint",Wi=(e)=>typeof e==="symbol",Vo,nR=(e)=>e===void 0,rR=(e)=>!1,tl=(e)=>typeof e==="object"&&e!==null,tn=(e)=>tl(e)||Vo(e),j,nl,zi=(e)=>e===null||e===void 0,oR=(e)=>e!==null&&e!==void 0,Dd=(e)=>e instanceof Date,Qh=(e)=>typeof e==="string"||j(e,Symbol.iterator),eg=(e)=>tl(e)&&!Array.isArray(e),iR=(e)=>j(e,"then")&&Vo(e.then);var Ce=S(()=>{ee();Vo=Zh,j=h(2,(e,t)=>tn(e)&&(t in e)),nl=h(2,(e,t)=>j(e,"_tag")&&e._tag===t)});var Ki=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class ng{_state;constructor(e,t,n,r){if(zi(t)&&zi(e))t=Math.random()*4294967295>>>0,e=0;else if(zi(t))t=e,e=0;if(zi(r)&&zi(n))r=this._state?this._state[3]:qF,n=this._state?this._state[2]:DF;else if(zi(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),aR(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*HF+t)/jF}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;BF(this._state,e,t,UF,$F),aR(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 BF(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 aR(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 rg(e){if(typeof e==="object"&&e!==null&&tg in e)return e[tg]();throw Error(Ki("yieldWrapGet"))}var hs,DF=335903614,qF=4150755663,UF=1481765933,$F=1284865837,jF=9007199254740992,HF=134217728,tg,io,cn,sR,VF,WF,Dt,MK;var Wo=S(()=>{Ce();hs=class hs{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 hs(this.self)}};tg=Symbol.for("effect/Utils/YieldWrap");io=class io{#e;constructor(e){this.#e=e}[tg](){return this.#e}};cn=te("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),sR={effect_internal_function:(e)=>e()},VF={effect_internal_function:(e)=>{try{return e()}finally{}}},WF=sR.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,Dt=WF?sR.effect_internal_function:VF.effect_internal_function,MK=function*(){}.constructor});var og,J,D=(e)=>{if(cn.enabled===!0)return 0;switch(typeof e){case"number":return Ud(e);case"bigint":return Re(e.toString(10));case"boolean":return Re(String(e));case"symbol":return Re(String(e));case"string":return Re(e);case"undefined":return Re("undefined");case"function":case"object":if(e===null)return Re("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return Re("Invalid Date");return D(e.toISOString())}else if(e instanceof URL)return D(e.href);else if(KF(e))return e[J]();else return rl(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},rl=(e)=>{if(!og.has(e))og.set(e,Ud(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return og.get(e)},ae=(e)=>(t)=>t*53^e,qd=(e)=>e&3221225471|e>>>1&1073741824,KF=(e)=>j(e,J),Ud=(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 qd(t)},Re=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return qd(t)},JF=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=x(Re(t[r]),ae(D(e[t[r]])));return qd(n)},$d=(e)=>JF(e,Object.keys(e)),On=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=x(t,ae(D(e[n])));return qd(t)},me=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 Be=S(()=>{ee();Ce();Wo();og=te(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),J=Symbol.for("effect/Hash")});function q(){if(arguments.length===1)return(e)=>jd(e,arguments[0]);return jd(arguments[0],arguments[1])}function jd(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(ol(e)&&ol(t))if(D(e)===D(t)&&e[W](t))return!0;else return cn.enabled&&cn.tester?cn.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(cn.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>jd(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)&&jd(e[i],t[i])))return cn.tester?cn.tester(e,t):!1;return!0}}return cn.tester?cn.tester(e,t):!1}}return cn.enabled&&cn.tester?cn.tester(e,t):!1}var W,ol=(e)=>j(e,W),il=()=>q;var Se=S(()=>{Be();Ce();Wo();W=Symbol.for("effect/Equal")});function GF(e){try{return e.toISOString()}catch{return"Invalid Date"}}function YF(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function al(e){return Lt(e)?JSON.stringify(e):String(e)}function Er(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":Tn(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 ig;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 S=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Ir(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&&ng(r.value))Ir(r.value,t)}Object.freeze(e)}function ng(e){return typeof e==="object"&&e!==null}var so="0.15",Rn="state-0.16";var hR=()=>{};function ms(e){return{ok:!0,value:e}}function Gi(e){return{ok:!1,error:e}}function Qc(e,t){return new st("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var st;var hs=S(()=>{st=class st extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,Ir(this.details),Object.freeze(this)}}});function x(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 rg=(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)}}}},_e=(e)=>e,el=(e)=>()=>e,tl,Wo,Ud,nl;var ee=S(()=>{tl=el(!0),Wo=el(!1),Ud=el(void 0),nl=Ud});var ol=(e)=>(t,n)=>t===n||e(t,n),rL=(e,t)=>e===t,oL=()=>rL,iL,og,gR,yR=(e)=>ol((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 il=S(()=>{ee();iL=oL(),og=h(2,(e,t)=>ol((n,r)=>e(t(n),t(r)))),gR=og(iL,(e)=>e.getTime())});var al,te=(e,t)=>{if(!al)globalThis["effect/GlobalValue"]??=new Map,al=globalThis["effect/GlobalValue"];if(!al.has(e))al.set(e,t());return al.get(e)};var qt=(e)=>typeof e==="string",Tn=(e)=>typeof e==="number",Yi=(e)=>typeof e==="boolean",zo=(e)=>typeof e==="bigint",Zi=(e)=>typeof e==="symbol",Ko,xR=(e)=>e===void 0,SR=(e)=>!1,sl=(e)=>typeof e==="object"&&e!==null,rn=(e)=>sl(e)||Ko(e),H,cl,Xi=(e)=>e===null||e===void 0,bR=(e)=>e!==null&&e!==void 0,Hd=(e)=>e instanceof Date,ig=(e)=>typeof e==="string"||H(e,Symbol.iterator),ag=(e)=>sl(e)&&!Array.isArray(e),_R=(e)=>H(e,"then")&&Ko(e.then);var Ee=S(()=>{ee();Ko=rg,H=h(2,(e,t)=>rn(e)&&(t in e)),cl=h(2,(e,t)=>H(e,"_tag")&&e._tag===t)});var Qi=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class cg{_state;constructor(e,t,n,r){if(Xi(t)&&Xi(e))t=Math.random()*4294967295>>>0,e=0;else if(Xi(t))t=e,e=0;if(Xi(r)&&Xi(n))r=this._state?this._state[3]:sL,n=this._state?this._state[2]:aL;else if(Xi(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),wR(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*dL+t)/uL}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;pL(this._state,e,t,cL,lL),wR(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 pL(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 wR(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 lg(e){if(typeof e==="object"&&e!==null&&sg in e)return e[sg]();throw Error(Qi("yieldWrapGet"))}var ys,aL=335903614,sL=4150755663,cL=1481765933,lL=1284865837,uL=9007199254740992,dL=134217728,sg,co,dn,vR,fL,mL,$t,uJ;var Jo=S(()=>{Ee();ys=class ys{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 ys(this.self)}};sg=Symbol.for("effect/Utils/YieldWrap");co=class co{#e;constructor(e){this.#e=e}[sg](){return this.#e}};dn=te("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),vR={effect_internal_function:(e)=>e()},fL={effect_internal_function:(e)=>{try{return e()}finally{}}},mL=vR.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,$t=mL?vR.effect_internal_function:fL.effect_internal_function,uJ=function*(){}.constructor});var ug,J,q=(e)=>{if(dn.enabled===!0)return 0;switch(typeof e){case"number":return Vd(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 q(e.toISOString())}else if(e instanceof URL)return q(e.href);else if(gL(e))return e[J]();else return ll(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},ll=(e)=>{if(!ug.has(e))ug.set(e,Vd(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return ug.get(e)},ae=(e)=>(t)=>t*53^e,Bd=(e)=>e&3221225471|e>>>1&1073741824,gL=(e)=>H(e,J),Vd=(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 Bd(t)},Oe=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Bd(t)},yL=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=x(Oe(t[r]),ae(q(e[t[r]])));return Bd(n)},Wd=(e)=>yL(e,Object.keys(e)),On=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=x(t,ae(q(e[n])));return Bd(t)},me=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 Be=S(()=>{ee();Ee();Jo();ug=te(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),J=Symbol.for("effect/Hash")});function U(){if(arguments.length===1)return(e)=>zd(e,arguments[0]);return zd(arguments[0],arguments[1])}function zd(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(ul(e)&&ul(t))if(q(e)===q(t)&&e[W](t))return!0;else return dn.enabled&&dn.tester?dn.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(dn.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>zd(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)&&zd(e[i],t[i])))return dn.tester?dn.tester(e,t):!1;return!0}}return dn.tester?dn.tester(e,t):!1}}return dn.enabled&&dn.tester?dn.tester(e,t):!1}var W,ul=(e)=>H(e,W),dl=()=>U;var we=S(()=>{Be();Ee();Jo();W=Symbol.for("effect/Equal")});function xL(e){try{return e.toISOString()}catch{return"Invalid Date"}}function SL(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function pl(e){return qt(e)?JSON.stringify(e):String(e)}function Ar(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":Tn(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 dg;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(Dd(l))return GF(l);if(!t?.ignoreToString&&j(l,"toString")&&Vo(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let d=YF(l);if(l instanceof Error&&l.cause)return`${d} (cause: ${c(l.cause,u)})`;return d}if(Lt(l))return JSON.stringify(l);if(Tn(l)||l==null||Vi(l)||Wi(l))return String(l);if(Bo(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return ig;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(tn(l)){if(r.has(l))return ig;r.add(l);let d=s(l);if(!o||d.length<=1){let f=`{${d.map((m)=>`${al(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,f)}let p=`{
7
- ${d.map((f)=>`${i(u+1)}${al(f)}: ${c(l[f],u+1)}`).join(`,
6
+ ${i(u)}]`}if(Hd(l))return xL(l);if(!t?.ignoreToString&&H(l,"toString")&&Ko(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let d=SL(l);if(l instanceof Error&&l.cause)return`${d} (cause: ${c(l.cause,u)})`;return d}if(qt(l))return JSON.stringify(l);if(Tn(l)||l==null||Yi(l)||Zi(l))return String(l);if(zo(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return dg;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(rn(l)){if(r.has(l))return dg;r.add(l);let d=s(l);if(!o||d.length<=1){let f=`{${d.map((m)=>`${pl(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,f)}let p=`{
7
+ ${d.map((f)=>`${i(u+1)}${pl(f)}: ${c(l[f],u+1)}`).join(`,
8
8
  `)}
9
- ${i(u)}}`;return a(l,p)}return String(l)}return c(e,0)}var ue,be=(e)=>{try{if(j(e,"toJSON")&&Vo(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(be)}catch{return{}}return uR(e)},ig="[Circular]",Te=(e)=>JSON.stringify(e,null,2),jK,ao=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?Hd(e,t):String(e)}catch{return String(e)}},Hd=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(Ji.fiberRefs!==void 0&&cR(i)?i[ag](Ji.fiberRefs):i):i,t);return n=void 0,r},ag,cR=(e)=>typeof e==="object"&&e!==null&&(ag in e),Ji,lR=(e,t)=>{let n=Ji.fiberRefs;Ji.fiberRefs=e;try{return t()}finally{Ji.fiberRefs=n}},uR=(e)=>{if(cR(e)&&Ji.fiberRefs!==void 0)return e[ag](Ji.fiberRefs);return e};var Xe=S(()=>{Ce();ue=Symbol.for("nodejs.util.inspect.custom");jK={toJSON(){return be(this)},[ue](){return this.toJSON()},toString(){return Te(this.toJSON())}},ag=Symbol.for("effect/Inspectable/Redactable"),Ji=te("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var M=(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 Yi="Async",Zi="Commit",ln="Failure",sl="OnFailure",gs="OnSuccess",ys="OnSuccessAndFailure",un="Success",Bd="Sync",dR="Tag",Xi="UpdateRuntimeFlags",xs="While",Ss="Iterator",Vd="WithRuntime",bs="Yield",cl="RevertFlags";var ZF="3.22.2",ll=()=>ZF;var fR,mR,hR,gR,zo,XF,QF,so,ul,Ko,cg,yR;var co=S(()=>{Se();Be();Ae();Wo();fR=Symbol.for("effect/Effect"),mR=Symbol.for("effect/Stream"),hR=Symbol.for("effect/Sink"),gR=Symbol.for("effect/Channel"),zo={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:ll()},XF={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},QF={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},so={[fR]:zo,[mR]:zo,[hR]:XF,[gR]:QF,[W](e){return this===e},[J](){return me(this,rl(this))},[Symbol.iterator](){return new hs(new io(this))},pipe(){return M(this,arguments)}},ul={[J](){return me(this,$d(this))},[W](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)&&q(this[r],e[r])))return!1;return!0}},Ko={...so,_op:Zi},cg={...Ko,...ul},yR=function(){function e(){}return e.prototype=Ko,e}()});var SR,bR,eL,tL,nL,lg=(e)=>j(e,SR),ug=(e)=>e._tag==="None",dg=(e)=>e._tag==="Some",Wd,dl=(e)=>{let t=Object.create(eL);return t.value=e,t};var pg=S(()=>{Se();Be();Xe();Ce();co();SR=Symbol.for("effect/Option"),bR={...so,[SR]:{_A:(e)=>e},[ue](){return this.toJSON()},toString(){return Te(this.toJSON())}},eL=Object.assign(Object.create(bR),{_tag:"Some",_op:"Some",[W](e){return lg(e)&&dg(e)&&q(this.value,e.value)},[J](){return me(this,ae(D(this._tag))(D(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:be(this.value)}}}),tL=D("None"),nL=Object.assign(Object.create(bR),{_tag:"None",_op:"None",[W](e){return lg(e)&&ug(e)},[J](){return tL},toJSON(){return{_id:"Option",_tag:this._tag}}}),Wd=Object.create(nL)});var fg,wR,rL,oL,zd=(e)=>j(e,fg),mg=(e)=>e._tag==="Left",hg=(e)=>e._tag==="Right",vR=(e)=>{let t=Object.create(oL);return t.left=e,t},RR=(e)=>{let t=Object.create(rL);return t.right=e,t};var TR=S(()=>{Se();Be();Xe();Ce();co();fg=Symbol.for("effect/Either"),wR={...so,[fg]:{_R:(e)=>e},[ue](){return this.toJSON()},toString(){return Te(this.toJSON())}},rL=Object.assign(Object.create(wR),{_tag:"Right",_op:"Right",[W](e){return zd(e)&&hg(e)&&q(this.right,e.right)},[J](){return ae(D(this._tag))(D(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:be(this.right)}}}),oL=Object.assign(Object.create(wR),{_tag:"Left",_op:"Left",[W](e){return zd(e)&&mg(e)&&q(this.left,e.left)},[J](){return ae(D(this._tag))(D(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:be(this.left)}}})});var ce,ie,gg,Le,It,Kd,OR,pl,CR,yg,ER;var dn=S(()=>{ee();TR();ce=RR,ie=vR,gg=zd,Le=mg,It=hg,Kd=h(2,(e,t)=>Le(e)?ie(t(e.left)):ce(e.right)),OR=h(2,(e,t)=>It(e)?ce(t(e.right)):ie(e.left)),pl=h(2,(e,{onLeft:t,onRight:n})=>Le(e)?t(e.left):n(e.right)),CR=pl({onLeft:xe,onRight:xe}),yg=h(2,(e,t)=>{if(It(e))return e.right;throw t(e.left)}),ER=yg(()=>Error("getOrThrow called on a Left"))});var xg=(e)=>e.length>0;var kR=(e)=>(t,n)=>t===n?0:e(t,n),IR,Jd,Sg=(e)=>h(2,(t,n)=>e(t,n)===1);var Gd=S(()=>{ee();IR=kR((e,t)=>e<t?-1:1),Jd=h(2,(e,t)=>kR((n,r)=>e(t(n),t(r))))});var H=()=>Wd,G,Ve,qe,st,De,Xn,AR,lo=(e)=>e==null?H():G(e),pn,PR=(e)=>(...t)=>{try{return G(e(...t))}catch{return H()}},Qn,er,MR,cL=(e)=>h(2,(t,n)=>Ve(t)?!1:e(t.value,n)),lL,NR,FR;var ct=S(()=>{Se();ee();pg();G=dl,Ve=ug,qe=dg,st=h(2,(e,{onNone:t,onSome:n})=>Ve(e)?t():n(e.value)),De=h(2,(e,t)=>Ve(e)?t():e.value),Xn=h(2,(e,t)=>Ve(e)?t():e),AR=h(2,(e,t)=>Ve(e)?G(t()):e),pn=De(Fd),Qn=h(2,(e,t)=>Ve(e)?H():G(t(e.value))),er=h(2,(e,t)=>Ve(e)?H():t(e.value)),MR=h(2,(e,t)=>Ve(e)?H():lo(t(e.value))),lL=il(),NR=cL(lL),FR=h(2,(e,t)=>Ve(e)?!1:t(e.value))});var LR=(...e)=>e;var DR=()=>{};var Qi=(e)=>Array(e),_g,Ue=(e)=>Array.isArray(e)?e:Array.from(e),wg=(e)=>Array.isArray(e)?e:[e],qR,_s,UR,vg,Rg,dL=(e)=>e.length===0,$R,Jo,Pe,jR=(e,t)=>e<0||e>=t.length,pL=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),fL,Tg,uo,ht,HR=(e)=>Pe(e)?G(Og(e)):H(),Og=(e)=>e[e.length-1],tr=(e)=>e.slice(1),mL=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},BR,VR,Cg=(e)=>Array.from(e).reverse(),po,Eg,WR,hL,gL,yL,ws=(e)=>e.slice(),xL,Go,fo=()=>[],Vt=(e)=>[e],nr,fl,Yd,Zd,vs,kg=(e,t)=>{let n=[],r=e,o;while(qe(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},Yo,zR,Ig=(e)=>zR(e,il()),mo;var Qe=S(()=>{Se();Qc();ee();ct();DR();_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}),qR=h(2,(e,{onEmpty:t,onNonEmpty:n})=>Pe(e)?n(ht(e),tr(e)):t()),_s=h(2,(e,t)=>[t,...e]),UR=h(2,(e,t)=>[...e,t]),vg=h(2,(e,t)=>Ue(e).concat(Ue(t))),Rg=Array.isArray,$R=dL,Jo=xg,Pe=xg,fL=h(2,(e,t)=>{let n=Math.floor(t);return jR(n,e)?H():G(e[n])}),Tg=h(2,(e,t)=>{let n=Math.floor(t);if(jR(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),uo=fL(0),ht=Tg(0),BR=h(2,(e,t)=>gL(e,mL(e,t))),VR=h(2,(e,t)=>{let n=Ue(e);return n.slice(pL(t,n),n.length)}),po=h(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),Eg=h(2,(e,t)=>WR(e,t,LR)),WR=h(3,(e,t,n)=>{let r=Ue(e),o=Ue(t);if(Pe(r)&&Pe(o)){let i=[n(ht(r),ht(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[]}),hL=il(),gL=h(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(Pe(n)){if(r>=1)return yL(n,r);return[[],n]}return[n,[]]}),yL=h(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[ws(e),[]]:[_s(e.slice(1,n),ht(e)),e.slice(n)]}),xL=h(3,(e,t,n)=>{let r=Ue(e),o=Ue(t);if(Pe(r)){if(Pe(o))return zR(n)(vg(r,o));return r}return o}),Go=h(2,(e,t)=>xL(e,t,hL)),nr=h(2,(e,t)=>e.map(t)),fl=h(2,(e,t)=>{if($R(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}),Yd=fl(xe),Zd=h(2,(e,t)=>{let n=Ue(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if(qe(i))r.push(i.value)}return r}),vs=h(3,(e,t,n)=>Ue(e).reduce((r,o,i)=>n(r,o,i),t)),Yo=tR,zR=h(2,(e,t)=>{let n=Ue(e);if(Pe(n)){let r=[ht(n)],o=tr(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),mo=h(2,(e,t)=>Ue(e).join(t))});function wL(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 JR,GR,vL=(e)=>Xc((t,n)=>t.length===n.length&&ho(t).every((r,o)=>e(r,Rs(n,o)))),RL,TL,_t=(e)=>{let t=Object.create(TL);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=kr,t.right=kr;break}case"ISingleton":{t.length=1,t.depth=0,t.left=kr,t.right=kr;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=kr,t.right=kr;break}}return t},YR=(e)=>j(e,JR),kr,Dn=()=>kr,ml=(...e)=>EL(e),gt=(e)=>_t({_tag:"ISingleton",a:e}),Xd=(e)=>YR(e)?e:hl(Ue(e)),Ag=(e,t,n)=>{switch(e.backing._tag){case"IArray":{wL(e.backing.array,0,t,n,e.length);break}case"IConcat":{Ag(e.left,t,n),Ag(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]=Rs(e,r),r+=1,o+=1;break}}},OL=(e)=>{switch(e.backing._tag){case"IEmpty":return GR;case"IArray":return e.backing.array;default:{let t=Array(e.length);return Ag(e,t,0),e.backing={_tag:"IArray",array:t},e.left=kr,e.right=kr,e.depth=0,t}}},ho,CL=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return _t({_tag:"IArray",array:Cg(e.backing.array)});case"IConcat":return _t({_tag:"IConcat",left:Zo(e.backing.right),right:Zo(e.backing.left)});case"ISlice":return hl(Cg(ho(e)))}},Zo,hl=(e)=>e.length===0?Dn():e.length===1?gt(e[0]):_t({_tag:"IArray",array:e}),EL=(e)=>hl(e),Rs,ZR,Wt,Pg,En,XR=(e)=>e.length===0,rr=(e)=>e.length>0,Mg=(e)=>Rs(e,0),or,ir=(e)=>Pg(e,1);var Ir=S(()=>{Qe();Se();Qc();ee();Be();Xe();Ae();Ce();JR=Symbol.for("effect/Chunk");GR=[],RL=vL(q),TL={[JR]:{_A:(e)=>e},toString(){return Te(this.toJSON())},toJSON(){return{_id:"Chunk",values:ho(this).map(be)}},[ue](){return this.toJSON()},[W](e){return YR(e)&&RL(this,e)},[J](){return me(this,On(ho(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return GR[Symbol.iterator]();default:return ho(this)[Symbol.iterator]()}},pipe(){return M(this,arguments)}},kr=_t({_tag:"IEmpty"}),ho=OL,Zo=CL,Rs=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?Rs(e.left,t):Rs(e.right,t-e.left.length);case"ISlice":return Rs(e.backing.chunk,t+e.backing.offset)}}),ZR=h(2,(e,t)=>En(e,gt(t))),Wt=h(2,(e,t)=>En(gt(t),e)),Pg=h(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return kr;else switch(e.backing._tag){case"ISlice":return _t({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return Pg(e.right,t-e.left.length);return _t({_tag:"IConcat",left:Pg(e.left,t),right:e.right})}default:return _t({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),En=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 _t({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=En(e.right,t);return _t({_tag:"IConcat",left:e.left,right:r})}else{let r=En(e.right.right,t);if(r.depth===e.depth-3){let o=_t({_tag:"IConcat",left:e.right.left,right:r});return _t({_tag:"IConcat",left:e.left,right:o})}else{let o=_t({_tag:"IConcat",left:e.left,right:e.right.left});return _t({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=En(e,t.left);return _t({_tag:"IConcat",left:r,right:t.right})}else{let r=En(e,t.left.left);if(r.depth===t.depth-3){let o=_t({_tag:"IConcat",left:r,right:t.left.right});return _t({_tag:"IConcat",left:o,right:t.right})}else{let o=_t({_tag:"IConcat",left:t.left.right,right:t.right});return _t({_tag:"IConcat",left:r,right:o})}}}),or=Mg});var Xo=5,Ng,QR,eT,tT;var Qd=S(()=>{Ng=Math.pow(2,5),QR=Ng-1,eT=Ng/2,tT=Ng/4});function kL(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 Qo(e,t){return t>>>e&QR}function ei(e){return 1<<e}function ep(e,t){return kL(e&t-1)}var Fg=S(()=>{Qd()});var nT=(e,t)=>({value:e,previous:t});function ea(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 Lg(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 rT(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 yo{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(H());if(Ve(a))return new yo;return++i.value,new ta(e,r,o,a)}}function qn(e){return nl(e,"EmptyNode")}function AL(e){return qn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function tp(e,t){return qn(e)?!1:t===e.edit}class ta{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(q(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Ve(s))return--i.value,new yo;if(tp(this,e))return this.value=s,this;return new ta(e,r,o,s)}let a=n(H());if(Ve(a))return this;return++i.value,oT(e,t,this.hash,this,r,new ta(e,r,o,a))}}class Dg{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=tp(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 Dg(e,this.hash,c):c[0]}let a=n(H());if(Ve(a))return this;return++i.value,oT(e,t,this.hash,this,r,new ta(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&&q(i,u.key)){let d=u.value,p=o(d);if(p===d)return r;if(Ve(p))return--a.value,Lg(e,l,r);return ea(e,l,new ta(t,n,i,p),r)}}let c=o(H());if(Ve(c))return r;return++a.value,ea(e,s,new ta(t,n,i,c),r)}}class Ts{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=Qo(t,r),l=ei(c),u=ep(a,l),d=a&l,p=tp(this,e);if(!d){let w=new yo().modify(e,t+Xo,n,r,o,i);if(!w)return this;return s.length>=eT?ML(e,c,w,a,s):new Ts(e,a|l,rT(p,u,w,s))}let f=s[u],m=f.modify(e,t+Xo,n,r,o,i);if(f===m)return this;let y=a,g;if(qn(m)){if(y&=~l,!y)return new yo;if(s.length<=2&&AL(s[u^1]))return s[u^1];g=Lg(p,u,s)}else g=ea(p,u,m,s);if(p)return this.mask=y,this.children=g,this;return new Ts(e,y,g)}}class qg{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=Qo(t,r),l=s[c],u=(l||new yo).modify(e,t+Xo,n,r,o,i);if(l===u)return this;let d=tp(this,e),p;if(qn(l)&&!qn(u))++a,p=ea(d,c,u,s);else if(!qn(l)&&qn(u)){if(--a,a<=tT)return PL(e,a,c,s);p=ea(d,c,new yo,s)}else p=ea(d,c,u,s);if(d)return this.size=a,this.children=p,this;return new qg(e,a,p)}}function PL(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&&!qn(l))o[i++]=l,a|=1<<s}return new Ts(e,a,o)}function ML(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 qg(e,s+1,i)}function NL(e,t,n,r,o,i){if(n===o)return new Dg(e,n,[i,r]);let a=Qo(t,n),s=Qo(t,o);if(a===s)return(c)=>new Ts(e,ei(a)|ei(s),[c]);else{let c=a<s?[r,i]:[i,r];return new Ts(e,ei(a)|ei(s),c)}}function oT(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=NL(e,s,n,r,o,i);if(typeof c==="function")a=nT(c,a),s=s+Xo;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var iT=S(()=>{Se();ct();Ce();Fg();Qd()});var aT="effect/HashMap",np,LL,Ug=(e,t,n,r)=>{let o=Object.create(LL);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},op,rp=(e)=>e?cT(e[0],e[1],e[2],e[3],e[4]):H(),sT=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if(qe(e.value))return G({value:t(e.key,e.value.value),cont:n});return rp(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return cT(r.length,r,0,t,n)}default:return rp(n)}},cT=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!qn(i))return sT(i,r,[e,t,n,r,o])}return rp(o)},DL,Os=()=>DL,lT=(e)=>{let t=sp(Os());for(let n of e)na(t,n[0],n[1]);return fT(t)},uT=(e)=>j(e,np),dT=(e)=>e&&qn(e._root),pT,ip,$g,na,qL,ap=(e)=>new op(e,(t)=>t),gl=(e)=>e._size,sp=(e)=>Ug(!0,e._edit+1,e._root,e._size),fT=(e)=>(e._editable=!1,e),cp,mT,lp,hT,jg,Cs;var Hg=S(()=>{Se();ee();ee();Be();Xe();ct();Ae();Ce();Fg();Qd();iT();np=Symbol.for(aT),LL={[np]:np,[Symbol.iterator](){return new op(this,(e,t)=>[e,t])},[J](){let e=D(aT);for(let t of this)e^=x(D(t[0]),ae(D(t[1])));return me(this,e)},[W](e){if(uT(e)){if(e._size!==this._size)return!1;for(let t of this){let n=x(e,ip(t[0],D(t[0])));if(Ve(n))return!1;else if(!q(t[1],n.value))return!1}return!0}return!1},toString(){return Te(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(be)}},[ue](){return this.toJSON()},pipe(){return M(this,arguments)}};op=class op{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=sT(this.map._root,this.f,void 0)}next(){if(Ve(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=rp(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new op(this.map,this.f)}};DL=Ug(!1,0,new yo,0),pT=h(2,(e,t)=>ip(e,t,D(t))),ip=h(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return q(t,r.key)?r.value:H();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&&q(t,c.key))return c.value}}return H()}case"IndexedNode":{let i=Qo(o,n),a=ei(i);if(r.mask&a){r=r.children[ep(r.mask,a)],o+=Xo;break}return H()}case"ArrayNode":{if(r=r.children[Qo(o,n)],r){o+=Xo;break}return H()}default:return H()}}),$g=h(2,(e,t)=>qe(ip(e,t,D(t)))),na=h(3,(e,t,n)=>cp(e,t,()=>G(n))),qL=h(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:Ug(e._editable,e._edit,t,n)}),cp=h(3,(e,t,n)=>mT(e,t,D(t),n)),mT=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 x(e,qL(i,o.value))}),lp=h(2,(e,t)=>cp(e,t,H)),hT=h(2,(e,t)=>Cs(e,Os(),(n,r,o)=>na(n,o,t(r,o)))),jg=h(2,(e,t)=>Cs(e,void 0,(n,r,o)=>t(r,o))),Cs=h(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return qe(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&&!qn(c))if(c._tag==="LeafNode"){if(qe(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var yT="effect/HashSet",up,UL,dp=(e)=>{let t=Object.create(UL);return t._keyMap=e,t},xT=(e)=>j(e,up),$L,yl=()=>$L,ST=(e)=>{let t=pp(yl());for(let n of e)Es(t,n);return fp(t)},bT=(...e)=>{let t=pp(yl());for(let n of e)Es(t,n);return fp(t)},_T,wT=(e)=>gl(e._keyMap),pp=(e)=>dp(sp(e._keyMap)),fp=(e)=>(e._keyMap._editable=!1,e),Bg,Es,Vg,vT,RT,TT,OT;var CT=S(()=>{Se();ee();Be();Xe();Ae();Ce();Hg();up=Symbol.for(yT),UL={[up]:up,[Symbol.iterator](){return ap(this._keyMap)},[J](){return me(this,ae(D(this._keyMap))(D(yT)))},[W](e){if(xT(e))return gl(this._keyMap)===gl(e._keyMap)&&q(this._keyMap,e._keyMap);return!1},toString(){return Te(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(be)}},[ue](){return this.toJSON()},pipe(){return M(this,arguments)}},$L=dp(Os()),_T=h(2,(e,t)=>$g(e._keyMap,t)),Bg=h(2,(e,t)=>{let n=pp(e);return t(n),fp(n)}),Es=h(2,(e,t)=>e._keyMap._editable?(na(t,!0)(e._keyMap),e):dp(na(t,!0)(e._keyMap))),Vg=h(2,(e,t)=>e._keyMap._editable?(lp(t)(e._keyMap),e):dp(lp(t)(e._keyMap))),vT=h(2,(e,t)=>Bg(e,(n)=>{for(let r of t)Vg(n,r)})),RT=h(2,(e,t)=>Bg(yl(),(n)=>{TT(e,(r)=>Es(n,r));for(let r of t)Es(n,r)})),TT=h(2,(e,t)=>jg(e._keyMap,(n,r)=>t(r))),OT=h(3,(e,t,n)=>Cs(e._keyMap,t,(r,o,i)=>n(r,i)))});var Ar,ET,ra,kT,xl,oa,Wg,zg,xo,ia;var aa=S(()=>{CT();Ar=yl,ET=ST,ra=bT,kT=_T,xl=wT,oa=Es,Wg=Vg,zg=vT,xo=RT,ia=OT});var Is="Die",ti="Empty",ni="Fail",sa="Interrupt",ca="Parallel",la="Sequential";var PT="effect/Cause",Gg,BL,As,So,Ps=(e)=>{let t=Object.create(As);return t._tag=ni,t.error=e,t},kn=(e)=>{let t=Object.create(As);return t._tag=Is,t.defect=e,t},ar=(e)=>{let t=Object.create(As);return t._tag=sa,t.fiberId=e,t},pa=(e,t)=>{let n=Object.create(As);return n._tag=ca,n.left=e,n.right=t,n},zt=(e,t)=>{let n=Object.create(As);return n._tag=la,n.left=e,n.right=t,n},MT=(e)=>j(e,Gg),Yg=(e)=>e._tag===ti,NT=(e)=>e._tag===ni,mp=(e)=>{if(e._tag===ti)return!0;return ua(e,!0,(t,n)=>{switch(n._tag){case ti:return G(t);case Is:case ni:case sa:return G(!1);default:return H()}})},hp=(e)=>qe(FT(e)),Ms=(e)=>xp(void 0,KL)(e),Zg=(e)=>Zo(ua(e,Dn(),(t,n)=>n._tag===ni?G(x(t,Wt(n.error))):H())),Xg=(e)=>Zo(ua(e,Dn(),(t,n)=>n._tag===Is?G(x(t,Wt(n.defect))):H())),Qg=(e)=>ua(e,Ar(),(t,n)=>n._tag===sa?G(x(t,oa(n.fiberId))):H()),ey=(e)=>ty(e,(t)=>t._tag===ni?G(t.error):H()),gp=(e)=>{let t=ey(e);switch(t._tag){case"None":return ce(e);case"Some":return ie(t.value)}},FT=(e)=>ty(e,(t)=>t._tag===sa?G(t.fiberId):H()),yp=(e)=>ny(e,{onEmpty:So,onFail:()=>So,onDie:kn,onInterrupt:ar,onSequential:zt,onParallel:pa}),LT=(e)=>ny(e,{onEmpty:So,onFail:kn,onDie:kn,onInterrupt:ar,onSequential:zt,onParallel:pa}),VL=(e,t)=>{let n=gt(e),r=gt(t);while(rr(n)&&rr(r)){let[o,i]=x(or(n),ua([Ar(),Dn()],([c,l],u)=>{let[d,p]=Kg(u);return G([x(c,xo(d)),x(l,En(p))])})),[a,s]=x(or(r),ua([Ar(),Dn()],([c,l],u)=>{let[d,p]=Kg(u);return G([x(c,xo(d)),x(l,En(p))])}));if(!q(o,a))return!1;n=i,r=s}return!0},WL=(e)=>zL(gt(e),Dn()),zL=(e,t)=>{while(!0){let[n,r]=x(e,vs([Ar(),Dn()],([i,a],s)=>{let[c,l]=Kg(s);return[x(i,xo(c)),x(a,En(l))]})),o=xl(n)>0?x(t,Wt(n)):t;if(XR(r))return Zo(o);e=r,t=o}throw Error(Ki("Cause.flattenCauseLoop"))},ty,Kg=(e)=>{let t=e,n=[],r=Ar(),o=Dn();while(t!==void 0)switch(t._tag){case ti:{if(n.length===0)return[r,o];t=n.pop();break}case ni:{if(r=oa(r,ml(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case Is:{if(r=oa(r,ml(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case sa:{if(r=oa(r,ml(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case la:{switch(t.left._tag){case ti:{t=t.right;break}case la:{t=zt(t.left.left,zt(t.left.right,t.right));break}case ca:{t=pa(zt(t.left.left,t.right),zt(t.left.right,t.right));break}default:{o=Wt(o,t.right),t=t.left;break}}break}case ca:{n.push(t.right),t=t.left;break}}throw Error(Ki("Cause.evaluateCauseLoop"))},KL,IT="SequentialCase",AT="ParallelCase",ny,ua,xp,sr=(e,t)=>{if(Ms(e))return"All fibers interrupted without errors.";return Sl(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
- ${DT(n.cause," ")}
9
+ ${i(u)}}`;return a(l,p)}return String(l)}return c(e,0)}var de,ve=(e)=>{try{if(H(e,"toJSON")&&Ko(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(ve)}catch{return{}}return OR(e)},dg="[Circular]",Ce=(e)=>JSON.stringify(e,null,2),xJ,lo=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?Kd(e,t):String(e)}catch{return String(e)}},Kd=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(ea.fiberRefs!==void 0&&RR(i)?i[pg](ea.fiberRefs):i):i,t);return n=void 0,r},pg,RR=(e)=>typeof e==="object"&&e!==null&&(pg in e),ea,TR=(e,t)=>{let n=ea.fiberRefs;ea.fiberRefs=e;try{return t()}finally{ea.fiberRefs=n}},OR=(e)=>{if(RR(e)&&ea.fiberRefs!==void 0)return e[pg](ea.fiberRefs);return e};var et=S(()=>{Ee();de=Symbol.for("nodejs.util.inspect.custom");xJ={toJSON(){return ve(this)},[de](){return this.toJSON()},toString(){return Ce(this.toJSON())}},pg=Symbol.for("effect/Inspectable/Redactable"),ea=te("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 Pe=()=>{};var na="Async",ra="Commit",pn="Failure",fl="OnFailure",xs="OnSuccess",Ss="OnSuccessAndFailure",fn="Success",Jd="Sync",CR="Tag",oa="UpdateRuntimeFlags",bs="While",_s="Iterator",Gd="WithRuntime",ws="Yield",ml="RevertFlags";var bL="3.22.2",hl=()=>bL;var kR,IR,AR,PR,Go,_L,wL,uo,gl,Yo,mg,MR;var po=S(()=>{we();Be();Pe();Jo();kR=Symbol.for("effect/Effect"),IR=Symbol.for("effect/Stream"),AR=Symbol.for("effect/Sink"),PR=Symbol.for("effect/Channel"),Go={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:hl()},_L={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},wL={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},uo={[kR]:Go,[IR]:Go,[AR]:_L,[PR]:wL,[W](e){return this===e},[J](){return me(this,ll(this))},[Symbol.iterator](){return new ys(new co(this))},pipe(){return F(this,arguments)}},gl={[J](){return me(this,Wd(this))},[W](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)&&U(this[r],e[r])))return!1;return!0}},Yo={...uo,_op:ra},mg={...Yo,...gl},MR=function(){function e(){}return e.prototype=Yo,e}()});var FR,LR,vL,RL,TL,hg=(e)=>H(e,FR),gg=(e)=>e._tag==="None",yg=(e)=>e._tag==="Some",Yd,yl=(e)=>{let t=Object.create(vL);return t.value=e,t};var xg=S(()=>{we();Be();et();Ee();po();FR=Symbol.for("effect/Option"),LR={...uo,[FR]:{_A:(e)=>e},[de](){return this.toJSON()},toString(){return Ce(this.toJSON())}},vL=Object.assign(Object.create(LR),{_tag:"Some",_op:"Some",[W](e){return hg(e)&&yg(e)&&U(this.value,e.value)},[J](){return me(this,ae(q(this._tag))(q(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:ve(this.value)}}}),RL=q("None"),TL=Object.assign(Object.create(LR),{_tag:"None",_op:"None",[W](e){return hg(e)&&gg(e)},[J](){return RL},toJSON(){return{_id:"Option",_tag:this._tag}}}),Yd=Object.create(TL)});var Sg,qR,OL,CL,Zd=(e)=>H(e,Sg),bg=(e)=>e._tag==="Left",_g=(e)=>e._tag==="Right",$R=(e)=>{let t=Object.create(CL);return t.left=e,t},UR=(e)=>{let t=Object.create(OL);return t.right=e,t};var jR=S(()=>{we();Be();et();Ee();po();Sg=Symbol.for("effect/Either"),qR={...uo,[Sg]:{_R:(e)=>e},[de](){return this.toJSON()},toString(){return Ce(this.toJSON())}},OL=Object.assign(Object.create(qR),{_tag:"Right",_op:"Right",[W](e){return Zd(e)&&_g(e)&&U(this.right,e.right)},[J](){return ae(q(this._tag))(q(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:ve(this.right)}}}),CL=Object.assign(Object.create(qR),{_tag:"Left",_op:"Left",[W](e){return Zd(e)&&bg(e)&&U(this.left,e.left)},[J](){return ae(q(this._tag))(q(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:ve(this.left)}}})});var ce,ie,wg,Fe,At,Xd,HR,xl,BR,vg,VR;var mn=S(()=>{ee();jR();ce=UR,ie=$R,wg=Zd,Fe=bg,At=_g,Xd=h(2,(e,t)=>Fe(e)?ie(t(e.left)):ce(e.right)),HR=h(2,(e,t)=>At(e)?ce(t(e.right)):ie(e.left)),xl=h(2,(e,{onLeft:t,onRight:n})=>Fe(e)?t(e.left):n(e.right)),BR=xl({onLeft:_e,onRight:_e}),vg=h(2,(e,t)=>{if(At(e))return e.right;throw t(e.left)}),VR=vg(()=>Error("getOrThrow called on a Left"))});var Rg=(e)=>e.length>0;var WR=(e)=>(t,n)=>t===n?0:e(t,n),zR,Qd,Tg=(e)=>h(2,(t,n)=>e(t,n)===1);var ep=S(()=>{ee();zR=WR((e,t)=>e<t?-1:1),Qd=h(2,(e,t)=>WR((n,r)=>e(t(n),t(r))))});var B=()=>Yd,Y,Ve,De,ct,Le,Qn,KR,fo=(e)=>e==null?B():Y(e),hn,JR=(e)=>(...t)=>{try{return Y(e(...t))}catch{return B()}},er,tr,GR,AL=(e)=>h(2,(t,n)=>Ve(t)?!1:e(t.value,n)),PL,YR,ZR;var lt=S(()=>{we();ee();xg();Y=yl,Ve=gg,De=yg,ct=h(2,(e,{onNone:t,onSome:n})=>Ve(e)?t():n(e.value)),Le=h(2,(e,t)=>Ve(e)?t():e.value),Qn=h(2,(e,t)=>Ve(e)?t():e),KR=h(2,(e,t)=>Ve(e)?Y(t()):e),hn=Le(Ud),er=h(2,(e,t)=>Ve(e)?B():Y(t(e.value))),tr=h(2,(e,t)=>Ve(e)?B():t(e.value)),GR=h(2,(e,t)=>Ve(e)?B():fo(t(e.value))),PL=dl(),YR=AL(PL),ZR=h(2,(e,t)=>Ve(e)?!1:t(e.value))});var XR=(...e)=>e;var QR=()=>{};var ia=(e)=>Array(e),Cg,qe=(e)=>Array.isArray(e)?e:Array.from(e),Eg=(e)=>Array.isArray(e)?e:[e],eT,vs,tT,kg,Ig,NL=(e)=>e.length===0,nT,Zo,Me,rT=(e,t)=>e<0||e>=t.length,FL=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),LL,Ag,mo,gt,oT=(e)=>Me(e)?Y(Pg(e)):B(),Pg=(e)=>e[e.length-1],nr=(e)=>e.slice(1),DL=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},iT,aT,Mg=(e)=>Array.from(e).reverse(),ho,Ng,sT,qL,$L,UL,Rs=(e)=>e.slice(),jL,Xo,go=()=>[],zt=(e)=>[e],rr,Sl,tp,np,Ts,Fg=(e,t)=>{let n=[],r=e,o;while(De(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},Qo,cT,Lg=(e)=>cT(e,dl()),yo;var tt=S(()=>{we();il();ee();lt();QR();Cg=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}),eT=h(2,(e,{onEmpty:t,onNonEmpty:n})=>Me(e)?n(gt(e),nr(e)):t()),vs=h(2,(e,t)=>[t,...e]),tT=h(2,(e,t)=>[...e,t]),kg=h(2,(e,t)=>qe(e).concat(qe(t))),Ig=Array.isArray,nT=NL,Zo=Rg,Me=Rg,LL=h(2,(e,t)=>{let n=Math.floor(t);return rT(n,e)?B():Y(e[n])}),Ag=h(2,(e,t)=>{let n=Math.floor(t);if(rT(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),mo=LL(0),gt=Ag(0),iT=h(2,(e,t)=>$L(e,DL(e,t))),aT=h(2,(e,t)=>{let n=qe(e);return n.slice(FL(t,n),n.length)}),ho=h(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),Ng=h(2,(e,t)=>sT(e,t,XR)),sT=h(3,(e,t,n)=>{let r=qe(e),o=qe(t);if(Me(r)&&Me(o)){let i=[n(gt(r),gt(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[]}),qL=dl(),$L=h(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(Me(n)){if(r>=1)return UL(n,r);return[[],n]}return[n,[]]}),UL=h(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[Rs(e),[]]:[vs(e.slice(1,n),gt(e)),e.slice(n)]}),jL=h(3,(e,t,n)=>{let r=qe(e),o=qe(t);if(Me(r)){if(Me(o))return cT(n)(kg(r,o));return r}return o}),Xo=h(2,(e,t)=>jL(e,t,qL)),rr=h(2,(e,t)=>e.map(t)),Sl=h(2,(e,t)=>{if(nT(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}),tp=Sl(_e),np=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}),Ts=h(3,(e,t,n)=>qe(e).reduce((r,o,i)=>n(r,o,i),t)),Qo=yR,cT=h(2,(e,t)=>{let n=qe(e);if(Me(n)){let r=[gt(n)],o=nr(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),yo=h(2,(e,t)=>qe(e).join(t))});function WL(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 uT,dT,zL=(e)=>ol((t,n)=>t.length===n.length&&xo(t).every((r,o)=>e(r,Os(n,o)))),KL,JL,wt=(e)=>{let t=Object.create(JL);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=Pr,t.right=Pr;break}case"ISingleton":{t.length=1,t.depth=0,t.left=Pr,t.right=Pr;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=Pr,t.right=Pr;break}}return t},pT=(e)=>H(e,uT),Pr,$n=()=>Pr,bl=(...e)=>ZL(e),yt=(e)=>wt({_tag:"ISingleton",a:e}),rp=(e)=>pT(e)?e:_l(qe(e)),Dg=(e,t,n)=>{switch(e.backing._tag){case"IArray":{WL(e.backing.array,0,t,n,e.length);break}case"IConcat":{Dg(e.left,t,n),Dg(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]=Os(e,r),r+=1,o+=1;break}}},GL=(e)=>{switch(e.backing._tag){case"IEmpty":return dT;case"IArray":return e.backing.array;default:{let t=Array(e.length);return Dg(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Pr,e.right=Pr,e.depth=0,t}}},xo,YL=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return wt({_tag:"IArray",array:Mg(e.backing.array)});case"IConcat":return wt({_tag:"IConcat",left:ei(e.backing.right),right:ei(e.backing.left)});case"ISlice":return _l(Mg(xo(e)))}},ei,_l=(e)=>e.length===0?$n():e.length===1?yt(e[0]):wt({_tag:"IArray",array:e}),ZL=(e)=>_l(e),Os,fT,Kt,qg,En,mT=(e)=>e.length===0,or=(e)=>e.length>0,$g=(e)=>Os(e,0),ir,ar=(e)=>qg(e,1);var Mr=S(()=>{tt();we();il();ee();Be();et();Pe();Ee();uT=Symbol.for("effect/Chunk");dT=[],KL=zL(U),JL={[uT]:{_A:(e)=>e},toString(){return Ce(this.toJSON())},toJSON(){return{_id:"Chunk",values:xo(this).map(ve)}},[de](){return this.toJSON()},[W](e){return pT(e)&&KL(this,e)},[J](){return me(this,On(xo(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return dT[Symbol.iterator]();default:return xo(this)[Symbol.iterator]()}},pipe(){return F(this,arguments)}},Pr=wt({_tag:"IEmpty"}),xo=GL,ei=YL,Os=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?Os(e.left,t):Os(e.right,t-e.left.length);case"ISlice":return Os(e.backing.chunk,t+e.backing.offset)}}),fT=h(2,(e,t)=>En(e,yt(t))),Kt=h(2,(e,t)=>En(yt(t),e)),qg=h(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return Pr;else switch(e.backing._tag){case"ISlice":return wt({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return qg(e.right,t-e.left.length);return wt({_tag:"IConcat",left:qg(e.left,t),right:e.right})}default:return wt({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),En=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 wt({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=En(e.right,t);return wt({_tag:"IConcat",left:e.left,right:r})}else{let r=En(e.right.right,t);if(r.depth===e.depth-3){let o=wt({_tag:"IConcat",left:e.right.left,right:r});return wt({_tag:"IConcat",left:e.left,right:o})}else{let o=wt({_tag:"IConcat",left:e.left,right:e.right.left});return wt({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=En(e,t.left);return wt({_tag:"IConcat",left:r,right:t.right})}else{let r=En(e,t.left.left);if(r.depth===t.depth-3){let o=wt({_tag:"IConcat",left:r,right:t.left.right});return wt({_tag:"IConcat",left:o,right:t.right})}else{let o=wt({_tag:"IConcat",left:t.left.right,right:t.right});return wt({_tag:"IConcat",left:r,right:o})}}}),ir=$g});var ti=5,Ug,hT,gT,yT;var op=S(()=>{Ug=Math.pow(2,5),hT=Ug-1,gT=Ug/2,yT=Ug/4});function XL(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 ni(e,t){return t>>>e&hT}function ri(e){return 1<<e}function ip(e,t){return XL(e&t-1)}var jg=S(()=>{op()});var xT=(e,t)=>({value:e,previous:t});function aa(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 Hg(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 ST(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 bo{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(B());if(Ve(a))return new bo;return++i.value,new sa(e,r,o,a)}}function Un(e){return cl(e,"EmptyNode")}function eD(e){return Un(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function ap(e,t){return Un(e)?!1:t===e.edit}class sa{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(U(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Ve(s))return--i.value,new bo;if(ap(this,e))return this.value=s,this;return new sa(e,r,o,s)}let a=n(B());if(Ve(a))return this;return++i.value,bT(e,t,this.hash,this,r,new sa(e,r,o,a))}}class Bg{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=ap(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 Bg(e,this.hash,c):c[0]}let a=n(B());if(Ve(a))return this;return++i.value,bT(e,t,this.hash,this,r,new sa(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&&U(i,u.key)){let d=u.value,p=o(d);if(p===d)return r;if(Ve(p))return--a.value,Hg(e,l,r);return aa(e,l,new sa(t,n,i,p),r)}}let c=o(B());if(Ve(c))return r;return++a.value,aa(e,s,new sa(t,n,i,c),r)}}class Cs{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=ni(t,r),l=ri(c),u=ip(a,l),d=a&l,p=ap(this,e);if(!d){let _=new bo().modify(e,t+ti,n,r,o,i);if(!_)return this;return s.length>=gT?nD(e,c,_,a,s):new Cs(e,a|l,ST(p,u,_,s))}let f=s[u],m=f.modify(e,t+ti,n,r,o,i);if(f===m)return this;let y=a,g;if(Un(m)){if(y&=~l,!y)return new bo;if(s.length<=2&&eD(s[u^1]))return s[u^1];g=Hg(p,u,s)}else g=aa(p,u,m,s);if(p)return this.mask=y,this.children=g,this;return new Cs(e,y,g)}}class Vg{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=ni(t,r),l=s[c],u=(l||new bo).modify(e,t+ti,n,r,o,i);if(l===u)return this;let d=ap(this,e),p;if(Un(l)&&!Un(u))++a,p=aa(d,c,u,s);else if(!Un(l)&&Un(u)){if(--a,a<=yT)return tD(e,a,c,s);p=aa(d,c,new bo,s)}else p=aa(d,c,u,s);if(d)return this.size=a,this.children=p,this;return new Vg(e,a,p)}}function tD(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&&!Un(l))o[i++]=l,a|=1<<s}return new Cs(e,a,o)}function nD(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 Vg(e,s+1,i)}function rD(e,t,n,r,o,i){if(n===o)return new Bg(e,n,[i,r]);let a=ni(t,n),s=ni(t,o);if(a===s)return(c)=>new Cs(e,ri(a)|ri(s),[c]);else{let c=a<s?[r,i]:[i,r];return new Cs(e,ri(a)|ri(s),c)}}function bT(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=xT(c,a),s=s+ti;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var _T=S(()=>{we();lt();Ee();jg();op()});var wT="effect/HashMap",sp,iD,Wg=(e,t,n,r)=>{let o=Object.create(iD);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},lp,cp=(e)=>e?RT(e[0],e[1],e[2],e[3],e[4]):B(),vT=(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 cp(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return RT(r.length,r,0,t,n)}default:return cp(n)}},RT=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!Un(i))return vT(i,r,[e,t,n,r,o])}return cp(o)},aD,Es=()=>aD,TT=(e)=>{let t=pp(Es());for(let n of e)ca(t,n[0],n[1]);return kT(t)},OT=(e)=>H(e,sp),CT=(e)=>e&&Un(e._root),ET,up,zg,ca,sD,dp=(e)=>new lp(e,(t)=>t),wl=(e)=>e._size,pp=(e)=>Wg(!0,e._edit+1,e._root,e._size),kT=(e)=>(e._editable=!1,e),fp,IT,mp,AT,Kg,ks;var Jg=S(()=>{we();ee();ee();Be();et();lt();Pe();Ee();jg();op();_T();sp=Symbol.for(wT),iD={[sp]:sp,[Symbol.iterator](){return new lp(this,(e,t)=>[e,t])},[J](){let e=q(wT);for(let t of this)e^=x(q(t[0]),ae(q(t[1])));return me(this,e)},[W](e){if(OT(e)){if(e._size!==this._size)return!1;for(let t of this){let n=x(e,up(t[0],q(t[0])));if(Ve(n))return!1;else if(!U(t[1],n.value))return!1}return!0}return!1},toString(){return Ce(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(ve)}},[de](){return this.toJSON()},pipe(){return F(this,arguments)}};lp=class lp{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=vT(this.map._root,this.f,void 0)}next(){if(Ve(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=cp(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new lp(this.map,this.f)}};aD=Wg(!1,0,new bo,0),ET=h(2,(e,t)=>up(e,t,q(t))),up=h(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return U(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&&U(t,c.key))return c.value}}return B()}case"IndexedNode":{let i=ni(o,n),a=ri(i);if(r.mask&a){r=r.children[ip(r.mask,a)],o+=ti;break}return B()}case"ArrayNode":{if(r=r.children[ni(o,n)],r){o+=ti;break}return B()}default:return B()}}),zg=h(2,(e,t)=>De(up(e,t,q(t)))),ca=h(3,(e,t,n)=>fp(e,t,()=>Y(n))),sD=h(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:Wg(e._editable,e._edit,t,n)}),fp=h(3,(e,t,n)=>IT(e,t,q(t),n)),IT=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 x(e,sD(i,o.value))}),mp=h(2,(e,t)=>fp(e,t,B)),AT=h(2,(e,t)=>ks(e,Es(),(n,r,o)=>ca(n,o,t(r,o)))),Kg=h(2,(e,t)=>ks(e,void 0,(n,r,o)=>t(r,o))),ks=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&&!Un(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 MT="effect/HashSet",hp,cD,gp=(e)=>{let t=Object.create(cD);return t._keyMap=e,t},NT=(e)=>H(e,hp),lD,vl=()=>lD,FT=(e)=>{let t=yp(vl());for(let n of e)Is(t,n);return xp(t)},LT=(...e)=>{let t=yp(vl());for(let n of e)Is(t,n);return xp(t)},DT,qT=(e)=>wl(e._keyMap),yp=(e)=>gp(pp(e._keyMap)),xp=(e)=>(e._keyMap._editable=!1,e),Gg,Is,Yg,$T,UT,jT,HT;var BT=S(()=>{we();ee();Be();et();Pe();Ee();Jg();hp=Symbol.for(MT),cD={[hp]:hp,[Symbol.iterator](){return dp(this._keyMap)},[J](){return me(this,ae(q(this._keyMap))(q(MT)))},[W](e){if(NT(e))return wl(this._keyMap)===wl(e._keyMap)&&U(this._keyMap,e._keyMap);return!1},toString(){return Ce(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(ve)}},[de](){return this.toJSON()},pipe(){return F(this,arguments)}},lD=gp(Es()),DT=h(2,(e,t)=>zg(e._keyMap,t)),Gg=h(2,(e,t)=>{let n=yp(e);return t(n),xp(n)}),Is=h(2,(e,t)=>e._keyMap._editable?(ca(t,!0)(e._keyMap),e):gp(ca(t,!0)(e._keyMap))),Yg=h(2,(e,t)=>e._keyMap._editable?(mp(t)(e._keyMap),e):gp(mp(t)(e._keyMap))),$T=h(2,(e,t)=>Gg(e,(n)=>{for(let r of t)Yg(n,r)})),UT=h(2,(e,t)=>Gg(vl(),(n)=>{jT(e,(r)=>Is(n,r));for(let r of t)Is(n,r)})),jT=h(2,(e,t)=>Kg(e._keyMap,(n,r)=>t(r))),HT=h(3,(e,t,n)=>ks(e._keyMap,t,(r,o,i)=>n(r,i)))});var Nr,VT,la,WT,Rl,ua,Zg,Xg,_o,da;var pa=S(()=>{BT();Nr=vl,VT=FT,la=LT,WT=DT,Rl=qT,ua=Is,Zg=Yg,Xg=$T,_o=UT,da=HT});var Ps="Die",oi="Empty",ii="Fail",fa="Interrupt",ma="Parallel",ha="Sequential";var JT="effect/Cause",ty,pD,Ms,wo,Ns=(e)=>{let t=Object.create(Ms);return t._tag=ii,t.error=e,t},kn=(e)=>{let t=Object.create(Ms);return t._tag=Ps,t.defect=e,t},sr=(e)=>{let t=Object.create(Ms);return t._tag=fa,t.fiberId=e,t},xa=(e,t)=>{let n=Object.create(Ms);return n._tag=ma,n.left=e,n.right=t,n},Jt=(e,t)=>{let n=Object.create(Ms);return n._tag=ha,n.left=e,n.right=t,n},GT=(e)=>H(e,ty),ny=(e)=>e._tag===oi,YT=(e)=>e._tag===ii,Sp=(e)=>{if(e._tag===oi)return!0;return ga(e,!0,(t,n)=>{switch(n._tag){case oi:return Y(t);case Ps:case ii:case fa:return Y(!1);default:return B()}})},bp=(e)=>De(ZT(e)),Fs=(e)=>vp(void 0,gD)(e),ry=(e)=>ei(ga(e,$n(),(t,n)=>n._tag===ii?Y(x(t,Kt(n.error))):B())),oy=(e)=>ei(ga(e,$n(),(t,n)=>n._tag===Ps?Y(x(t,Kt(n.defect))):B())),iy=(e)=>ga(e,Nr(),(t,n)=>n._tag===fa?Y(x(t,ua(n.fiberId))):B()),ay=(e)=>sy(e,(t)=>t._tag===ii?Y(t.error):B()),_p=(e)=>{let t=ay(e);switch(t._tag){case"None":return ce(e);case"Some":return ie(t.value)}},ZT=(e)=>sy(e,(t)=>t._tag===fa?Y(t.fiberId):B()),wp=(e)=>cy(e,{onEmpty:wo,onFail:()=>wo,onDie:kn,onInterrupt:sr,onSequential:Jt,onParallel:xa}),XT=(e)=>cy(e,{onEmpty:wo,onFail:kn,onDie:kn,onInterrupt:sr,onSequential:Jt,onParallel:xa}),fD=(e,t)=>{let n=yt(e),r=yt(t);while(or(n)&&or(r)){let[o,i]=x(ir(n),ga([Nr(),$n()],([c,l],u)=>{let[d,p]=Qg(u);return Y([x(c,_o(d)),x(l,En(p))])})),[a,s]=x(ir(r),ga([Nr(),$n()],([c,l],u)=>{let[d,p]=Qg(u);return Y([x(c,_o(d)),x(l,En(p))])}));if(!U(o,a))return!1;n=i,r=s}return!0},mD=(e)=>hD(yt(e),$n()),hD=(e,t)=>{while(!0){let[n,r]=x(e,Ts([Nr(),$n()],([i,a],s)=>{let[c,l]=Qg(s);return[x(i,_o(c)),x(a,En(l))]})),o=Rl(n)>0?x(t,Kt(n)):t;if(mT(r))return ei(o);e=r,t=o}throw Error(Qi("Cause.flattenCauseLoop"))},sy,Qg=(e)=>{let t=e,n=[],r=Nr(),o=$n();while(t!==void 0)switch(t._tag){case oi:{if(n.length===0)return[r,o];t=n.pop();break}case ii:{if(r=ua(r,bl(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case Ps:{if(r=ua(r,bl(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case fa:{if(r=ua(r,bl(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case ha:{switch(t.left._tag){case oi:{t=t.right;break}case ha:{t=Jt(t.left.left,Jt(t.left.right,t.right));break}case ma:{t=xa(Jt(t.left.left,t.right),Jt(t.left.right,t.right));break}default:{o=Kt(o,t.right),t=t.left;break}}break}case ma:{n.push(t.right),t=t.left;break}}throw Error(Qi("Cause.evaluateCauseLoop"))},gD,zT="SequentialCase",KT="ParallelCase",cy,ga,vp,cr=(e,t)=>{if(Fs(e))return"All fibers interrupted without errors.";return Tl(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
+ ${QT(n.cause," ")}
11
11
  }`}).join(`
12
- `)},DT=(e,t)=>{let n=e.stack.split(`
12
+ `)},QT=(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
- ${DT(e.cause,`${t} `)}
16
- ${t}}`;return r},Jg=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(JL(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:Jg(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(da in e)r.span=e[da];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=ZL(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},JL=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(j(e,"toString")&&Vo(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return Hd(e)},GL,YL,ZL=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
15
+ ${QT(e.cause,`${t} `)}
16
+ ${t}}`;return r},ey=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(yD(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:ey(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(ya in e)r.span=e[ya];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=bD(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},yD=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(H(e,"toString")&&Ko(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return Kd(e)},xD,SD,bD=(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=YL.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(GL),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=pn(i.parent),a++}}return r.join(`
19
- `)},da,Sl=(e)=>xp(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[Jg(n)],failCase:(t,n)=>[Jg(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Ns=S(()=>{Qe();Ir();dn();Se();ee();Be();aa();Xe();ct();Ae();Ce();Gg=Symbol.for(PT),BL={_E:(e)=>e},As={[Gg]:BL,[J](){return x(D(PT),ae(D(WL(this))),me(this))},[W](e){return MT(e)&&VL(this,e)},pipe(){return M(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:be(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:be(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:be(this.left),right:be(this.right)}}},toString(){return sr(this)},[ue](){return this.toJSON()}},So=(()=>{let e=Object.create(As);return e._tag=ti,e})(),ty=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 la:case ca:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return H()}),KL={emptyCase:Gc,failCase:Ho,dieCase:Ho,interruptCase:Gc,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},ny=h(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>xp(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)})),ua=h(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=qe(a)?a.value:r,o._tag){case la:{i.push(o.right),o=o.left;break}case ca:{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}),xp=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case ti:{o.push(ce(n.emptyCase(t)));break}case ni:{o.push(ce(n.failCase(t,a.error)));break}case Is:{o.push(ce(n.dieCase(t,a.defect)));break}case sa:{o.push(ce(n.interruptCase(t,a.fiberId)));break}case la:{r.push(a.right),r.push(a.left),o.push(ie({_tag:IT}));break}case ca:{r.push(a.right),r.push(a.left),o.push(ie({_tag:AT}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case IT:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case AT:{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()}),GL=/\((.*)\)/g,YL=te("effect/Tracer/spanToTrace",()=>new WeakMap),da=Symbol.for("effect/SpanAnnotation")});var qT,_l,XL="effect/STM",QL,UT,eD,$T=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(UT);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},jT=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,eD),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},oy,tD,ri=(e)=>{let t=Object.create(tD);return t.unsafeMap=e,t},nD=(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=SD.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(xD),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=hn(i.parent),a++}}return r.join(`
19
+ `)},ya,Tl=(e)=>vp(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[ey(n)],failCase:(t,n)=>[ey(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Ls=S(()=>{tt();Mr();mn();we();ee();Be();pa();et();lt();Pe();Ee();ty=Symbol.for(JT),pD={_E:(e)=>e},Ms={[ty]:pD,[J](){return x(q(JT),ae(q(mD(this))),me(this))},[W](e){return GT(e)&&fD(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:ve(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:ve(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:ve(this.left),right:ve(this.right)}}},toString(){return cr(this)},[de](){return this.toJSON()}},wo=(()=>{let e=Object.create(Ms);return e._tag=oi,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 ha:case ma:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return B()}),gD={emptyCase:tl,failCase:Wo,dieCase:Wo,interruptCase:tl,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},cy=h(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>vp(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)})),ga=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 ha:{i.push(o.right),o=o.left;break}case ma:{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}),vp=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case oi:{o.push(ce(n.emptyCase(t)));break}case ii:{o.push(ce(n.failCase(t,a.error)));break}case Ps:{o.push(ce(n.dieCase(t,a.defect)));break}case fa:{o.push(ce(n.interruptCase(t,a.fiberId)));break}case ha:{r.push(a.right),r.push(a.left),o.push(ie({_tag:zT}));break}case ma:{r.push(a.right),r.push(a.left),o.push(ie({_tag:KT}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case zT:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case KT:{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()}),xD=/\((.*)\)/g,SD=te("effect/Tracer/spanToTrace",()=>new WeakMap),ya=Symbol.for("effect/SpanAnnotation")});var eO,Cl,_D="effect/STM",wD,tO,vD,nO=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(tO);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},rO=()=>(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},uy,RD,ai=(e)=>{let t=Object.create(RD);return t.unsafeMap=e,t},TD=(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},HT=(e)=>j(e,oy),BT=(e)=>j(e,_l),rD,VT=()=>rD,iy=(e,t)=>ri(new Map([[e.key,t]])),WT,ry,ay=(e)=>{if(ry.has(e.key))return ry.get(e.key);let t=e.defaultValue();return ry.set(e.key,t),t},zT=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):ay(t),sy,KT,JT,GT;var Sp=S(()=>{Se();ee();Be();Xe();Ae();Ce();co();pg();qT=Symbol.for("effect/Context/Tag"),_l=Symbol.for("effect/Context/Reference"),QL=Symbol.for(XL),UT={...so,_op:"Tag",[QL]:zo,[qT]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return Te(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[ue](){return this.toJSON()},of(e){return e},context(e){return iy(this,e)}},eD={...UT,[_l]:_l},oy=Symbol.for("effect/Context"),tD={[oy]:{_Services:(e)=>e},[W](e){if(HT(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!q(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[J](){return me(this,Ud(this.unsafeMap.size))},pipe(){return M(this,arguments)},toString(){return Te(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(be)}},[ue](){return this.toJSON()}},rD=ri(new Map),WT=h(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),ri(r)}),ry=te("effect/Context/defaultValueCache",()=>new Map),sy=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(_l in t)return ay(t);throw nD(t)}return e.unsafeMap.get(t.key)}),KT=sy,JT=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return BT(t)?dl(ay(t)):Wd;return dl(e.unsafeMap.get(t.key))}),GT=h(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return ri(n)})});var fn,oi,ZT,Pr,wl,vl,ii,Rl,Tl;var Un=S(()=>{Sp();fn=$T,oi=VT,ZT=iy,Pr=WT,wl=KT,vl=sy,ii=JT,Rl=GT,Tl=jT});var ly,nO,XT,bp,uy,QT,eO,oD,bo=(e)=>{if(rO(e))return e;else if(Tn(e))return _p(e);else if(Bo(e))return cy(e);else if(Array.isArray(e)&&e.length===2&&e.every(Tn)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return dy;if(e[0]===1/0||e[1]===1/0)return cD;return cy(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(Lt(e)){let t=oD.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 lD(BigInt(r));case"milli":case"millis":return _p(i);case"second":case"seconds":return uD(i);case"minute":case"minutes":return dD(i);case"hour":case"hours":return pD(i);case"day":case"days":return fD(i);case"week":case"weeks":return mD(i)}}}throw Error("Invalid DurationInput")},tO,iD,aD,Mr=(e)=>{let t=Object.create(aD);if(Tn(e))if(isNaN(e)||e<=0)t.value=tO;else if(!Number.isFinite(e))t.value=iD;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<=nO)t.value=tO;else t.value={_tag:"Nanos",nanos:e};return t},rO=(e)=>j(e,ly),sD=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===nO;case"Infinity":return!1}},dy,cD,cy=(e)=>Mr(e),lD=(e)=>Mr(e*uy),_p=(e)=>Mr(e),uD=(e)=>Mr(e*1000),dD=(e)=>Mr(e*60000),pD=(e)=>Mr(e*3600000),fD=(e)=>Mr(e*86400000),mD=(e)=>Mr(e*604800000),wp=(e)=>yD(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),hD=(e)=>{let t=bo(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))}},gD=(e)=>{let t=bo(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/eO),Number(t.value.nanos%eO)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},yD,py,xD=(e,t)=>py(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),oO,iO,SD,bD=(e)=>{let t=bo(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=hD(t),r=n/QT,o=r/uy,i=o/bp,a=i/bp,s=a/XT;return{days:Number(s),hours:Number(a%XT),minutes:Number(i%bp),seconds:Number(o%bp),millis:Number(r%uy),nanos:Number(n%QT)}},_D=(e)=>{let t=bo(e);if(t.value._tag==="Infinity")return"Infinity";if(sD(t))return"0";let n=bD(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 fy=S(()=>{Se();ee();Be();Xe();Ae();Ce();ly=Symbol.for("effect/Duration"),nO=BigInt(0),XT=BigInt(24),bp=BigInt(60),uy=BigInt(1000),QT=BigInt(1e6),eO=BigInt(1e9),oD=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,tO={_tag:"Millis",millis:0},iD={_tag:"Infinity"},aD={[ly]:ly,[J](){return me(this,$d(this.value))},[W](e){return rO(e)&&SD(this,e)},toString(){return`Duration(${_D(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:gD(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[ue](){return this.toJSON()},pipe(){return M(this,arguments)}},dy=Mr(0),cD=Mr(1/0),yD=h(2,(e,t)=>{let n=bo(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)}}),py=h(3,(e,t,n)=>{let r=bo(e),o=bo(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(wp(r),wp(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)}),oO=h(2,(e,t)=>py(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),iO=h(2,(e,t)=>py(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),SD=h(2,(e,t)=>xD(bo(e),bo(t)))});var sO,wD,vp=(e)=>{let t=Object.create(wD);return t.current=e,t},Fs=(e)=>e.current,Rp;var my=S(()=>{ee();Xe();Ae();sO=Symbol.for("effect/MutableRef"),wD={[sO]:sO,toString(){return Te(this.toJSON())},toJSON(){return{_id:"MutableRef",current:be(this.current)}},[ue](){return this.toJSON()},pipe(){return M(this,arguments)}},Rp=h(2,(e,t)=>(e.current=t,e))});var gy="effect/FiberId",Ls,Tp="None",hy="Runtime",vD="Composite",RD,uO,dO,pO,yy=(e)=>j(e,Ls),Op=(e)=>{switch(e._tag){case Tp:return Ar();case hy:return ra(e.id);case vD:return x(Op(e.left),xo(Op(e.right)))}},lO,Cp=(e)=>Array.from(Op(e)).map((n)=>`#${n}`).join(","),fO=()=>{let e=Fs(lO);return x(lO,Rp(e+1)),new dO(e,Date.now())};var xy=S(()=>{Se();ee();Be();aa();Xe();my();Ce();Ls=Symbol.for(gy),RD=Re(`${gy}-${Tp}`);uO=class uO{[Ls]=Ls;_tag=Tp;id=-1;startTimeMillis=-1;[J](){return RD}[W](e){return yy(e)&&e._tag===Tp}toString(){return Te(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[ue](){return this.toJSON()}};dO=class dO{id;startTimeMillis;[Ls]=Ls;_tag=hy;constructor(e,t){this.id=e,this.startTimeMillis=t}[J](){return me(this,Re(`${gy}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[W](e){return yy(e)&&e._tag===hy&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Te(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[ue](){return this.toJSON()}};pO=new uO,lO=te(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>vp(0))});var $n,hO,Ep;var Ds=S(()=>{xy();$n=pO,hO=Cp,Ep=fO});var qs,gO,yO,Sy,by,_y,xO,SO,wy;var kp=S(()=>{Hg();qs=Os,gO=lT,yO=dT,Sy=pT,by=na,_y=ap,xO=cp,SO=hT,wy=Cs});var Cl,Ry=(e)=>Ue(e),TD=(e)=>Xh(Yo(e),Ry),OD,CD,Ip=(e,t)=>{let n=Object.create(CD);return n.head=e,n.tail=t,n},ED,kD,bO,_O=(e)=>j(e,Cl),Nr=(e)=>e._tag==="Nil",Ty=(e)=>e._tag==="Cons",ID=()=>bO,_o=(e,t)=>Ip(e,t),ai,El=(e)=>Ip(e,bO),wO,AD,PD,vO,RO=(e)=>{let t=ai(),n=e;while(!Nr(n))t=AD(t,n.head),n=n.tail;return t};var Ap=S(()=>{Qe();Se();Qc();ee();Be();Xe();Ae();Ce();Cl=Symbol.for("effect/List"),OD=TD(q),CD={[Cl]:Cl,_tag:"Cons",toString(){return Te(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:Ry(this).map(be)}},[ue](){return this.toJSON()},[W](e){return _O(e)&&this._tag===e._tag&&OD(this,e)},[J](){return me(this,On(Ry(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 M(this,arguments)}},ED=Re("Nil"),kD={[Cl]:Cl,_tag:"Nil",toString(){return Te(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[ue](){return this.toJSON()},[J](){return ED},[W](e){return _O(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return M(this,arguments)}},bO=Object.create(kD),ai=ID,wO=h(2,(e,t)=>PD(t,e)),AD=h(2,(e,t)=>_o(t,e)),PD=h(2,(e,t)=>{if(Nr(e))return t;else if(Nr(t))return e;else{let n=Ip(t.head,e),r=n,o=t.tail;while(!Nr(o)){let i=Ip(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),vO=h(3,(e,t,n)=>{let r=t,o=e;while(!Nr(o))r=n(r,o.head),o=o.tail;return r})});var f7,Us;var Pp=S(()=>{Se();Be();co();f7=Object.assign(Object.create(Array.prototype),{[J](){return me(this,On(this))},[W](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>q(t,e[n]));else return!1}}),Us=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=ul,e}()});function TO(e){return e}var ND,Il,FD,LD,Cy=()=>LD,DD,qD=(e,t)=>{let n=Object.create(DD);return n.first=e,n.second=t,n},UD,$D=(e,t)=>{let n=Object.create(UD);return n.key=e,n.service=t,n},jD,HD=(e)=>{let t=Object.create(jD);return t.key=e,t},BD,VD=(e,t)=>{let n=Object.create(BD);return n.key=e,n.update=t,n},OO=(e,t)=>{let n=new Map(e.unsafeMap),r=Cy();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!q(a,i))r=kl(VD(o,()=>i))(r)}else n.delete(o),r=kl($D(o,i))(r);for(let[o]of n.entries())r=kl(HD(o))(r);return r},kl,CO;var EO=S(()=>{Ir();Se();ee();Sp();Pp();ND=Symbol.for("effect/DifferContextPatch");Il={...Us.prototype,[ND]:{_Value:TO,_Patch:TO}},FD=Object.assign(Object.create(Il),{_tag:"Empty"}),LD=Object.create(FD),DD=Object.assign(Object.create(Il),{_tag:"AndThen"}),UD=Object.assign(Object.create(Il),{_tag:"AddService"}),jD=Object.assign(Object.create(Il),{_tag:"RemoveService"}),BD=Object.assign(Object.create(Il),{_tag:"UpdateService"}),kl=h(2,(e,t)=>qD(e,t)),CO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=gt(e),o=new Map(t.unsafeMap);while(rr(r)){let a=or(r),s=ir(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=Wt(Wt(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 ri(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 ri(i)})});function Ey(e){return e}var zD,Np,KD,JD,ky=()=>JD,GD,YD=(e,t)=>{let n=Object.create(GD);return n.first=e,n.second=t,n},ZD,XD=(e)=>{let t=Object.create(ZD);return t.value=e,t},QD,eq=(e)=>{let t=Object.create(QD);return t.value=e,t},kO=(e,t)=>{let[n,r]=ia([e,ky()],([o,i],a)=>{if(kT(a)(o))return[Wg(a)(o),i];return[o,Mp(XD(a))(i)]})(t);return ia(r,(o,i)=>Mp(eq(i))(o))(n)},Mp,IO;var AO=S(()=>{Ir();ee();aa();Pp();zD=Symbol.for("effect/DifferHashSetPatch");Np={...Us.prototype,[zD]:{_Value:Ey,_Key:Ey,_Patch:Ey}},KD=Object.assign(Object.create(Np),{_tag:"Empty"}),JD=Object.create(KD),GD=Object.assign(Object.create(Np),{_tag:"AndThen"}),ZD=Object.assign(Object.create(Np),{_tag:"Add"}),QD=Object.assign(Object.create(Np),{_tag:"Remove"}),Mp=h(2,(e,t)=>YD(e,t)),IO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=gt(e);while(rr(r)){let o=or(r),i=ir(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=Wt(o.first)(Wt(o.second)(i));break}case"Add":{n=oa(o.value)(n),r=i;break}case"Remove":n=Wg(o.value)(n),r=i}}return n})});function PO(e){return e}var nq,Pl,rq,oq,Iy=()=>oq,iq,aq=(e,t)=>{let n=Object.create(iq);return n.first=e,n.second=t,n},sq,cq=(e)=>{let t=Object.create(sq);return t.values=e,t},lq,uq=(e,t)=>{let n=Object.create(lq);return n.from=e,n.until=t,n},dq,pq=(e,t)=>{let n=Object.create(dq);return n.index=e,n.patch=t,n},MO=(e)=>{let t=0,n=Iy();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(!q(i,e.differ.empty))n=Al(n,pq(t,i));t=t+1}if(t<e.oldValue.length)n=Al(n,uq(0,t));if(t<e.newValue.length)n=Al(n,cq(VR(t)(e.newValue)));return n},Al,NO;var FO=S(()=>{Qe();Se();ee();Pp();nq=Symbol.for("effect/DifferReadonlyArrayPatch");Pl={...Us.prototype,[nq]:{_Value:PO,_Patch:PO}},rq=Object.assign(Object.create(Pl),{_tag:"Empty"}),oq=Object.create(rq),iq=Object.assign(Object.create(Pl),{_tag:"AndThen"}),sq=Object.assign(Object.create(Pl),{_tag:"Append"}),lq=Object.assign(Object.create(Pl),{_tag:"Slice"}),dq=Object.assign(Object.create(Pl),{_tag:"Update"}),Al=h(2,(e,t)=>aq(e,t)),NO=h(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=Vt(e);while(Jo(o)){let i=ht(o),a=tr(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 LO,mq,si=(e)=>{let t=Object.create(mq);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},Ay=()=>si({empty:Cy(),combine:(e,t)=>kl(t)(e),diff:(e,t)=>OO(e,t),patch:(e,t)=>CO(t)(e)}),Py=()=>si({empty:ky(),combine:(e,t)=>Mp(t)(e),diff:(e,t)=>kO(e,t),patch:(e,t)=>IO(t)(e)}),My=(e)=>si({empty:Iy(),combine:(t,n)=>Al(t,n),diff:(t,n)=>MO({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>NO(t,n,e)}),Fp=()=>DO((e,t)=>t),DO=(e)=>si({empty:xe,combine:(t,n)=>{if(t===xe)return n;if(n===xe)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(q(t,n))return xe;return Jc(n)},patch:(t,n)=>e(n,t(n))});var Lp=S(()=>{Se();ee();Ae();EO();AO();FO();LO=Symbol.for("effect/Differ"),mq={[LO]:{_P:xe,_V:xe},pipe(){return M(this,arguments)}}});var Ml=255,qO=8,Dp=(e)=>e&Ml,qp=(e)=>e>>qO&Ml,fa=(e,t)=>(e&Ml)+((t&e&Ml)<<qO),Fy,UO=(e)=>fa(e,e),$O=(e)=>fa(e,0),jO,Ly,HO=(e)=>~e>>>0&Ml;var Dy=S(()=>{ee();Fy=fa(0,0),jO=h(2,(e,t)=>fa(Dp(e)&~t,qp(e))),Ly=h(2,(e,t)=>e|t)});var hq=0,wo=1,VO=2,qy=4,Up=16,Uy=32,WO=(e)=>$p(e,Uy),$y,vo=(e)=>jy(e)&&!gq(e),jy=(e)=>$p(e,wo),$p,Hy=(...e)=>e.reduce((t,n)=>t|n,0),zO,By=(e)=>$p(e,qy),gq=(e)=>$p(e,Up),Nl,Fl,Vy;var Ll=S(()=>{ee();Lp();Dy();$y=h(2,(e,t)=>e|t),$p=h(2,(e,t)=>(e&t)!==0),zO=Hy(hq),Nl=h(2,(e,t)=>fa(e^t,t)),Fl=h(2,(e,t)=>e&(HO(Dp(t))|qp(t))|Dp(t)&qp(t)),Vy=si({empty:Fy,diff:(e,t)=>Nl(e,t),combine:(e,t)=>Ly(t)(e),patch:(e,t)=>Fl(t,e)})});var KO,zy,Ky;var Jy=S(()=>{Dy();KO=UO,zy=$O,Ky=jO});var Yy=(e,t)=>({_tag:"Par",left:e,right:t}),jp=(e,t)=>({_tag:"Seq",left:e,right:t}),GO=(e)=>{let t=El(e),n=ai();while(!0){let[r,o]=vO(t,[YO(),ai()],([i,a],s)=>{let[c,l]=yq(s);return[wq(i,c),wO(a,l)]});if(n=xq(n,r),Nr(o))return RO(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},yq=(e)=>{let t=e,n=YO(),r=ai(),o=ai();while(!0)switch(t._tag){case"Empty":{if(Nr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=_o(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=Yy(jp(s,a),jp(c,a));break}case"Seq":{let{left:s,right:c}=i;t=jp(s,jp(c,a));break}case"Single":{t=i,o=_o(a,o);break}}break}case"Single":{if(n=_q(n,t),Nr(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")},xq=(e,t)=>{if(Nr(e))return El(Gy(t));if(vq(t))return e;let n=kq(e.head),r=Rq(t);if(n.length===1&&r.length===1&&q(n[0],r[0]))return _o(Eq(e.head,Gy(t)),e.tail);return _o(Gy(t),e)},Sq,bq,Hp,YO=()=>new Hp(qs()),_q=(e,t)=>new Hp(xO(e.map,t.dataSource,(n)=>AR(Qn(n,ZR(t.blockedRequest)),()=>gt(t.blockedRequest)))),wq=(e,t)=>new Hp(wy(e.map,t.map,(n,r,o)=>by(n,o,st(Sy(n,o),{onNone:()=>r,onSome:(i)=>En(r,i)})))),vq=(e)=>yO(e.map),Rq=(e)=>Array.from(_y(e.map)),Gy=(e)=>Cq(SO(e.map,(t)=>gt(t))),Tq,Oq,Zy,Cq=(e)=>new Zy(e),Eq=(e,t)=>new Zy(wy(t.map,e.map,(n,r,o)=>by(n,o,st(Sy(n,o),{onNone:()=>Dn(),onSome:(i)=>En(i,r)})))),kq=(e)=>Array.from(_y(e.map)),ZO=(e)=>Array.from(e.map);var XO=S(()=>{Ir();Se();kp();Ap();ct();Sq=Symbol.for("effect/RequestBlock/RequestBlockParallel"),bq={_R:(e)=>e};Hp=class Hp{map;[Sq]=bq;constructor(e){this.map=e}};Tq=Symbol.for("effect/RequestBlock/RequestBlockSequential"),Oq={_R:(e)=>e};Zy=class Zy{map;[Tq]=Oq;constructor(e){this.map=e}}});var $s="Pending",Bp="Done";var Aq="effect/Deferred",eC,tC,nC=(e)=>({_tag:$s,joiners:e}),rC=(e)=>({_tag:Bp,effect:e});var oC=S(()=>{eC=Symbol.for(Aq),tC={_E:(e)=>e,_A:(e)=>e}});var js;var iC=S(()=>{js=class js{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 js(this.self)}}});class tx{patch;op;_op=cl;constructor(e,t){this.patch=e,this.op=t}}var zp=(e,t)=>{let n=new At("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},ex=(e)=>{let t=new At("RunBlocked");return t.effect_instruction_i0=e,t},ci,At,nx,rx,Hs=(e)=>j(e,ci),qt=(e)=>{let t=new At(Vd);return t.effect_instruction_i0=e,t},mC,Ro,To=(e)=>Ro(e,void 0),ox=function(){let e=new At(Zi);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(Ki("you're not supposed to end up here"))}return e},Dl=(e,t=$n)=>{let n=new At(Yi),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,jl(n,(o)=>Hs(r)?r:yt)},hC=(e,t=$n)=>$e(()=>Dl(e,t)),li=(e,t=$n)=>ox(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 At(Yi);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=Dt(()=>this.effect_instruction_i0(o,s.signal));else a=Dt(()=>this.effect_instruction_i0(o));return a||s?jl(i,(c)=>{if(s)s.abort();return a??yt}):i}),ql,aC,Kp=(e,t)=>{if(qe(t))return new Proxy(e,{has(n,r){return r===da||r===aC||r in n},get(n,r){if(r===da)return t.value;if(r===aC)return e;return n[r]}});return e},Jp=(e)=>tn(e)&&!(da in e)?qt((t)=>Kt(kn(Kp(e,df(t))))):Kt(kn(e)),ix=(e)=>gC(()=>kn(new $q(e))),ma=(e)=>Bs(e,{onFailure:(t)=>_e(ie(t)),onSuccess:(t)=>_e(ce(t))}),ui=(e)=>yC(e,{onFailure:Me,onSuccess:He}),Pt=(e)=>tn(e)&&!(da in e)?qt((t)=>Kt(Ps(Kp(e,df(t))))):Kt(Ps(e)),ax=(e)=>re(Y(e),Pt),Kt=(e)=>{let t=new nx(ln);return t.effect_instruction_i0=e,t},gC=(e)=>re(Y(e),Kt),sx,Ul=(e)=>qt((t)=>e(t.id())),re,cx=(e)=>{let t=new At("OnStep");return t.effect_instruction_i0=e,t},$l=(e)=>re(e,xe),yC,jn,Bs,Hn,ha,Gp=(e)=>{let t=new At(Xi);return t.effect_instruction_i0=KO(wo),t.effect_instruction_i1=()=>e,t},et,Yp,ga,Vs,jl,_e=(e)=>{let t=new rx(un);return t.effect_instruction_i0=e,t},$e=(e)=>{let t=new At(Zi);return t.commit=e,t},Y=(e)=>{let t=new At(Bd);return t.effect_instruction_i0=e,t},Zp,lx=(e)=>qt((t)=>{let n=t.getFiberRef(Wp),r=x(n,De(()=>t.scope()));return e(fi(Wp,G(r)))}),Xp=(e)=>{let t=new At(Xi);return t.effect_instruction_i0=zy(wo),t.effect_instruction_i1=()=>e,t},di=(e)=>ox(e,function(){let t=new At(Xi);return t.effect_instruction_i0=zy(wo),t.effect_instruction_i1=(n)=>jy(n)?Dt(()=>this.effect_instruction_i0(Gp)):Dt(()=>this.effect_instruction_i0(Xp)),t}),yt,ux=(e)=>{let t=new At(Xi);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},Hl=(e)=>{let t=new At(xs);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},Bl=(e)=>{let t=new At(bs);return typeof e?.priority<"u"?EC(t,e.priority):t},Qp,ef,pi,Vl,xC=(e)=>re(sx,(t)=>x(e,Wl(t))),Wl,SC,bC,_C,dx,px,fx,wC,vC,Fq="effect/FiberRef",Lq,Dq,tf=(e)=>qt((t)=>He(t.getFiberRef(e))),ya,Xy,qq,fi,Ut=(e,t)=>xa(e,{differ:Fp(),fork:t?.fork??xe,join:t?.join}),RC=(e)=>{let t=Py();return xa(e,{differ:t,fork:t.empty})},Uq=(e)=>{let t=My(Fp());return xa(e,{differ:t,fork:t.empty})},nf=(e)=>{let t=Ay();return xa(e,{differ:t,fork:t.empty})},xa=(e,t)=>({...Ko,[Lq]:Dq,initial:e,commit(){return tf(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)}),TC=(e)=>xa(e,{differ:Vy,fork:Vy.empty}),Sa,Ws,mx,OC,hx,CC,EC,kC,IC,AC,PC,zl,Wp,Kl,rf,of,af=(e,t)=>e.addFinalizer(()=>To(t)),gx=(e,t)=>e.close(t),zs=(e,t)=>e.fork(t),sf,ba=(e,t)=>{class n extends sf{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},sC,$q,Qy,V7,MC=(e)=>j(e,Qy),cC,jq,lC,Jl,uC,W7,dC,z7,pC,K7,fC,Hq,Ks=(e)=>Hs(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),yx=(e)=>e._tag==="Success",NC,Gl=(e)=>NC(e,void 0),_a=(e,t)=>Bq(e,t?.parallel?pa:zt),xx=(e)=>Me(kn(e)),Yl=(e)=>Me(Ps(e)),Me=(e)=>{let t=new nx(ln);return t.effect_instruction_i0=e,t},Sx=(e)=>Me(ar(e)),Vp,cf,He=(e)=>{let t=new rx(un);return t.effect_instruction_i0=e,t},Bn,bx,Bq=(e,t)=>{let n=Xd(e);if(!rr(n))return H();return x(ir(n),vs(x(or(n),Vp(gt)),(r,o)=>x(r,bx(o,{onSuccess:(i,a)=>x(i,Wt(a)),onFailure:t}))),Vp(Zo),Vp((r)=>ho(r)),G)},FC=(e)=>({...Ko,[eC]:tC,state:vp(nC([])),commit(){return lf(this)},blockingOn:e}),lf=(e)=>hC((t)=>{let n=Fs(e.state);switch(n._tag){case Bp:return t(n.effect);case $s:return n.joiners.push(t),Vq(e,t)}},e.blockingOn),uf=(e,t)=>{let n=Fs(e.state);if(n._tag===$s){Rp(e.state,rC(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},Vq=(e,t)=>Y(()=>{let n=Fs(e.state);if(n._tag===$s){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),Wq,LC=()=>Wq,wa=(e)=>re(LC(),e),zq,_x,df=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?G(t):H()};var xt=S(()=>{Qe();Ir();Un();dn();Se();Ds();ee();Be();kp();Xe();Ap();my();ct();Ae();Ce();Jy();Wo();Ns();oC();Lp();co();Ll();iC();ci=Symbol.for("effect/Effect");At=class At{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ci]=zo;constructor(e){this._op=e}[W](e){return this===e}[J](){return me(this,rl(this))}pipe(){return M(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:be(this.effect_instruction_i0),effect_instruction_i1:be(this.effect_instruction_i1),effect_instruction_i2:be(this.effect_instruction_i2)}}toString(){return Te(this.toJSON())}[ue](){return this.toJSON()}[Symbol.iterator](){return new js(new io(this))}};nx=class nx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ci]=zo;constructor(e){this._op=e,this._tag=e}[W](e){return Ks(e)&&e._op==="Failure"&&q(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return x(Re(this._tag),ae(D(this.effect_instruction_i0)),me(this))}get cause(){return this.effect_instruction_i0}pipe(){return M(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return Te(this.toJSON())}[ue](){return this.toJSON()}[Symbol.iterator](){return new js(new io(this))}};rx=class rx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[ci]=zo;constructor(e){this._op=e,this._tag=e}[W](e){return Ks(e)&&e._op==="Success"&&q(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return x(Re(this._tag),ae(D(this.effect_instruction_i0)),me(this))}get value(){return this.effect_instruction_i0}pipe(){return M(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:be(this.value)}}toString(){return Te(this.toJSON())}[ue](){return this.toJSON()}[Symbol.iterator](){return new js(new io(this))}};mC=h(3,(e,t,n)=>di((r)=>re(e,(o)=>re(ui($e(()=>r(t(o)))),(i)=>$e(()=>n(o,i)).pipe(jn({onFailure:(a)=>{switch(i._tag){case ln:return Kt(zt(i.effect_instruction_i0,a));case un:return Kt(a)}},onSuccess:()=>i})))))),Ro=h(2,(e,t)=>re(e,()=>_e(t))),ql=h(2,(e,t)=>Bs(e,{onFailure:t,onSuccess:_e})),aC=Symbol.for("effect/OriginalAnnotation"),sx=qt((e)=>_e(e.id())),re=h(2,(e,t)=>{let n=new At(gs);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),yC=h(2,(e,t)=>jn(e,{onFailure:(n)=>_e(t.onFailure(n)),onSuccess:(n)=>_e(t.onSuccess(n))})),jn=h(2,(e,t)=>{let n=new At(ys);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),Bs=h(2,(e,t)=>jn(e,{onFailure:(n)=>{if(Xg(n).length>0)return Kt(LT(n));let o=Zg(n);if(o.length>0)return t.onFailure(Mg(o));return Kt(n)},onSuccess:t.onSuccess})),Hn=h(2,(e,t)=>$e(()=>{let n=Ue(e),r=Qi(n.length),o=0;return Ro(Hl({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),ha=h(2,(e,t)=>$e(()=>{let n=Ue(e),r=0;return Hl({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),et=h(2,(e,t)=>re(e,(n)=>Y(()=>t(n)))),Yp=h(2,(e,t)=>Bs(e,{onFailure:(n)=>ax(()=>t.onFailure(n)),onSuccess:(n)=>Y(()=>t.onSuccess(n))})),ga=h(2,(e,t)=>jn(e,{onFailure:(n)=>{let r=gp(n);switch(r._tag){case"Left":return ax(()=>t(r.left));case"Right":return Kt(r.right)}},onSuccess:_e})),Vs=h(2,(e,t)=>di((n)=>jn(n(e),{onFailure:(r)=>{let o=Me(r);return jn(t(o),{onFailure:(i)=>Me(zt(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=He(r);return pi(t(o),o)}}))),jl=h(2,(e,t)=>Vs(e,cf({onFailure:(n)=>Ms(n)?To(t(Qg(n))):yt,onSuccess:()=>yt}))),Zp=h((e)=>e.length===3||e.length===2&&!(tn(e[1])&&("onlyEffect"in e[1])),(e,t)=>re(e,(n)=>{let r=typeof t==="function"?t(n):t;if(Hs(r))return Ro(r,n);else if(iR(r))return Dl((o)=>{r.then((i)=>o(_e(n)),(i)=>o(Pt(new Hq(i,"An unknown error occurred in Effect.tap"))))});return _e(n)})),yt=_e(void 0),Qp=h(2,(e,t)=>re(e,(n)=>et(t,(r)=>[n,r]))),ef=h(2,(e,t)=>re(e,(n)=>Ro(t,n))),pi=h(2,(e,t)=>re(e,()=>t)),Vl=hC(()=>{let e=setInterval(()=>{},2147483647);return Y(()=>clearInterval(e))}),Wl=h(2,(e,t)=>re(e.interruptAsFork(t),()=>e.await)),SC={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return M(this,arguments)}},bC={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return M(this,arguments)}},_C={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return M(this,arguments)}},dx={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return M(this,arguments)}},px={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return M(this,arguments)}},fx={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return M(this,arguments)}},wC={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return M(this,arguments)}},vC={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return M(this,arguments)}},Lq=Symbol.for(Fq),Dq={_A:(e)=>e},ya=h(2,(e,t)=>re(tf(e),t)),Xy=h(2,(e,t)=>qq(e,()=>[void 0,t])),qq=h(2,(e,t)=>qt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),_e(r)})),fi=h(3,(e,t,n)=>mC(ef(tf(t),Xy(t,n)),()=>e,(r)=>Xy(t,r))),Sa=te(Symbol.for("effect/FiberRef/currentContext"),()=>nf(oi())),Ws=te(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>Ut(0)),mx=te(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>Ut(2048)),OC=te(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>Ut(qs())),hx=te(Symbol.for("effect/FiberRef/currentLogLevel"),()=>Ut(px)),CC=te(Symbol.for("effect/FiberRef/currentLogSpan"),()=>Ut(ai())),EC=h(2,(e,t)=>fi(e,Ws,t)),kC=te(Symbol.for("effect/FiberRef/currentConcurrency"),()=>Ut("unbounded")),IC=te(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>Ut(!0)),AC=te(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>Ut(G(fx))),PC=te(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>Ut(G(dx))),zl=te(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>Uq(fo())),Wp=te(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>Ut(H(),{fork:()=>H(),join:(e,t)=>e})),Kl=te(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>Ut(So,{fork:()=>So,join:(e,t)=>e})),rf=Symbol.for("effect/Scope"),of=Symbol.for("effect/CloseableScope"),sf=function(){class e extends globalThis.Error{commit(){return Pt(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[ue](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
22
+ `)}return t},oO=(e)=>H(e,uy),iO=(e)=>H(e,Cl),OD,aO=()=>OD,dy=(e,t)=>ai(new Map([[e.key,t]])),sO,ly,py=(e)=>{if(ly.has(e.key))return ly.get(e.key);let t=e.defaultValue();return ly.set(e.key,t),t},cO=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):py(t),fy,lO,uO,dO;var Rp=S(()=>{we();ee();Be();et();Pe();Ee();po();xg();eO=Symbol.for("effect/Context/Tag"),Cl=Symbol.for("effect/Context/Reference"),wD=Symbol.for(_D),tO={...uo,_op:"Tag",[wD]:Go,[eO]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return Ce(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[de](){return this.toJSON()},of(e){return e},context(e){return dy(this,e)}},vD={...tO,[Cl]:Cl},uy=Symbol.for("effect/Context"),RD={[uy]:{_Services:(e)=>e},[W](e){if(oO(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!U(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[J](){return me(this,Vd(this.unsafeMap.size))},pipe(){return F(this,arguments)},toString(){return Ce(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(ve)}},[de](){return this.toJSON()}},OD=ai(new Map),sO=h(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),ai(r)}),ly=te("effect/Context/defaultValueCache",()=>new Map),fy=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(Cl in t)return py(t);throw TD(t)}return e.unsafeMap.get(t.key)}),lO=fy,uO=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return iO(t)?yl(py(t)):Yd;return yl(e.unsafeMap.get(t.key))}),dO=h(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return ai(n)})});var gn,si,fO,Fr,El,kl,ci,Il,Al;var jn=S(()=>{Rp();gn=nO,si=aO,fO=dy,Fr=sO,El=lO,kl=fy,ci=uO,Il=dO,Al=rO});var hy,xO,mO,Tp,gy,hO,gO,CD,vo=(e)=>{if(SO(e))return e;else if(Tn(e))return Op(e);else if(zo(e))return my(e);else if(Array.isArray(e)&&e.length===2&&e.every(Tn)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return yy;if(e[0]===1/0||e[1]===1/0)return AD;return my(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(qt(e)){let t=CD.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return my(BigInt(r));case"micro":case"micros":return PD(BigInt(r));case"milli":case"millis":return Op(i);case"second":case"seconds":return MD(i);case"minute":case"minutes":return ND(i);case"hour":case"hours":return FD(i);case"day":case"days":return LD(i);case"week":case"weeks":return DD(i)}}}throw Error("Invalid DurationInput")},yO,ED,kD,Lr=(e)=>{let t=Object.create(kD);if(Tn(e))if(isNaN(e)||e<=0)t.value=yO;else if(!Number.isFinite(e))t.value=ED;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<=xO)t.value=yO;else t.value={_tag:"Nanos",nanos:e};return t},SO=(e)=>H(e,hy),ID=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===xO;case"Infinity":return!1}},yy,AD,my=(e)=>Lr(e),PD=(e)=>Lr(e*gy),Op=(e)=>Lr(e),MD=(e)=>Lr(e*1000),ND=(e)=>Lr(e*60000),FD=(e)=>Lr(e*3600000),LD=(e)=>Lr(e*86400000),DD=(e)=>Lr(e*604800000),Cp=(e)=>UD(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),qD=(e)=>{let t=vo(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))}},$D=(e)=>{let t=vo(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/gO),Number(t.value.nanos%gO)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},UD,xy,jD=(e,t)=>xy(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),bO,_O,HD,BD=(e)=>{let t=vo(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=qD(t),r=n/hO,o=r/gy,i=o/Tp,a=i/Tp,s=a/mO;return{days:Number(s),hours:Number(a%mO),minutes:Number(i%Tp),seconds:Number(o%Tp),millis:Number(r%gy),nanos:Number(n%hO)}},VD=(e)=>{let t=vo(e);if(t.value._tag==="Infinity")return"Infinity";if(ID(t))return"0";let n=BD(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 Sy=S(()=>{we();ee();Be();et();Pe();Ee();hy=Symbol.for("effect/Duration"),xO=BigInt(0),mO=BigInt(24),Tp=BigInt(60),gy=BigInt(1000),hO=BigInt(1e6),gO=BigInt(1e9),CD=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,yO={_tag:"Millis",millis:0},ED={_tag:"Infinity"},kD={[hy]:hy,[J](){return me(this,Wd(this.value))},[W](e){return SO(e)&&HD(this,e)},toString(){return`Duration(${VD(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:$D(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[de](){return this.toJSON()},pipe(){return F(this,arguments)}},yy=Lr(0),AD=Lr(1/0),UD=h(2,(e,t)=>{let n=vo(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)}}),xy=h(3,(e,t,n)=>{let r=vo(e),o=vo(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(Cp(r),Cp(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)}),bO=h(2,(e,t)=>xy(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),_O=h(2,(e,t)=>xy(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),HD=h(2,(e,t)=>jD(vo(e),vo(t)))});var vO,WD,Ep=(e)=>{let t=Object.create(WD);return t.current=e,t},Ds=(e)=>e.current,kp;var by=S(()=>{ee();et();Pe();vO=Symbol.for("effect/MutableRef"),WD={[vO]:vO,toString(){return Ce(this.toJSON())},toJSON(){return{_id:"MutableRef",current:ve(this.current)}},[de](){return this.toJSON()},pipe(){return F(this,arguments)}},kp=h(2,(e,t)=>(e.current=t,e))});var wy="effect/FiberId",qs,Ip="None",_y="Runtime",zD="Composite",KD,OO,CO,EO,vy=(e)=>H(e,qs),Ap=(e)=>{switch(e._tag){case Ip:return Nr();case _y:return la(e.id);case zD:return x(Ap(e.left),_o(Ap(e.right)))}},TO,Pp=(e)=>Array.from(Ap(e)).map((n)=>`#${n}`).join(","),kO=()=>{let e=Ds(TO);return x(TO,kp(e+1)),new CO(e,Date.now())};var Ry=S(()=>{we();ee();Be();pa();et();by();Ee();qs=Symbol.for(wy),KD=Oe(`${wy}-${Ip}`);OO=class OO{[qs]=qs;_tag=Ip;id=-1;startTimeMillis=-1;[J](){return KD}[W](e){return vy(e)&&e._tag===Ip}toString(){return Ce(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[de](){return this.toJSON()}};CO=class CO{id;startTimeMillis;[qs]=qs;_tag=_y;constructor(e,t){this.id=e,this.startTimeMillis=t}[J](){return me(this,Oe(`${wy}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[W](e){return vy(e)&&e._tag===_y&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Ce(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[de](){return this.toJSON()}};EO=new OO,TO=te(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Ep(0))});var Hn,AO,Mp;var $s=S(()=>{Ry();Hn=EO,AO=Pp,Mp=kO});var Us,PO,MO,Ty,Oy,Cy,NO,FO,Ey;var Np=S(()=>{Jg();Us=Es,PO=TT,MO=CT,Ty=ET,Oy=ca,Cy=dp,NO=fp,FO=AT,Ey=ks});var Ml,Iy=(e)=>qe(e),JD=(e)=>og(Qo(e),Iy),GD,YD,Fp=(e,t)=>{let n=Object.create(YD);return n.head=e,n.tail=t,n},ZD,XD,LO,DO=(e)=>H(e,Ml),Dr=(e)=>e._tag==="Nil",Ay=(e)=>e._tag==="Cons",QD=()=>LO,Ro=(e,t)=>Fp(e,t),li,Nl=(e)=>Fp(e,LO),qO,eq,tq,$O,UO=(e)=>{let t=li(),n=e;while(!Dr(n))t=eq(t,n.head),n=n.tail;return t};var Lp=S(()=>{tt();we();il();ee();Be();et();Pe();Ee();Ml=Symbol.for("effect/List"),GD=JD(U),YD={[Ml]:Ml,_tag:"Cons",toString(){return Ce(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:Iy(this).map(ve)}},[de](){return this.toJSON()},[W](e){return DO(e)&&this._tag===e._tag&&GD(this,e)},[J](){return me(this,On(Iy(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)}},ZD=Oe("Nil"),XD={[Ml]:Ml,_tag:"Nil",toString(){return Ce(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[de](){return this.toJSON()},[J](){return ZD},[W](e){return DO(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return F(this,arguments)}},LO=Object.create(XD),li=QD,qO=h(2,(e,t)=>tq(t,e)),eq=h(2,(e,t)=>Ro(t,e)),tq=h(2,(e,t)=>{if(Dr(e))return t;else if(Dr(t))return e;else{let n=Fp(t.head,e),r=n,o=t.tail;while(!Dr(o)){let i=Fp(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),$O=h(3,(e,t,n)=>{let r=t,o=e;while(!Dr(o))r=n(r,o.head),o=o.tail;return r})});var V7,js;var Dp=S(()=>{we();Be();po();V7=Object.assign(Object.create(Array.prototype),{[J](){return me(this,On(this))},[W](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>U(t,e[n]));else return!1}}),js=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=gl,e}()});function jO(e){return e}var rq,Ll,oq,iq,My=()=>iq,aq,sq=(e,t)=>{let n=Object.create(aq);return n.first=e,n.second=t,n},cq,lq=(e,t)=>{let n=Object.create(cq);return n.key=e,n.service=t,n},uq,dq=(e)=>{let t=Object.create(uq);return t.key=e,t},pq,fq=(e,t)=>{let n=Object.create(pq);return n.key=e,n.update=t,n},HO=(e,t)=>{let n=new Map(e.unsafeMap),r=My();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!U(a,i))r=Fl(fq(o,()=>i))(r)}else n.delete(o),r=Fl(lq(o,i))(r);for(let[o]of n.entries())r=Fl(dq(o))(r);return r},Fl,BO;var VO=S(()=>{Mr();we();ee();Rp();Dp();rq=Symbol.for("effect/DifferContextPatch");Ll={...js.prototype,[rq]:{_Value:jO,_Patch:jO}},oq=Object.assign(Object.create(Ll),{_tag:"Empty"}),iq=Object.create(oq),aq=Object.assign(Object.create(Ll),{_tag:"AndThen"}),cq=Object.assign(Object.create(Ll),{_tag:"AddService"}),uq=Object.assign(Object.create(Ll),{_tag:"RemoveService"}),pq=Object.assign(Object.create(Ll),{_tag:"UpdateService"}),Fl=h(2,(e,t)=>sq(e,t)),BO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=yt(e),o=new Map(t.unsafeMap);while(or(r)){let a=ir(r),s=ar(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=Kt(Kt(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 ai(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 ai(i)})});function Ny(e){return e}var hq,$p,gq,yq,Fy=()=>yq,xq,Sq=(e,t)=>{let n=Object.create(xq);return n.first=e,n.second=t,n},bq,_q=(e)=>{let t=Object.create(bq);return t.value=e,t},wq,vq=(e)=>{let t=Object.create(wq);return t.value=e,t},WO=(e,t)=>{let[n,r]=da([e,Fy()],([o,i],a)=>{if(WT(a)(o))return[Zg(a)(o),i];return[o,qp(_q(a))(i)]})(t);return da(r,(o,i)=>qp(vq(i))(o))(n)},qp,zO;var KO=S(()=>{Mr();ee();pa();Dp();hq=Symbol.for("effect/DifferHashSetPatch");$p={...js.prototype,[hq]:{_Value:Ny,_Key:Ny,_Patch:Ny}},gq=Object.assign(Object.create($p),{_tag:"Empty"}),yq=Object.create(gq),xq=Object.assign(Object.create($p),{_tag:"AndThen"}),bq=Object.assign(Object.create($p),{_tag:"Add"}),wq=Object.assign(Object.create($p),{_tag:"Remove"}),qp=h(2,(e,t)=>Sq(e,t)),zO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=yt(e);while(or(r)){let o=ir(r),i=ar(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=Kt(o.first)(Kt(o.second)(i));break}case"Add":{n=ua(o.value)(n),r=i;break}case"Remove":n=Zg(o.value)(n),r=i}}return n})});function JO(e){return e}var Tq,ql,Oq,Cq,Ly=()=>Cq,Eq,kq=(e,t)=>{let n=Object.create(Eq);return n.first=e,n.second=t,n},Iq,Aq=(e)=>{let t=Object.create(Iq);return t.values=e,t},Pq,Mq=(e,t)=>{let n=Object.create(Pq);return n.from=e,n.until=t,n},Nq,Fq=(e,t)=>{let n=Object.create(Nq);return n.index=e,n.patch=t,n},GO=(e)=>{let t=0,n=Ly();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(!U(i,e.differ.empty))n=Dl(n,Fq(t,i));t=t+1}if(t<e.oldValue.length)n=Dl(n,Mq(0,t));if(t<e.newValue.length)n=Dl(n,Aq(aT(t)(e.newValue)));return n},Dl,YO;var ZO=S(()=>{tt();we();ee();Dp();Tq=Symbol.for("effect/DifferReadonlyArrayPatch");ql={...js.prototype,[Tq]:{_Value:JO,_Patch:JO}},Oq=Object.assign(Object.create(ql),{_tag:"Empty"}),Cq=Object.create(Oq),Eq=Object.assign(Object.create(ql),{_tag:"AndThen"}),Iq=Object.assign(Object.create(ql),{_tag:"Append"}),Pq=Object.assign(Object.create(ql),{_tag:"Slice"}),Nq=Object.assign(Object.create(ql),{_tag:"Update"}),Dl=h(2,(e,t)=>kq(e,t)),YO=h(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=zt(e);while(Zo(o)){let i=gt(o),a=nr(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 XO,Dq,ui=(e)=>{let t=Object.create(Dq);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},Dy=()=>ui({empty:My(),combine:(e,t)=>Fl(t)(e),diff:(e,t)=>HO(e,t),patch:(e,t)=>BO(t)(e)}),qy=()=>ui({empty:Fy(),combine:(e,t)=>qp(t)(e),diff:(e,t)=>WO(e,t),patch:(e,t)=>zO(t)(e)}),$y=(e)=>ui({empty:Ly(),combine:(t,n)=>Dl(t,n),diff:(t,n)=>GO({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>YO(t,n,e)}),Up=()=>QO((e,t)=>t),QO=(e)=>ui({empty:_e,combine:(t,n)=>{if(t===_e)return n;if(n===_e)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(U(t,n))return _e;return el(n)},patch:(t,n)=>e(n,t(n))});var jp=S(()=>{we();ee();Pe();VO();KO();ZO();XO=Symbol.for("effect/Differ"),Dq={[XO]:{_P:_e,_V:_e},pipe(){return F(this,arguments)}}});var $l=255,eC=8,Hp=(e)=>e&$l,Bp=(e)=>e>>eC&$l,Sa=(e,t)=>(e&$l)+((t&e&$l)<<eC),jy,tC=(e)=>Sa(e,e),nC=(e)=>Sa(e,0),rC,Hy,oC=(e)=>~e>>>0&$l;var By=S(()=>{ee();jy=Sa(0,0),rC=h(2,(e,t)=>Sa(Hp(e)&~t,Bp(e))),Hy=h(2,(e,t)=>e|t)});var qq=0,To=1,aC=2,Vy=4,Vp=16,Wy=32,sC=(e)=>Wp(e,Wy),zy,Oo=(e)=>Ky(e)&&!$q(e),Ky=(e)=>Wp(e,To),Wp,Jy=(...e)=>e.reduce((t,n)=>t|n,0),cC,Gy=(e)=>Wp(e,Vy),$q=(e)=>Wp(e,Vp),Ul,jl,Yy;var Hl=S(()=>{ee();jp();By();zy=h(2,(e,t)=>e|t),Wp=h(2,(e,t)=>(e&t)!==0),cC=Jy(qq),Ul=h(2,(e,t)=>Sa(e^t,t)),jl=h(2,(e,t)=>e&(oC(Hp(t))|Bp(t))|Hp(t)&Bp(t)),Yy=ui({empty:jy,diff:(e,t)=>Ul(e,t),combine:(e,t)=>Hy(t)(e),patch:(e,t)=>jl(t,e)})});var lC,Xy,Qy;var ex=S(()=>{By();lC=tC,Xy=nC,Qy=rC});var nx=(e,t)=>({_tag:"Par",left:e,right:t}),zp=(e,t)=>({_tag:"Seq",left:e,right:t}),dC=(e)=>{let t=Nl(e),n=li();while(!0){let[r,o]=$O(t,[pC(),li()],([i,a],s)=>{let[c,l]=Uq(s);return[Wq(i,c),qO(a,l)]});if(n=jq(n,r),Dr(o))return UO(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},Uq=(e)=>{let t=e,n=pC(),r=li(),o=li();while(!0)switch(t._tag){case"Empty":{if(Dr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Ro(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=nx(zp(s,a),zp(c,a));break}case"Seq":{let{left:s,right:c}=i;t=zp(s,zp(c,a));break}case"Single":{t=i,o=Ro(a,o);break}}break}case"Single":{if(n=Vq(n,t),Dr(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")},jq=(e,t)=>{if(Dr(e))return Nl(tx(t));if(zq(t))return e;let n=Xq(e.head),r=Kq(t);if(n.length===1&&r.length===1&&U(n[0],r[0]))return Ro(Zq(e.head,tx(t)),e.tail);return Ro(tx(t),e)},Hq,Bq,Kp,pC=()=>new Kp(Us()),Vq=(e,t)=>new Kp(NO(e.map,t.dataSource,(n)=>KR(er(n,fT(t.blockedRequest)),()=>yt(t.blockedRequest)))),Wq=(e,t)=>new Kp(Ey(e.map,t.map,(n,r,o)=>Oy(n,o,ct(Ty(n,o),{onNone:()=>r,onSome:(i)=>En(r,i)})))),zq=(e)=>MO(e.map),Kq=(e)=>Array.from(Cy(e.map)),tx=(e)=>Yq(FO(e.map,(t)=>yt(t))),Jq,Gq,rx,Yq=(e)=>new rx(e),Zq=(e,t)=>new rx(Ey(t.map,e.map,(n,r,o)=>Oy(n,o,ct(Ty(n,o),{onNone:()=>$n(),onSome:(i)=>En(i,r)})))),Xq=(e)=>Array.from(Cy(e.map)),fC=(e)=>Array.from(e.map);var mC=S(()=>{Mr();we();Np();Lp();lt();Hq=Symbol.for("effect/RequestBlock/RequestBlockParallel"),Bq={_R:(e)=>e};Kp=class Kp{map;[Hq]=Bq;constructor(e){this.map=e}};Jq=Symbol.for("effect/RequestBlock/RequestBlockSequential"),Gq={_R:(e)=>e};rx=class rx{map;[Jq]=Gq;constructor(e){this.map=e}}});var Hs="Pending",Jp="Done";var e$="effect/Deferred",gC,yC,xC=(e)=>({_tag:Hs,joiners:e}),SC=(e)=>({_tag:Jp,effect:e});var bC=S(()=>{gC=Symbol.for(e$),yC={_E:(e)=>e,_A:(e)=>e}});var Bs;var _C=S(()=>{Bs=class Bs{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 Bs(this.self)}}});class sx{patch;op;_op=ml;constructor(e,t){this.patch=e,this.op=t}}var Zp=(e,t)=>{let n=new Pt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},ax=(e)=>{let t=new Pt("RunBlocked");return t.effect_instruction_i0=e,t},di,Pt,cx,lx,Vs=(e)=>H(e,di),Ut=(e)=>{let t=new Pt(Gd);return t.effect_instruction_i0=e,t},IC,Co,Eo=(e)=>Co(e,void 0),ux=function(){let e=new Pt(ra);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(Qi("you're not supposed to end up here"))}return e},Bl=(e,t=Hn)=>{let n=new Pt(na),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,Kl(n,(o)=>Vs(r)?r:xt)},AC=(e,t=Hn)=>$e(()=>Bl(e,t)),pi=(e,t=Hn)=>ux(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 Pt(na);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?Kl(i,(c)=>{if(s)s.abort();return a??xt}):i}),Vl,wC,Xp=(e,t)=>{if(De(t))return new Proxy(e,{has(n,r){return r===ya||r===wC||r in n},get(n,r){if(r===ya)return t.value;if(r===wC)return e;return n[r]}});return e},Qp=(e)=>rn(e)&&!(ya in e)?Ut((t)=>Gt(kn(Xp(e,gf(t))))):Gt(kn(e)),dx=(e)=>PC(()=>kn(new l$(e))),ba=(e)=>Ws(e,{onFailure:(t)=>Re(ie(t)),onSuccess:(t)=>Re(ce(t))}),fi=(e)=>MC(e,{onFailure:Ne,onSuccess:He}),Mt=(e)=>rn(e)&&!(ya in e)?Ut((t)=>Gt(Ns(Xp(e,gf(t))))):Gt(Ns(e)),px=(e)=>re(Z(e),Mt),Gt=(e)=>{let t=new cx(pn);return t.effect_instruction_i0=e,t},PC=(e)=>re(Z(e),Gt),fx,Wl=(e)=>Ut((t)=>e(t.id())),re,mx=(e)=>{let t=new Pt("OnStep");return t.effect_instruction_i0=e,t},zl=(e)=>re(e,_e),MC,Bn,Ws,Vn,_a,ef=(e)=>{let t=new Pt(oa);return t.effect_instruction_i0=lC(To),t.effect_instruction_i1=()=>e,t},nt,tf,wa,zs,Kl,Re=(e)=>{let t=new lx(fn);return t.effect_instruction_i0=e,t},$e=(e)=>{let t=new Pt(ra);return t.commit=e,t},Z=(e)=>{let t=new Pt(Jd);return t.effect_instruction_i0=e,t},nf,hx=(e)=>Ut((t)=>{let n=t.getFiberRef(Yp),r=x(n,Le(()=>t.scope()));return e(gi(Yp,Y(r)))}),rf=(e)=>{let t=new Pt(oa);return t.effect_instruction_i0=Xy(To),t.effect_instruction_i1=()=>e,t},mi=(e)=>ux(e,function(){let t=new Pt(oa);return t.effect_instruction_i0=Xy(To),t.effect_instruction_i1=(n)=>Ky(n)?$t(()=>this.effect_instruction_i0(ef)):$t(()=>this.effect_instruction_i0(rf)),t}),xt,gx=(e)=>{let t=new Pt(oa);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},Jl=(e)=>{let t=new Pt(bs);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},Gl=(e)=>{let t=new Pt(ws);return typeof e?.priority<"u"?VC(t,e.priority):t},of,af,hi,Yl,NC=(e)=>re(fx,(t)=>x(e,Zl(t))),Zl,FC,LC,DC,yx,xx,Sx,qC,$C,o$="effect/FiberRef",i$,a$,sf=(e)=>Ut((t)=>He(t.getFiberRef(e))),va,ox,s$,gi,jt=(e,t)=>Ra(e,{differ:Up(),fork:t?.fork??_e,join:t?.join}),UC=(e)=>{let t=qy();return Ra(e,{differ:t,fork:t.empty})},c$=(e)=>{let t=$y(Up());return Ra(e,{differ:t,fork:t.empty})},cf=(e)=>{let t=Dy();return Ra(e,{differ:t,fork:t.empty})},Ra=(e,t)=>({...Yo,[i$]:a$,initial:e,commit(){return sf(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)}),jC=(e)=>Ra(e,{differ:Yy,fork:Yy.empty}),Ta,Ks,bx,HC,_x,BC,VC,WC,zC,KC,JC,Xl,Yp,Ql,lf,uf,df=(e,t)=>e.addFinalizer(()=>Eo(t)),wx=(e,t)=>e.close(t),Js=(e,t)=>e.fork(t),pf,Oa=(e,t)=>{class n extends pf{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},vC,l$,ix,_Y,GC=(e)=>H(e,ix),RC,u$,TC,eu,OC,wY,CC,vY,EC,RY,kC,d$,Gs=(e)=>Vs(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),vx=(e)=>e._tag==="Success",YC,tu=(e)=>YC(e,void 0),Ca=(e,t)=>p$(e,t?.parallel?xa:Jt),Rx=(e)=>Ne(kn(e)),nu=(e)=>Ne(Ns(e)),Ne=(e)=>{let t=new cx(pn);return t.effect_instruction_i0=e,t},Tx=(e)=>Ne(sr(e)),Gp,ff,He=(e)=>{let t=new lx(fn);return t.effect_instruction_i0=e,t},Wn,Ox,p$=(e,t)=>{let n=rp(e);if(!or(n))return B();return x(ar(n),Ts(x(ir(n),Gp(yt)),(r,o)=>x(r,Ox(o,{onSuccess:(i,a)=>x(i,Kt(a)),onFailure:t}))),Gp(ei),Gp((r)=>xo(r)),Y)},ZC=(e)=>({...Yo,[gC]:yC,state:Ep(xC([])),commit(){return mf(this)},blockingOn:e}),mf=(e)=>AC((t)=>{let n=Ds(e.state);switch(n._tag){case Jp:return t(n.effect);case Hs:return n.joiners.push(t),f$(e,t)}},e.blockingOn),hf=(e,t)=>{let n=Ds(e.state);if(n._tag===Hs){kp(e.state,SC(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},f$=(e,t)=>Z(()=>{let n=Ds(e.state);if(n._tag===Hs){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),m$,XC=()=>m$,Ea=(e)=>re(XC(),e),h$,Cx,gf=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?Y(t):B()};var St=S(()=>{tt();Mr();jn();mn();we();$s();ee();Be();Np();et();Lp();by();lt();Pe();Ee();ex();Jo();Ls();bC();jp();po();Hl();_C();di=Symbol.for("effect/Effect");Pt=class Pt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[di]=Go;constructor(e){this._op=e}[W](e){return this===e}[J](){return me(this,ll(this))}pipe(){return F(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:ve(this.effect_instruction_i0),effect_instruction_i1:ve(this.effect_instruction_i1),effect_instruction_i2:ve(this.effect_instruction_i2)}}toString(){return Ce(this.toJSON())}[de](){return this.toJSON()}[Symbol.iterator](){return new Bs(new co(this))}};cx=class cx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[di]=Go;constructor(e){this._op=e,this._tag=e}[W](e){return Gs(e)&&e._op==="Failure"&&U(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return x(Oe(this._tag),ae(q(this.effect_instruction_i0)),me(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 Ce(this.toJSON())}[de](){return this.toJSON()}[Symbol.iterator](){return new Bs(new co(this))}};lx=class lx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[di]=Go;constructor(e){this._op=e,this._tag=e}[W](e){return Gs(e)&&e._op==="Success"&&U(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return x(Oe(this._tag),ae(q(this.effect_instruction_i0)),me(this))}get value(){return this.effect_instruction_i0}pipe(){return F(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:ve(this.value)}}toString(){return Ce(this.toJSON())}[de](){return this.toJSON()}[Symbol.iterator](){return new Bs(new co(this))}};IC=h(3,(e,t,n)=>mi((r)=>re(e,(o)=>re(fi($e(()=>r(t(o)))),(i)=>$e(()=>n(o,i)).pipe(Bn({onFailure:(a)=>{switch(i._tag){case pn:return Gt(Jt(i.effect_instruction_i0,a));case fn:return Gt(a)}},onSuccess:()=>i})))))),Co=h(2,(e,t)=>re(e,()=>Re(t))),Vl=h(2,(e,t)=>Ws(e,{onFailure:t,onSuccess:Re})),wC=Symbol.for("effect/OriginalAnnotation"),fx=Ut((e)=>Re(e.id())),re=h(2,(e,t)=>{let n=new Pt(xs);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),MC=h(2,(e,t)=>Bn(e,{onFailure:(n)=>Re(t.onFailure(n)),onSuccess:(n)=>Re(t.onSuccess(n))})),Bn=h(2,(e,t)=>{let n=new Pt(Ss);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),Ws=h(2,(e,t)=>Bn(e,{onFailure:(n)=>{if(oy(n).length>0)return Gt(XT(n));let o=ry(n);if(o.length>0)return t.onFailure($g(o));return Gt(n)},onSuccess:t.onSuccess})),Vn=h(2,(e,t)=>$e(()=>{let n=qe(e),r=ia(n.length),o=0;return Co(Jl({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),_a=h(2,(e,t)=>$e(()=>{let n=qe(e),r=0;return Jl({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),nt=h(2,(e,t)=>re(e,(n)=>Z(()=>t(n)))),tf=h(2,(e,t)=>Ws(e,{onFailure:(n)=>px(()=>t.onFailure(n)),onSuccess:(n)=>Z(()=>t.onSuccess(n))})),wa=h(2,(e,t)=>Bn(e,{onFailure:(n)=>{let r=_p(n);switch(r._tag){case"Left":return px(()=>t(r.left));case"Right":return Gt(r.right)}},onSuccess:Re})),zs=h(2,(e,t)=>mi((n)=>Bn(n(e),{onFailure:(r)=>{let o=Ne(r);return Bn(t(o),{onFailure:(i)=>Ne(Jt(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=He(r);return hi(t(o),o)}}))),Kl=h(2,(e,t)=>zs(e,ff({onFailure:(n)=>Fs(n)?Eo(t(iy(n))):xt,onSuccess:()=>xt}))),nf=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(Vs(r))return Co(r,n);else if(_R(r))return Bl((o)=>{r.then((i)=>o(Re(n)),(i)=>o(Mt(new d$(i,"An unknown error occurred in Effect.tap"))))});return Re(n)})),xt=Re(void 0),of=h(2,(e,t)=>re(e,(n)=>nt(t,(r)=>[n,r]))),af=h(2,(e,t)=>re(e,(n)=>Co(t,n))),hi=h(2,(e,t)=>re(e,()=>t)),Yl=AC(()=>{let e=setInterval(()=>{},2147483647);return Z(()=>clearInterval(e))}),Zl=h(2,(e,t)=>re(e.interruptAsFork(t),()=>e.await)),FC={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return F(this,arguments)}},LC={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return F(this,arguments)}},DC={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return F(this,arguments)}},yx={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return F(this,arguments)}},xx={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return F(this,arguments)}},Sx={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return F(this,arguments)}},qC={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return F(this,arguments)}},$C={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return F(this,arguments)}},i$=Symbol.for(o$),a$={_A:(e)=>e},va=h(2,(e,t)=>re(sf(e),t)),ox=h(2,(e,t)=>s$(e,()=>[void 0,t])),s$=h(2,(e,t)=>Ut((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),Re(r)})),gi=h(3,(e,t,n)=>IC(af(sf(t),ox(t,n)),()=>e,(r)=>ox(t,r))),Ta=te(Symbol.for("effect/FiberRef/currentContext"),()=>cf(si())),Ks=te(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>jt(0)),bx=te(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>jt(2048)),HC=te(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>jt(Us())),_x=te(Symbol.for("effect/FiberRef/currentLogLevel"),()=>jt(xx)),BC=te(Symbol.for("effect/FiberRef/currentLogSpan"),()=>jt(li())),VC=h(2,(e,t)=>gi(e,Ks,t)),WC=te(Symbol.for("effect/FiberRef/currentConcurrency"),()=>jt("unbounded")),zC=te(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>jt(!0)),KC=te(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>jt(Y(Sx))),JC=te(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>jt(Y(yx))),Xl=te(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>c$(go())),Yp=te(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>jt(B(),{fork:()=>B(),join:(e,t)=>e})),Ql=te(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>jt(wo,{fork:()=>wo,join:(e,t)=>e})),lf=Symbol.for("effect/Scope"),uf=Symbol.for("effect/CloseableScope"),pf=function(){class e extends globalThis.Error{commit(){return Mt(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[de](){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 sr(Ps(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,cg),e}(),sC=Symbol.for("effect/Cause/errors/RuntimeException"),$q=ba({[sC]:sC},"RuntimeException"),Qy=Symbol.for("effect/Cause/errors/InterruptedException"),V7=ba({[Qy]:Qy},"InterruptedException"),cC=Symbol.for("effect/Cause/errors/IllegalArgument"),jq=ba({[cC]:cC},"IllegalArgumentException"),lC=Symbol.for("effect/Cause/errors/NoSuchElement"),Jl=ba({[lC]:lC},"NoSuchElementException"),uC=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),W7=ba({[uC]:uC},"InvalidPubSubCapacityException"),dC=Symbol.for("effect/Cause/errors/ExceededCapacityException"),z7=ba({[dC]:dC},"ExceededCapacityException"),pC=Symbol.for("effect/Cause/errors/Timeout"),K7=ba({[pC]:pC},"TimeoutException"),fC=Symbol.for("effect/Cause/errors/UnknownException"),Hq=function(){class e extends sf{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[fC]:fC,name:"UnknownException"}),e}(),NC=h(2,(e,t)=>{switch(e._tag){case ln:return Me(e.effect_instruction_i0);case un:return He(t)}}),Vp=h(2,(e,t)=>{switch(e._tag){case ln:return Me(e.effect_instruction_i0);case un:return He(t(e.effect_instruction_i0))}}),cf=h(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case ln:return t(e.effect_instruction_i0);case un:return n(e.effect_instruction_i0)}}),Bn=He(void 0),bx=h(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case ln:switch(t._tag){case un:return Me(e.effect_instruction_i0);case ln:return Me(n(e.effect_instruction_i0,t.effect_instruction_i0))}case un:switch(t._tag){case un:return He(r(e.effect_instruction_i0,t.effect_instruction_i0));case ln:return Me(t.effect_instruction_i0)}}}),Wq=qt((e)=>He(e.currentContext)),zq=h(2,(e,t)=>fi(Sa,t)(e)),_x=h(2,(e,t)=>wa((n)=>zq(e,t(n))))});var DC,qC;var UC=S(()=>{Ns();DC=NT,qC=sr});var pf="And",ff="Or",mf="InvalidData",hf="MissingData",gf="SourceUnavailable",yf="Unsupported";var Gq="effect/ConfigError",$C,Js,xf=(e,t)=>{let n=Object.create(Js);return n._op=pf,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},Sf=(e,t)=>{let n=Object.create(Js);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},wx=(e,t,n={pathDelim:"."})=>{let r=Object.create(Js);return r._op=mf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${x(this.path,mo(n.pathDelim))}: "${this.message}")`}}),r},Fr=(e,t,n={pathDelim:"."})=>{let r=Object.create(Js);return r._op=hf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${x(this.path,mo(n.pathDelim))}: "${this.message}")`}}),r},vx=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(Js);return o._op=gf,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${x(this.path,mo(r.pathDelim))}: "${this.message}")`}}),o},Rx=(e,t,n={pathDelim:"."})=>{let r=Object.create(Js);return r._op=yf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${x(this.path,mo(n.pathDelim))}: "${this.message}")`}}),r},mi,jC;var Tx=S(()=>{Qe();dn();ee();$C=Symbol.for(Gq),Js={_tag:"ConfigError",[$C]:$C},mi=h(2,(e,t)=>{switch(e._op){case pf:return xf(mi(e.left,t),mi(e.right,t));case ff:return Sf(mi(e.left,t),mi(e.right,t));case mf:return wx([...t,...e.path],e.message);case hf:return Fr([...t,...e.path],e.message);case gf:return vx([...t,...e.path],e.message,e.cause);case yf:return Rx([...t,...e.path],e.message)}}),jC=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case pf:{r.push(a.right),r.push(a.left),o.push(ie({_op:"AndCase"}));break}case ff:{r.push(a.right),r.push(a.left),o.push(ie({_op:"OrCase"}));break}case mf:{o.push(ce(n.invalidDataCase(t,a.path,a.message)));break}case hf:{o.push(ce(n.missingDataCase(t,a.path,a.message)));break}case gf:{o.push(ce(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case yf:{o.push(ce(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 Yq="effect/Clock",BC,Zl,Zq=2147483647,VC,WC,Xq,zC,KC=()=>new zC;var Ox=S(()=>{Un();fy();ee();xt();BC=Symbol.for(Yq),Zl=fn("effect/Clock"),VC={unsafeSchedule(e,t){let n=wp(t);if(n>Zq)return Ho;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},WC=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))}}(),Xq=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return WC;let t=WC()-e.bigint();return()=>t+e.bigint()}();zC=class zC{[BC]=BC;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return Xq()}currentTimeMillis=Y(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=Y(()=>this.unsafeCurrentTimeNanos());scheduler(){return _e(VC)}sleep(e){return li((t)=>{let n=VC.unsafeSchedule(()=>t(yt),e);return To(Y(n))})}}});var Lr;var Xl=S(()=>{Gd();Lr=IR});var Gs=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var Cx=()=>{};var YC,_f;var ZC=S(()=>{Qe();dn();ee();Ap();ct();Tx();YC={_tag:"Empty"},_f=h(2,(e,t)=>{let n=El(t),r=e;while(Ty(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=_o(o.first,_o(o.second,n.tail));break}case"MapName":{r=nr(r,o.f),n=n.tail;break}case"Nested":{r=_s(r,o.name),n=n.tail;break}case"Unnested":{if(x(uo(r),NR(o.name)))r=tr(r),n=n.tail;else return ie(Fr(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return ce(r)})});var XC="Constant",QC="Fail",eE="Fallback",tE="Described",nE="Lazy",rE="MapOrFail",oE="Nested",iE="Primitive",aE="Redacted",sE="Sequence",cE="HashMap",lE="ZipWith";var wf=(e,t)=>[...e,...t],iU="effect/ConfigProvider",uE,pE,aU="effect/ConfigProviderFlat",dE,sU=(e)=>({[uE]:uE,pipe(){return M(this,arguments)},...e}),cU=(e)=>({[dE]:dE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),lU=(e)=>sU({load:(t)=>re(In(e,fo(),t,!1),(n)=>st(uo(n),{onNone:()=>Pt(Fr(fo(),`Expected a single value having structure: ${t}`)),onSome:_e})),flattened:e}),fE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>x(c,mo(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return lU(cU({load:(c,l,u=!0)=>{let d=r(c),p=i(),f=d in p?G(p[d]):H();return x(f,ga(()=>Fr(c,`Expected ${d} to exist in the process context`)),re((m)=>gU(m,c,l,n,u)))},enumerateChildren:(c)=>Y(()=>{let l=i(),p=Object.keys(l).map((f)=>o(f.toUpperCase())).filter((f)=>{for(let m=0;m<c.length;m++){let y=x(c,Tg(m)),g=f[m];if(g===void 0||y!==g)return!1}return!0}).flatMap((f)=>f.slice(c.length,c.length+1));return ET(p)}),patch:YC}))},uU=(e,t,n,r)=>{let o=kg(n.length,(c)=>c>=r.length?H():G([e(c),c+1])),i=kg(r.length,(c)=>c>=n.length?H():G([t(c),c+1])),a=wf(n,o),s=wf(r,i);return[a,s]},dU=(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},pU,fU=(e)=>jC(e,void 0,pU),In=(e,t,n,r)=>{let o=n;switch(o._tag){case XC:return _e(Vt(o.value));case tE:return $e(()=>In(e,t,o.config,r));case QC:return Pt(Fr(t,o.message));case eE:return x($e(()=>In(e,t,o.first,r)),ql((i)=>{if(o.condition(i))return x(In(e,t,o.second,r),ql((a)=>Pt(Sf(i,a))));return Pt(i)}));case nE:return $e(()=>In(e,t,o.config(),r));case rE:return $e(()=>x(In(e,t,o.original,r),re(Hn((i)=>x(o.mapOrFail(i),ga(mi(dU(t,o.original))))))));case oE:return $e(()=>In(e,wf(t,Vt(o.name)),o.config,r));case iE:return x(_f(t,e.patch),re((i)=>x(e.load(i,o,r),re((a)=>{if(a.length===0){let s=x(HR(i),De(()=>"<n/a>"));return Pt(Fr([],`Expected ${o.description} with name ${s}`))}return _e(a)}))));case aE:return $e(()=>x(In(e,t,o.original,r),ga(fU),et(nr(o.redact))));case sE:return x(_f(t,e.patch),re((i)=>x(e.enumerateChildren(i),re(xU),re((a)=>{if(a.length===0)return $e(()=>et(In(e,t,o.config,!0),Vt));return x(Hn(a,(s)=>In(e,UR(t,`[${s}]`),o.config,!0)),et((s)=>{let c=Yd(s);if(c.length===0)return Vt(fo());return Vt(c)}))}))));case cE:return $e(()=>x(_f(t,e.patch),re((i)=>x(e.enumerateChildren(i),re((a)=>x(a,Hn((s)=>In(e,wf(i,Vt(s)),o.valueConfig,r)),et((s)=>{if(s.length===0)return Vt(qs());return x(yU(s),nr((c)=>gO(Eg(Ue(a),c))))})))))));case lE:return $e(()=>x(In(e,t,o.left,r),ma,re((i)=>x(In(e,t,o.right,r),ma,re((a)=>{if(Le(i)&&Le(a))return Pt(xf(i.left,a.left));if(Le(i)&&It(a))return Pt(i.left);if(It(i)&&Le(a))return Pt(a.left);if(It(i)&&It(a)){let s=x(t,mo(".")),c=mU(t,s),[l,u]=uU(c,c,x(i.right,nr(ce)),x(a.right,nr(ce)));return x(l,Eg(u),Hn(([d,p])=>x(Qp(d,p),et(([f,m])=>o.zip(f,m)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},mU=(e,t)=>(n)=>ie(Fr(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),hU=(e,t)=>e.split(new RegExp(`\\s*${Gs(t)}\\s*`)),gU=(e,t,n,r,o)=>{if(!o)return x(n.parse(e),Yp({onFailure:mi(t),onSuccess:Vt}));return x(hU(e,r),Hn((i)=>n.parse(i.trim())),ga(mi(t)))},yU=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),xU=(e)=>x(Hn(e,bU),Yp({onFailure:()=>fo(),onSuccess:po(Lr)}),ma,et(CR)),SU,bU=(e)=>{let t=e.match(SU);if(t!==null){let n=t[2];return x(n!==void 0&&n.length>0?G(n):H(),er(_U))}return H()},_U=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?H():G(t)};var mE=S(()=>{Qe();Un();dn();ee();kp();aa();Xl();ct();Ae();Cx();Tx();ZC();xt();uE=Symbol.for(iU),pE=fn("effect/ConfigProvider"),dE=Symbol.for(aU),pU={andCase:(e,t,n)=>xf(t,n),orCase:(e,t,n)=>Sf(t,n),invalidDataCase:(e,t)=>wx(t,"<redacted>"),missingDataCase:(e,t)=>Fr(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>vx(t,"<redacted>",r),unsupportedCase:(e,t)=>Rx(t,"<redacted>")},SU=/^(\[(\d+)\])$/});var hE,vf,gE;var Ex=S(()=>{Un();xt();hE=Symbol.for("effect/Console"),vf=fn("effect/Console"),gE={[hE]:hE,assert(e,...t){return Y(()=>{console.assert(e,...t)})},clear:Y(()=>{console.clear()}),count(e){return Y(()=>{console.count(e)})},countReset(e){return Y(()=>{console.countReset(e)})},debug(...e){return Y(()=>{console.debug(...e)})},dir(e,t){return Y(()=>{console.dir(e,t)})},dirxml(...e){return Y(()=>{console.dirxml(...e)})},error(...e){return Y(()=>{console.error(...e)})},group(e){return e?.collapsed?Y(()=>console.groupCollapsed(e?.label)):Y(()=>console.group(e?.label))},groupEnd:Y(()=>{console.groupEnd()}),info(...e){return Y(()=>{console.info(...e)})},log(...e){return Y(()=>{console.log(...e)})},table(e,t){return Y(()=>{console.table(e,t)})},time(e){return Y(()=>console.time(e))},timeEnd(e){return Y(()=>console.timeEnd(e))},timeLog(e,...t){return Y(()=>{console.timeLog(e,...t)})},trace(...e){return Y(()=>{console.trace(...e)})},warn(...e){return Y(()=>{console.warn(...e)})},unsafe:console}});var RU="effect/Random",yE,xE,SE,TU=(e,t)=>$e(()=>x(Y(()=>Array.from(e)),re((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return x(r,ha((o)=>x(t(o),et((i)=>OU(n,o-1,i)))),Ro(Xd(n)))}))),OU=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},bE=(e)=>new SE(D(e));var _E=S(()=>{Ir();Un();ee();Be();Wo();xt();yE=Symbol.for(RU),xE=fn("effect/Random");SE=class SE{seed;[yE]=yE;PRNG;constructor(e){this.seed=e,this.PRNG=new ng(e)}get next(){return Y(()=>this.PRNG.number())}get nextBoolean(){return et(this.next,(e)=>e>0.5)}get nextInt(){return Y(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return et(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return Y(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return TU(e,(t)=>this.nextIntBetween(0,t))}}});class RE{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:vE(32),this.spanId=vE(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 wE,EU=(e)=>({[wE]:wE,...e}),Ql,Rf,vE,TE,OE;var Tf=S(()=>{Un();ee();wE=Symbol.for("effect/Tracer"),Ql=fn("effect/Tracer"),Rf=fn("effect/ParentSpan"),vE=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();TE=EU({span:(e,t,n,r,o,i)=>new RE(e,t,n,r,o,i),context:(e)=>e()}),OE=Tl()("effect/Tracer/DisablePropagation",{defaultValue:Ho})});var AU,eu;var CE=S(()=>{Un();ee();Ox();mE();xt();Ex();_E();Tf();AU=x(oi(),Pr(Zl,KC()),Pr(vf,gE),Pr(xE,bE(Math.random())),Pr(pE,fE()),Pr(Ql,TE)),eu=te(Symbol.for("effect/DefaultServices/currentServices"),()=>nf(AU))});var MU,EE=(e)=>{let t={BaseEffectError:class extends MU{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var kE=S(()=>{xt();MU=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends sf{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 IE,NU,Ix;var Ax=S(()=>{co();IE=so,NU=yR;Ix=class Ix extends NU{}});var PE="Sequential",ME="Parallel",FU="ParallelN",Ys,NE,FE=(e)=>({_tag:FU,parallelism:e}),Px=(e)=>e._tag===PE,Mx=(e)=>e._tag===ME;var Of=S(()=>{Ys={_tag:PE},NE={_tag:ME}});var Cf,Ef,kf;var LE=S(()=>{Of();Cf=Ys,Ef=NE,kf=FE});function DE(e){return new Oo(e)}function qE(){return DE(new Map)}var Fx,Oo,DU=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(Pe(i)&&Pe(a)){let l=ht(i)[0],u=tr(i),d=ht(a)[0],p=ht(a)[1],f=tr(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},Dx,qx,UE=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(q(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},tu,Ux,hi,Zs,Lx=(e,t,n,r)=>{let o=e.get(n)??[],i;if(Pe(o)){let[a,s]=ht(o);if(a[W](t))if(q(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},$E;var If=S(()=>{Qe();Se();ee();ct();Ae();Fx=Symbol.for("effect/FiberRefs");Oo=class Oo{locals;[Fx]=Fx;constructor(e){this.locals=e}pipe(){return M(this,arguments)}};Dx=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][W](t)){if(!r.has(i)){if(q(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=DU(i,s,o);if(l){let u=i.diff(c,a),d=s[0][1],p=i.join(d,i.patch(u)(d));if(!q(d,p)){let f,m=s[0][0];if(m[W](t))f=[[m,p],...s.slice(1)];else f=[[t,p],...s];r.set(i,f)}}}}),new Oo(r)}),qx=h(2,(e,t)=>{let n=new Map;return UE(e,n,t),new Oo(n)}),tu=h(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new Oo(n)}),Ux=h(2,(e,t)=>{if(!e.locals.has(t))return H();return G(ht(e.locals.get(t))[1])}),hi=h(2,(e,t)=>x(Ux(e,t),De(()=>t.initial))),Zs=h(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new Oo(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return Lx(o,t,n,r),new Oo(o)}),$E=h(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new Oo(new Map(t));let r=new Map(e.locals);if(n!==void 0)UE(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)Lx(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{Lx(r,a,o,s)})}),new Oo(r)})});var jE,HE,BE;var jx=S(()=>{If();jE=hi,HE=$E,BE=qE});var WE="Empty",zE="Add",KE="Remove",JE="Update",GE="AndThen",YE,ZE=(e,t)=>{let n=new Map(e.locals),r=YE;for(let[o,i]of t.locals.entries()){let a=ht(i)[1],s=n.get(o);if(s!==void 0){let c=ht(s)[1];if(!q(c,a))r=Af({_tag:JE,fiberRef:o,patch:o.diff(c,a)})(r)}else r=Af({_tag:zE,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=Af({_tag:KE,fiberRef:o})(r);return r},Af,XE;var QE=S(()=>{Qe();Se();ee();If();YE={_tag:WE},Af=h(2,(e,t)=>({_tag:GE,first:e,second:t})),XE=h(3,(e,t,n)=>{let r=n,o=Vt(e);while(Pe(o)){let i=ht(o),a=tr(o);switch(i._tag){case WE:{o=a;break}case zE:{r=Zs(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case KE:{r=tu(r,i.fiberRef),o=a;break}case JE:{let s=hi(r,i.fiberRef);r=Zs(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case GE:{o=_s(i.first)(_s(i.second)(a));break}}}return r})});var ek,tk;var nk=S(()=>{QE();ek=ZE,tk=XE});var Mf="effect/FiberStatus",gi,Pf="Done",rk="Running",ok="Suspended",$U,ik,ak,sk,ck,lk=(e)=>new ak(e),uk=(e,t)=>new sk(e,t),Nf=(e)=>j(e,gi),dk=(e)=>e._tag===Pf;var pk=S(()=>{Se();ee();Be();Ce();gi=Symbol.for(Mf),$U=Re(`${Mf}-${Pf}`);ik=class ik{[gi]=gi;_tag=Pf;[J](){return $U}[W](e){return Nf(e)&&e._tag===Pf}};ak=class ak{runtimeFlags;[gi]=gi;_tag=rk;constructor(e){this.runtimeFlags=e}[J](){return x(D(Mf),ae(D(this._tag)),ae(D(this.runtimeFlags)),me(this))}[W](e){return Nf(e)&&e._tag===rk&&this.runtimeFlags===e.runtimeFlags}};sk=class sk{runtimeFlags;blockingOn;[gi]=gi;_tag=ok;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[J](){return x(D(Mf),ae(D(this._tag)),ae(D(this.runtimeFlags)),ae(D(this.blockingOn)),me(this))}[W](e){return Nf(e)&&e._tag===ok&&this.runtimeFlags===e.runtimeFlags&&q(this.blockingOn,e.blockingOn)}};ck=new ik});var fk,Hx,mk,hk;var gk=S(()=>{pk();fk=ck,Hx=lk,mk=uk,hk=dk});var BU,VU,WU,zU,KU,JU,GU,YU,ZU,yk,xk=(e)=>{switch(e){case"All":return BU;case"Debug":return JU;case"Error":return WU;case"Fatal":return VU;case"Info":return KU;case"Trace":return GU;case"None":return YU;case"Warning":return zU}};var Sk=S(()=>{ee();xt();Xl();Gd();BU=SC,VU=bC,WU=_C,zU=dx,KU=px,JU=fx,GU=wC,YU=vC,ZU=x(Lr,Jd((e)=>e.ordinal)),yk=Sg(ZU)});function s$(e){return Vx("Micro.evaluate: Not implemented")}class Zx{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,m$(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(Ak)}flush(){while(this.tasks.length>0)this.runTasks()}}var QU,Lf,bk,e$,Wx,vk,t$=(e,t=[])=>new vk(e,t),Rk,n$=(e=[])=>new Rk(e),r$=(e)=>e._tag==="Interrupt",_k,o$,Tk,wk,Ok,wt,Bx,Qs,Xs,Df,Ff,i$,a$,Uf=(e)=>({...a$,[Ok]:e.op,[Bx]:e.eval??s$,[Qs]:e.contA,[Xs]:e.contE,[Df]:e.ensure}),zx=(e)=>{let t=Uf(e);return function(){let n=Object.create(t);return n[wt]=e.single===!1?arguments:arguments[0],n}},Ck=(e)=>{let t={...Uf(e),[Lf]:Lf,_tag:e.op,get[e.prop](){return this[wt]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[wt]}},[W](n){return p$(n)&&n._tag===e.op&&q(this[wt],n[wt])},[J](){return me(this,ae(Re(e.op))(D(this[wt])))}};return function(n){let r=Object.create(t);return r[wt]=n,r[Qs]=void 0,r[Xs]=void 0,r[Df]=void 0,r}},Kx,Ek,c$,l$,u$,Jx,qf,d$,p$=(e)=>j(e,Lf),kk,Gx,Yx,Vx=(e)=>Gx(t$(e)),f$,m$,h$,Ik,Ak,$f,g$,y$,x$,Pk,S$=(e)=>Jx((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(Pk(!1)),t._interrupted)return Yx;return e}),b$=(e)=>Jx((t)=>{if(!t.interruptible)return e(xe);return t.interruptible=!1,t._stack.push(Pk(!0)),e(S$)}),Mk=(e,t)=>{let n=new Tk($f.context(t?.scheduler??new Zx));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 Nk=S(()=>{Un();Ax();Se();ee();Be();Xe();Sp();Ae();Ce();Wo();QU=Symbol.for("effect/Micro"),Lf=Symbol.for("effect/Micro/MicroExit"),bk=Symbol.for("effect/Micro/MicroCause"),e$={_E:xe};Wx=class Wx extends globalThis.Error{_tag;traces;[bk];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 cr(Ns(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,mg),e}(),vC=Symbol.for("effect/Cause/errors/RuntimeException"),l$=Oa({[vC]:vC},"RuntimeException"),ix=Symbol.for("effect/Cause/errors/InterruptedException"),_Y=Oa({[ix]:ix},"InterruptedException"),RC=Symbol.for("effect/Cause/errors/IllegalArgument"),u$=Oa({[RC]:RC},"IllegalArgumentException"),TC=Symbol.for("effect/Cause/errors/NoSuchElement"),eu=Oa({[TC]:TC},"NoSuchElementException"),OC=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),wY=Oa({[OC]:OC},"InvalidPubSubCapacityException"),CC=Symbol.for("effect/Cause/errors/ExceededCapacityException"),vY=Oa({[CC]:CC},"ExceededCapacityException"),EC=Symbol.for("effect/Cause/errors/Timeout"),RY=Oa({[EC]:EC},"TimeoutException"),kC=Symbol.for("effect/Cause/errors/UnknownException"),d$=function(){class e extends pf{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[kC]:kC,name:"UnknownException"}),e}(),YC=h(2,(e,t)=>{switch(e._tag){case pn:return Ne(e.effect_instruction_i0);case fn:return He(t)}}),Gp=h(2,(e,t)=>{switch(e._tag){case pn:return Ne(e.effect_instruction_i0);case fn:return He(t(e.effect_instruction_i0))}}),ff=h(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case pn:return t(e.effect_instruction_i0);case fn:return n(e.effect_instruction_i0)}}),Wn=He(void 0),Ox=h(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case pn:switch(t._tag){case fn:return Ne(e.effect_instruction_i0);case pn:return Ne(n(e.effect_instruction_i0,t.effect_instruction_i0))}case fn:switch(t._tag){case fn:return He(r(e.effect_instruction_i0,t.effect_instruction_i0));case pn:return Ne(t.effect_instruction_i0)}}}),m$=Ut((e)=>He(e.currentContext)),h$=h(2,(e,t)=>gi(Ta,t)(e)),Cx=h(2,(e,t)=>Ea((n)=>h$(e,t(n))))});var QC,eE;var tE=S(()=>{Ls();QC=YT,eE=cr});var yf="And",xf="Or",Sf="InvalidData",bf="MissingData",_f="SourceUnavailable",wf="Unsupported";var x$="effect/ConfigError",nE,Ys,vf=(e,t)=>{let n=Object.create(Ys);return n._op=yf,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},Rf=(e,t)=>{let n=Object.create(Ys);return n._op=xf,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},Ex=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ys);return r._op=Sf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${x(this.path,yo(n.pathDelim))}: "${this.message}")`}}),r},qr=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ys);return r._op=bf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${x(this.path,yo(n.pathDelim))}: "${this.message}")`}}),r},kx=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(Ys);return o._op=_f,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${x(this.path,yo(r.pathDelim))}: "${this.message}")`}}),o},Ix=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ys);return r._op=wf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${x(this.path,yo(n.pathDelim))}: "${this.message}")`}}),r},yi,rE;var Ax=S(()=>{tt();mn();ee();nE=Symbol.for(x$),Ys={_tag:"ConfigError",[nE]:nE},yi=h(2,(e,t)=>{switch(e._op){case yf:return vf(yi(e.left,t),yi(e.right,t));case xf:return Rf(yi(e.left,t),yi(e.right,t));case Sf:return Ex([...t,...e.path],e.message);case bf:return qr([...t,...e.path],e.message);case _f:return kx([...t,...e.path],e.message,e.cause);case wf:return Ix([...t,...e.path],e.message)}}),rE=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case yf:{r.push(a.right),r.push(a.left),o.push(ie({_op:"AndCase"}));break}case xf:{r.push(a.right),r.push(a.left),o.push(ie({_op:"OrCase"}));break}case Sf:{o.push(ce(n.invalidDataCase(t,a.path,a.message)));break}case bf:{o.push(ce(n.missingDataCase(t,a.path,a.message)));break}case _f:{o.push(ce(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case wf:{o.push(ce(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 S$="effect/Clock",iE,ru,b$=2147483647,aE,sE,_$,cE,lE=()=>new cE;var Px=S(()=>{jn();Sy();ee();St();iE=Symbol.for(S$),ru=gn("effect/Clock"),aE={unsafeSchedule(e,t){let n=Cp(t);if(n>b$)return Wo;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},sE=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))}}(),_$=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return sE;let t=sE()-e.bigint();return()=>t+e.bigint()}();cE=class cE{[iE]=iE;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return _$()}currentTimeMillis=Z(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=Z(()=>this.unsafeCurrentTimeNanos());scheduler(){return Re(aE)}sleep(e){return pi((t)=>{let n=aE.unsafeSchedule(()=>t(xt),e);return Eo(Z(n))})}}});var $r;var ou=S(()=>{ep();$r=zR});var Zs=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var Mx=()=>{};var pE,Of;var fE=S(()=>{tt();mn();ee();Lp();lt();Ax();pE={_tag:"Empty"},Of=h(2,(e,t)=>{let n=Nl(t),r=e;while(Ay(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Ro(o.first,Ro(o.second,n.tail));break}case"MapName":{r=rr(r,o.f),n=n.tail;break}case"Nested":{r=vs(r,o.name),n=n.tail;break}case"Unnested":{if(x(mo(r),YR(o.name)))r=nr(r),n=n.tail;else return ie(qr(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return ce(r)})});var mE="Constant",hE="Fail",gE="Fallback",yE="Described",xE="Lazy",SE="MapOrFail",bE="Nested",_E="Primitive",wE="Redacted",vE="Sequence",RE="HashMap",TE="ZipWith";var Cf=(e,t)=>[...e,...t],E$="effect/ConfigProvider",OE,EE,k$="effect/ConfigProviderFlat",CE,I$=(e)=>({[OE]:OE,pipe(){return F(this,arguments)},...e}),A$=(e)=>({[CE]:CE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),P$=(e)=>I$({load:(t)=>re(In(e,go(),t,!1),(n)=>ct(mo(n),{onNone:()=>Mt(qr(go(),`Expected a single value having structure: ${t}`)),onSome:Re})),flattened:e}),kE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>x(c,yo(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return P$(A$({load:(c,l,u=!0)=>{let d=r(c),p=i(),f=d in p?Y(p[d]):B();return x(f,wa(()=>qr(c,`Expected ${d} to exist in the process context`)),re((m)=>$$(m,c,l,n,u)))},enumerateChildren:(c)=>Z(()=>{let l=i(),p=Object.keys(l).map((f)=>o(f.toUpperCase())).filter((f)=>{for(let m=0;m<c.length;m++){let y=x(c,Ag(m)),g=f[m];if(g===void 0||y!==g)return!1}return!0}).flatMap((f)=>f.slice(c.length,c.length+1));return VT(p)}),patch:pE}))},M$=(e,t,n,r)=>{let o=Fg(n.length,(c)=>c>=r.length?B():Y([e(c),c+1])),i=Fg(r.length,(c)=>c>=n.length?B():Y([t(c),c+1])),a=Cf(n,o),s=Cf(r,i);return[a,s]},N$=(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},F$,L$=(e)=>rE(e,void 0,F$),In=(e,t,n,r)=>{let o=n;switch(o._tag){case mE:return Re(zt(o.value));case yE:return $e(()=>In(e,t,o.config,r));case hE:return Mt(qr(t,o.message));case gE:return x($e(()=>In(e,t,o.first,r)),Vl((i)=>{if(o.condition(i))return x(In(e,t,o.second,r),Vl((a)=>Mt(Rf(i,a))));return Mt(i)}));case xE:return $e(()=>In(e,t,o.config(),r));case SE:return $e(()=>x(In(e,t,o.original,r),re(Vn((i)=>x(o.mapOrFail(i),wa(yi(N$(t,o.original))))))));case bE:return $e(()=>In(e,Cf(t,zt(o.name)),o.config,r));case _E:return x(Of(t,e.patch),re((i)=>x(e.load(i,o,r),re((a)=>{if(a.length===0){let s=x(oT(i),Le(()=>"<n/a>"));return Mt(qr([],`Expected ${o.description} with name ${s}`))}return Re(a)}))));case wE:return $e(()=>x(In(e,t,o.original,r),wa(L$),nt(rr(o.redact))));case vE:return x(Of(t,e.patch),re((i)=>x(e.enumerateChildren(i),re(j$),re((a)=>{if(a.length===0)return $e(()=>nt(In(e,t,o.config,!0),zt));return x(Vn(a,(s)=>In(e,tT(t,`[${s}]`),o.config,!0)),nt((s)=>{let c=tp(s);if(c.length===0)return zt(go());return zt(c)}))}))));case RE:return $e(()=>x(Of(t,e.patch),re((i)=>x(e.enumerateChildren(i),re((a)=>x(a,Vn((s)=>In(e,Cf(i,zt(s)),o.valueConfig,r)),nt((s)=>{if(s.length===0)return zt(Us());return x(U$(s),rr((c)=>PO(Ng(qe(a),c))))})))))));case TE:return $e(()=>x(In(e,t,o.left,r),ba,re((i)=>x(In(e,t,o.right,r),ba,re((a)=>{if(Fe(i)&&Fe(a))return Mt(vf(i.left,a.left));if(Fe(i)&&At(a))return Mt(i.left);if(At(i)&&Fe(a))return Mt(a.left);if(At(i)&&At(a)){let s=x(t,yo(".")),c=D$(t,s),[l,u]=M$(c,c,x(i.right,rr(ce)),x(a.right,rr(ce)));return x(l,Ng(u),Vn(([d,p])=>x(of(d,p),nt(([f,m])=>o.zip(f,m)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},D$=(e,t)=>(n)=>ie(qr(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),q$=(e,t)=>e.split(new RegExp(`\\s*${Zs(t)}\\s*`)),$$=(e,t,n,r,o)=>{if(!o)return x(n.parse(e),tf({onFailure:yi(t),onSuccess:zt}));return x(q$(e,r),Vn((i)=>n.parse(i.trim())),wa(yi(t)))},U$=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),j$=(e)=>x(Vn(e,B$),tf({onFailure:()=>go(),onSuccess:ho($r)}),ba,nt(BR)),H$,B$=(e)=>{let t=e.match(H$);if(t!==null){let n=t[2];return x(n!==void 0&&n.length>0?Y(n):B(),tr(V$))}return B()},V$=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?B():Y(t)};var IE=S(()=>{tt();jn();mn();ee();Np();pa();ou();lt();Pe();Mx();Ax();fE();St();OE=Symbol.for(E$),EE=gn("effect/ConfigProvider"),CE=Symbol.for(k$),F$={andCase:(e,t,n)=>vf(t,n),orCase:(e,t,n)=>Rf(t,n),invalidDataCase:(e,t)=>Ex(t,"<redacted>"),missingDataCase:(e,t)=>qr(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>kx(t,"<redacted>",r),unsupportedCase:(e,t)=>Ix(t,"<redacted>")},H$=/^(\[(\d+)\])$/});var AE,Ef,PE;var Nx=S(()=>{jn();St();AE=Symbol.for("effect/Console"),Ef=gn("effect/Console"),PE={[AE]:AE,assert(e,...t){return Z(()=>{console.assert(e,...t)})},clear:Z(()=>{console.clear()}),count(e){return Z(()=>{console.count(e)})},countReset(e){return Z(()=>{console.countReset(e)})},debug(...e){return Z(()=>{console.debug(...e)})},dir(e,t){return Z(()=>{console.dir(e,t)})},dirxml(...e){return Z(()=>{console.dirxml(...e)})},error(...e){return Z(()=>{console.error(...e)})},group(e){return e?.collapsed?Z(()=>console.groupCollapsed(e?.label)):Z(()=>console.group(e?.label))},groupEnd:Z(()=>{console.groupEnd()}),info(...e){return Z(()=>{console.info(...e)})},log(...e){return Z(()=>{console.log(...e)})},table(e,t){return Z(()=>{console.table(e,t)})},time(e){return Z(()=>console.time(e))},timeEnd(e){return Z(()=>console.timeEnd(e))},timeLog(e,...t){return Z(()=>{console.timeLog(e,...t)})},trace(...e){return Z(()=>{console.trace(...e)})},warn(...e){return Z(()=>{console.warn(...e)})},unsafe:console}});var K$="effect/Random",ME,NE,FE,J$=(e,t)=>$e(()=>x(Z(()=>Array.from(e)),re((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return x(r,_a((o)=>x(t(o),nt((i)=>G$(n,o-1,i)))),Co(rp(n)))}))),G$=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},LE=(e)=>new FE(q(e));var DE=S(()=>{Mr();jn();ee();Be();Jo();St();ME=Symbol.for(K$),NE=gn("effect/Random");FE=class FE{seed;[ME]=ME;PRNG;constructor(e){this.seed=e,this.PRNG=new cg(e)}get next(){return Z(()=>this.PRNG.number())}get nextBoolean(){return nt(this.next,(e)=>e>0.5)}get nextInt(){return Z(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return nt(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return Z(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return J$(e,(t)=>this.nextIntBetween(0,t))}}});class UE{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:$E(32),this.spanId=$E(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 qE,Z$=(e)=>({[qE]:qE,...e}),iu,kf,$E,jE,HE;var If=S(()=>{jn();ee();qE=Symbol.for("effect/Tracer"),iu=gn("effect/Tracer"),kf=gn("effect/ParentSpan"),$E=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();jE=Z$({span:(e,t,n,r,o,i)=>new UE(e,t,n,r,o,i),context:(e)=>e()}),HE=Al()("effect/Tracer/DisablePropagation",{defaultValue:Wo})});var eU,au;var BE=S(()=>{jn();ee();Px();IE();St();Nx();DE();If();eU=x(si(),Fr(ru,lE()),Fr(Ef,PE),Fr(NE,LE(Math.random())),Fr(EE,kE()),Fr(iu,jE)),au=te(Symbol.for("effect/DefaultServices/currentServices"),()=>cf(eU))});var nU,VE=(e)=>{let t={BaseEffectError:class extends nU{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var WE=S(()=>{St();nU=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends pf{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 zE,rU,Lx;var Dx=S(()=>{po();zE=uo,rU=MR;Lx=class Lx extends rU{}});var JE="Sequential",GE="Parallel",oU="ParallelN",Xs,YE,ZE=(e)=>({_tag:oU,parallelism:e}),qx=(e)=>e._tag===JE,$x=(e)=>e._tag===GE;var Af=S(()=>{Xs={_tag:JE},YE={_tag:GE}});var Pf,Mf,Nf;var XE=S(()=>{Af();Pf=Xs,Mf=YE,Nf=ZE});function QE(e){return new ko(e)}function ek(){return QE(new Map)}var jx,ko,aU=(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=gt(i)[0],u=nr(i),d=gt(a)[0],p=gt(a)[1],f=nr(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},Bx,Vx,tk=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(U(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},su,Wx,xi,Qs,Hx=(e,t,n,r)=>{let o=e.get(n)??[],i;if(Me(o)){let[a,s]=gt(o);if(a[W](t))if(U(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},nk;var Ff=S(()=>{tt();we();ee();lt();Pe();jx=Symbol.for("effect/FiberRefs");ko=class ko{locals;[jx]=jx;constructor(e){this.locals=e}pipe(){return F(this,arguments)}};Bx=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][W](t)){if(!r.has(i)){if(U(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=aU(i,s,o);if(l){let u=i.diff(c,a),d=s[0][1],p=i.join(d,i.patch(u)(d));if(!U(d,p)){let f,m=s[0][0];if(m[W](t))f=[[m,p],...s.slice(1)];else f=[[t,p],...s];r.set(i,f)}}}}),new ko(r)}),Vx=h(2,(e,t)=>{let n=new Map;return tk(e,n,t),new ko(n)}),su=h(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new ko(n)}),Wx=h(2,(e,t)=>{if(!e.locals.has(t))return B();return Y(gt(e.locals.get(t))[1])}),xi=h(2,(e,t)=>x(Wx(e,t),Le(()=>t.initial))),Qs=h(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new ko(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return Hx(o,t,n,r),new ko(o)}),nk=h(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new ko(new Map(t));let r=new Map(e.locals);if(n!==void 0)tk(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)Hx(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{Hx(r,a,o,s)})}),new ko(r)})});var rk,ok,ik;var Kx=S(()=>{Ff();rk=xi,ok=nk,ik=ek});var sk="Empty",ck="Add",lk="Remove",uk="Update",dk="AndThen",pk,fk=(e,t)=>{let n=new Map(e.locals),r=pk;for(let[o,i]of t.locals.entries()){let a=gt(i)[1],s=n.get(o);if(s!==void 0){let c=gt(s)[1];if(!U(c,a))r=Lf({_tag:uk,fiberRef:o,patch:o.diff(c,a)})(r)}else r=Lf({_tag:ck,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=Lf({_tag:lk,fiberRef:o})(r);return r},Lf,mk;var hk=S(()=>{tt();we();ee();Ff();pk={_tag:sk},Lf=h(2,(e,t)=>({_tag:dk,first:e,second:t})),mk=h(3,(e,t,n)=>{let r=n,o=zt(e);while(Me(o)){let i=gt(o),a=nr(o);switch(i._tag){case sk:{o=a;break}case ck:{r=Qs(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case lk:{r=su(r,i.fiberRef),o=a;break}case uk:{let s=xi(r,i.fiberRef);r=Qs(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case dk:{o=vs(i.first)(vs(i.second)(a));break}}}return r})});var gk,yk;var xk=S(()=>{hk();gk=fk,yk=mk});var qf="effect/FiberStatus",Si,Df="Done",Sk="Running",bk="Suspended",lU,_k,wk,vk,Rk,Tk=(e)=>new wk(e),Ok=(e,t)=>new vk(e,t),$f=(e)=>H(e,Si),Ck=(e)=>e._tag===Df;var Ek=S(()=>{we();ee();Be();Ee();Si=Symbol.for(qf),lU=Oe(`${qf}-${Df}`);_k=class _k{[Si]=Si;_tag=Df;[J](){return lU}[W](e){return $f(e)&&e._tag===Df}};wk=class wk{runtimeFlags;[Si]=Si;_tag=Sk;constructor(e){this.runtimeFlags=e}[J](){return x(q(qf),ae(q(this._tag)),ae(q(this.runtimeFlags)),me(this))}[W](e){return $f(e)&&e._tag===Sk&&this.runtimeFlags===e.runtimeFlags}};vk=class vk{runtimeFlags;blockingOn;[Si]=Si;_tag=bk;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[J](){return x(q(qf),ae(q(this._tag)),ae(q(this.runtimeFlags)),ae(q(this.blockingOn)),me(this))}[W](e){return $f(e)&&e._tag===bk&&this.runtimeFlags===e.runtimeFlags&&U(this.blockingOn,e.blockingOn)}};Rk=new _k});var kk,Jx,Ik,Ak;var Pk=S(()=>{Ek();kk=Rk,Jx=Tk,Ik=Ok,Ak=Ck});var pU,fU,mU,hU,gU,yU,xU,SU,bU,Mk,Nk=(e)=>{switch(e){case"All":return pU;case"Debug":return yU;case"Error":return mU;case"Fatal":return fU;case"Info":return gU;case"Trace":return xU;case"None":return SU;case"Warning":return hU}};var Fk=S(()=>{ee();St();ou();ep();pU=FC,fU=LC,mU=DC,hU=yx,gU=xx,yU=Sx,xU=qC,SU=$C,bU=x($r,Qd((e)=>e.ordinal)),Mk=Tg(bU)});function IU(e){return Yx("Micro.evaluate: Not implemented")}class rS{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,DU(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(Kk)}flush(){while(this.tasks.length>0)this.runTasks()}}var wU,jf,Lk,vU,Zx,$k,RU=(e,t=[])=>new $k(e,t),Uk,TU=(e=[])=>new Uk(e),OU=(e)=>e._tag==="Interrupt",Dk,CU,jk,qk,Hk,vt,Gx,tc,ec,Hf,Uf,EU,kU,Vf=(e)=>({...kU,[Hk]:e.op,[Gx]:e.eval??IU,[tc]:e.contA,[ec]:e.contE,[Hf]:e.ensure}),Xx=(e)=>{let t=Vf(e);return function(){let n=Object.create(t);return n[vt]=e.single===!1?arguments:arguments[0],n}},Bk=(e)=>{let t={...Vf(e),[jf]:jf,_tag:e.op,get[e.prop](){return this[vt]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[vt]}},[W](n){return FU(n)&&n._tag===e.op&&U(this[vt],n[vt])},[J](){return me(this,ae(Oe(e.op))(q(this[vt])))}};return function(n){let r=Object.create(t);return r[vt]=n,r[tc]=void 0,r[ec]=void 0,r[Hf]=void 0,r}},Qx,Vk,AU,PU,MU,eS,Bf,NU,FU=(e)=>H(e,jf),Wk,tS,nS,Yx=(e)=>tS(RU(e)),LU,DU,qU,zk,Kk,Wf,$U,UU,jU,Jk,HU=(e)=>eS((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(Jk(!1)),t._interrupted)return nS;return e}),BU=(e)=>eS((t)=>{if(!t.interruptible)return e(_e);return t.interruptible=!1,t._stack.push(Jk(!0)),e(HU)}),Gk=(e,t)=>{let n=new jk(Wf.context(t?.scheduler??new rS));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 Yk=S(()=>{jn();Dx();we();ee();Be();et();Rp();Pe();Ee();Jo();wU=Symbol.for("effect/Micro"),jf=Symbol.for("effect/Micro/MicroExit"),Lk=Symbol.for("effect/Micro/MicroCause"),vU={_E:_e};Zx=class Zx extends globalThis.Error{_tag;traces;[Lk];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=ao(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
28
+ `)}`:`${o}: ${i}`}else o=r,i=lo(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
29
29
  ${n.join(`
30
- `)}`;super(i);this._tag=e,this.traces=n,this[bk]=e$,this.name=o,this.stack=a}pipe(){return M(this,arguments)}toString(){return this.stack}[ue](){return this.stack}};vk=class vk extends Wx{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};Rk=class Rk extends Wx{constructor(e=[]){super("Interrupt","interrupted",e)}};_k=Symbol.for("effect/Micro/MicroFiber"),o$={_A:xe,_E:xe};Tk=class Tk{context;interruptible;[_k];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[_k]=o$}getRef(e){return zT(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),Yc;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(Yx)}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===Ff)return;let n=wk.interruptChildren&&wk.interruptChildren(this);if(n!==void 0)return this.evaluate(qf(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($f).shouldYield(this)){t=!0;let r=n;n=qf(l$,()=>r)}if(n=n[Bx](this),n===Ff){let r=this._yielded;if(Lf in r)return this._yielded=void 0,r;return Ff}}}catch(r){if(!j(n,Bx))return Vx(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return Vx(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[Df]&&t[Df](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Ff}children(){return this._children??=new Set}};wk=te("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),Ok=Symbol.for("effect/Micro/identifier"),wt=Symbol.for("effect/Micro/args"),Bx=Symbol.for("effect/Micro/evaluate"),Qs=Symbol.for("effect/Micro/successCont"),Xs=Symbol.for("effect/Micro/failureCont"),Df=Symbol.for("effect/Micro/ensureCont"),Ff=Symbol.for("effect/Micro/Yield"),i$={_A:xe,_E:xe,_R:xe},a$={...IE,_op:"Micro",[QU]:i$,pipe(){return M(this,arguments)},[Symbol.iterator](){return new hs(new io(this))},toJSON(){return{_id:"Micro",op:this[Ok],...wt in this?{args:this[wt]}:void 0}},toString(){return Te(this)},[ue](){return Te(this)}};Kx=Ck({op:"Success",prop:"value",eval(e){let t=e.getCont(Qs);return t?t[Qs](this[wt],e):e.yieldWith(this)}}),Ek=Ck({op:"Failure",prop:"cause",eval(e){let t=e.getCont(Xs);while(r$(this[wt])&&t&&e.interruptible)t=e.getCont(Xs);return t?t[Xs](this[wt],e):e.yieldWith(this)}}),c$=zx({op:"Yield",eval(e){let t=!1;return e.getRef($f).scheduleTask(()=>{if(t)return;e.evaluate(f$)},this[wt]??0),e.yieldWith(()=>{t=!0})}}),l$=c$(0),u$=Kx(void 0),Jx=zx({op:"WithMicroFiber",eval(e){return this[wt](e)}}),qf=h(2,(e,t)=>{let n=Object.create(d$);return n[wt]=e,n[Qs]=t,n}),d$=Uf({op:"OnSuccess",eval(e){return e._stack.push(this),this[wt]}}),kk=Kx,Gx=Ek,Yx=Gx(n$()),f$=kk(void 0),m$="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);h$=h(2,(e,t)=>Jx((n)=>{let r=n.context;return n.context=t(r),x$(e,()=>(n.context=r,u$))})),Ik=h(2,(e,t)=>h$(e,Rl(t)));Ak=class Ak extends Tl()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};$f=class $f extends Tl()("effect/Micro/currentScheduler",{defaultValue:()=>new Zx}){};g$=h(2,(e,t)=>{let n=Object.create(y$);return n[wt]=e,n[Qs]=t.onSuccess,n[Xs]=t.onFailure,n}),y$=Uf({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[wt]}}),x$=h(2,(e,t)=>b$((n)=>g$(n(e),{onFailure:(r)=>qf(t(Gx(r)),()=>Ek(r)),onSuccess:(r)=>qf(t(kk(r)),()=>Kx(r))}))),Pk=zx({op:"SetInterruptible",ensure(e){if(e.interruptible=this[wt],e._interrupted&&e.interruptible)return()=>Yx}})});class jf{scheduleDrain;running=!1;tasks=new Xx;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 jf(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new jf(e),n.set(r,o);return o}}}class Xx{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 Fk{maxNextTickBeforeTimer;getRunner=jf.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(mx)?e.getFiberRef(Ws):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class nu{tasks=new Xx;deferred=!1;scheduleTask(e,t,n){if(this.deferred)Lk.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(mx)?e.getFiberRef(Ws):!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 Lk,Hf;var Bf=S(()=>{xt();Lk=te(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new Fk(2048));Hf=te(Symbol.for("effect/FiberRef/currentScheduler"),()=>Ut(Lk))});var Vf;var Qx=S(()=>{xt();Vf=te(Symbol.for("effect/FiberRef/currentRequestMap"),()=>Ut(new Map))});var eS=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return ya(kC,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var qk=S(()=>{xt()});var tS=(e)=>e.replace(/[\s="]/g,"_"),Uk=(e)=>(t)=>`${tS(t.label)}=${e-t.startTime}ms`;var $k="effect/MetricLabel",nS,jk,Hk=(e,t)=>new jk(e,t),T$=(e)=>j(e,nS);var Bk=S(()=>{Se();Be();Ae();Ce();nS=Symbol.for($k);jk=class jk{key;value;[nS]=nS;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=Re($k+this.key+this.value)}[J](){return this._hash}[W](e){return T$(e)&&this.key===e.key&&this.value===e.value}pipe(){return M(this,arguments)}}});var rS;var Vk=S(()=>{Un();ct();Tf();rS=er((e)=>wl(e.context,OE)?e._tag==="Span"?rS(e.parent):H():G(e))});var Wk;var zk=S(()=>{xt();Wk=yx});var oS="InterruptSignal",iS="Stateful",aS="Resume",sS="YieldNow",Wf=(e)=>({_tag:"InterruptSignal",cause:e}),ec=(e)=>({_tag:"Stateful",onFiber:e}),va=(e)=>({_tag:"Resume",effect:e}),Kk=()=>({_tag:"YieldNow"});var A$="effect/FiberScope",zf,Gk,Yk,Zk=(e)=>new Yk(e.id(),e),ru;var cS=S(()=>{Ds();zf=Symbol.for(A$);Gk=class Gk{[zf]=zf;fiberId=$n;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};Yk=class Yk{fiberId;parent;[zf]=zf;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(ec((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};ru=te(Symbol.for("effect/FiberScope/Global"),()=>new Gk)});var N$="effect/Fiber",lS,uS,F$,L$="effect/Fiber",Qk,Kf=(e)=>ef($l(e.await),e.inheritAll),EY,yi="effect/FiberCurrent";var eI=S(()=>{Ds();ct();Ae();xt();co();lS=Symbol.for(N$),uS={_E:(e)=>e,_A:(e)=>e},F$={[lS]:uS,pipe(){return M(this,arguments)}},Qk=Symbol.for(L$),EY={...Ko,commit(){return Kf(this)},...F$,id:()=>$n,await:Vl,children:_e([]),inheritAll:Vl,poll:_e(H()),interruptAsFork:()=>Vl}});var q$="effect/Logger",tI,nI,Jf=(e)=>({[tI]:nI,log:e,pipe(){return M(this,arguments)}}),AY,U$,$$=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(U$)?m:e(m),u=(m,y)=>`${tS(m)}=${l(y)}`,d=(m,y)=>" "+u(m,y),p=u("timestamp",o.toISOString());p+=d("level",a.label),p+=d("fiber",Cp(i));let f=wg(s);for(let m=0;m<f.length;m++)p+=d("message",ao(f[m],t));if(!Yg(r))p+=d("cause",sr(r,{renderErrorCause:!0}));for(let m of c)p+=" "+Uk(o.getTime())(m);for(let[m,y]of n)p+=d(m,ao(y,t));return p},j$=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,rI,Ra,PY,oI,MY,NY;var iI=S(()=>{Qe();ee();Xe();Ae();Ns();xy();tI=Symbol.for(q$),nI={_Message:(e)=>e,_Output:(e)=>e},AY={[tI]:nI,log:Yc,pipe(){return M(this,arguments)}},U$=/^[^\s"=]*$/,rI=Jf($$(j$)),Ra={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},PY={None:[],All:[],Trace:[Ra.gray],Debug:[Ra.blue],Info:[Ra.green],Warning:[Ra.yellow],Error:[Ra.red],Fatal:[Ra.bgBrightRed,Ra.black]},oI=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,MY=oI&&process.stdout.isTTY===!0,NY=oI||"Deno"in globalThis});var aI="effect/MetricBoundaries",dS,sI,B$=(e)=>j(e,dS),V$=(e)=>{let t=x(e,vg(gt(Number.POSITIVE_INFINITY)),Ig);return new sI(t)},cI=(e)=>x(_g(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),hl,V$);var lI=S(()=>{Qe();Ir();Se();ee();Be();Ae();Ce();dS=Symbol.for(aI);sI=class sI{values;[dS]=dS;constructor(e){this.values=e,this._hash=x(Re(aI),ae(On(this.values)))}_hash;[J](){return this._hash}[W](e){return B$(e)&&q(this.values,e.values)}pipe(){return M(this,arguments)}}});var z$="effect/MetricKeyType",uI,dI="effect/MetricKeyType/Counter",pS,K$="effect/MetricKeyType/Frequency",J$,G$="effect/MetricKeyType/Gauge",Y$,pI="effect/MetricKeyType/Histogram",fS,Z$="effect/MetricKeyType/Summary",X$,fI,mI,hI,gI=(e)=>new mI(e?.incremental??!1,e?.bigint??!1),yI=(e)=>new hI(e),mS=(e)=>j(e,pS),xI=(e)=>j(e,J$),SI=(e)=>j(e,Y$),hS=(e)=>j(e,fS),bI=(e)=>j(e,X$);var gS=S(()=>{Se();ee();Be();Ae();Ce();uI=Symbol.for(z$),pS=Symbol.for(dI),J$=Symbol.for(K$),Y$=Symbol.for(G$),fS=Symbol.for(pI),X$=Symbol.for(Z$),fI={_In:(e)=>e,_Out:(e)=>e};mI=class mI{incremental;bigint;[uI]=fI;[pS]=pS;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=Re(dI)}_hash;[J](){return this._hash}[W](e){return mS(e)}pipe(){return M(this,arguments)}};hI=class hI{boundaries;[uI]=fI;[fS]=fS;constructor(e){this.boundaries=e,this._hash=x(Re(pI),ae(D(this.boundaries)))}_hash;[J](){return this._hash}[W](e){return hS(e)&&q(this.boundaries,e.boundaries)}pipe(){return M(this,arguments)}}});var Q$="effect/MetricKey",wI,e2,t2,Gf,n2=(e)=>j(e,wI),vI=(e,t)=>new Gf(e,gI(t),lo(t?.description)),RI=(e,t,n)=>new Gf(e,yI(t),lo(n)),TI;var OI=S(()=>{Qe();Se();ee();Be();ct();Ae();Ce();gS();wI=Symbol.for(Q$),e2={_Type:(e)=>e},t2=Yo(q);Gf=class Gf{name;keyType;description;tags;[wI]=e2;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=x(Re(this.name+this.description),ae(D(this.keyType)),ae(On(this.tags)))}_hash;[J](){return this._hash}[W](e){return n2(e)&&this.name===e.name&&q(this.keyType,e.keyType)&&q(this.description,e.description)&&t2(this.tags,e.tags)}pipe(){return M(this,arguments)}};TI=h(2,(e,t)=>t.length===0?e:new Gf(e.name,e.keyType,e.description,Go(e.tags,t)))});class EI{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 CI,o2,yS,kI=()=>{let e=Object.create(o2);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},xi,i2=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[W](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return G(a)}return H()},tc,nc,a2=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[W](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var II=S(()=>{Se();ee();Be();Xe();ct();Ae();CI=Symbol.for("effect/MutableHashMap"),o2={[CI]:CI,[Symbol.iterator](){return new yS(this)},toString(){return Te(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(be)}},[ue](){return this.toJSON()},pipe(){return M(this,arguments)}};yS=class yS{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 EI(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new yS(this.self)}};xi=h(2,(e,t)=>{if(ol(t)===!1)return e.referential.has(t)?G(e.referential.get(t)):H();let n=t[J](),r=e.buckets.get(n);if(r===void 0)return H();return i2(e,r,t)}),tc=h(2,(e,t)=>qe(xi(e,t))),nc=h(3,(e,t,n)=>{if(ol(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 a2(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var c2="effect/MetricState",ou,AI="effect/MetricState/Counter",xS,PI="effect/MetricState/Frequency",SS,MI="effect/MetricState/Gauge",bS,NI="effect/MetricState/Histogram",_S,FI="effect/MetricState/Summary",wS,iu,LI,l2,DI,qI,UI,$I,jI=(e)=>new LI(e),HI=(e)=>new DI(e),BI=(e)=>new qI(e),VI=(e)=>new UI(e.buckets,e.count,e.min,e.max,e.sum),WI=(e)=>new $I(e.error,e.quantiles,e.count,e.min,e.max,e.sum),u2=(e)=>j(e,xS),d2=(e)=>j(e,SS),p2=(e)=>j(e,bS),f2=(e)=>j(e,_S),m2=(e)=>j(e,wS);var zI=S(()=>{Qe();Se();ee();Be();Ae();Ce();ou=Symbol.for(c2),xS=Symbol.for(AI),SS=Symbol.for(PI),bS=Symbol.for(MI),_S=Symbol.for(NI),wS=Symbol.for(FI),iu={_A:(e)=>e};LI=class LI{count;[ou]=iu;[xS]=xS;constructor(e){this.count=e}[J](){return x(D(AI),ae(D(this.count)),me(this))}[W](e){return u2(e)&&this.count===e.count}pipe(){return M(this,arguments)}};l2=Yo(q);DI=class DI{occurrences;[ou]=iu;[SS]=SS;constructor(e){this.occurrences=e}_hash;[J](){return x(Re(PI),ae(On(Ue(this.occurrences.entries()))),me(this))}[W](e){return d2(e)&&l2(Ue(this.occurrences.entries()),Ue(e.occurrences.entries()))}pipe(){return M(this,arguments)}};qI=class qI{value;[ou]=iu;[bS]=bS;constructor(e){this.value=e}[J](){return x(D(MI),ae(D(this.value)),me(this))}[W](e){return p2(e)&&this.value===e.value}pipe(){return M(this,arguments)}};UI=class UI{buckets;count;min;max;sum;[ou]=iu;[_S]=_S;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[J](){return x(D(NI),ae(D(this.buckets)),ae(D(this.count)),ae(D(this.min)),ae(D(this.max)),ae(D(this.sum)),me(this))}[W](e){return f2(e)&&q(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return M(this,arguments)}};$I=class $I{error;quantiles;count;min;max;sum;[ou]=iu;[wS]=wS;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 x(D(FI),ae(D(this.error)),ae(D(this.quantiles)),ae(D(this.count)),ae(D(this.min)),ae(D(this.max)),ae(D(this.sum)),me(this))}[W](e){return m2(e)&&this.error===e.error&&q(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return M(this,arguments)}}});var g2="effect/MetricHook",y2,x2,au=(e)=>({[y2]:x2,pipe(){return M(this,arguments)},...e}),KI,GI=(e)=>{let t=e.keyType.bigint?KI:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=KI:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return au({get:()=>jI(t),update:r,modify:r})},YI=(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 au({get:()=>HI(t),update:n,modify:n})},ZI=(e,t)=>{let n=t;return au({get:()=>BI(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},XI=(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;x(t,po(Lr),nr((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=Qi(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 au({get:()=>VI({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},QI=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=x(o,po(Lr)),a=Qi(r),s=0,c=0,l=0,u=0,d=0,p=(m)=>{let y=[],g=0;while(g!==r-1){let w=a[g];if(w!=null){let[A,b]=w,I=_p(m-A);if(iO(I,dy)&&oO(I,n))y.push(b)}g=g+1}return S2(t,i,po(y,Lr))},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 au({get:()=>WI({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)})},S2=(e,t,n)=>{let r=n.length;if(!Pe(t))return fo();let o=t[0],i=t.slice(1),a=JI(e,r,H(),0,o,n),s=Vt(a);return i.forEach((c)=>{s.push(JI(e,r,a.value,a.consumed,c,a.rest))}),nr(s,(c)=>[c.quantile,c.value])},JI=(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,w=i;while(!0){if(!Pe(d))return{quantile:u,value:H(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:G(Og(d)),consumed:l+d.length,rest:[]};let A=ht(d),b=BR(d,(k)=>k===A),I=u*s,O=a/2*I,v=l+b[0].length,_=Math.abs(v-I);if(v<I-O){p=a,f=s,m=uo(d),y=v,g=u,w=b[1],a=p,s=f,c=m,l=y,u=g,d=w;continue}if(v>I+O){let k=Ve(c)?G(A):c;return{quantile:u,value:k,consumed:l,rest:d}}switch(c._tag){case"None":{p=a,f=s,m=uo(d),y=v,g=u,w=b[1],a=p,s=f,c=m,l=y,u=g,d=w;continue}case"Some":{let k=Math.abs(I-c.value);if(_<k){p=a,f=s,m=uo(d),y=v,g=u,w=b[1],a=p,s=f,c=m,l=y,u=g,d=w;continue}return{quantile:u,value:G(c.value),consumed:l,rest:d}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var eA=S(()=>{Qe();fy();ee();Xl();ct();Ae();zI();y2=Symbol.for(g2),x2={_In:(e)=>e,_Out:(e)=>e},KI=BigInt(0)});var _2="effect/MetricPair",w2,v2,tA=(e,t)=>({[w2]:v2,metricKey:e,metricState:t,pipe(){return M(this,arguments)}});var nA=S(()=>{Ae();w2=Symbol.for(_2),v2={_Type:(e)=>e}});var T2="effect/MetricRegistry",rA,oA,iA=()=>new oA;var aA=S(()=>{ee();II();ct();eA();gS();nA();rA=Symbol.for(T2);oA=class oA{[rA]=rA;map=kI();snapshot(){let e=[];for(let[t,n]of this.map)e.push(tA(t,n.get()));return e}get(e){let t=x(this.map,xi(e),pn);if(t==null){if(mS(e.keyType))return this.getCounter(e);if(SI(e.keyType))return this.getGauge(e);if(xI(e.keyType))return this.getFrequency(e);if(hS(e.keyType))return this.getHistogram(e);if(bI(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=x(this.map,xi(e),pn);if(t==null){let n=GI(e);if(!x(this.map,tc(e)))x(this.map,nc(e,n));t=n}return t}getFrequency(e){let t=x(this.map,xi(e),pn);if(t==null){let n=YI(e);if(!x(this.map,tc(e)))x(this.map,nc(e,n));t=n}return t}getGauge(e){let t=x(this.map,xi(e),pn);if(t==null){let n=ZI(e,e.keyType.bigint?BigInt(0):0);if(!x(this.map,tc(e)))x(this.map,nc(e,n));t=n}return t}getHistogram(e){let t=x(this.map,xi(e),pn);if(t==null){let n=XI(e);if(!x(this.map,tc(e)))x(this.map,nc(e,n));t=n}return t}getSummary(e){let t=x(this.map,xi(e),pn);if(t==null){let n=QI(e);if(!x(this.map,tc(e)))x(this.map,nc(e,n));t=n}return t}}});var C2="effect/Metric",E2,k2,sA,cA=function(e,t,n,r){let o=Object.assign((i)=>Zp(i,(a)=>A2(o,a)),{[E2]:k2,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return M(this,arguments)}});return o},su=(e,t)=>lA(vI(e,t)),lA=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=sA.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=sA.get(TI(e,o)),n.set(o,i),i};return cA(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},uA=(e,t,n)=>lA(RI(e,t,n)),dA,I2,A2;var pA=S(()=>{Qe();ee();Ae();xt();OI();Bk();aA();E2=Symbol.for(C2),k2={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},sA=te(Symbol.for("effect/Metric/globalMetricRegistry"),()=>iA()),dA=h(3,(e,t,n)=>I2(e,[Hk(t,n)])),I2=h(2,(e,t)=>cA(e.keyType,(n,r)=>e.unsafeUpdate(n,Go(t,r)),(n)=>e.unsafeValue(Go(t,n)),(n,r)=>e.unsafeModify(n,Go(t,r)))),A2=h(2,(e,t)=>ya(zl,(n)=>Y(()=>e.unsafeUpdate(t,n))))});var M2="effect/Request",N2,F2,d6,fA;var mA=S(()=>{ee();Qx();xt();co();N2=Symbol.for(M2),F2={_E:(e)=>e,_A:(e)=>e},d6={...ul,[N2]:F2},fA=h(2,(e,t)=>ya(Vf,(n)=>Y(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,uf(r.result,t)}})))});var L2="effect/Supervisor",Yf,vS,Zf,Xf,RS=(e)=>j(e,Yf)&&nl(e,"Zip"),hA,D2=(e)=>new hA(e),Ta;var Qf=S(()=>{ee();Ce();xt();Yf=Symbol.for(L2),vS={_T:(e)=>e};Zf=class Zf{underlying;value0;[Yf]=vS;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 Zf(this,x(this.value,et(e)))}zip(e){return new Xf(this,e)}};Xf=class Xf{left;right;_tag="Zip";[Yf]=vS;constructor(e,t){this.left=e,this.right=t}get value(){return Qp(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 Zf(this,x(this.value,et(e)))}zip(e){return new Xf(this,e)}};hA=class hA{effect;[Yf]=vS;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 Zf(this,x(this.value,et(e)))}zip(e){return new Xf(this,e)}onRun(e,t){return e()}};Ta=te("effect/Supervisor/none",()=>D2(yt))});var gA;var yA=S(()=>{Lp();gA=si});var xA="Empty",SA="AddSupervisor",bA="RemoveSupervisor",_A="AndThen",rc,em=(e,t)=>({_tag:_A,first:e,second:t}),U2=(e,t)=>$2(t,gt(e)),$2=(e,t)=>{let n=e,r=t;while(rr(r)){let o=or(r);switch(o._tag){case xA:{r=ir(r);break}case SA:{n=n.zip(o.supervisor),r=ir(r);break}case bA:{n=OS(n,o.supervisor),r=ir(r);break}case _A:{r=Wt(o.first)(Wt(o.second)(ir(r)));break}}}return n},OS=(e,t)=>{if(q(e,t))return Ta;else if(RS(e))return OS(e.left,t).zip(OS(e.right,t));else return e},tm=(e)=>{if(q(e,Ta))return Ar();else if(RS(e))return x(tm(e.left),xo(tm(e.right)));else return ra(e)},j2=(e,t)=>{if(q(e,t))return rc;let n=tm(e),r=tm(t),o=x(r,zg(n),ia(rc,(a,s)=>em(a,{_tag:SA,supervisor:s}))),i=x(n,zg(r),ia(rc,(a,s)=>em(a,{_tag:bA,supervisor:s})));return em(o,i)},wA;var vA=S(()=>{Ir();yA();Se();ee();aa();Qf();rc={_tag:xA},wA=gA({empty:rc,patch:U2,combine:em,diff:j2})});var Z2,RA,X2,Q2,ej,cu="Continue",tj="Done",TA="Yield",nj,nm=(e)=>{throw Error(`BUG: FiberRuntime - ${ao(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Co,Eo,lu,rj,oj=(e)=>ha(GO(e),(t)=>Oa(ZO(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(ho(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return fi(Sj(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),Vf,o)},!1,!1)),ij,rm,aj,sj=(e)=>Jf((t)=>{let n=jE(t.context,eu);wl(n,vf).unsafe.log(e.log(t))}),cj,lj,uj,EA,kA=(e,t,n)=>$e(()=>{let r=Ue(e),o=Array(r.length);return pi(Oa(r,(a,s)=>re(t(a,s),(c)=>Y(()=>o[s]=c)),n,!1),_e(o))}),Oa=(e,t,n,r,o)=>di((i)=>lx((a)=>qt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return yt;let u=0,d=!1,p=o?Math.min(c.length,o):c.length,f=new Set,m=[],y=()=>f.forEach((k)=>{k.currentScheduler.scheduleTask(()=>{k.unsafeInterruptAsFork(s.id())},0,k)}),g=[],w=[],A=[],b=()=>{let k=m.filter(({exit:P})=>P._tag==="Failure").sort((P,N)=>P.index<N.index?-1:P.index===N.index?0:1).map(({exit:P})=>P);if(k.length===0)k.push(Bn);return k},I=(k,P=!1)=>{let N=Xp(a(k)),U=pj(N,s,s.currentRuntimeFlags,ru);return s.currentScheduler.scheduleTask(()=>{if(P)U.unsafeInterruptAsFork(s.id());U.resume(N)},0,U),U},O=()=>{if(!r)l-=c.length,c=[];d=!0,y()},v=n?cx:ui,_=I(li((k)=>{let P=(U,ke)=>{if(U._op==="Blocked")A.push(U);else if(m.push({index:ke,exit:U}),U._op==="Failure"&&!d)O()},N=()=>{if(c.length>0){let U=c.pop(),ke=u++,pt=()=>{let St=c.pop();return ke=u++,re(Bl(),()=>re(v(i(t(St,ke))),kt))},kt=(St)=>{if(c.length>0){if(P(St,ke),c.length>0)return pt()}return _e(St)},bn=re(v(i(t(U,ke))),kt),Je=I(bn);if(g.push(Je),f.add(Je),d)Je.currentScheduler.scheduleTask(()=>{Je.unsafeInterruptAsFork(s.id())},0,Je);Je.addObserver((St)=>{let Ft;if(St._op==="Failure")Ft=St;else Ft=St.effect_instruction_i0;if(w.push(Je),f.delete(Je),P(Ft,ke),m.length===l)k(_e(De(_a(b(),{parallel:!0}),()=>Bn)));else if(A.length+m.length===l){let Xr=b(),Uc=A.map((Qr)=>Qr.effect_instruction_i0).reduce(Yy);k(_e(zp(Uc,Oa([De(_a(Xr,{parallel:!0}),()=>Bn),...A.map((Qr)=>Qr.effect_instruction_i1)],(Qr)=>Qr,n,!0,o))))}else N()})}};for(let U=0;U<p;U++)N()}));return To(Vs($l(i(Kf(_))),cf({onFailure:(k)=>{O();let P=A.length+1,N=Math.min(typeof o==="number"?o:A.length,A.length),U=Array.from(A);return li((ke)=>{let pt=[],kt=0,bn=0,Je=(Ft,Xr)=>(Uc)=>{if(pt[Ft]=Uc,kt++,kt===P)ke(He(Me(k)));if(U.length>0&&Xr)St()},St=()=>{I(U.pop(),!0).addObserver(Je(bn,!0)),bn++};_.addObserver(Je(bn,!1)),bn++;for(let Ft=0;Ft<N;Ft++)St()})},onSuccess:()=>Hn(w,(k)=>k.inheritAll)})))}))),CS=(e,t,n,r)=>$e(()=>{let o=Ue(e),i=Array(o.length);return pi(Oa(o,(s,c)=>et(n(s,c),(l)=>i[c]=l),r,!1,t),_e(i))}),IS=(e)=>fj(e,ru),dj=(e,t,n,r=null)=>{let o=IA(e,t,n,r);return o.resume(e),o},pj=(e,t,n,r=null)=>IA(e,t,n,r),IA=(e,t,n,r=null)=>{let o=Ep(),i=t.getFiberRefs(),a=qx(i,o),s=new rm(o,a,n),c=hi(a,Sa),l=s.currentSupervisor;return l.onStart(c,e,G(t),s),s.addObserver((d)=>l.onEnd(d,s)),(r!==null?r:x(t.getFiberRef(Wp),De(()=>t.scope()))).add(n,s),s},fj=(e,t)=>qt((n,r)=>_e(dj(e,n,r.runtimeFlags,t))),ES=(e)=>wa((t)=>st(ii(t,uu),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return re(zs(n,Ef),(r)=>AS(e,r))}}})),OA=(e)=>(t)=>wa((n)=>st(ii(n,uu),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return re(zs(r,kf(e)),(o)=>AS(t,o))}})),oc=(e,t)=>(n)=>wa((r)=>st(ii(r,uu),{onNone:()=>n(xe),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?ES:e._tag==="Sequential"?kS:OA(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(ES));case"Sequential":return i(n(kS));case"ParallelN":return i(n(OA(o.strategy.parallelism)))}}else return n(xe)}})),kS=(e)=>wa((t)=>st(ii(t,uu),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return re(zs(n,Cf),(r)=>AS(e,r))}}})),uu,mj=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},hj,gj=(e=Ys)=>{let t=Object.create(hj);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},AS,yj=(e)=>xa(e,{differ:wA,fork:rc}),CA,xj,AA,Sj=(e,t,n)=>Ul((r)=>AA(re(IS(Gp(e)),(o)=>li((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"&&Ks(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&hp(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(xC(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(),Y(()=>{c.forEach((l)=>l())})})),$e(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return ha(o,(i)=>fA(i.request,Sx(r)))})));var PS=S(()=>{Qe();Ir();Un();Ax();LE();Ds();jx();nk();gk();ee();aa();Xe();Sk();Nk();ct();Ae();Ce();Jy();Bf();Wo();XO();Ns();Ox();Qx();qk();Vk();xt();CE();Ex();Of();eI();If();cS();iI();pA();lI();mA();Ll();Ll();Qf();vA();Tf();Z2=su("effect_fiber_started",{incremental:!0}),RA=su("effect_fiber_active"),X2=su("effect_fiber_successes",{incremental:!0}),Q2=su("effect_fiber_failures",{incremental:!0}),ej=dA(uA("effect_fiber_lifetimes",cI({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),nj={_E:(e)=>e,_A:(e)=>e},Co=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),Eo=te("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),lu={[gs]:(e,t,n)=>Dt(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>He(He(n)),[ys]:(e,t,n)=>Dt(()=>t.effect_instruction_i2(n)),[cl]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),vo(e.currentRuntimeFlags)&&e.isInterrupted())return Me(e.getInterruptedCause());else return He(n)},[xs]:(e,t,n)=>{if(Dt(()=>t.effect_instruction_i2(n)),Dt(()=>t.effect_instruction_i0()))return e.pushStack(t),Dt(()=>t.effect_instruction_i1());else return yt},[Ss]:(e,t,n)=>{while(!0){let r=Dt(()=>t.effect_instruction_i0.next(n));if(r.done)return He(r.value);let o=rg(r.value);if(!Ks(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},rj={[oS]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),vo(t)?Me(r.cause):n),[aS]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[iS]:(e,t,n,r)=>(r.onFiber(e,Hx(t)),n),[sS]:(e,t,n,r)=>re(Bl(),()=>n)},ij=ll();rm=class rm extends Ix{[lS]=uS;[Qk]=nj;_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,By(n)){let r=this.getFiberRef(zl);Z2.unsafeUpdate(1,r),RA.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return Kf(this)}id(){return this._fiberId}resume(e){this.tell(va(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(hk(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return Zk(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(Kl)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return $e(()=>{let t=FC(this._fiberId);return this.tell(ec((n,r)=>{uf(t,Y(()=>e(n,r)))})),lf(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return li((e)=>{let t=(n)=>e(_e(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(ec((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),Y(()=>this.tell(ec((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return qt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=Dx(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(CA),c=x(Nl(o,s),Ky(wo),Ky(Up));return ux(c)})}get poll(){return Y(()=>lo(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return Y(()=>this.tell(Wf(ar(e))))}unsafeInterruptAsFork(e){this.tell(Wf(ar(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(CA,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=tu(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=Zs(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(eu),this.currentTracer=this.currentDefaultServices.unsafeMap.get(Ql.key),this.currentSupervisor=this.getFiberRef(xj),this.currentScheduler=this.getFiberRef(Hf),this.currentContext=this.getFiberRef(Sa),this.currentSpan=this.currentContext.unsafeMap.get(Rf.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=cu,n=globalThis[yi];globalThis[yi]=this;try{while(t===cu)t=this._queue.length===0?tj:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[yi]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===TA)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Ws),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=rj[r._tag](this,e,n,r)}return n}isInterrupted(){return!mp(this.getFiberRef(Kl))}addInterruptedCause(e){let t=this.getFiberRef(Kl);this.setFiberRef(Kl,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(Wf(ar(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return Hl({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return To(r.value.await);else return Y(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(By(this.currentRuntimeFlags)){let t=this.getFiberRef(zl),n=this.id().startTimeMillis,r=Date.now();switch(ej.unsafeUpdate(r-n,t),RA.unsafeUpdate(-1,t),e._tag){case un:{X2.unsafeUpdate(1,t);break}case ln:{Q2.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(AC);if(!Ms(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(uj)}log(e,t,n){let r=qe(n)?n.value:this.getFiberRef(hx),o=this.getFiberRef(aj);if(yk(o,r))return;let i=this.getFiberRef(CC),a=this.getFiberRef(OC),s=this.getLoggers(),c=this.getFiberRefs();if(xl(s)>0){let l=wl(this.getFiberRef(eu),Zl),u=new Date(l.unsafeCurrentTimeMillis());lR(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 sS:return TA;case oS:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Me(e.cause)),this._asyncInterruptor=null;return cu}case aS:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),cu;case iS:return e.onFiber(this,this._exitValue!==null?fk:mk(this.currentRuntimeFlags,this._asyncBlockingOn)),cu;default:return nm(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=vo(this.currentRuntimeFlags)&&this.isInterrupted()?Me(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===Co){let o=Eo.currentOp;if(Eo.currentOp=null,o._op===bs)if(WO(this.currentRuntimeFlags))this.tell(Kk()),this.tell(va(Bn)),t=null;else t=Bn;else if(o._op===Yi)t=null}else{this.currentRuntimeFlags=x(this.currentRuntimeFlags,$y(Up));let o=this.interruptAllChildren();if(o!==null)t=re(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(va(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[yi];globalThis[yi]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[yi]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(va(e))}startFork(e){this.tell(va(e))}patchRuntimeFlags(e,t){let n=Fl(e,t);return globalThis[yi]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(va(o))};if(vo(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(Kt(kn(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!==sl)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==gs&&e._op!==xs&&e._op!==Ss)return e;e=this.popStack()}}[dR](e){return Y(()=>vl(this.currentContext,e))}["Left"](e){return Pt(e.left)}["None"](e){return Pt(new Jl)}["Right"](e){return He(e.right)}["Some"](e){return He(e.value)}["Micro"](e){return Dl((t)=>{let n=t,r=Mk(Ik(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(He(o.value));switch(o.cause._tag){case"Interrupt":return n(Me(ar($n)));case"Fail":return n(Pt(o.cause.error));case"Die":return n(Jp(o.cause.defect))}}),Dl((o)=>{n=(i)=>{o(yt)},r.unsafeInterrupt()})})}[Bd](e){let t=Dt(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in lu))nm(n);return lu[n._op](this,n,t)}else return Eo.currentOp=He(t),Co}[un](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in lu))nm(n);return lu[n._op](this,n,t.effect_instruction_i0)}else return Eo.currentOp=t,Co}[ln](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case sl:case ys:if(!(vo(this.currentRuntimeFlags)&&this.isInterrupted()))return Dt(()=>n.effect_instruction_i1(t));else return Me(yp(t));case"OnStep":if(!(vo(this.currentRuntimeFlags)&&this.isInterrupted()))return He(Me(t));else return Me(yp(t));case cl:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),vo(this.currentRuntimeFlags)&&this.isInterrupted())return Me(zt(t,this.getInterruptedCause()));else return Me(t);default:nm(n)}else return Eo.currentOp=Me(t),Co}[Vd](e){return Dt(()=>e.effect_instruction_i0(this,Hx(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=ek(o.refs,t),s=Nl(o.flags,n);return He(zp(e.effect_instruction_i0,qt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(tk(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=Fl(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return di((r)=>re(IS(ex(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return oj(e.effect_instruction_i0)}[Xi](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=Fl(n,t);if(vo(r)&&this.isInterrupted())return Me(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Nl(r,n);return this.pushStack(new tx(o,e)),Dt(()=>e.effect_instruction_i1(n))}else return Bn}[gs](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[sl](e){return this.pushStack(e),e.effect_instruction_i0}[ys](e){return this.pushStack(e),e.effect_instruction_i0}[Yi](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),Eo.currentOp=e,Co}[bs](e){return this._isYielding=!1,Eo.currentOp=e,Co}[xs](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return Bn}[Ss](e){return lu[Ss](this,e,void 0)}[Zi](e){return Dt(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&VO)!==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(Bl({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(ij!==t[ci]._V){let n=this.getFiberRef(PC);if(n._tag==="Some"){let r=t[ci]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${ll()}, 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`,So,n)}}return this[t._op](t)},this),t===Co){let n=Eo.currentOp;if(n._op===bs||n._op===Yi)return Co;return Eo.currentOp=null,n._op===un||n._op===ln?n:Me(kn(n))}}catch(n){if(t!==Co&&!j(t,"_op")||!(t._op in this))t=ix(`Not a valid effect: ${ao(t)}`);else if(MC(n))t=Me(zt(kn(n),ar($n)));else t=Jp(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};aj=te("effect/FiberRef/currentMinimumLogLevel",()=>Ut(xk("Info"))),cj=te(Symbol.for("effect/Logger/defaultLogger"),()=>sj(rI)),lj=te(Symbol.for("effect/Logger/tracerLogger"),()=>Jf(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=rS(ii(hi(n,Sa),Rf));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=vl(hi(n,eu),Zl),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=hO(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=sr(t,{renderErrorCause:!0});a.value.event(ao(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),uj=te(Symbol.for("effect/FiberRef/currentLoggers"),()=>RC(ra(cj,lj))),EA=h((e)=>Qh(e[0]),(e,t,n)=>qt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(IC);if(n?.discard)return eS(n.concurrency,()=>oc(Cf,n?.concurrentFinalizers)((i)=>o?Oa(e,(a,s)=>i(t(a,s)),!0,!1,1):ha(e,(a,s)=>i(t(a,s)))),()=>oc(Ef,n?.concurrentFinalizers)((i)=>Oa(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>oc(kf(i),n?.concurrentFinalizers)((a)=>Oa(e,(s,c)=>a(t(s,c)),o,!1,i)));return eS(n?.concurrency,()=>oc(Cf,n?.concurrentFinalizers)((i)=>o?CS(e,1,(a,s)=>i(t(a,s)),!0):Hn(e,(a,s)=>i(t(a,s)))),()=>oc(Ef,n?.concurrentFinalizers)((i)=>kA(e,(a,s)=>i(t(a,s)),o)),(i)=>oc(kf(i),n?.concurrentFinalizers)((a)=>CS(e,i,(s,c)=>a(t(s,c)),o)))})),uu=fn("effect/Scope"),hj={[rf]:rf,[of]:of,pipe(){return M(this,arguments)},fork(e){return Y(()=>{let t=gj(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),mj(t,(o)=>Y(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return $e(()=>{if(this.state._tag==="Closed")return yt;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return yt;return Px(this.strategy)?x(Hn(t,(n)=>ui(n(e))),re((n)=>x(_a(n),Qn(Gl),De(()=>Bn)))):Mx(this.strategy)?x(kA(t,(n)=>ui(n(e)),!1),re((n)=>x(_a(n,{parallel:!0}),Qn(Gl),De(()=>Bn)))):x(CS(t,this.strategy.parallelism,(n)=>ui(n(e)),!1),re((n)=>x(_a(n,{parallel:!0}),Qn(Gl),De(()=>Bn))))})},addFinalizer(e){return $e(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),yt})}},AS=h(2,(e,t)=>_x(e,Rl(ZT(uu,t)))),CA=TC(zO),xj=yj(Ta),AA=h(2,(e,t)=>di((n)=>jn(n(e),{onFailure:(r)=>jn(t,{onFailure:(o)=>Kt(zt(r,o)),onSuccess:()=>Kt(r)}),onSuccess:(r)=>Ro(t,r)})))});var MA,NA;var FA=S(()=>{xt();MA=gx,NA=zs});class UA{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return M(this,arguments)}}var NS=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},LA,vj,DA,Rj=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new DA(e);return Error.stackTraceLimit=t,n},MS,om,qA,Tj=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new qA(e);return Error.stackTraceLimit=t,n},Oj=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return Yl(t.left);case"Right":return He(t.right);case"Some":return He(t.value);case"None":return Yl(new Jl)}},Cj,Ej=(e)=>new UA(e.context,e.runtimeFlags,e.fiberRefs),kj,$A,jA,HA;var BA=S(()=>{Un();Se();Ds();jx();Xe();ct();Ae();Bf();FA();Ns();xt();Of();PS();cS();Ll();Qf();LA=NS((e,t,n)=>{let r=Ep(),o=[[Sa,[[r,e.context]]]];if(n?.scheduler)o.push([Hf,[[r,n.scheduler]]]);let i=HE(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new rm(r,i,e.runtimeFlags),s=t;if(n?.scope)s=re(NA(n.scope,Ys),(l)=>pi(af(l,Ul((u)=>q(u,a.id())?yt:Wl(a,u))),Vs(t,(u)=>MA(l,u))));let c=a.currentSupervisor;if(c!==Ta)c.onStart(e.context,s,H(),a),a.addObserver((l)=>c.onEnd(l,a));if(ru.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),vj=NS((e,t)=>{let n=Cj(e)(t);if(n._tag==="Failure")throw Tj(n.effect_instruction_i0);return n.effect_instruction_i0});DA=class DA 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}};MS=Symbol.for("effect/Runtime/FiberFailure"),om=Symbol.for("effect/Runtime/FiberFailure/Cause");qA=class qA extends Error{[MS];[om];constructor(e){let t=Sl(e)[0];super(t?.message||"An error has occurred");if(this[MS]=MS,this[om]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[om].toJSON()}}toString(){return"(FiberFailure) "+sr(this[om],{renderErrorCause:!0})}[ue](){return this.toString()}};Cj=NS((e,t)=>{let n=Oj(t);if(n)return n;let r=new nu,o=LA(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return xx(Kp(Rj(o),df(o)))});kj=Hy(wo,Uy,qy),$A=Ej({context:oi(),runtimeFlags:kj,fiberRefs:BE()}),jA=LA($A),HA=vj($A)});var VA,du,pu,An,WA,im,zA,Ca,lr,KA,JA;var GA=S(()=>{xt();PS();BA();VA=Hs,du=EA,pu=$e,An=yt,WA=ql,im=et,zA=ga,Ca=ma,lr=re,KA=jA,JA=HA});var FS=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return FS(e,t.from)}},fu=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},LS=(e)=>Array.isArray(e),ZA=(e)=>!Array.isArray(e),YA=(e)=>`[${al(e)}]`,am=(e)=>LS(e)?e.map(YA).join(""):YA(e);var mu=S(()=>{Xe()});var Si=(e,t,n,r)=>{let o=e;if(n&&Pe(n))o+=`
31
- at path: ${am(n)}`;if(t!==void 0)o+=`
30
+ `)}`;super(i);this._tag=e,this.traces=n,this[Lk]=vU,this.name=o,this.stack=a}pipe(){return F(this,arguments)}toString(){return this.stack}[de](){return this.stack}};$k=class $k extends Zx{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};Uk=class Uk extends Zx{constructor(e=[]){super("Interrupt","interrupted",e)}};Dk=Symbol.for("effect/Micro/MicroFiber"),CU={_A:_e,_E:_e};jk=class jk{context;interruptible;[Dk];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[Dk]=CU}getRef(e){return cO(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),nl;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(nS)}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===Uf)return;let n=qk.interruptChildren&&qk.interruptChildren(this);if(n!==void 0)return this.evaluate(Bf(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(Wf).shouldYield(this)){t=!0;let r=n;n=Bf(PU,()=>r)}if(n=n[Gx](this),n===Uf){let r=this._yielded;if(jf in r)return this._yielded=void 0,r;return Uf}}}catch(r){if(!H(n,Gx))return Yx(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return Yx(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[Hf]&&t[Hf](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Uf}children(){return this._children??=new Set}};qk=te("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),Hk=Symbol.for("effect/Micro/identifier"),vt=Symbol.for("effect/Micro/args"),Gx=Symbol.for("effect/Micro/evaluate"),tc=Symbol.for("effect/Micro/successCont"),ec=Symbol.for("effect/Micro/failureCont"),Hf=Symbol.for("effect/Micro/ensureCont"),Uf=Symbol.for("effect/Micro/Yield"),EU={_A:_e,_E:_e,_R:_e},kU={...zE,_op:"Micro",[wU]:EU,pipe(){return F(this,arguments)},[Symbol.iterator](){return new ys(new co(this))},toJSON(){return{_id:"Micro",op:this[Hk],...vt in this?{args:this[vt]}:void 0}},toString(){return Ce(this)},[de](){return Ce(this)}};Qx=Bk({op:"Success",prop:"value",eval(e){let t=e.getCont(tc);return t?t[tc](this[vt],e):e.yieldWith(this)}}),Vk=Bk({op:"Failure",prop:"cause",eval(e){let t=e.getCont(ec);while(OU(this[vt])&&t&&e.interruptible)t=e.getCont(ec);return t?t[ec](this[vt],e):e.yieldWith(this)}}),AU=Xx({op:"Yield",eval(e){let t=!1;return e.getRef(Wf).scheduleTask(()=>{if(t)return;e.evaluate(LU)},this[vt]??0),e.yieldWith(()=>{t=!0})}}),PU=AU(0),MU=Qx(void 0),eS=Xx({op:"WithMicroFiber",eval(e){return this[vt](e)}}),Bf=h(2,(e,t)=>{let n=Object.create(NU);return n[vt]=e,n[tc]=t,n}),NU=Vf({op:"OnSuccess",eval(e){return e._stack.push(this),this[vt]}}),Wk=Qx,tS=Vk,nS=tS(TU()),LU=Wk(void 0),DU="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);qU=h(2,(e,t)=>eS((n)=>{let r=n.context;return n.context=t(r),jU(e,()=>(n.context=r,MU))})),zk=h(2,(e,t)=>qU(e,Il(t)));Kk=class Kk extends Al()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};Wf=class Wf extends Al()("effect/Micro/currentScheduler",{defaultValue:()=>new rS}){};$U=h(2,(e,t)=>{let n=Object.create(UU);return n[vt]=e,n[tc]=t.onSuccess,n[ec]=t.onFailure,n}),UU=Vf({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[vt]}}),jU=h(2,(e,t)=>BU((n)=>$U(n(e),{onFailure:(r)=>Bf(t(tS(r)),()=>Vk(r)),onSuccess:(r)=>Bf(t(Wk(r)),()=>Qx(r))}))),Jk=Xx({op:"SetInterruptible",ensure(e){if(e.interruptible=this[vt],e._interrupted&&e.interruptible)return()=>nS}})});class zf{scheduleDrain;running=!1;tasks=new oS;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 zf(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new zf(e),n.set(r,o);return o}}}class oS{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 Zk{maxNextTickBeforeTimer;getRunner=zf.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(bx)?e.getFiberRef(Ks):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class cu{tasks=new oS;deferred=!1;scheduleTask(e,t,n){if(this.deferred)Xk.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(bx)?e.getFiberRef(Ks):!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 Xk,Kf;var Jf=S(()=>{St();Xk=te(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new Zk(2048));Kf=te(Symbol.for("effect/FiberRef/currentScheduler"),()=>jt(Xk))});var Gf;var iS=S(()=>{St();Gf=te(Symbol.for("effect/FiberRef/currentRequestMap"),()=>jt(new Map))});var aS=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return va(WC,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var eI=S(()=>{St()});var sS=(e)=>e.replace(/[\s="]/g,"_"),tI=(e)=>(t)=>`${sS(t.label)}=${e-t.startTime}ms`;var nI="effect/MetricLabel",cS,rI,oI=(e,t)=>new rI(e,t),JU=(e)=>H(e,cS);var iI=S(()=>{we();Be();Pe();Ee();cS=Symbol.for(nI);rI=class rI{key;value;[cS]=cS;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=Oe(nI+this.key+this.value)}[J](){return this._hash}[W](e){return JU(e)&&this.key===e.key&&this.value===e.value}pipe(){return F(this,arguments)}}});var lS;var aI=S(()=>{jn();lt();If();lS=tr((e)=>El(e.context,HE)?e._tag==="Span"?lS(e.parent):B():Y(e))});var sI;var cI=S(()=>{St();sI=vx});var uS="InterruptSignal",dS="Stateful",pS="Resume",fS="YieldNow",Yf=(e)=>({_tag:"InterruptSignal",cause:e}),nc=(e)=>({_tag:"Stateful",onFiber:e}),ka=(e)=>({_tag:"Resume",effect:e}),lI=()=>({_tag:"YieldNow"});var e2="effect/FiberScope",Zf,dI,pI,fI=(e)=>new pI(e.id(),e),lu;var mS=S(()=>{$s();Zf=Symbol.for(e2);dI=class dI{[Zf]=Zf;fiberId=Hn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};pI=class pI{fiberId;parent;[Zf]=Zf;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(nc((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};lu=te(Symbol.for("effect/FiberScope/Global"),()=>new dI)});var r2="effect/Fiber",hS,gS,o2,i2="effect/Fiber",hI,Xf=(e)=>af(zl(e.await),e.inheritAll),i6,bi="effect/FiberCurrent";var gI=S(()=>{$s();lt();Pe();St();po();hS=Symbol.for(r2),gS={_E:(e)=>e,_A:(e)=>e},o2={[hS]:gS,pipe(){return F(this,arguments)}},hI=Symbol.for(i2),i6={...Yo,commit(){return Xf(this)},...o2,id:()=>Hn,await:Yl,children:Re([]),inheritAll:Yl,poll:Re(B()),interruptAsFork:()=>Yl}});var s2="effect/Logger",yI,xI,Qf=(e)=>({[yI]:xI,log:e,pipe(){return F(this,arguments)}}),c6,c2,l2=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(c2)?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",Pp(i));let f=Eg(s);for(let m=0;m<f.length;m++)p+=d("message",lo(f[m],t));if(!ny(r))p+=d("cause",cr(r,{renderErrorCause:!0}));for(let m of c)p+=" "+tI(o.getTime())(m);for(let[m,y]of n)p+=d(m,lo(y,t));return p},u2=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,SI,Ia,l6,bI,u6,d6;var _I=S(()=>{tt();ee();et();Pe();Ls();Ry();yI=Symbol.for(s2),xI={_Message:(e)=>e,_Output:(e)=>e},c6={[yI]:xI,log:nl,pipe(){return F(this,arguments)}},c2=/^[^\s"=]*$/,SI=Qf(l2(u2)),Ia={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},l6={None:[],All:[],Trace:[Ia.gray],Debug:[Ia.blue],Info:[Ia.green],Warning:[Ia.yellow],Error:[Ia.red],Fatal:[Ia.bgBrightRed,Ia.black]},bI=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,u6=bI&&process.stdout.isTTY===!0,d6=bI||"Deno"in globalThis});var wI="effect/MetricBoundaries",yS,vI,p2=(e)=>H(e,yS),f2=(e)=>{let t=x(e,kg(yt(Number.POSITIVE_INFINITY)),Lg);return new vI(t)},RI=(e)=>x(Cg(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),_l,f2);var TI=S(()=>{tt();Mr();we();ee();Be();Pe();Ee();yS=Symbol.for(wI);vI=class vI{values;[yS]=yS;constructor(e){this.values=e,this._hash=x(Oe(wI),ae(On(this.values)))}_hash;[J](){return this._hash}[W](e){return p2(e)&&U(this.values,e.values)}pipe(){return F(this,arguments)}}});var h2="effect/MetricKeyType",OI,CI="effect/MetricKeyType/Counter",xS,g2="effect/MetricKeyType/Frequency",y2,x2="effect/MetricKeyType/Gauge",S2,EI="effect/MetricKeyType/Histogram",SS,b2="effect/MetricKeyType/Summary",_2,kI,II,AI,PI=(e)=>new II(e?.incremental??!1,e?.bigint??!1),MI=(e)=>new AI(e),bS=(e)=>H(e,xS),NI=(e)=>H(e,y2),FI=(e)=>H(e,S2),_S=(e)=>H(e,SS),LI=(e)=>H(e,_2);var wS=S(()=>{we();ee();Be();Pe();Ee();OI=Symbol.for(h2),xS=Symbol.for(CI),y2=Symbol.for(g2),S2=Symbol.for(x2),SS=Symbol.for(EI),_2=Symbol.for(b2),kI={_In:(e)=>e,_Out:(e)=>e};II=class II{incremental;bigint;[OI]=kI;[xS]=xS;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=Oe(CI)}_hash;[J](){return this._hash}[W](e){return bS(e)}pipe(){return F(this,arguments)}};AI=class AI{boundaries;[OI]=kI;[SS]=SS;constructor(e){this.boundaries=e,this._hash=x(Oe(EI),ae(q(this.boundaries)))}_hash;[J](){return this._hash}[W](e){return _S(e)&&U(this.boundaries,e.boundaries)}pipe(){return F(this,arguments)}}});var w2="effect/MetricKey",qI,v2,R2,em,T2=(e)=>H(e,qI),$I=(e,t)=>new em(e,PI(t),fo(t?.description)),UI=(e,t,n)=>new em(e,MI(t),fo(n)),jI;var HI=S(()=>{tt();we();ee();Be();lt();Pe();Ee();wS();qI=Symbol.for(w2),v2={_Type:(e)=>e},R2=Qo(U);em=class em{name;keyType;description;tags;[qI]=v2;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=x(Oe(this.name+this.description),ae(q(this.keyType)),ae(On(this.tags)))}_hash;[J](){return this._hash}[W](e){return T2(e)&&this.name===e.name&&U(this.keyType,e.keyType)&&U(this.description,e.description)&&R2(this.tags,e.tags)}pipe(){return F(this,arguments)}};jI=h(2,(e,t)=>t.length===0?e:new em(e.name,e.keyType,e.description,Xo(e.tags,t)))});class VI{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 BI,C2,vS,WI=()=>{let e=Object.create(C2);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},_i,E2=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[W](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return Y(a)}return B()},rc,oc,k2=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[W](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var zI=S(()=>{we();ee();Be();et();lt();Pe();BI=Symbol.for("effect/MutableHashMap"),C2={[BI]:BI,[Symbol.iterator](){return new vS(this)},toString(){return Ce(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(ve)}},[de](){return this.toJSON()},pipe(){return F(this,arguments)}};vS=class vS{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 VI(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new vS(this.self)}};_i=h(2,(e,t)=>{if(ul(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 E2(e,r,t)}),rc=h(2,(e,t)=>De(_i(e,t))),oc=h(3,(e,t,n)=>{if(ul(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 k2(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var A2="effect/MetricState",uu,KI="effect/MetricState/Counter",RS,JI="effect/MetricState/Frequency",TS,GI="effect/MetricState/Gauge",OS,YI="effect/MetricState/Histogram",CS,ZI="effect/MetricState/Summary",ES,du,XI,P2,QI,eA,tA,nA,rA=(e)=>new XI(e),oA=(e)=>new QI(e),iA=(e)=>new eA(e),aA=(e)=>new tA(e.buckets,e.count,e.min,e.max,e.sum),sA=(e)=>new nA(e.error,e.quantiles,e.count,e.min,e.max,e.sum),M2=(e)=>H(e,RS),N2=(e)=>H(e,TS),F2=(e)=>H(e,OS),L2=(e)=>H(e,CS),D2=(e)=>H(e,ES);var cA=S(()=>{tt();we();ee();Be();Pe();Ee();uu=Symbol.for(A2),RS=Symbol.for(KI),TS=Symbol.for(JI),OS=Symbol.for(GI),CS=Symbol.for(YI),ES=Symbol.for(ZI),du={_A:(e)=>e};XI=class XI{count;[uu]=du;[RS]=RS;constructor(e){this.count=e}[J](){return x(q(KI),ae(q(this.count)),me(this))}[W](e){return M2(e)&&this.count===e.count}pipe(){return F(this,arguments)}};P2=Qo(U);QI=class QI{occurrences;[uu]=du;[TS]=TS;constructor(e){this.occurrences=e}_hash;[J](){return x(Oe(JI),ae(On(qe(this.occurrences.entries()))),me(this))}[W](e){return N2(e)&&P2(qe(this.occurrences.entries()),qe(e.occurrences.entries()))}pipe(){return F(this,arguments)}};eA=class eA{value;[uu]=du;[OS]=OS;constructor(e){this.value=e}[J](){return x(q(GI),ae(q(this.value)),me(this))}[W](e){return F2(e)&&this.value===e.value}pipe(){return F(this,arguments)}};tA=class tA{buckets;count;min;max;sum;[uu]=du;[CS]=CS;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[J](){return x(q(YI),ae(q(this.buckets)),ae(q(this.count)),ae(q(this.min)),ae(q(this.max)),ae(q(this.sum)),me(this))}[W](e){return L2(e)&&U(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)}};nA=class nA{error;quantiles;count;min;max;sum;[uu]=du;[ES]=ES;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 x(q(ZI),ae(q(this.error)),ae(q(this.quantiles)),ae(q(this.count)),ae(q(this.min)),ae(q(this.max)),ae(q(this.sum)),me(this))}[W](e){return D2(e)&&this.error===e.error&&U(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 $2="effect/MetricHook",U2,j2,pu=(e)=>({[U2]:j2,pipe(){return F(this,arguments)},...e}),lA,dA=(e)=>{let t=e.keyType.bigint?lA:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=lA:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return pu({get:()=>rA(t),update:r,modify:r})},pA=(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 pu({get:()=>oA(t),update:n,modify:n})},fA=(e,t)=>{let n=t;return pu({get:()=>iA(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},mA=(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;x(t,ho($r),rr((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=ia(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 pu({get:()=>aA({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},hA=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=x(o,ho($r)),a=ia(r),s=0,c=0,l=0,u=0,d=0,p=(m)=>{let y=[],g=0;while(g!==r-1){let _=a[g];if(_!=null){let[I,b]=_,A=Op(m-I);if(_O(A,yy)&&bO(A,n))y.push(b)}g=g+1}return H2(t,i,ho(y,$r))},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 pu({get:()=>sA({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)})},H2=(e,t,n)=>{let r=n.length;if(!Me(t))return go();let o=t[0],i=t.slice(1),a=uA(e,r,B(),0,o,n),s=zt(a);return i.forEach((c)=>{s.push(uA(e,r,a.value,a.consumed,c,a.rest))}),rr(s,(c)=>[c.quantile,c.value])},uA=(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,_=i;while(!0){if(!Me(d))return{quantile:u,value:B(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:Y(Pg(d)),consumed:l+d.length,rest:[]};let I=gt(d),b=iT(d,(k)=>k===I),A=u*s,O=a/2*A,v=l+b[0].length,w=Math.abs(v-A);if(v<A-O){p=a,f=s,m=mo(d),y=v,g=u,_=b[1],a=p,s=f,c=m,l=y,u=g,d=_;continue}if(v>A+O){let k=Ve(c)?Y(I):c;return{quantile:u,value:k,consumed:l,rest:d}}switch(c._tag){case"None":{p=a,f=s,m=mo(d),y=v,g=u,_=b[1],a=p,s=f,c=m,l=y,u=g,d=_;continue}case"Some":{let k=Math.abs(A-c.value);if(w<k){p=a,f=s,m=mo(d),y=v,g=u,_=b[1],a=p,s=f,c=m,l=y,u=g,d=_;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 gA=S(()=>{tt();Sy();ee();ou();lt();Pe();cA();U2=Symbol.for($2),j2={_In:(e)=>e,_Out:(e)=>e},lA=BigInt(0)});var V2="effect/MetricPair",W2,z2,yA=(e,t)=>({[W2]:z2,metricKey:e,metricState:t,pipe(){return F(this,arguments)}});var xA=S(()=>{Pe();W2=Symbol.for(V2),z2={_Type:(e)=>e}});var J2="effect/MetricRegistry",SA,bA,_A=()=>new bA;var wA=S(()=>{ee();zI();lt();gA();wS();xA();SA=Symbol.for(J2);bA=class bA{[SA]=SA;map=WI();snapshot(){let e=[];for(let[t,n]of this.map)e.push(yA(t,n.get()));return e}get(e){let t=x(this.map,_i(e),hn);if(t==null){if(bS(e.keyType))return this.getCounter(e);if(FI(e.keyType))return this.getGauge(e);if(NI(e.keyType))return this.getFrequency(e);if(_S(e.keyType))return this.getHistogram(e);if(LI(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=x(this.map,_i(e),hn);if(t==null){let n=dA(e);if(!x(this.map,rc(e)))x(this.map,oc(e,n));t=n}return t}getFrequency(e){let t=x(this.map,_i(e),hn);if(t==null){let n=pA(e);if(!x(this.map,rc(e)))x(this.map,oc(e,n));t=n}return t}getGauge(e){let t=x(this.map,_i(e),hn);if(t==null){let n=fA(e,e.keyType.bigint?BigInt(0):0);if(!x(this.map,rc(e)))x(this.map,oc(e,n));t=n}return t}getHistogram(e){let t=x(this.map,_i(e),hn);if(t==null){let n=mA(e);if(!x(this.map,rc(e)))x(this.map,oc(e,n));t=n}return t}getSummary(e){let t=x(this.map,_i(e),hn);if(t==null){let n=hA(e);if(!x(this.map,rc(e)))x(this.map,oc(e,n));t=n}return t}}});var Y2="effect/Metric",Z2,X2,vA,RA=function(e,t,n,r){let o=Object.assign((i)=>nf(i,(a)=>ej(o,a)),{[Z2]:X2,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return F(this,arguments)}});return o},fu=(e,t)=>TA($I(e,t)),TA=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=vA.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=vA.get(jI(e,o)),n.set(o,i),i};return RA(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},OA=(e,t,n)=>TA(UI(e,t,n)),CA,Q2,ej;var EA=S(()=>{tt();ee();Pe();St();HI();iI();wA();Z2=Symbol.for(Y2),X2={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},vA=te(Symbol.for("effect/Metric/globalMetricRegistry"),()=>_A()),CA=h(3,(e,t,n)=>Q2(e,[oI(t,n)])),Q2=h(2,(e,t)=>RA(e.keyType,(n,r)=>e.unsafeUpdate(n,Xo(t,r)),(n)=>e.unsafeValue(Xo(t,n)),(n,r)=>e.unsafeModify(n,Xo(t,r)))),ej=h(2,(e,t)=>va(Xl,(n)=>Z(()=>e.unsafeUpdate(t,n))))});var nj="effect/Request",rj,oj,H6,kA;var IA=S(()=>{ee();iS();St();po();rj=Symbol.for(nj),oj={_E:(e)=>e,_A:(e)=>e},H6={...gl,[rj]:oj},kA=h(2,(e,t)=>va(Gf,(n)=>Z(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,hf(r.result,t)}})))});var ij="effect/Supervisor",tm,kS,nm,rm,IS=(e)=>H(e,tm)&&cl(e,"Zip"),AA,aj=(e)=>new AA(e),Aa;var om=S(()=>{ee();Ee();St();tm=Symbol.for(ij),kS={_T:(e)=>e};nm=class nm{underlying;value0;[tm]=kS;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 nm(this,x(this.value,nt(e)))}zip(e){return new rm(this,e)}};rm=class rm{left;right;_tag="Zip";[tm]=kS;constructor(e,t){this.left=e,this.right=t}get value(){return of(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 nm(this,x(this.value,nt(e)))}zip(e){return new rm(this,e)}};AA=class AA{effect;[tm]=kS;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 nm(this,x(this.value,nt(e)))}zip(e){return new rm(this,e)}onRun(e,t){return e()}};Aa=te("effect/Supervisor/none",()=>aj(xt))});var PA;var MA=S(()=>{jp();PA=ui});var NA="Empty",FA="AddSupervisor",LA="RemoveSupervisor",DA="AndThen",ic,im=(e,t)=>({_tag:DA,first:e,second:t}),cj=(e,t)=>lj(t,yt(e)),lj=(e,t)=>{let n=e,r=t;while(or(r)){let o=ir(r);switch(o._tag){case NA:{r=ar(r);break}case FA:{n=n.zip(o.supervisor),r=ar(r);break}case LA:{n=PS(n,o.supervisor),r=ar(r);break}case DA:{r=Kt(o.first)(Kt(o.second)(ar(r)));break}}}return n},PS=(e,t)=>{if(U(e,t))return Aa;else if(IS(e))return PS(e.left,t).zip(PS(e.right,t));else return e},am=(e)=>{if(U(e,Aa))return Nr();else if(IS(e))return x(am(e.left),_o(am(e.right)));else return la(e)},uj=(e,t)=>{if(U(e,t))return ic;let n=am(e),r=am(t),o=x(r,Xg(n),da(ic,(a,s)=>im(a,{_tag:FA,supervisor:s}))),i=x(n,Xg(r),da(ic,(a,s)=>im(a,{_tag:LA,supervisor:s})));return im(o,i)},qA;var $A=S(()=>{Mr();MA();we();ee();pa();om();ic={_tag:NA},qA=PA({empty:ic,patch:cj,combine:im,diff:uj})});var bj,UA,_j,wj,vj,mu="Continue",Rj="Done",jA="Yield",Tj,sm=(e)=>{throw Error(`BUG: FiberRuntime - ${lo(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Io,Ao,hu,Oj,Cj=(e)=>_a(dC(e),(t)=>Pa(fC(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(xo(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return gi(Hj(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),Gf,o)},!1,!1)),Ej,cm,kj,Ij=(e)=>Qf((t)=>{let n=rk(t.context,au);El(n,Ef).unsafe.log(e.log(t))}),Aj,Pj,Mj,VA,WA=(e,t,n)=>$e(()=>{let r=qe(e),o=Array(r.length);return hi(Pa(r,(a,s)=>re(t(a,s),(c)=>Z(()=>o[s]=c)),n,!1),Re(o))}),Pa=(e,t,n,r,o)=>mi((i)=>hx((a)=>Ut((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return xt;let u=0,d=!1,p=o?Math.min(c.length,o):c.length,f=new Set,m=[],y=()=>f.forEach((k)=>{k.currentScheduler.scheduleTask(()=>{k.unsafeInterruptAsFork(s.id())},0,k)}),g=[],_=[],I=[],b=()=>{let k=m.filter(({exit:P})=>P._tag==="Failure").sort((P,L)=>P.index<L.index?-1:P.index===L.index?0:1).map(({exit:P})=>P);if(k.length===0)k.push(Wn);return k},A=(k,P=!1)=>{let L=rf(a(k)),j=Fj(L,s,s.currentRuntimeFlags,lu);return s.currentScheduler.scheduleTask(()=>{if(P)j.unsafeInterruptAsFork(s.id());j.resume(L)},0,j),j},O=()=>{if(!r)l-=c.length,c=[];d=!0,y()},v=n?mx:fi,w=A(pi((k)=>{let P=(j,Ie)=>{if(j._op==="Blocked")I.push(j);else if(m.push({index:Ie,exit:j}),j._op==="Failure"&&!d)O()},L=()=>{if(c.length>0){let j=c.pop(),Ie=u++,ft=()=>{let bt=c.pop();return Ie=u++,re(Gl(),()=>re(v(i(t(bt,Ie))),It))},It=(bt)=>{if(c.length>0){if(P(bt,Ie),c.length>0)return ft()}return Re(bt)},wn=re(v(i(t(j,Ie))),It),Je=A(wn);if(g.push(Je),f.add(Je),d)Je.currentScheduler.scheduleTask(()=>{Je.unsafeInterruptAsFork(s.id())},0,Je);Je.addObserver((bt)=>{let Lt;if(bt._op==="Failure")Lt=bt;else Lt=bt.effect_instruction_i0;if(_.push(Je),f.delete(Je),P(Lt,Ie),m.length===l)k(Re(Le(Ca(b(),{parallel:!0}),()=>Wn)));else if(I.length+m.length===l){let eo=b(),to=I.map((Vi)=>Vi.effect_instruction_i0).reduce(nx);k(Re(Zp(to,Pa([Le(Ca(eo,{parallel:!0}),()=>Wn),...I.map((Vi)=>Vi.effect_instruction_i1)],(Vi)=>Vi,n,!0,o))))}else L()})}};for(let j=0;j<p;j++)L()}));return Eo(zs(zl(i(Xf(w))),ff({onFailure:(k)=>{O();let P=I.length+1,L=Math.min(typeof o==="number"?o:I.length,I.length),j=Array.from(I);return pi((Ie)=>{let ft=[],It=0,wn=0,Je=(Lt,eo)=>(to)=>{if(ft[Lt]=to,It++,It===P)Ie(He(Ne(k)));if(j.length>0&&eo)bt()},bt=()=>{A(j.pop(),!0).addObserver(Je(wn,!0)),wn++};w.addObserver(Je(wn,!1)),wn++;for(let Lt=0;Lt<L;Lt++)bt()})},onSuccess:()=>Vn(_,(k)=>k.inheritAll)})))}))),MS=(e,t,n,r)=>$e(()=>{let o=qe(e),i=Array(o.length);return hi(Pa(o,(s,c)=>nt(n(s,c),(l)=>i[c]=l),r,!1,t),Re(i))}),LS=(e)=>Lj(e,lu),Nj=(e,t,n,r=null)=>{let o=zA(e,t,n,r);return o.resume(e),o},Fj=(e,t,n,r=null)=>zA(e,t,n,r),zA=(e,t,n,r=null)=>{let o=Mp(),i=t.getFiberRefs(),a=Vx(i,o),s=new cm(o,a,n),c=xi(a,Ta),l=s.currentSupervisor;return l.onStart(c,e,Y(t),s),s.addObserver((d)=>l.onEnd(d,s)),(r!==null?r:x(t.getFiberRef(Yp),Le(()=>t.scope()))).add(n,s),s},Lj=(e,t)=>Ut((n,r)=>Re(Nj(e,n,r.runtimeFlags,t))),NS=(e)=>Ea((t)=>ct(ci(t,gu),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return re(Js(n,Mf),(r)=>DS(e,r))}}})),HA=(e)=>(t)=>Ea((n)=>ct(ci(n,gu),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return re(Js(r,Nf(e)),(o)=>DS(t,o))}})),ac=(e,t)=>(n)=>Ea((r)=>ct(ci(r,gu),{onNone:()=>n(_e),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?NS:e._tag==="Sequential"?FS:HA(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(NS));case"Sequential":return i(n(FS));case"ParallelN":return i(n(HA(o.strategy.parallelism)))}}else return n(_e)}})),FS=(e)=>Ea((t)=>ct(ci(t,gu),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return re(Js(n,Pf),(r)=>DS(e,r))}}})),gu,Dj=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},qj,$j=(e=Xs)=>{let t=Object.create(qj);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},DS,Uj=(e)=>Ra(e,{differ:qA,fork:ic}),BA,jj,KA,Hj=(e,t,n)=>Wl((r)=>KA(re(LS(ef(e)),(o)=>pi((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"&&Gs(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&bp(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(NC(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(),Z(()=>{c.forEach((l)=>l())})})),$e(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return _a(o,(i)=>kA(i.request,Tx(r)))})));var qS=S(()=>{tt();Mr();jn();Dx();XE();$s();Kx();xk();Pk();ee();pa();et();Fk();Yk();lt();Pe();Ee();ex();Jf();Jo();mC();Ls();Px();iS();eI();aI();St();BE();Nx();Af();gI();Ff();mS();_I();EA();TI();IA();Hl();Hl();om();$A();If();bj=fu("effect_fiber_started",{incremental:!0}),UA=fu("effect_fiber_active"),_j=fu("effect_fiber_successes",{incremental:!0}),wj=fu("effect_fiber_failures",{incremental:!0}),vj=CA(OA("effect_fiber_lifetimes",RI({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),Tj={_E:(e)=>e,_A:(e)=>e},Io=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),Ao=te("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),hu={[xs]:(e,t,n)=>$t(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>He(He(n)),[Ss]:(e,t,n)=>$t(()=>t.effect_instruction_i2(n)),[ml]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),Oo(e.currentRuntimeFlags)&&e.isInterrupted())return Ne(e.getInterruptedCause());else return He(n)},[bs]:(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 xt},[_s]:(e,t,n)=>{while(!0){let r=$t(()=>t.effect_instruction_i0.next(n));if(r.done)return He(r.value);let o=lg(r.value);if(!Gs(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},Oj={[uS]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),Oo(t)?Ne(r.cause):n),[pS]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[dS]:(e,t,n,r)=>(r.onFiber(e,Jx(t)),n),[fS]:(e,t,n,r)=>re(Gl(),()=>n)},Ej=hl();cm=class cm extends Lx{[hS]=gS;[hI]=Tj;_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,Gy(n)){let r=this.getFiberRef(Xl);bj.unsafeUpdate(1,r),UA.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return Xf(this)}id(){return this._fiberId}resume(e){this.tell(ka(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(Ak(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(Ql)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return $e(()=>{let t=ZC(this._fiberId);return this.tell(nc((n,r)=>{hf(t,Z(()=>e(n,r)))})),mf(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return pi((e)=>{let t=(n)=>e(Re(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(nc((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),Z(()=>this.tell(nc((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return Ut((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=Bx(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(BA),c=x(Ul(o,s),Qy(To),Qy(Vp));return gx(c)})}get poll(){return Z(()=>fo(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return Z(()=>this.tell(Yf(sr(e))))}unsafeInterruptAsFork(e){this.tell(Yf(sr(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(BA,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=su(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=Qs(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(au),this.currentTracer=this.currentDefaultServices.unsafeMap.get(iu.key),this.currentSupervisor=this.getFiberRef(jj),this.currentScheduler=this.getFiberRef(Kf),this.currentContext=this.getFiberRef(Ta),this.currentSpan=this.currentContext.unsafeMap.get(kf.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=mu,n=globalThis[bi];globalThis[bi]=this;try{while(t===mu)t=this._queue.length===0?Rj:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[bi]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===jA)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Ks),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=Oj[r._tag](this,e,n,r)}return n}isInterrupted(){return!Sp(this.getFiberRef(Ql))}addInterruptedCause(e){let t=this.getFiberRef(Ql);this.setFiberRef(Ql,Jt(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(Yf(sr(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return Jl({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Eo(r.value.await);else return Z(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(Gy(this.currentRuntimeFlags)){let t=this.getFiberRef(Xl),n=this.id().startTimeMillis,r=Date.now();switch(vj.unsafeUpdate(r-n,t),UA.unsafeUpdate(-1,t),e._tag){case fn:{_j.unsafeUpdate(1,t);break}case pn:{wj.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(KC);if(!Fs(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(Mj)}log(e,t,n){let r=De(n)?n.value:this.getFiberRef(_x),o=this.getFiberRef(kj);if(Mk(o,r))return;let i=this.getFiberRef(BC),a=this.getFiberRef(HC),s=this.getLoggers(),c=this.getFiberRefs();if(Rl(s)>0){let l=El(this.getFiberRef(au),ru),u=new Date(l.unsafeCurrentTimeMillis());TR(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 fS:return jA;case uS:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Ne(e.cause)),this._asyncInterruptor=null;return mu}case pS:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),mu;case dS:return e.onFiber(this,this._exitValue!==null?kk:Ik(this.currentRuntimeFlags,this._asyncBlockingOn)),mu;default:return sm(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=Oo(this.currentRuntimeFlags)&&this.isInterrupted()?Ne(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===Io){let o=Ao.currentOp;if(Ao.currentOp=null,o._op===ws)if(sC(this.currentRuntimeFlags))this.tell(lI()),this.tell(ka(Wn)),t=null;else t=Wn;else if(o._op===na)t=null}else{this.currentRuntimeFlags=x(this.currentRuntimeFlags,zy(Vp));let o=this.interruptAllChildren();if(o!==null)t=re(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(ka(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[bi];globalThis[bi]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[bi]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(ka(e))}startFork(e){this.tell(ka(e))}patchRuntimeFlags(e,t){let n=jl(e,t);return globalThis[bi]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(ka(o))};if(Oo(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(Gt(kn(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!==fl)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==xs&&e._op!==bs&&e._op!==_s)return e;e=this.popStack()}}[CR](e){return Z(()=>kl(this.currentContext,e))}["Left"](e){return Mt(e.left)}["None"](e){return Mt(new eu)}["Right"](e){return He(e.right)}["Some"](e){return He(e.value)}["Micro"](e){return Bl((t)=>{let n=t,r=Gk(zk(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(He(o.value));switch(o.cause._tag){case"Interrupt":return n(Ne(sr(Hn)));case"Fail":return n(Mt(o.cause.error));case"Die":return n(Qp(o.cause.defect))}}),Bl((o)=>{n=(i)=>{o(xt)},r.unsafeInterrupt()})})}[Jd](e){let t=$t(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in hu))sm(n);return hu[n._op](this,n,t)}else return Ao.currentOp=He(t),Io}[fn](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in hu))sm(n);return hu[n._op](this,n,t.effect_instruction_i0)}else return Ao.currentOp=t,Io}[pn](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case fl:case Ss:if(!(Oo(this.currentRuntimeFlags)&&this.isInterrupted()))return $t(()=>n.effect_instruction_i1(t));else return Ne(wp(t));case"OnStep":if(!(Oo(this.currentRuntimeFlags)&&this.isInterrupted()))return He(Ne(t));else return Ne(wp(t));case ml:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),Oo(this.currentRuntimeFlags)&&this.isInterrupted())return Ne(Jt(t,this.getInterruptedCause()));else return Ne(t);default:sm(n)}else return Ao.currentOp=Ne(t),Io}[Gd](e){return $t(()=>e.effect_instruction_i0(this,Jx(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=gk(o.refs,t),s=Ul(o.flags,n);return He(Zp(e.effect_instruction_i0,Ut((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(yk(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=jl(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return mi((r)=>re(LS(ax(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return Cj(e.effect_instruction_i0)}[oa](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=jl(n,t);if(Oo(r)&&this.isInterrupted())return Ne(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Ul(r,n);return this.pushStack(new sx(o,e)),$t(()=>e.effect_instruction_i1(n))}else return Wn}[xs](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[fl](e){return this.pushStack(e),e.effect_instruction_i0}[Ss](e){return this.pushStack(e),e.effect_instruction_i0}[na](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),Ao.currentOp=e,Io}[ws](e){return this._isYielding=!1,Ao.currentOp=e,Io}[bs](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return Wn}[_s](e){return hu[_s](this,e,void 0)}[ra](e){return $t(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&aC)!==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(Gl({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(Ej!==t[di]._V){let n=this.getFiberRef(JC);if(n._tag==="Some"){let r=t[di]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${hl()}, 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`,wo,n)}}return this[t._op](t)},this),t===Io){let n=Ao.currentOp;if(n._op===ws||n._op===na)return Io;return Ao.currentOp=null,n._op===fn||n._op===pn?n:Ne(kn(n))}}catch(n){if(t!==Io&&!H(t,"_op")||!(t._op in this))t=dx(`Not a valid effect: ${lo(t)}`);else if(GC(n))t=Ne(Jt(kn(n),sr(Hn)));else t=Qp(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};kj=te("effect/FiberRef/currentMinimumLogLevel",()=>jt(Nk("Info"))),Aj=te(Symbol.for("effect/Logger/defaultLogger"),()=>Ij(SI)),Pj=te(Symbol.for("effect/Logger/tracerLogger"),()=>Qf(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=lS(ci(xi(n,Ta),kf));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=kl(xi(n,au),ru),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=AO(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=cr(t,{renderErrorCause:!0});a.value.event(lo(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),Mj=te(Symbol.for("effect/FiberRef/currentLoggers"),()=>UC(la(Aj,Pj))),VA=h((e)=>ig(e[0]),(e,t,n)=>Ut((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(zC);if(n?.discard)return aS(n.concurrency,()=>ac(Pf,n?.concurrentFinalizers)((i)=>o?Pa(e,(a,s)=>i(t(a,s)),!0,!1,1):_a(e,(a,s)=>i(t(a,s)))),()=>ac(Mf,n?.concurrentFinalizers)((i)=>Pa(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>ac(Nf(i),n?.concurrentFinalizers)((a)=>Pa(e,(s,c)=>a(t(s,c)),o,!1,i)));return aS(n?.concurrency,()=>ac(Pf,n?.concurrentFinalizers)((i)=>o?MS(e,1,(a,s)=>i(t(a,s)),!0):Vn(e,(a,s)=>i(t(a,s)))),()=>ac(Mf,n?.concurrentFinalizers)((i)=>WA(e,(a,s)=>i(t(a,s)),o)),(i)=>ac(Nf(i),n?.concurrentFinalizers)((a)=>MS(e,i,(s,c)=>a(t(s,c)),o)))})),gu=gn("effect/Scope"),qj={[lf]:lf,[uf]:uf,pipe(){return F(this,arguments)},fork(e){return Z(()=>{let t=$j(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),Dj(t,(o)=>Z(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return $e(()=>{if(this.state._tag==="Closed")return xt;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return xt;return qx(this.strategy)?x(Vn(t,(n)=>fi(n(e))),re((n)=>x(Ca(n),er(tu),Le(()=>Wn)))):$x(this.strategy)?x(WA(t,(n)=>fi(n(e)),!1),re((n)=>x(Ca(n,{parallel:!0}),er(tu),Le(()=>Wn)))):x(MS(t,this.strategy.parallelism,(n)=>fi(n(e)),!1),re((n)=>x(Ca(n,{parallel:!0}),er(tu),Le(()=>Wn))))})},addFinalizer(e){return $e(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),xt})}},DS=h(2,(e,t)=>Cx(e,Il(fO(gu,t)))),BA=jC(cC),jj=Uj(Aa),KA=h(2,(e,t)=>mi((n)=>Bn(n(e),{onFailure:(r)=>Bn(t,{onFailure:(o)=>Gt(Jt(r,o)),onSuccess:()=>Gt(r)}),onSuccess:(r)=>Co(t,r)})))});var GA,YA;var ZA=S(()=>{St();GA=wx,YA=Js});class tP{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return F(this,arguments)}}var US=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},XA,zj,QA,Kj=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new QA(e);return Error.stackTraceLimit=t,n},$S,lm,eP,Jj=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new eP(e);return Error.stackTraceLimit=t,n},Gj=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return nu(t.left);case"Right":return He(t.right);case"Some":return He(t.value);case"None":return nu(new eu)}},Yj,Zj=(e)=>new tP(e.context,e.runtimeFlags,e.fiberRefs),Xj,nP,rP,oP;var iP=S(()=>{jn();we();$s();Kx();et();lt();Pe();Jf();ZA();Ls();St();Af();qS();mS();Hl();om();XA=US((e,t,n)=>{let r=Mp(),o=[[Ta,[[r,e.context]]]];if(n?.scheduler)o.push([Kf,[[r,n.scheduler]]]);let i=ok(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new cm(r,i,e.runtimeFlags),s=t;if(n?.scope)s=re(YA(n.scope,Xs),(l)=>hi(df(l,Wl((u)=>U(u,a.id())?xt:Zl(a,u))),zs(t,(u)=>GA(l,u))));let c=a.currentSupervisor;if(c!==Aa)c.onStart(e.context,s,B(),a),a.addObserver((l)=>c.onEnd(l,a));if(lu.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),zj=US((e,t)=>{let n=Yj(e)(t);if(n._tag==="Failure")throw Jj(n.effect_instruction_i0);return n.effect_instruction_i0});QA=class QA 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}};$S=Symbol.for("effect/Runtime/FiberFailure"),lm=Symbol.for("effect/Runtime/FiberFailure/Cause");eP=class eP extends Error{[$S];[lm];constructor(e){let t=Tl(e)[0];super(t?.message||"An error has occurred");if(this[$S]=$S,this[lm]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[lm].toJSON()}}toString(){return"(FiberFailure) "+cr(this[lm],{renderErrorCause:!0})}[de](){return this.toString()}};Yj=US((e,t)=>{let n=Gj(t);if(n)return n;let r=new cu,o=XA(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return Rx(Xp(Kj(o),gf(o)))});Xj=Jy(To,Wy,Vy),nP=Zj({context:si(),runtimeFlags:Xj,fiberRefs:ik()}),rP=XA(nP),oP=zj(nP)});var aP,yu,xu,An,sP,um,cP,Ma,ur,lP,uP;var dP=S(()=>{St();qS();iP();aP=Vs,yu=VA,xu=$e,An=xt,sP=Vl,um=nt,cP=wa,Ma=ba,ur=re,lP=rP,uP=oP});var jS=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return jS(e,t.from)}},Su=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},HS=(e)=>Array.isArray(e),fP=(e)=>!Array.isArray(e),pP=(e)=>`[${pl(e)}]`,dm=(e)=>HS(e)?e.map(pP).join(""):pP(e);var bu=S(()=>{et()});var wi=(e,t,n,r)=>{let o=e;if(n&&Me(n))o+=`
31
+ at path: ${dm(n)}`;if(t!==void 0)o+=`
32
32
  details: ${t}`;if(r)o+=`
33
- schema (${r._tag}): ${r}`;return o},XA=(e)=>Si("Invalid Argument",e),QA=(e)=>Si("Unsupported key schema",void 0,void 0,e),eP=(e)=>Si("Unsupported literal",`literal value: ${Er(e)}`),DS=(e)=>Si("Duplicate index signature",`${e} index signature`),tP,nP,qS=(e)=>Si("Duplicate property signature transformation",`Duplicate key ${Er(e)}`),US=(e)=>Si("Duplicate property signature",`Duplicate key ${Er(e)}`);var $S=S(()=>{Qe();Xe();mu();tP=Si("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),nP=Si("Invalid element","A required element cannot follow an optional element. ts(1257)")});var oP,iP,aP,sP,cP,lP,uP;var dP=S(()=>{oP=Symbol.for("effect/SchemaId/DateFromSelf"),iP=Symbol.for("effect/SchemaId/GreaterThan"),aP=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),sP=Symbol.for("effect/SchemaId/Int"),cP=Symbol.for("effect/SchemaId/MinLength"),lP=Symbol.for("effect/SchemaId/MaxLength"),uP=Symbol.for("effect/SchemaId/MinItems")});class ic{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 De(qr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:Ye(this.annotations)}}}class Ea{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return De(qr(this),()=>Er(this.literal))}toJSON(){return{_tag:this._tag,literal:Bo(this.literal)?String(this.literal):this.literal,annotations:Ye(this.annotations)}}}class pm{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return De(qr(this),()=>Er(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:Ye(this.annotations)}}}class RP{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class TP{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class OP{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class CP{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class EP{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class IP{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class PP{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class NP{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class LP{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class DP{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class UP{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return ur(this)}toJSON(){return{_tag:this._tag,annotations:Ye(this.annotations)}}}class ac{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:Ye(this.annotations)}}toString(){return String(this.type)}}class yu{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(nP)}toString(){return De(qr(this),()=>$j(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:Ye(this.annotations)}}}class sc{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,jP(e))this.parameter=e;else throw Error(tP)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class Ur{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(US(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=xb(t[i].parameter);if(hm(a)){if(o.string)throw Error(DS("string"));o.string=!0}else if(qP(a)){if(o.symbol)throw Error(DS("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return De(qr(this),()=>jj(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:Ye(this.annotations)}}}class nn{types;annotations;static make=(e,t)=>gm(e)?new nn(e,t):e.length===1?e[0]:mm;static unify=(e,t)=>nn.make(Vj(HP(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return De(qr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:Ye(this.annotations)}}}class ym{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=fu(e)}toString(){return qr(this).pipe(Xn(()=>er(PR(this.f)(),(e)=>qr(e))),De(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=jS.get(e);if(t)return t;return jS.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:Ye(this.annotations)},jS.set(e,t),t}}class xu{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return hu(this).pipe(De(()=>st(KP(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Su(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:Ye(this.annotations)}}}class fb{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 De(qr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:Ye(this.annotations)}}}class mb{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class hb{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(qS(o));t[o]=!0;let i=r.to;if(n[i])throw Error(qS(i));n[i]=!0}}}function Vn(e,t){let n=!1,r=Qi(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 Gj(e){return st(ob(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Er(n)}>`).join("")})}var fP,BS,mP,VS,cm,lm,mn,um,ko,WS,zS,KS,JS,GS,YS,hP,ZS,XS,QS,eb,tb,nb,rb,Jt,ob,gP,yP,ib,ab,hu,sb,xP,SP,bP,_P,wP,cb,Mj,lb=(e)=>FR(Mj(e),(t)=>t===!0),ub,Nj,Fj=(e)=>Xn(Nj(e),()=>hu(e)),gu=(e)=>(t)=>t._tag===e,dm,vP,fm,Lj,mm,db,kP,AP,hm,MP,FP,Dj,qj,qP,Uj,bi,$P=(e)=>e.map((t)=>t.type),$j=(e)=>{let t=e.elements.map(String).join(", ");return qR(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}>`}})},Rt,jP=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return jP(e.from)}return!1},pP=(e)=>e.map(String).join("; "),jj=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${pP(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${pP(e.indexSignatures)} }`;else return"{}"},Hj,Bj,HP=(e)=>fl(e,(t)=>pb(t)?HP(t.types):[t]),Vj=(e)=>{let t=Hj(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[kP];case"UnknownKeyword":return[db];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=Bj[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},BP=(e,t)=>e.map(t),gm=(e)=>e.length>1,pb,jS,Su,xm,bu=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[lm];let o={...r,...t},i=cb(e);if(qe(i))o[nb]=bu(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},Wj="[\\s\\S]*?",zj="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",VP=(e,t)=>{switch(e._tag){case"Literal":return Gs(String(e.literal));case"StringKeyword":return Wj;case"NumberKeyword":return zj;case"TemplateLiteral":return WP(e,t,!1);case"Union":return e.types.map((n)=>VP(n,t)).join("|")}},Kj=(e,t,n,r)=>{if(pb(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},WP=(e,t,n)=>{let r="";if(e.head!==""){let o=Gs(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=VP(o.type,t);if(r+=Kj(o.type,i,t,n),o.literal!==""){let a=Gs(o.literal);r+=t&&n?`(${a})`:a}}return r},zP=(e)=>new RegExp(`^${WP(e,!1,!0)}$`),gb=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new sc(i,t,!0));break;case"Literal":if(Lt(i.literal)||Tn(i.literal))n.push(new Rt(i.literal,t,!1,!0));else throw Error(eP(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new Rt(s,t,!1,!0));break}case"UniqueSymbol":n.push(new Rt(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(QA(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},yb=(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},Jj,vt=(e)=>{switch(e._tag){case"Declaration":{let t=Vn(e.typeParameters,vt);return t===e.typeParameters?e:new ic(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Vn(e.elements,(o)=>{let i=vt(o.type);return i===o.type?o:new bi(i,o.isOptional)}),n=$P(e.rest),r=Vn(n,vt);return t===e.elements&&r===n?e:new yu(t,r.map((o)=>new ac(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Vn(e.propertySignatures,(r)=>{let o=vt(r.type);return o===r.type?r:new Rt(r.name,o,r.isOptional,r.isReadonly)}),n=Vn(e.indexSignatures,(r)=>{let o=vt(r.type);return o===r.type?r:new sc(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new Ur(t,n,e.annotations)}case"Union":{let t=Vn(e.types,vt);return t===e.types?e:nn.make(t,e.annotations)}case"Suspend":return new ym(()=>vt(e.f()),e.annotations);case"Refinement":{let t=vt(e.from);return t===e.from?e:new xu(t,e.filter,e.annotations)}case"Transformation":{let t=Jj(e);return vt(t!==void 0?bu(e.to,t):e.to)}}return e},HS=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return HS(e.from);case"Suspend":return HS(e.f())}},Dr=(e,t)=>{switch(e._tag){case"Declaration":{let n=Vn(e.typeParameters,(r)=>Dr(r,t));return n===e.typeParameters?e:new ic(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=Vn(e.elements,(i)=>{let a=Dr(i.type,t);return a===i.type?i:new bi(a,i.isOptional)}),r=$P(e.rest),o=Vn(r,(i)=>Dr(i,t));return n===e.elements&&o===r?e:new yu(n,o.map((i)=>new ac(i)),e.isReadonly)}case"TypeLiteral":{let n=Vn(e.propertySignatures,(o)=>{let i=Dr(o.type,t);return i===o.type?o:new Rt(o.name,i,o.isOptional,o.isReadonly)}),r=Vn(e.indexSignatures,(o)=>{let i=Dr(o.type,t);return i===o.type?o:new sc(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new Ur(n,r)}case"Union":{let n=Vn(e.types,(r)=>Dr(r,t));return n===e.types?e:nn.make(n)}case"Suspend":{let n=void 0,r=Fj(e);if(qe(r)){let o=t?"Bound":"";n={[ub]:`${r.value}Encoded${o}`}}return new ym(()=>Dr(e.f(),t),n)}case"Refinement":{let n=Dr(e.from,t);if(t){if(n===e.from)return e;if(HS(e.from)===void 0&&lb(e))return new xu(n,e.filter,e.annotations);return n}else return n}case"Transformation":return Dr(e.from,t)}return e},Sm=(e)=>Dr(e,!1),Ye=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},xb=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return xb(e.from)}},ur=(e)=>De(qr(e),()=>e._tag),KP=(e)=>ib(e).pipe(Xn(()=>sb(e)),Xn(()=>ab(e)),Qn((t)=>t+Gj(e))),qr=(e)=>Xn(hu(e),()=>KP(e));var Sb=S(()=>{Qe();ee();Xe();$S();mu();Xl();ct();Gd();Ce();Cx();fP=Symbol.for("effect/annotation/TypeConstructor"),BS=Symbol.for("effect/annotation/Brand"),mP=Symbol.for("effect/annotation/SchemaId"),VS=Symbol.for("effect/annotation/Message"),cm=Symbol.for("effect/annotation/MissingMessage"),lm=Symbol.for("effect/annotation/Identifier"),mn=Symbol.for("effect/annotation/Title"),um=Symbol.for("effect/annotation/AutoTitle"),ko=Symbol.for("effect/annotation/Description"),WS=Symbol.for("effect/annotation/Examples"),zS=Symbol.for("effect/annotation/Default"),KS=Symbol.for("effect/annotation/JSONSchema"),JS=Symbol.for("effect/annotation/Arbitrary"),GS=Symbol.for("effect/annotation/Pretty"),YS=Symbol.for("effect/annotation/Equivalence"),hP=Symbol.for("effect/annotation/Documentation"),ZS=Symbol.for("effect/annotation/Concurrency"),XS=Symbol.for("effect/annotation/Batching"),QS=Symbol.for("effect/annotation/ParseIssueTitle"),eb=Symbol.for("effect/annotation/ParseOptions"),tb=Symbol.for("effect/annotation/DecodingFallback"),nb=Symbol.for("effect/annotation/Surrogate"),rb=Symbol.for("effect/annotation/StableFilter"),Jt=h(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?G(e.annotations[t]):H()),ob=Jt(BS),gP=Jt(VS),yP=Jt(cm),ib=Jt(mn),ab=Jt(um),hu=Jt(lm),sb=Jt(ko),xP=Jt(ZS),SP=Jt(XS),bP=Jt(QS),_P=Jt(eb),wP=Jt(tb),cb=Jt(nb),Mj=Jt(rb),ub=Symbol.for("effect/annotation/JSONIdentifier"),Nj=Jt(ub);dm=gu("Literal"),vP=new Ea(null);fm=new RP({[mn]:"undefined"});Lj=new TP({[mn]:"void"});mm=new OP({[mn]:"never"});db=new CP({[mn]:"unknown"});kP=new EP({[mn]:"any"});AP=new IP({[mn]:"string",[ko]:"a string"}),hm=gu("StringKeyword");MP=new PP({[mn]:"number",[ko]:"a number"});FP=new NP({[mn]:"boolean",[ko]:"a boolean"});Dj=new LP({[mn]:"bigint",[ko]:"a bigint"});qj=new DP({[mn]:"symbol",[ko]:"a symbol"}),qP=gu("SymbolKeyword");Uj=new UP({[mn]:"object",[ko]:"an object in the TypeScript meaning, i.e. the `object` type"});bi=class bi extends ac{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:Ye(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};Rt=class Rt extends bi{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:Ye(this.annotations)}}};Hj=po(Jd(Lr,(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})),Bj={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};pb=gu("Union"),jS=te(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Su=gu("Refinement"),xm={};Jj=yb([WS,zS,KS,JS,GS,YS])});class Tt{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class wb{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class cc{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class Ze{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class _m{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class wm{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Wn{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class vb{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function dr(e){return e.sort(eH).map((t)=>t[1])}function aH(e){return sb(e).pipe(Xn(()=>ib(e)),Xn(()=>ab(e)),Xn(()=>hu(e)),De(()=>`{ ${e.from} | filter }`))}function sH(e){if(e.message!==void 0)return e.message;return`Expected ${Su(e.ast)?aH(e.ast):String(e.ast)}, actual ${Er(e.actual)}`}var GP,XP,Tb=(e)=>new XP({issue:e}),QP,eM,gn,Io,pr,vm,tM,nM=(e,t)=>{if(t===void 0||Tn(t))return e;if(e===void 0)return t;return{...e,...t}},rM=(e,t,n)=>{let r=Gt(e,t);return(o,i)=>r(o,nM(n,i))},Yj=(e,t,n)=>{let r=rM(e,t,n);return(o,i)=>yg(r(o,i),Tb)},oM=(e,t)=>rM(e.ast,!0,t),Rm=(e,t)=>Yj(vt(e.ast),!0,t),Zj,Xj,Gt=(e,t)=>{let n=t?Zj:Xj,r=n.get(e);if(r)return r;let o=Qj(e,t),i=_P(e),a=qe(i)?(l,u)=>o(l,nM(u,i.value)):o,s=wP(e),c=t&&qe(s)?(l,u)=>wu(tM(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},bb=(e)=>pn(xP(e)),_b=(e)=>pn(SP(e)),Qj=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=Gt(e.from,!0);return(r,o)=>{o=o??xm;let i=o?.errors==="all",a=Io(tM(n(r,o),(s)=>{let c=new _m(e,r,"From",s);if(i&&lb(e)&&lM(s))return st(e.filter(r,o,e),{onNone:()=>ie(c),onSome:(l)=>ie(new Ze(e,r,[c,new _m(e,r,"Predicate",l)]))});return ie(c)}),(s)=>st(e.filter(s,o,e),{onNone:()=>ce(s),onSome:(c)=>ie(new _m(e,r,"Predicate",c))}));return wu(a,e,r,o)}}else{let n=Gt(vt(e),!0),r=Gt(aM(e.from),!1);return(o,i)=>wu(Io(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=tH(e.transformation,t),r=t?Gt(e.from,!0):Gt(e.to,!1),o=t?Gt(e.to,!0):Gt(e.from,!1);return(i,a)=>wu(Io(vm(r(i,a),(s)=>new wm(e,i,t?"Encoded":"Type",s)),(s)=>Io(vm(n(s,a??xm,e,i),(c)=>new wm(e,i,"Transformation",c)),(c)=>vm(o(c,a),(l)=>new wm(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)=>wu(n(r,o??xm,e),e,r,o)}case"Literal":return hn(e,(n)=>n===e.literal);case"UniqueSymbol":return hn(e,(n)=>n===e.symbol);case"UndefinedKeyword":return hn(e,nR);case"NeverKeyword":return hn(e,rR);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return ce;case"StringKeyword":return hn(e,Lt);case"NumberKeyword":return hn(e,Tn);case"BooleanKeyword":return hn(e,Vi);case"BigIntKeyword":return hn(e,Bo);case"SymbolKeyword":return hn(e,Wi);case"ObjectKeyword":return hn(e,tn);case"Enums":return hn(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>hm(r.type)))return hn(e,(r)=>{if(!Lt(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=zP(e);return hn(e,(r)=>Lt(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>Gt(l.type,t)),r=e.rest.map((l)=>Gt(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=bb(e),c=_b(e);return(l,u)=>{if(!Rg(l))return ie(new Wn(e,l));let d=u?.errors==="all",p=[],f=0,m=[],y=l.length;for(let b=y;b<=i-1;b++){let I=new Tt(b,l,new cc(o[b-y]));if(d){p.push([f++,I]);continue}else return ie(new Ze(e,l,I,m))}if(e.rest.length===0)for(let b=e.elements.length;b<=y-1;b++){let I=new Tt(b,l,new wb(l[b],`is unexpected, expected: ${a}`));if(d){p.push([f++,I]);continue}else return ie(new Ze(e,l,I,m))}let g=0,w=void 0;for(;g<n.length;g++)if(y<g+1){if(e.elements[g].isOptional)continue}else{let b=n[g],I=b(l[g],u);if(gn(I)){if(Le(I)){let O=new Tt(g,l,I.left);if(d){p.push([f++,O]);continue}else return ie(new Ze(e,l,O,dr(m)))}m.push([f++,I.right])}else{let O=f++,v=g;if(!w)w=[];w.push(({es:_,output:k})=>lr(Ca(I),(P)=>{if(Le(P)){let N=new Tt(v,l,P.left);if(d)return _.push([O,N]),An;else return ie(new Ze(e,l,N,dr(k)))}return k.push([O,P.right]),An}))}}if(Pe(r)){let[b,...I]=r;for(;g<y-I.length;g++){let O=b(l[g],u);if(gn(O))if(Le(O)){let v=new Tt(g,l,O.left);if(d){p.push([f++,v]);continue}else return ie(new Ze(e,l,v,dr(m)))}else m.push([f++,O.right]);else{let v=f++,_=g;if(!w)w=[];w.push(({es:k,output:P})=>lr(Ca(O),(N)=>{if(Le(N)){let U=new Tt(_,l,N.left);if(d)return k.push([v,U]),An;else return ie(new Ze(e,l,U,dr(P)))}else return P.push([v,N.right]),An}))}}for(let O=0;O<I.length;O++){let v=g+O;if(y<v+1)continue;else{let _=I[O](l[v],u);if(gn(_)){if(Le(_)){let k=new Tt(v,l,_.left);if(d){p.push([f++,k]);continue}else return ie(new Ze(e,l,k,dr(m)))}m.push([f++,_.right])}else{let k=f++;if(!w)w=[];w.push(({es:P,output:N})=>lr(Ca(_),(U)=>{if(Le(U)){let ke=new Tt(v,l,U.left);if(d)return P.push([k,ke]),An;else return ie(new Ze(e,l,ke,dr(N)))}return N.push([k,U.right]),An}))}}}}let A=({es:b,output:I})=>Jo(b)?ie(new Ze(e,l,dr(b),dr(I))):ce(dr(I));if(w&&w.length>0){let b=w;return pu(()=>{let I={es:ws(p),output:ws(m)};return lr(du(b,(O)=>O(I),{concurrency:s,batching:c,discard:!0}),()=>A(I))})}return A({output:m,es:p})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return hn(e,oR);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([Gt(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Gt(u.parameter,t),Gt(u.type,t),u.parameter]),a=nn.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>Wi(u)?new pm(u):new Ea(u)))),s=Gt(a,t),c=bb(e),l=_b(e);return(u,d)=>{if(!eg(u))return ie(new Wn(e,u));let p=d?.errors==="all",f=[],m=0,y=d?.onExcessProperty==="error",g=d?.onExcessProperty==="preserve",w={},A;if(y||g){A=Reflect.ownKeys(u);for(let v of A){let _=s(v,d);if(gn(_)&&Le(_))if(y){let k=new Tt(v,u,new wb(u[v],`is unexpected, expected: ${String(a)}`));if(p){f.push([m++,k]);continue}else return ie(new Ze(e,u,k,w))}else w[v]=u[v]}}let b=void 0,I=d?.exact===!0;for(let v=0;v<n.length;v++){let _=n[v][1],k=_.name,P=Object.prototype.hasOwnProperty.call(u,k);if(!P){if(_.isOptional)continue;else if(I){let ke=new Tt(k,u,new cc(_));if(p){f.push([m++,ke]);continue}else return ie(new Ze(e,u,ke,w))}}let N=n[v][0],U=N(u[k],d);if(gn(U)){if(Le(U)){let ke=new Tt(k,u,P?U.left:new cc(_));if(p){f.push([m++,ke]);continue}else return ie(new Ze(e,u,ke,w))}w[k]=U.right}else{let ke=m++,pt=k;if(!b)b=[];b.push(({es:kt,output:bn})=>lr(Ca(U),(Je)=>{if(Le(Je)){let St=new Tt(pt,u,P?Je.left:new cc(_));if(p)return kt.push([ke,St]),An;else return ie(new Ze(e,u,St,bn))}return bn[pt]=Je.right,An}))}}for(let v=0;v<i.length;v++){let _=i[v],k=_[0],P=_[1],N=FS(u,_[2]);for(let U of N){let ke=k(U,d);if(gn(ke)&&It(ke)){let pt=P(u[U],d);if(gn(pt)){if(Le(pt)){let kt=new Tt(U,u,pt.left);if(p){f.push([m++,kt]);continue}else return ie(new Ze(e,u,kt,w))}else if(!Object.prototype.hasOwnProperty.call(r,U))w[U]=pt.right}else{let kt=m++,bn=U;if(!b)b=[];b.push(({es:Je,output:St})=>lr(Ca(pt),(Ft)=>{if(Le(Ft)){let Xr=new Tt(bn,u,Ft.left);if(p)return Je.push([kt,Xr]),An;else return ie(new Ze(e,u,Xr,St))}else{if(!Object.prototype.hasOwnProperty.call(r,U))St[U]=Ft.right;return An}}))}}}}let O=({es:v,output:_})=>{if(Jo(v))return ie(new Ze(e,u,dr(v),_));if(d?.propertyOrder==="original"){let k=A||Reflect.ownKeys(u);for(let N of o)if(k.indexOf(N)===-1)k.push(N);let P={};for(let N of k)if(Object.prototype.hasOwnProperty.call(_,N))P[N]=_[N];return ce(P)}return ce(_)};if(b&&b.length>0){let v=b;return pu(()=>{let _={es:ws(f),output:Object.assign({},w)};return lr(du(v,(k)=>k(_),{concurrency:c,batching:l,discard:!0}),()=>O(_))})}return O({es:f,output:w})}}case"Union":{let n=iM(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],Gt(e.types[l],t));let s=bb(e)??1,c=_b(e);return(l,u)=>{let d=[],p=0,f=[];if(o>0)if(tl(l))for(let g=0;g<o;g++){let w=r[g],A=n.keys[w].buckets;if(Object.prototype.hasOwnProperty.call(l,w)){let b=String(l[w]);if(Object.prototype.hasOwnProperty.call(A,b))f=f.concat(A[b]);else{let{candidates:I,literals:O}=n.keys[w],v=nn.make(O),_=I.length===i?new Ur([new Rt(w,v,!1,!0)],[]):nn.make(I);d.push([p++,new Ze(_,l,new Tt(w,l,new Wn(v,l[w])))])}}else{let{candidates:b,literals:I}=n.keys[w],O=new Rt(w,nn.make(I),!1,!0),v=b.length===i?new Ur([O],[]):nn.make(b);d.push([p++,new Ze(v,l,new Tt(w,l,new cc(O)))])}}else{let g=n.candidates.length===i?e:nn.make(n.candidates);d.push([p++,new Wn(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 w=f[g],A=a.get(w)(l,u);if(gn(A)&&(!m||m.length===0))if(It(A))return A;else d.push([p++,A.left]);else{let b=p++;if(!m)m=[];m.push((I)=>pu(()=>{if("finalResult"in I)return An;else return lr(Ca(A),(O)=>{if(It(O))I.finalResult=O;else I.es.push([b,O.left]);return An})}))}}let y=(g)=>Jo(g)?g.length===1&&g[0][1]._tag==="Type"?ie(g[0][1]):ie(new Ze(e,l,dr(g))):ie(new Wn(e,l));if(m&&m.length>0){let g=m;return pu(()=>{let w={es:ws(d)};return lr(du(g,(A)=>A(w),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in w)return w.finalResult;return y(w.es)})})}return y(d)}}case"Suspend":{let n=fu(()=>Gt(e.f(),t));return(r,o)=>n()(r,o)}}},hn=(e,t)=>(n)=>t(n)?ce(n):ie(new Wn(e,n)),_u=(e,t)=>{switch(e._tag){case"Declaration":{let n=cb(e);if(qe(n))return _u(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?Sm(o.type):vt(o.type);if(dm(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?Sm(o.type):vt(o.type);if(dm(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return _u(e.from,t);case"Suspend":return _u(e.f(),t);case"Transformation":return _u(t?e.from:e.to,t)}return[]},iM=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=_u(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}},aM=(e)=>Su(e)?aM(e.from):e,wu=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(gn(e))return e;let o=new nu,i=KA(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(Wk(a))return ce(a.value);let s=a.cause;if(DC(s))return ie(s.error);return ie(new vb(t,n,qC(s)))}return ie(new vb(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},eH=([e],[t])=>e>t?1:e<t?-1:0,tH=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return ce;case"TypeLiteralTransformation":return(n)=>{let r=ce(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=pr(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?G(l[i]):H());if(delete l[i],qe(u))l[a]=u.value;return l})}return r}}},rn=(e,t=[])=>({value:e,forest:t}),vu,nH=(e)=>e.value+sM(`
34
- `,e.forest),sM=(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+=sM(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},rH=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},oH=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},cM=(e)=>("ast"in e)?G(e.ast):H(),Rb,iH=(e)=>cM(e).pipe(er(gP),st({onNone:()=>Rb,onSome:(t)=>{let n=t(e);if(Lt(n))return ce({message:n,override:!1});if(VA(n))return im(n,(r)=>({message:r,override:!1}));if(Lt(n.message))return ce({message:n.message,override:n.override});return im(n.message,(r)=>({message:r,override:n.override}))}})),Ob=(e)=>(t)=>t._tag===e,lM,YP,ZP,Ru=(e)=>Io(iH(e),(t)=>{if(t!==void 0)return!t.override&&(lM(e)||YP(e)&&e.kind==="From"||ZP(e)&&e.kind!=="Transformation")?ZP(e)||YP(e)?Ru(e.issue):Rb:ce(t.message);return Rb}),uM=(e)=>cM(e).pipe(er(bP),MR((t)=>t(e)),pn),cH=(e)=>pr(Ru(e),(t)=>t??uM(e)??sH(e)),bm=(e)=>uM(e)??String(e.ast),lH=(e)=>e.message??"is forbidden",uH=(e)=>e.message??"is unexpected",dH=(e)=>{let t=yP(e.ast);if(qe(t)){let n=t.value();return Lt(n)?ce(n):n}return ce(e.message??"is missing")},lc=(e)=>{switch(e._tag){case"Type":return pr(cH(e),rn);case"Forbidden":return ce(rn(bm(e),[rn(lH(e))]));case"Unexpected":return ce(rn(uH(e)));case"Missing":return pr(dH(e),rn);case"Transformation":return Io(Ru(e),(t)=>{if(t!==void 0)return ce(rn(t));return pr(lc(e.issue),(n)=>rn(bm(e),[rn(rH(e.kind),[n])]))});case"Refinement":return Io(Ru(e),(t)=>{if(t!==void 0)return ce(rn(t));return pr(lc(e.issue),(n)=>rn(bm(e),[rn(oH(e.kind),[n])]))});case"Pointer":return pr(lc(e.issue),(t)=>rn(am(e.path),[t]));case"Composite":return Io(Ru(e),(t)=>{if(t!==void 0)return ce(rn(t));let n=bm(e);return LS(e.issues)?pr(du(e.issues,lc),(r)=>rn(n,r)):pr(lc(e.issues),(r)=>rn(n,[r]))})}};var dM=S(()=>{Qe();UC();kE();GA();dn();zk();ee();Xe();mu();ct();Ce();Bf();Sb();GP=Symbol.for("effect/Schema/ParseErrorTypeId");XP=class XP extends EE("ParseError"){[GP]=GP;get message(){return this.toString()}toString(){return vu.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[ue](){return this.toJSON()}};QP=ce,eM=ie,gn=gg,Io=h(2,(e,t)=>gn(e)?pl(e,{onLeft:ie,onRight:t}):lr(e,t)),pr=h(2,(e,t)=>gn(e)?OR(e,t):im(e,t)),vm=h(2,(e,t)=>gn(e)?Kd(e,t):zA(e,t)),tM=h(2,(e,t)=>gn(e)?pl(e,{onLeft:t,onRight:ce}):WA(e,t)),Zj=te(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),Xj=te(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);vu={formatIssue:(e)=>pr(lc(e),nH),formatIssueSync:(e)=>{let t=vu.formatIssue(e);return gn(t)?ER(t):JA(t)},formatError:(e)=>vu.formatIssue(e.issue),formatErrorSync:(e)=>vu.formatIssueSync(e.issue)},Rb=ce(void 0),lM=Ob("Composite"),YP=Ob("Refinement"),ZP=Ob("Transformation")});var pM,fM;var mM=S(()=>{ee();Ce();pM=h((e)=>tn(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),fM=h((e)=>tn(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function $t(e){return class{[Tu]=hM;static ast=e;static annotations(n){return $t($r(this.ast,n))}static pipe(){return M(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Tu]=hM}}function mH(e){return gm(e)?nn.make(BP(e,(t)=>new Ea(t))):new Ea(e[0])}function wM(e,t=mH(e)){return class extends $t(t){static annotations(r){return wM(this.literals,$r(this.ast,r))}static literals=[...e]}}function C(...e){return Pe(e)?wM(e):kb}function Eb(e,t){return class extends $t(t){static annotations(r){return Eb(this.typeParameters,$r(this.ast,r))}static typeParameters=[...e]}}function RM(e,t=yH(e)){return class extends $t(t){static annotations(r){return RM(this.members,$r(this.ast,r))}static members=[...e]}}function he(...e){return gm(e)?RM(e):Pe(e)?e[0]:kb}function Tm(e,t,n=SH(e,t)){return class extends $t(n){static annotations(o){return Tm(this.elements,this.rest,$r(this.ast,o))}static elements=[...e];static rest=[...t]}}function TM(...e){return Array.isArray(e[0])?Tm(e[0],e.slice(1)):Tm(e,[])}function OM(e,t){return class extends Tm([],[e],t){static annotations(r){return OM(this.value,$r(this.ast,r))}static value=e}}class EM{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<${Cb(this.to.isOptional)}, ${this.to.type}, ${bH(this.from.fromKey)}, ${Cb(this.from.isOptional)}, ${this.from.type}>`}}function Nb(e,t,n=wH(e,t)){return class extends $t(n){static annotations(o){return Nb(this.fields,this.records,$r(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=vH(e,{...o});return qb(i)?a:Rm(this)(a)};static pick(...o){return T(pM(e,...o))}static omit(...o){return T(fM(e,...o))}}}function T(e,...t){return Nb(e,t)}function PM(e,t,n){return class extends Nb({},[{key:e,value:t}],n){static annotations(o){return PM(e,t,$r(this.ast,o))}static key=e;static value=t}}function MM(e,t){return class extends $t(t){static annotations(r){return MM(this.from,$r(this.ast,r))}static make=(r,o)=>qb(o)?r:Rm(this)(r);static from=e}}function NM(e,t,n){return class extends $t(n){static annotations(o){return NM(this.from,this.filter,$r(this.ast,o))}static[RH]=e;static from=e;static filter=t;static make=(o,i)=>qb(i)?o:Rm(this)(o)}}function We(e,t){return(n)=>{function r(i,a,s){return TH(e(i,a,s),s,i)}let o=new xu(n.ast,r,ka(t));return NM(n,r,o)}}function qb(e){return Vi(e)?e:e?.disableValidation??!1}var Tu,hM,gM,ka=(e)=>{if(!e)return{};let t={...e};for(let n in gM)if(n in e){let r=gM[n];t[r]=e[n],delete t[n]}return t},$r=(e,t)=>bu(e,ka(t)),Om=(e,t)=>{let n=oM(e,t);return(r,o)=>Kd(n(r,o),Tb)},yM=(e)=>j(e,Tu)&&tn(e[Tu]),hH=(e,t,n)=>Eb(e,new ic(e.map((r)=>r.ast),(...r)=>t.decode(...r.map($t)),(...r)=>t.encode(...r.map($t)),ka(n))),gH=(e,t)=>{let n=()=>(o,i,a)=>e(o)?QP(o):eM(new Wn(a,o));return Eb([],new ic([],n,n,ka(t)))},X=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return hH(n,r,o)}let e=arguments[0],t=arguments[1];return gH(e,t)},vM,Ot,kb,Ib,F,yn,B,yH=(e)=>nn.make(e.map((t)=>t.ast)),xH=(e)=>he(e,vM),SH=(e,t)=>new yu(e.map((n)=>yM(n)?new bi(n.ast,!1):n.ast),t.map((n)=>yM(n)?new ac(n.ast):n.ast),!0),z=(e)=>OM(e),Cb=(e)=>e?'"?:"':'":"',Ab,CM,bH=(e)=>{if(e===void 0)return"never";if(Lt(e))return JSON.stringify(e);return String(e)},kM=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new Ab(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new EM(e.from,new CM(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},IM,AM=(e)=>j(e,IM),Pb,Mb,R=(e)=>{let t=e.ast===fm||e.ast===mm?fm:xH(e).ast;return new Mb(new Ab(t,!0,!0,{},void 0),e)},_H,wH=(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(AM(u)){let d=u.ast;switch(d._tag){case"PropertySignatureDeclaration":{let{type:p,isOptional:f,annotations:m}=d;i.push(new Rt(l,p,f,!0,_H(d))),a.push(new Rt(l,vt(p),f,!0,m)),r.push(new Rt(l,p,f,!0,m));break}case"PropertySignatureTransformation":{let p=d.from.fromKey??l;i.push(new Rt(p,d.from.type,d.from.isOptional,!0,d.from.annotations)),a.push(new Rt(l,d.to.type,d.to.isOptional,!0,d.to.annotations)),s.push(new mb(p,l,d.decode,d.encode));break}}}else i.push(new Rt(l,u.ast,!1,!0)),a.push(new Rt(l,vt(u.ast),!1,!0)),r.push(new Rt(l,u.ast,!1,!0))}if(Pe(s)){let c=[],l=[];for(let u of t){let{indexSignatures:d,propertySignatures:p}=gb(u.key.ast,u.value.ast);p.forEach((f)=>{i.push(f),a.push(new Rt(f.name,vt(f.type),f.isOptional,f.isReadonly,f.annotations))}),d.forEach((f)=>{c.push(f),l.push(new sc(f.parameter,vt(f.type),f.isReadonly))})}return new fb(new Ur(i,c,{[um]:"Struct (Encoded side)"}),new Ur(a,l,{[um]:"Struct (Type side)"}),new hb(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=gb(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new Ur(r,o)},vH=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&AM(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},Cm=(e)=>PM(e.key,e.value),Ou=(e,t)=>(n)=>{let r=st(ob(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=bu(n.ast,ka({[BS]:r,...t}));return MM(n,o)},RH,xM=(e,t,n)=>{if(Vi(e))return e?H():G(new Wn(t,n));if(Lt(e))return G(new Wn(t,n,e));if(e!==void 0){if("_tag"in e)return G(e);let r=new Wn(t,n,e.message);return G(Pe(e.path)?new Tt(e.path,n,r):r)}return H()},TH=(e,t,n)=>{if(ZA(e))return xM(e,t,n);if(Pe(e)){let r=Zd(e,(o)=>xM(o,t,n));if(Pe(r))return G(r.length===1?r[0]:new Ze(t,n,r))}return H()},OH,Fb=(e,t)=>(n)=>n.pipe(We((r)=>r.length<=e,{schemaId:OH,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),CH,uc=(e,t)=>(n)=>n.pipe(We((r)=>r.length>=e,{schemaId:CH,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),SM,ge=(e,t)=>(n)=>{let r=e.source;return n.pipe(We((o)=>(e.lastIndex=0,e.test(o)),{schemaId:SM,[SM]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},EH,bM,kH,IH,Lb=(e,t)=>(n)=>n.pipe(We((r)=>r>e,{schemaId:IH,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),AH,FM=(e,t)=>(n)=>n.pipe(We((r)=>r>=e,{schemaId:AH,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),PH,Em=(e)=>(t)=>t.pipe(We((n)=>Number.isSafeInteger(n),{schemaId:PH,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),Db=(e)=>Lb(0,{title:"positive",...e}),km,MH,jr=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(XA(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(We((o)=>o.length>=r,{schemaId:MH,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[rb]:!0,...t}))},_M,NH;var Nt=S(()=>{Qe();dn();Qc();$S();dP();mu();ct();dM();Ae();Ce();Sb();mM();Tu=Symbol.for("effect/Schema");hM={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},gM={typeConstructor:fP,schemaId:mP,message:VS,missingMessage:cm,identifier:lm,title:mn,description:ko,examples:WS,default:zS,documentation:hP,jsonSchema:KS,arbitrary:JS,pretty:GS,equivalence:YS,concurrency:ZS,batching:XS,parseIssueTitle:QS,parseOptions:eb,decodingFallback:tb};vM=class vM extends $t(fm){};Ot=class Ot extends $t(vP){};kb=class kb extends $t(mm){};Ib=class Ib extends $t(db){};F=class F extends $t(AP){};yn=class yn extends $t(MP){};B=class B extends $t(FP){};Ab=class Ab extends bi{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=Cb(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};CM=class CM extends bi{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};IM=Symbol.for("effect/PropertySignature");Pb=class Pb{ast;[Tu];[IM]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return M(this,arguments)}annotations(e){return new Pb(kM(this.ast,ka(e)))}toString(){return String(this.ast)}};Mb=class Mb extends Pb{from;constructor(e,t){super(e);this.from=t}annotations(e){return new Mb(kM(this.ast,ka(e)),this.from)}};_H=yb([cm]);RH=Symbol.for("effect/SchemaId/Refine");OH=lP,CH=cP,SM=Symbol.for("effect/SchemaId/Pattern"),EH=Symbol.for("effect/SchemaId/UUID"),bM=/^[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;kH=class kH extends F.pipe(ge(bM,{schemaId:EH,identifier:"UUID",jsonSchema:{format:"uuid",pattern:bM.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};IH=iP,AH=aP,PH=sP;km=class km extends yn.pipe(Em({identifier:"Int"})){};MH=uP,_M=oP;NH=class NH extends X(Dd,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:_M,[_M]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>eR}){}});function zn(e,t){return Om(e,FH)(t)}var FH;var dc=S(()=>{Nt();FH={onExcessProperty:"error"}});function $M(e){let t=Om(pc)(e);return It(t)?t.right:void 0}function Ub(e){return $M(e)!==void 0}function jM(e){return Ub(e)&&!e.includes("-")}function LM(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 LH(e){let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!jM(t))return!1;let[o,i,a,s]=n.split(".");return o==="dev"&&s===void 0&&LM(i)&&LM(a)}function Im(e){let t=$M(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 Eu(e,t){let n=DM(e),r=DM(t),o=Cu(n.minor,r.minor);if(o!==0)return o;let i=Cu(n.patch,r.patch);if(i!==0)return i;return DH(n.suffix,r.suffix)}function jb(e,t){let n=Im(t);if(e!=="patch"&&e!=="minor"){if(!Ub(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 DM(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 Cu(e,t){let n=BigInt(e),r=BigInt(t);if(n<r)return-1;if(n>r)return 1;return 0}function DH(e,t){let n=qM(e),r=qM(t);if(n<r)return-1;if(n>r)return 1;if(e.kind==="numeric"&&t.kind==="numeric")return Cu(e.value,t.value);if(e.kind==="development"&&t.kind==="development"){let o=Cu(e.runNumber,t.runNumber);return o===0?Cu(e.runAttempt,t.runAttempt):o}return 0}function qM(e){if(e.kind==="development")return 0;if(e.kind==="base")return 1;return 2}var UM,pc,$b,HM,fc;var BM=S(()=>{dn();Nt();UM=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,pc=F.pipe(ge(UM));$b=F.pipe(We(jM));HM=F.pipe(We(LH)),fc=he(pc,HM)});function Vb(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(Bb.includes(r)&&o==="openai-bundled"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:e};if(!zM(r)||!WM(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function fr(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(zM(n)&&WM(r))return`${n}@openai-curated`;if(Bb.includes(n)&&r==="openai-bundled")return`${n}@openai-bundled`;return}function Wb(e){let t=fr(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 WM(e){return VM.includes(e)}function zM(e){return Am.includes(e)}function zb(e,t){let n=t??Yt;return{browser_use:e?.browser_use??n.browser_use,computer_use:e?.computer_use??n.computer_use,sites:e?.sites??n.sites}}function mc(e,t=[]){let n=[...JM],r=new Set(n);for(let o of KM){if(!e[o])continue;for(let i of Ao[o].pluginIds)if(!r.has(i))r.add(i),n.push(i)}for(let o of t)if(!r.has(o))r.add(o),n.push(o);return n}var ku,Hb,qH,UH,VM,Am,Bb,Ct,_i,$H,jH,Ao,KM,HH,JM,BH,Yt;var Kb=S(()=>{Nt();ku=C("browser_use","computer_use","frontend","security","sites"),Hb=C("browser_use","computer_use","sites"),qH=C("installed","disabled","missing","uncertain"),UH=C("healthy","missing","disabled","uncertain"),VM=Object.freeze(["openai-curated","openai-curated-remote"]),Am=Object.freeze(["build-web-apps","codex-security"]),Bb=Object.freeze(["browser","computer-use","sites"]);Ct=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),_i=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([])}),$H=_i.frontend,jH={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Ct.frontend,semanticSkillIds:Object.freeze(_i.frontend.map(({skillId:e})=>e)),applicability:_i.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Ct.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:_i.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Ct.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:_i.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:["browser@openai-bundled"],defaultSelected:Ct.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:_i.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:Ct.sites,migrationKey:"sites",semanticSkillIds:[],applicability:_i.sites,ownership:"shared-preserve"}},Ao=Object.freeze(jH),KM=Object.freeze(["browser_use","computer_use","sites"]),HH=Object.freeze(["frontend","security"]),JM=Object.freeze([...Ao.frontend.pluginIds,...Ao.security.pluginIds]),BH=Object.freeze(["writing-instructions","babysit-ci"]),Yt=Object.freeze({browser_use:Ct.browser_use,computer_use:Ct.computer_use,sites:Ct.sites})});function Hr(e){return T({identifier:C(e),label:F,requiresRootApproval:B})}function GM(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 YM(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var ZM,VH,WH,Jb,zH,XM,KH,JH,GH;var QM=S(()=>{Nt();ZM=C("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"),VH=T({identifier:ZM,label:F,requiresRootApproval:B});WH=T({localRepositoryEdit:Hr("local.repository.edit"),localRepositoryCheck:Hr("local.repository.check"),localRepositoryLint:Hr("local.repository.lint"),localRepositoryFormat:Hr("local.repository.format"),localRepositoryCommit:Hr("local.repository.commit"),externalRead:Hr("external.read"),specialistDispatch:Hr("specialist.dispatch"),versionControlServerMutation:Hr("vcs.server.mutation"),versionControlServerCiTrigger:Hr("vcs.server.ci-trigger"),unknownEffect:Hr("unknown.effect")}),Jb={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}};Cr(Jb);zH=C("never","root"),XM=Object.values(Jb);KH=XM.filter((e)=>!e.requiresRootApproval),JH=XM.filter((e)=>e.requiresRootApproval),GH=Object.freeze({noRootApproval:`${YM(GM(KH))} actions do not require Root approval.`,rootApproval:`${YM(GM(JH))} require Root approval.`})});function Pm(e){let t=zn(YH,e);if(Le(t))return Bi(Kc("sha256 digest",t.left));return ps(t.right)}var mr,Gb,sZ,cZ,lZ,YH,ZH,XH,QH,e1;var Mm=S(()=>{dn();Nt();fs();dc();mr=F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Gb=F.pipe(ge(/^[0-9a-f]{64}$/u)),sZ=mr.pipe(Ou("RunId")),cZ=mr.pipe(Ou("ProjectId")),lZ=mr.pipe(Ou("TrustId")),YH=Gb.pipe(Ou("Sha256Digest"));ZH=T({run_id:mr,objective_lineage:mr,parent_run_id:R(he(mr,Ot))}),XH=T({project_id:mr,trust_id:mr,trust_digest:Gb}),QH=T({project_id:mr,project_digest:Gb}),e1=F.pipe(ge(/^state-[0-9]+\.[0-9]+$/u))});function Fm(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 rN(e){return typeof e==="string"&&i1.has(e)}function s1(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!rN(t)||typeof n!=="string")return!1;return Au.get(t)?.tasks.some((r)=>r.name===n)===!0}function Lm(e,t){return typeof t==="string"&&Au.get(e)?.tasks.some((n)=>n.name===t)===!0}function oN(e){return typeof e==="string"&&a1.has(e)}function Qb(e){let t=`${e.role}.${e.task}`;if(!Zb.has(t))throw Error("Unknown native specialist agent type.");return t}function e_(e){let t=Au.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return e.role==="Librarian"?`${n1} ${t.instruction}`:t.instruction}function t_(e){let t=Au.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function aN(e){let t=Au.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function n_(e){let n=aN(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 Br,eN,hr,Mo,t1,Iu="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.",Po="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",n1="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.",r1,tN,o1,No,Au,i1,Yb,a1,nN,Zb,Xb,c1,l1,u1,d1,Pu,Ia,iN,Vr,p1,Dm,sN,Nm,f1,m1,h1,r_,Mu,g1,wi,y1,x1,K;var Nu=S(()=>{Nt();Br=C("low","default","high"),eN=C("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),hr=he(Br,eN);Mo=C("standard","fast","fast-all"),t1=C("low","medium","high","xhigh","max"),r1=C("none"),tN=Object.freeze(["implementation","review","validation","integration","vcs"]),o1=C("read-only","workspace-write"),No=[{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. ${Po}`,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. ${Po}`,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. ${Po}`,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. ${Po}`,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. ${Po}`,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:`Observe the assigned CI or release gate for the Root-supplied exact ref or SHA until it reaches a terminal state; report the matching result and failure evidence. ${Po}`,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. ${Po}`,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:"plan",description:"Adversarial implementation-plan review specialist.",instruction:`Adversarially inspect the assigned implementation plan for missing requirements, invalid assumptions, unsafe ordering, unowned seams, and inadequate proof. Return actionable plan findings or a fixed-point verdict; do not implement the plan. ${Po}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{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}}];Cr(No);Au=new Map(No.map((e)=>[e.role,e])),i1=new Set(No.map((e)=>e.role)),Yb=No.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),a1=new Set(Yb),nN=Yb.map((e)=>e.replace(":",".")),Zb=new Set(nN);Xb=X(rN),c1=X((e)=>Lm("Explorer",e)),l1=X((e)=>Lm("Librarian",e)),u1=X((e)=>Lm("Worker",e)),d1=X((e)=>Lm("Reviewer",e)),Pu=X(s1),Ia=Object.freeze(Yb.filter((e)=>oN(e))),iN=X(oN),Vr=Object.freeze(nN.filter((e)=>Zb.has(e))),p1=X((e)=>typeof e==="string"&&Zb.has(e)),Dm=Object.freeze(["worker","explorer","reviewer","librarian"]);sN=T({profile:Br,service_tier:R(Mo)}),Nm=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects"]),f1=C(...Nm),m1=C("delegated","root_direct","unavailable"),h1=C(...Nm),r_=C("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),Mu=Object.freeze({rule:"Use the smallest meaningful proof proportionate to changed behavior, scope, and risk, plus repository-required gates. Avoid redundant equivalent checks and speculative edge-case tests.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),g1=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}),wi=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnInspectionImplementationAndRenderedAcceptance:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["specialist_implements","specialist_renders_and_interacts","specialist_judges_current_result","root_accepts_terminal_evidence","root_assigns_discrepancies","specialist_repairs","root_rerenders_and_retests"])}),y1=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),x1=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),K=Object.freeze({requiresDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:Vr,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:Dm,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:Nm,rootOwnedAuthority:Nm,requestUserInputGates:Object.freeze(["plan_approval","installation_profile_approval","remote_origin_server_vcs_mutation","public_publication_or_release","ambiguity_or_missing_material_input"]),surgicalMutationRule:Iu,phaseOrder:tN,phaseGates:Object.freeze({implementationLeavesTerminalBeforeReviewerCode:!0,reviewerCodeFixedPointBeforeWorkerValidation:!0,workerValidationBeforeRootIntegration:!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,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:Mu,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Zt(e,t){return new at("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function o_(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw Zt(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw Zt(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw Zt(t,"invalid number");return r}case"undefined":throw Zt(t,"undefined is not JSON");case"bigint":throw Zt(t,"bigint is not JSON");case"function":throw Zt(t,"function is not JSON");case"symbol":throw Zt(t,"symbol is not JSON");case"object":break}if(n.has(e))throw Zt(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw Zt(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 Zt(`${t}[${s}]`,"sparse or accessor array item");a.push(o_(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 Zt(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw Zt(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Zt(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw Zt(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 Zt(`${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 Zt(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${o_(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function Pn(e){return o_(e,"$",new Set)}function gr(e){return new TextEncoder().encode(Pn(e))}function cN(e,t){if(e.length===0||e.includes("\x00"))throw new at("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 at("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 b1(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function yr(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new at("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",_1(cN(e,t)));return b1(new Uint8Array(r))}function _1(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var i_=S(()=>{fs();Mm()});function dN(e){try{return Pn(e)!==void 0}catch{return!1}}function Um(e){let t=zn(xN,e);if(Le(t))return Bi(Kc("CLI envelope",t.left));return ps(t.right)}var lN,uN,pN,w1,v1,a_="holycodex-specialist-outcome-2",Ht,hc,Fu,R1,T1,O1,C1,E1,k1,qm,I1,A1,P1,M1,N1,fN,mN,hN,F1,gN,yN,xN;var s_=S(()=>{dn();Nt();i_();Kb();fs();Mm();Nu();dc();lN=C("blocked","completed","failed","partial"),uN=he(C("high","max","xhigh"),Ot);pN=X((e)=>dN(e)),w1=X((e)=>Yh(e)&&!Array.isArray(e)&&dN(e)),v1=T({blocked:B,changed_files:z(F),confidence:yn,context_owner:he(F,Ot),material_findings:z(F),needs_more_context:B,needs_root_decision:B,needs_verification:B,relevant_files:z(F),remaining_risk:z(F),reuse_recommended:B,status:lN,suggested_followup:he(F,Ot),suggested_luna_effort:uN,suggested_specialist:he(Xb,Ot),verification:z(F),verification_passed:B}),Ht=F.pipe(uc(1)),hc=T({state:r_,evidence:z(Ht).pipe(jr(1)),library:R(Ht),version:R(Ht)}),Fu={protocol_version:C(a_),route:Pu,evidence:z(Ht),context7:R(hc)},R1=T(Fu),T1=T({...Fu,status:C("completed"),summary:Ht}),O1=T({...Fu,status:C("blocked"),reason:Ht,needs_root_decision:B}),C1=T({...Fu,status:C("partial"),summary:Ht,completed:z(Ht),remaining:z(Ht),needs_root_decision:B}),E1=T({...Fu,status:C("failed"),error:Ht}),k1=he(T1,O1,C1,E1),qm={protocol_version:C(a_),capability:ku,route:he(Pu,Ot),evidence:z(Ht),context7:R(hc),data:pN},I1=T({...qm,status:C("completed"),summary:Ht}),A1=T({...qm,status:C("blocked"),reason:Ht,needs_root_decision:B}),P1=T({...qm,status:C("partial"),summary:Ht,completed:z(Ht),remaining:z(Ht),needs_root_decision:B}),M1=T({...qm,status:C("failed"),error:Ht}),N1=he(I1,A1,P1,M1),fN=z(F),mN=F.pipe(ge(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),hN=C(oo),F1=T({code:mr,message:F,details:w1}),gN=T({schema_version:hN,ok:C(!0),command:mN,data:pN,warnings:fN}),yN=T({schema_version:hN,ok:C(!1),command:mN,error:F1,warnings:fN}),xN=he(gN,yN)});function L1(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:Lu,effort:n}}function U1(e){let t=q1.get(e);if(t===void 0)throw new at("catalog_invalid","A profile has no route effort policy.",{profile:e});return No.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new at("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return L1(n.role,r.name,i)}))}function c_(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:Lu,defaultServiceTier:"standard",routes:U1(e.name)}}function $1(e){let t=["low","default","high"];if(e.length!==t.length)throw new at("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 at("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=o==="high"?u_:l_,a=o==="low"?"medium":"high";if(r.root.model!==i||r.root.effort!==a||r.specialistModel!==Lu)throw new at("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==Ia.length)throw new at("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let c of r.routes){if(s.has(c.key)||!D1.has(c.key)||c.model!==Lu||`${c.role}:${c.task}`!==c.key)throw new at("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(c.key)}if(s.size!==Ia.length)throw new at("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<Ia.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||SN[i.effort]<r)throw new at("catalog_invalid","Profile route effort is not monotonic.",{route:Ia[n]??"unknown"});r=SN[i.effort]}}}function Wr(e){let t=zn(Br,e);if(Le(t))return Bi(new at("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=_N.get(t.right);if(!n)return Bi(new at("invalid_profile","Unknown profile selection.",{profile:t.right}));return ps(n)}var u_="gpt-6-astra",l_="gpt-6-sol",Lu="gpt-6-luna",D1,SN,d_,q1,p_,bN,_N,j1;var wN=S(()=>{dn();fs();Nu();dc();D1=new Set(Ia),SN={low:0,medium:1,high:2,xhigh:3,max:4},d_=[{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:plan":"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:plan":"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:plan":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];Cr(d_);q1=new Map(d_.map((e)=>[e.profile,e]));p_=[c_({name:"low",rootModel:l_,rootEffort:"medium"}),c_({name:"default",rootModel:l_,rootEffort:"high"}),c_({name:"high",rootModel:u_,rootEffort:"high"})];$1(p_);Cr(p_);bN=p_,_N=new Map,j1=new Map;for(let e of bN){_N.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);j1.set(e.name,t)}});import{execFile as B1}from"child_process";import{promisify as V1}from"util";var RN="holycodex-intent-1",TN="holycodex-plan-1",ON="holycodex-assignment-1",$m="toon-4",Q,xr,jm,CN,gc,Kn,ut,NZ,f_,Aa,m_,h_,W1,vN,z1,K1,g_,EN,kN,Du,y_,J1,G1,FZ,Y1="holycodex-work-state-transaction-1",LZ,DZ,Z1,X1,Q1,eB,tB,nB,rB,oB,qZ,iB,UZ;var IN=S(()=>{Nt();s_();Nu();dc();Q=F.pipe(We((e)=>e.trim().length>0)),xr=F.pipe(ge(/^[a-z0-9][a-z0-9-]{0,95}$/u)),jm=F.pipe(ge(/^[a-f0-9]{64}$/u)),CN=F.pipe(ge(/^[a-f0-9]{40}$/u)),gc=km.pipe(FM(1)),Kn=F.pipe(We((e)=>!Number.isNaN(Date.parse(e)))),ut=z(Q),NZ=T({pid:km.pipe(Lb(0)),token:Q}),f_=T({role:C("Explorer","Librarian","Worker","Reviewer"),task:Q}).pipe(We((e)=>No.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),Aa=T({kind:C("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:Q,result:R(C("passed","failed","observed","unknown"))}),m_=T({root:Q,git_common_dir:Q,initial_head:Q,expected_head:Q,expected_changes:ut,expected_status_digest:jm,integrated_commit:R(CN),updated_at:Kn}),h_=C("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),W1=C("scoping","ready","executing","verifying","reviewing"),vN=T({required:B,status:C("not_required","missing","passed","failed","accepted","rejected"),evidence:z(Aa)}),z1=T({schema_version:C(RN),toon_compatibility:C($m),id:xr,slug:xr,title:Q,goal:Q,acceptance_criteria:ut,state:h_,revision:gc,plan_required:B,active_plan_revision:R(gc),active_plan_digest:R(jm),blockers:ut,resume_state:R(W1),verification:vN,review:vN,acceptance_met:B,root_readiness:B,evidence:z(Aa),baseline:m_,created_at:Kn,updated_at:Kn}),K1=T({schema_version:C(TN),toon_compatibility:C($m),intent_id:xr,revision:gc,predecessor_digest:R(jm),approach:Q,scope:ut,exclusions:ut,assignments:ut,dependencies:ut,architecture:ut,risks:ut,assumptions:ut,open_questions:ut,verification:ut,recovery:ut,updated_at:Kn}),g_=C("completed","blocked","needs_root_input","failed"),EN=C("pending","executing","completed","blocked","needs_root_input","failed","superseded"),kN=T({id:xr,outcome:g_,started_at:Kn,finished_at:Kn,summary:Q,evidence:z(Aa),context7:R(hc),blocker:R(Q),remaining_risk:ut}),Du=jm,y_={schema_version:C(ON),toon_compatibility:C($m),intent_id:xr,id:xr,objective:Q,owner:f_,scope:ut,constraints:ut,exclusions:ut,dependencies:ut,acceptance_criteria:ut,status:EN,revision:gc,invocations:z(kN),active_invocation_id:R(Q),active_started_at:R(Kn),supersedes:R(xr),superseded_by:R(xr),supersession_reason:R(Q),supersession_provenance:R(Q),evidence:z(Aa),blocker:R(Q),remaining_risk:ut,created_at:Kn,updated_at:Kn},J1=T(y_),G1=T({...y_,capability:Du}),FZ=T({...y_,active_invocation_capability_verifier:R(Du),active_invocation_capability:R(Du)}),LZ=T({schema_version:C(Y1),state:C("prepared","committed"),files:z(T({path:Q,previous:F,next:F})).pipe(jr(1))}),DZ=T({schema_version:C("holycodex-intent-0"),id:xr,slug:xr,title:Q,goal:Q,acceptance_criteria:ut,state:h_,revision:gc,baseline:m_,created_at:Kn,updated_at:Kn}),Z1=T({title:Q,goal:Q,acceptanceCriteria:z(Q).pipe(jr(1)),planRequired:R(B),verificationRequired:R(B),reviewRequired:R(B)}),X1=T({approach:Q,scope:R(z(Q)),exclusions:R(z(Q)),assignments:R(z(Q)),dependencies:R(z(Q)),architecture:R(z(Q)),risks:R(z(Q)),assumptions:R(z(Q)),openQuestions:R(z(Q)),verification:R(z(Q)),recovery:R(z(Q))}),Q1=T({id:R(Q),objective:Q,owner:f_,scope:z(Q).pipe(jr(1)),constraints:R(z(Q)),exclusions:R(z(Q)),dependencies:R(z(Q)),acceptanceCriteria:z(Q).pipe(jr(1))}),eB=T({scope:z(Q).pipe(jr(1))}),tB=T({scope:R(z(Q).pipe(jr(1)))}),nB=T({replacementId:xr,replacementRevision:R(gc),reason:Q,provenance:Q}),rB=T({commit:CN}),oB=T({invocationId:R(Q),capability:R(Du),outcome:g_,startedAt:R(Q),summary:Q,scope:R(z(Q).pipe(jr(1))),evidence:R(z(Aa)),context7:R(hc),blocker:R(Q),remainingRisk:R(z(Q))}),qZ=T({invocationId:Q,startedAt:Kn,interruptionReason:Q}),iB=T({evidence:R(z(Aa)),verification:R(C("passed","failed")),review:R(C("accepted","rejected")),acceptanceMet:R(B),rootReadiness:R(B),clearBlockers:R(B)}),UZ=V1(B1)});var dt=S(()=>{Qv();fs();dc();BM();Kb();QM();Mm();Nu();s_();wN();i_();IN()});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 ze(e){try{return Pn(e),!0}catch{return!1}}function yB(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 MN(e){return{ok:!1,error:e}}function NN(e){return{ok:!0,value:e}}function Mn(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 Pa(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return Mn(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>Pa(n,t+1));if(de(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=Mn(r,96);if(i.length>0)n[i]=Pa(o,t+1)}return n}return"[redacted]"}function FN(e){let t=Pa(e);return de(t)?t:{value:t}}function Ke(e,t,n){return new oe("invalid_external_data",`Invalid ${e}.`,{field:e,received:Pa(t)},n===void 0?void 0:{cause:n})}function je(e,t,n){let r=zn(e,t);if(Le(r))throw Ke(n,t,String(r.left));return r.right}function LN(e,t){try{return je(e,t,"value"),!0}catch{return!1}}var __,ju=1048576,w_=65536,Nn,Ri,N9,Fo,gB,oe;var zr=S(()=>{dt();dn();Nt();__=oo;Nn=X((e)=>ze(e)),Ri=X((e)=>de(e)&&ze(e)),N9=F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Fo=F.pipe(We((e)=>e.length>0&&e.length<=4096)),gB=yn.pipe(We((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=yB(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var v_,Hu,Bu,R_,T_,O_,C_="turn/completed";var Bm=S(()=>{v_=["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"],Hu=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],Bu=["item/permissions/requestApproval"],R_=["mcpServer/elicitation/request"],T_=["item/tool/call"],O_={method:"initialized"}});function yc(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)=>yc(n,t));return de(e)&&Object.values(e).every((n)=>yc(n,t))}finally{t.delete(e)}}function Kr(e){return de(e)&&yc(e)}function E_(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('"')?SB(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Vr.includes(c))throw Ke("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 Ke("TOML key path",e);if(t.some((i)=>i==="__proto__"||i==="constructor"||i==="prototype"))throw Ke("TOML key path",e);return t}function SB(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Ke("TOML quoted key",e)}function Ne(e,t){if(!Kr(e))throw Ke("TOML document",e);let n=e;for(let r of E_(t)){if(!Kr(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function Vm(e){if(Array.isArray(e))return e.map(Vm);if(de(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Vm(n)]));return e}function Wm(e){return Vm(e)}function Oi(e,t,n){if(!Kr(e)||!yc(n))throw Ke("TOML write",{keyPath:t});let r=E_(t),o={...Wm(e)},i=o;for(let a of r.slice(0,-1)){let s=i[a];if(s!==void 0&&!Kr(s))throw Ke("TOML table path",t);let c=s===void 0?{}:{...s};i[a]=c,i=c}return i[r.at(-1)]=Vm(n),o}function Jr(e,t){if(!Kr(e))throw Ke("TOML document",e);let n=E_(t),r={...Wm(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!Kr(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(Kr(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function Na(e){if(typeof e!=="string")return!1;if(qN.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Vr.some((t)=>e===`agents."${t}".config_file`)}function zm(e){return Na(e)||Ci.includes(e)}function Ti(e){return typeof e==="string"&&_B.test(e)}function k_(e){return e==="gpt-6-astra"||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 wB(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function I_(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function A_(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function P_(e){if(!de(e)||!A_(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return k_(e.value);case"number":return I_(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&Gm(e.value);case"digest":return wB(e.value);default:return!1}}function DN(e,t){switch(N_(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-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 HN(e){return de(e)&&e.kind==="absent"?Object.keys(e).length===1:P_(e)}function BN(e){return de(e)&&A_(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Ti(e.schema)&&Ti(e.installId)&&zm(e.keyPath)&&HN(e.originalValue)&&P_(e.lastManagedValue)&&DN(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||DN(e.keyPath,e.originalValue))}function xc(e){if(!de(e)||!A_(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Ti(e.schema)||!Ti(e.installId)||!de(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>zm(t)&&BN(n)&&n.keyPath===t)}function Jm(e){if(!Ti(e.schema)||!Ti(e.installId))throw Ke("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Gm(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 M_(e){if(!Gm(e))throw Ke("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function Fa(e,t){let n=M_(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 N_(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.context_management.experimental_mode"||Ci.includes(e)||e==="sandbox_workspace_write.network_access")return"boolean";return"enum"}function vB(e,t){let n=N_(e);if(n==="number")return I_(t);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&Gm(t);if(n==="digest")return typeof t==="string";if(e==="model")return t==="gpt-6-astra"||t==="gpt-6-sol"||t==="gpt-6-luna";return typeof t==="string"&&k_(t)}async function on(e,t){if(!zm(e)||!yc(t))throw Ke("managed config value",{keyPath:e});let n=N_(e);if(n==="number"&&I_(t))return{kind:n,value:t};if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&Gm(t))return{kind:n,value:M_(t)};if(n==="enum"&&typeof t==="string"&&k_(t))return{kind:n,value:t};return{kind:"digest",value:await yr("holycodex-managed-config-value",[gr({keyPath:e,value:t})])}}function RB(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function Sc(e,t,n,r){if(!Kr(e)||!xc(t)||!Ti(r.schema)||!Ti(r.installId))throw Ke("managed runtime config",{});let o={...t.managed},i=Wm(e),a=[];for(let[c,l]of Object.entries(n)){if(!Na(c)||typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Ke("managed config key",c);let u=c,d=t.managed[u],p=Ne(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 on(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 on(u,p));if(!vB(u,l))throw Ke("managed config value",{keyPath:u});i=Oi(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:f,lastManagedValue:await on(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!xc(s))throw Ke("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Sr(e,t,n){if(!Kr(e)||!xc(t))throw Ke("managed runtime config",{});let r=Wm(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!zm(c))throw Ke("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=Ne(r,u);if(!(d!==void 0&&JSON.stringify(await on(u,d))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=Jr(r,u),i.push(u),delete o[u];else{let f=RB(l.originalValue);if(f===void 0){s.push(u),a.push(u);continue}r=Oi(r,u,f),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function La(e,t,n){if(!Na(n)||!xc(t))throw Ke("managed config key",n);let r=t.managed[n],o=Ne(e,n),i=o===void 0?void 0:await on(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 xB,Ma,qN,Ci,bB,UN,$N,jN,Km,_B;var Ym=S(()=>{dt();dt();Nt();zr();xB=X((e)=>yc(e)),Ma=X((e)=>Kr(e));qN=["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.context_management.experimental_mode"],Ci=["model_auto_compact_token_limit","features.default_mode_request_user_input","features.agent_message_board","features.multi_agent_v2","features.context_management"],bB=X((e)=>Na(e));UN=X((e)=>P_(e)),$N=X((e)=>HN(e)),jN=X((e)=>BN(e)),Km=X((e)=>xc(e)),_B=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function OB(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function VN(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)=>OB(e[i]))}function KN(e){if(!de(e)||!ze(e))return!1;return VN(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||VN(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function Zm(e){return de(e)&&ze(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function JN(e){return de(e)&&ze(e)&&Zm(e.thread)}function kB(e){return de(e)&&ze(e)&&typeof e.id==="string"}function Ei(e){return de(e)&&ze(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function GN(e){return de(e)&&ze(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||KN(e.usage))}function IB(e){return de(e)&&ze(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 YN(e){if(Bu.some((t)=>t===e))return"permissions";if(Hu.some((t)=>t===e))return"approval";if(R_.some((t)=>t===e))return"elicitation";if(T_.some((t)=>t===e))return"dynamic_tool";return"other"}var WN,Vu,zN,Wu,TB,F_,zu,CB,Xm,L_,D_,EB,Ku,q_,U_,$_,j_,H_,B_,V_,W_,z_,K_,J_,G_,Y_,Z_,X_,Q_,ew,tw,nw,rw,ow,iw,aw,sw,cw,lw,uw,dw,V9,AB,W9;var pw=S(()=>{Nt();zr();Bm();Ym();WN=F.pipe(ge(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),Vu=he(F.pipe(uc(1)),yn.pipe(We((e)=>Number.isSafeInteger(e)))),zN=T({code:yn.pipe(We((e)=>Number.isSafeInteger(e))),message:F,data:R(Nn)}),Wu=he(T({id:Vu,result:Nn}),T({id:Vu,error:zN})),TB=T({id:Vu,error:zN}),F_=T({method:WN,params:R(Nn)}),zu=T({id:Vu,method:WN,params:R(Nn),trace:R(Nn)});CB=X(KN),Xm=T({clientInfo:T({name:Fo,version:Fo,title:he(Fo,Ot)}),capabilities:he(T({experimentalApi:B,requestAttestation:B,mcpServerOpenaiFormElicitation:R(B),optOutNotificationMethods:R(he(z(F),Ot)),extensions:R(Ri)}),Ot)}),L_=X((e)=>de(e)&&ze(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),D_=T({method:C("initialized")});EB=X(Zm);Ku=X((e)=>JN(e)||kB(e)),q_=Ku,U_=Ku,$_=X(Ei),j_=X((e)=>de(e)&&ze(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),H_=X((e)=>JN(e)),B_=X((e)=>{if(!de(e)||!ze(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>Zm(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>Zm(r));return t&&e.threads===void 0||n&&e.data===void 0}),V_=X((e)=>de(e)&&ze(e));W_=X(Ei),z_=X(Ei),K_=X(Ei),J_=X((e)=>de(e)&&ze(e));G_=X((e)=>Ei(e)&&(Array.isArray(e.input)&&e.input.every((t)=>ze(t))||typeof e.prompt==="string"&&e.prompt.length>0)),Y_=X((e)=>Ei(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>ze(t))),Z_=X((e)=>de(e)&&ze(e)&&(e.turn!==void 0&&GN(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),X_=X((e)=>de(e)&&ze(e)&&typeof e.turnId==="string"&&e.turnId.length>0),Q_=X((e)=>Ei(e)&&typeof e.turnId==="string"&&e.turnId.length>0),ew=X((e)=>de(e)&&ze(e)),tw=X((e)=>Ei(e)&&(e.turn!==void 0&&GN(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),nw=X((e)=>de(e)&&ze(e));rw=X((e)=>de(e)&&ze(e)&&Array.isArray(e.data)&&e.data.every((t)=>IB(t))),ow=Ri,iw=Ri,aw=T({includeLayers:R(B),cwd:R(he(F,Ot))}),sw=T({config:Ma,origins:Ri,layers:he(z(Ri),Ot)}),cw=Ri,lw=Ri,uw=X((e)=>de(e)&&ze(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")),dw=Nn,V9=X((e)=>de(e)&&ze(e)&&typeof e.kind==="string"&&typeof e.method==="string");AB=he(C("stable","experimental","disabled"),B),W9=Cm({key:F,value:AB})});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=PB){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=je(Xm,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",V_,e,Ku)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",W_,t,q_)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",z_,t,H_)}async listThreads(e={}){return this.action("thread/list",J_,e,B_)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",K_,t,U_)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",$_,t,j_)}async startTurn(e){return this.action("turn/start",G_,e,Z_)}async steerTurn(e){return this.action("turn/steer",Y_,e,X_)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",Q_,n,ew)}async listModels(e={}){return this.action("model/list",nw,e,rw)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",ow,e,iw)}async readConfig(e={}){return this.action("config/read",aw,e,sw)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",cw,e,lw)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(je(Xm,t,"initialize parameters"));return je(Nn,r,"initialize result")}let n=je(zu,{id:1,method:e,params:t},"App Server method");if(!MB.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",je(Nn,e,"initialize parameters")),n=je(L_,t,"initialize result"),r=je(D_,O_,"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=je(t,n,`${e} parameters`),i=je(Nn,o,`${e} parameters`),a=await this.request(e,i);return je(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=je(zu,{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(Wu,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(zu,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(F_,t);if(o!==void 0){this.handleNotification(o);return}throw Ke("JSON-RPC message",t)}tryDecode(e,t){try{return je(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=FB(t.method);t.reject(new oe(r,`The App Server rejected ${t.method}: ${Mn(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:Pa(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=je(uw,{...e,params:t,category:YN(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,Mn(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,Mn(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=je(dw,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,Mn(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=je(Wu,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=je(Wu,{id:e,error:{code:t,message:NB(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===C_){let n=je(tw,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:FN({params:Pa(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 NB(e){let t=Mn(e);return t.length>0?t:"server request failed"}function FB(e){if(Bu.some((t)=>t===e))return"permission_denied";if(Hu.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var PB,MB;var fw=S(()=>{zr();Bm();pw();PB={clientInfo:{name:"holycodex",title:null,version:__},capabilities:null},MB=new Set(v_)});import{isAbsolute as LB}from"path";function ki(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 mw(e=process.env){return Object.freeze(ki(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 bc(e){return Mn(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}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(!LB(e.executablePath))throw new oe("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??ju,this.maxDiagnosticBytes=e.maxDiagnosticBytes??w_,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:ki(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=bc(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var rh=S(()=>{zr()});import{lstat as tX,mkdir as nX,readFile as DB,readdir as rX,realpath as qB,stat as UB}from"fs/promises";import{delimiter as $B,isAbsolute as iX,join as aX,relative as sX,resolve as ZN}from"path";async function HB(e){let t=[];if(e.executablePath!==void 0)t.push(ZN(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($B).filter((i)=>i.length>0))for(let i of r)t.push(ZN(o,i))}for(let n of t)try{let r=await UB(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await qB(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 BB(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 WB(Promise.all([eh(n.stdout,16384),eh(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=Mn(th(r,"Codex version output"));if(i!==0||a.length===0){let s=bc(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 VB(e){let t=await DB(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=Pm(r);if(!o.ok)throw new oe("discovery_failed","The Codex executable digest was invalid.");return o.value}async function hw(e={}){let t=await HB(e),n=ki(e.environment),r=e.versionRunner?Mn(await e.versionRunner(t,n)):await BB(t,n);if(r.length===0)throw new oe("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await VB(t)}}async function WB(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))},jB)})])}finally{if(r!==void 0)clearTimeout(r)}}var jB=30000,dX;var XN=S(()=>{dt();Nt();zr();rh();dX=T({exitCode:yn.pipe(We((e)=>Number.isSafeInteger(e))),stdout:F.pipe(Fb(1048576)),stderr:F.pipe(Fb(1048576))})});var zB="packages/codex/generated",KB,JB,gw,hX,gX;var QN=S(()=>{dt();Nt();zr();KB=/^codex-cli \d+\.\d+\.\d+$/u,JB=/^codex-app-server-\d+\.\d+\.\d+$/u,gw=F.pipe(ge(/^[a-f0-9]{64}$/u)),hX=T({schema_version:C("holycodex-generated-v2"),artifact_root:C(zB),codex_cli_version:F.pipe(ge(KB)),codex_cli_digest:gw,protocol_epoch:F.pipe(ge(JB)),generator:T({command:TM(C("app-server"),C("generate-ts")),supported_surface:C("codex app-server generators")}),typescript_root:C("typescript"),files:T({count:yn.pipe(Em(),Db()),digest:gw})}),gX=T({path:F.pipe(uc(1)),size:yn.pipe(Em(),Db()),sha256:gw})});var GB;var e0=S(()=>{Nt();Ym();GB=T({owner:C("holycodex"),schema:F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});import{spawn as YB}from"child_process";import{lstat as Ai,mkdir as ZB,mkdtemp as XB,readFile as QB,readdir as eV,realpath as yw,rename as tV,rm as nV,stat as wX}from"fs/promises";import{dirname as n0,isAbsolute as ww,join as Ii,relative as r0,resolve as ih,sep as o0}from"path";async function a0(e){let t=Ow(e.selectedPluginIds);if(t.length===0)return;if(u0(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new Ee("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>Tw(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&sh(r,t))return r;let o=e.initializeRuntime??(()=>fV(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??Rw,c=e.pollIntervalMs??rV,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new Ee("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&sh(u,t))return u;let d=s-(Date.now()-l);if(d<=0)break;await(e.sleep??hV)(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 Ee&&s.code==="cancelled")throw s;a=s instanceof Ee?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 s0({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 Ee)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 s0(e){let t=Ow(e.selectedPluginIds);if(t.length===0)throw se("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(u0(e.timeoutMs,void 0),!ww(e.codexHome))throw se("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new Ee("cancelled","Official Codex marketplace fallback was cancelled.");let n=ki(e.environment),r=e.gitRunner??f0("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??Rw,i;try{i=await aV(r,o,e.signal)}catch(u){if(u instanceof Ee)throw u;throw se("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Ii(e.codexHome,"plugins"),s=Ii(a,vw[1]);if(await cV(a,e.codexHome),await Ai(s).catch((u)=>{if(Zu(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 XB(Ii(a,".openai-plugins-stage-"));try{if(await Sw(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(Da,l)}catch(m){if(mV(m))throw se("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",Da,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await ah(l);let u=await c0(l,e.codexHome,t);if(u===void 0||!sh(u,t))throw se("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await sV(r,l,o,e.signal)!==i)throw se("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Ai(s).catch((m)=>{if(Zu(m))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await tV(l,s);let f=await Tw(e.codexHome,e.selectedPluginIds);if(f===void 0||!sh(f,t))throw se("marketplace_invalid","The published official marketplace failed validation.");return f}catch(u){if(u instanceof Ee)throw u;throw se("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await nV(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function aV(e,t,n){let r=await e.run(["ls-remote",Da,"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 sV(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 cV(e,t){await xw(t,e),await ZB(e,{recursive:!0}),await xw(t,e)}async function xw(e,t){let n=ih(e),r=ih(t);while(!0){if((await Ai(r).catch((a)=>{if(Zu(a))return;throw a}))?.isSymbolicLink())throw se("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=n0(r);if(i===r||i!==n&&!lV(n,i))throw se("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function lV(e,t){let n=r0(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${o0}`)&&!ww(n)}async function ah(e){let t=await Ai(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 eV(e,{withFileTypes:!0});for(let r of n){let o=Ii(e,r.name),i=await Ai(o);if(i.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await ah(o)}}async function Tw(e,t=[]){return await c0(Ii(e,...vw),e,Ow(t))}async function c0(e,t,n=[]){if(t!==void 0)await xw(t,e);let r=await Ai(e).catch((l)=>{if(Zu(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 Sw(t,e);else await ah(e);if(t!==void 0)await ah(e);let o=await yw(e),i=[Ii(o,".agents","plugins","marketplace.json"),Ii(o,".codex-plugin","marketplace.json"),Ii(o,"marketplace.json")],a,s;for(let l of i){let u=await Ai(l).catch((d)=>{if(Zu(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 Sw(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 QB(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 l0(c,o,a,n)}function l0(e,t=`${vw.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!de(e)||e.name!==Yu)throw se("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");uV(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=dV(s);if(!pV(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:Yu,source:Da,rootPath:t,manifestPath:n,plugins:i}}function uV(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)!==Da)throw se("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function dV(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 pV(e){if(e===void 0||e.length===0||ww(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 Ow(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!==Yu&&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(!d0(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function sh(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 fV(e){let t=ki(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??Rw,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 u0(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 Sw(e,t){let n=await yw(e),r=await yw(t),o=r0(n,r);if(o===""||o===".."||o.startsWith(`..${o0}`))throw se("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=ih(e),a=ih(t);while(!0){if((await Ai(a)).isSymbolicLink())throw se("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=n0(a);if(c===a)throw se("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Zu(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function mV(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function hV(e){await new Promise((t)=>setTimeout(t,e))}function se(e,t,n){return new Ee(e,t,n instanceof Error?{cause:bc(n.message)}:{})}function Gr(e,t){let n=fr(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=Vb(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 d0(e){return Am.includes(e)}function p0(e){if(!LN(_w,e))return MN(Ke("live official plugin list",e));return NN(je(_w,e,"live official plugin list"))}function ch(e){let t=e.runner??f0(e.executable,{environment:e.environment??ki(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=async()=>{let r=await t.run(["plugin","list","--json"]);if(r.exitCode!==0)throw oh("list",r);let o;try{o=JSON.parse(r.stdout)}catch{throw new Ee("command_failed","Codex returned invalid plugin data.")}let i=p0(o);if(!i.ok)throw new Ee("command_failed","Codex returned an invalid official plugin list.");return i.value};return{list:n,ensureOfficialMarketplace:async(r)=>{if(e.codexHome===void 0)throw new Ee("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await a0({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:r,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(r,o)=>{let i=je(Gu,r,"plugin marketplace source");if(i===Yu||i===Da)throw new Ee("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.");let a=await t.run(["plugin","marketplace","add",i],o===void 0?void 0:{signal:o});if(a.exitCode!==0&&!/already (?:exists|added)/iu.test(a.stderr))throw oh("marketplace add",a,i)},add:async(r,o)=>{let i=je(Gu,r,"official plugin id"),a=await t.run(["plugin","add",i,"--json"],o===void 0?void 0:{signal:o});if(a.exitCode!==0)throw oh("add",a,i);let s=await n(),c=Gr(s,i),l=fr(i),u=[...s.installed,...s.available].filter((p)=>p.pluginId===i&&(l===void 0||p.marketplaceName==null)),d=c?.entry??u.find((p)=>p.installed)??u[0];if(!d)throw new Ee("readback_mismatch",`Codex did not report ${i} after installation.`,{plugin_id:i});if(!d.installed)throw new Ee("plugin_missing",`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!d.enabled)throw new Ee("plugin_disabled",`Codex installed ${i} but it is disabled; enable it in Codex and retry.`,{plugin_id:i})},remove:async(r,o)=>{let i=je(Gu,r,"official plugin id"),a=i;if(fr(i)===i){let u=await n(),d=Gr(u,i);if(d?.entry.installed)a=d.entry.pluginId}let s=await t.run(["plugin","remove",a,"--json"],o===void 0?void 0:{signal:o});if(s.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(s.stderr))throw oh("remove",s,a);let c=await n(),l=[...c.installed,...c.available].find((u)=>u.pluginId===a);if(l?.installed)throw new Ee("readback_mismatch",`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:l.pluginId})}}}function oh(e,t,n){let r=bc(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new Ee("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function f0(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>yV(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 yV(e,t,n){if(n.signal?.aborted)throw new Ee("cancelled","The Codex plugin command was cancelled.");let r=YB(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=t0(r.stdout,n.stdoutLimit),i=t0(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 Ee("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 Ee("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 Ee)throw d;throw new Ee("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function t0(e,t){if(e===null)return Promise.reject(new Ee("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 Ee("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new Ee("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 Yu="openai-curated",Da="https://github.com/openai/plugins.git",vw,Rw=30000,rV=100,i0,oV,Ju,Gu,iV,gV,bw,_w,Ee;var Cw=S(()=>{dt();Nt();fw();zr();rh();vw=["plugins","openai-plugins"],i0=F.pipe(ge(/^[a-z][a-z0-9._-]{1,63}$/u)),oV=F.pipe(ge(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),Ju=z(F),Gu=F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),iV=T({name:i0,version:oV,description:Fo,author:R(Nn),license:R(Fo),homepage:R(Fo),repository:R(Fo),keywords:R(Ju),skills:R(Ju),commands:R(Ju),hooks:R(Ju),assets:R(Ju),official:R(B)});gV=T({id:i0,selected:C(!0)}),bw=T({pluginId:Gu,installed:B,enabled:B,name:R(he(F,Ot)),marketplaceName:R(he(F,Ot)),version:R(he(F,Ot))},Cm({key:F,value:Ib})),_w=T({installed:z(bw),available:z(bw)});Ee=class Ee extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});var _c=S(()=>{zr();zr();Bm();pw();fw();rh();XN();QN();e0();Ym();Cw();Cw()});function xn(e){if(!wc(e))throw Error("The value is not JSON serializable.");return Pn(e),e}function wc(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)=>wc(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>wc(n,t))}finally{t.delete(e)}}var Xu=S(()=>{dt()});function Fe(e,t){let n=zn(e,t);return It(n)?n.right:void 0}function _0(e){return Fe(Qu,e)!==void 0}var Qu,fQ,xV,SV,ed,bV,Pi,_V,wV,vV,h0,td,uh,nd,g0,Xt,Ew,RV,TV,OV,CV,EV,kV,IV,AV,PV,lh,MV,m0,NV,dh,vc,FV,kw,LV,Iw,DV,y0,Aw,Pw,Mi,x0,qV,S0,UV,b0;var qa=S(()=>{_c();dt();dn();Nt();Xu();Qu=X((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&wc(e)),fQ=X(wc),xV=fc,SV=F.pipe(ge(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),ed=F.pipe(ge(/^[0-9a-f]{64}$/u)),bV=F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Pi=F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),_V=F.pipe(We((e)=>!Number.isNaN(Date.parse(e)))),wV=T({path:F.pipe(ge(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:ed}),vV=T({browser_use:B,computer_use:B,sites:B,coding:C(!0)}),h0=T({browser_use:R(B),computer_use:R(B),sites:R(B)}),td=T({profile:R(Br),tier:R(Mo),optional:R(h0),officialPlugins:R(z(Pi))}),uh=td,nd=T({schema_version:C(1),profile:Br,tier:Mo,capabilities:z(Hb),additional_plugins:z(Pi)}),g0=T({schema_version:C(1),profile:Br,tier:Mo,capabilities:z(ku),additional_plugins:z(Pi)}),Xt=T({selected:B,status:C("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:z(Pi),reason:R(F)}),Ew=T({browser_use:Xt,computer_use:Xt,frontend:Xt,security:Xt,sites:Xt}),RV=T({browser_use:R(B),computer_use:B,frontend:B,security:B,sites:R(B),coding:C(!0),work:B}),TV=T({browser_use:R(B),computer_use:R(B),frontend:R(B),security:R(B),sites:R(B),work:R(B)}),OV=T({browser_use:R(Xt),computer_use:Xt,frontend:Xt,security:Xt,sites:R(Xt),work:Xt}),CV=T({computer_use:B,frontend:B,security:B,coding:C(!0)}),EV=T({computer_use:R(B),frontend:R(B),security:R(B)}),kV=T({computer_use:Xt,frontend:Xt,security:Xt}),IV=he(T({status:C("not_applicable")}),T({status:C("missing")}),T({status:C("healthy"),path:F,installed:B})),AV=T({manager:C("bun","npm","pnpm"),launcher:C("bunx","npx","pnpm dlx"),version:SV,executable:F,ownership:C("user","holycodex"),identity:R(ed)}),PV=T({git_bash:IV,context7:R(AV)}),lh=T({presence:C("absent","present"),digest:ed,safe_value:R(he(T({kind:C("boolean"),value:B}),T({kind:C("marketplace"),source_type:C("git"),source:C("https://github.com/davidbasilefilho/holycodex.git")})))}),MV=T({plugin_id:C("holycodex@holycodex"),before:T({preference:lh,marketplace:lh}),after:T({preference:lh,marketplace:lh})}),m0=T({presence:C("absent","present"),digest:ed,safe_value:R(T({kind:C("boolean"),value:B}))}),NV=T({plugin_id:Pi,before:m0,after:m0}),dh={owner:C("holycodex"),schema_epoch:C(Rn),install_id:bV,version:xV,digest:ed,profile:Br,tier:Mo,optional_selections:vV,explicit_optional_selections:h0,official_plugins:R(z(Pi)),capability_state:R(Ew),managed_artifacts:z(wV),installed_at:_V,status:R(C("active")),step:R(C("active")),managed_config:R(Km),plugin_snapshot:R(z(T({plugin_id:Pi,status:C("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:R(MV),provider_config:R(z(NV)),owned_plugins:R(z(Pi)),tooling:R(PV)},vc=T(dh),FV=(({profile:e,...t})=>t)(dh),kw={...dh,optional_selections:RV,explicit_optional_selections:TV,capability_state:R(OV)},LV=(({profile:e,...t})=>t)(kw),Iw={...dh,optional_selections:CV,explicit_optional_selections:EV,capability_state:R(kV)},DV=(({profile:e,...t})=>t)(Iw),y0=he(T({...kw,profile:hr}),T({...LV,plan:hr}),T({...FV,plan:hr}),T({...Iw,profile:hr}),T({...DV,plan:hr})),Aw=C("preparing","conflicted"),Pw=C("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),Mi=T({...vc.fields,status:Aw,step:Pw}),x0={...kw,status:Aw,step:Pw},qV=(({profile:e,...t})=>t)(x0),S0={...Iw,status:Aw,step:Pw},UV=(({profile:e,...t})=>t)(S0),b0=he(Mi,T({...x0,profile:hr}),T({...qV,plan:hr}),T({...S0,profile:hr}),T({...UV,plan:hr}))});import{lstat as $V,mkdir as jV}from"fs/promises";import{homedir as HV}from"os";import{dirname as BV,join as Ni,posix as w0,resolve as VV,sep as v0,win32 as R0}from"path";function br(e={},t=process.env){let n=HV(),r=e.paths?.codexHome??t.CODEX_HOME??Ni(n,".codex"),o=Nw(r,"CODEX_HOME"),i=Ni(o,WV);return{codexHome:o,stateRoot:i,activeRecord:Ni(i,zV),preparingRecord:Ni(i,KV),conflictedRecord:Ni(i,JV),installOptions:Ni(i,GV),roleRoot:Ni(i,"agents"),configFile:Ni(o,"config.toml")}}function Nw(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||ZV(e))throw new Jn("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?R0:w0,o=Mw(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new Jn("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":v0).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new Jn("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new Jn("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function ZV(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function rd(e){Nw(e,"owned path"),await Lo(e),await jV(e,{recursive:!0}),await Lo(e)}async function Lo(e){let n=VV(e);while(!0){try{if((await $V(n)).isSymbolicLink())throw new Jn("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof Jn)throw o;if(!rt(o,"ENOENT"))throw o}let r=BV(n);if(r===n)break;n=r}}async function Ua(e){await Lo(e)}function Fi(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?R0:w0,o=r.resolve(Mw(e,n)),i=r.resolve(Mw(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":v0}`)&&a!==".."&&!r.isAbsolute(a)}function Mw(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function rt(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var WV="holycodex",zV="active.json",KV="preparing.json",JV="conflicted.json",GV="install.toml",YV,Jn;var $a=S(()=>{dt();YV=Rn;Jn=class Jn extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as T0,open as XV,readFile as O0,rename as QV,unlink as eW,writeFile as tW}from"fs/promises";import{dirname as nW}from"path";async function C0(e){let t;try{t=await XV(e,"r"),await t.sync()}catch(n){if(!E0(n))throw n}finally{await t?.close().catch(()=>{return})}}async function oW(e){await C0(e).catch((t)=>{if(!E0(t))throw t})}async function Ha(e,t){await Gn(e,`${Pn(t)}
36
- `)}async function Gn(e,t){let n=nW(e);await rd(n),await Lo(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await tW(r,t,{encoding:"utf8",mode:384}),await C0(r),await QV(r,e),await oW(n)}catch(o){throw await eW(r).catch(()=>{return}),o}}async function iW(e,t){let n=await T0(e);if(!n.isFile()||n.isSymbolicLink())throw new ja("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await O0(e,"utf8"))}catch(i){throw new ja("state_corrupt","A persisted file is not valid JSON.",i)}let o=Fe(t,r);if(o===void 0)throw new ja("state_corrupt","A persisted file failed schema validation.");return o}async function ot(e){try{let t=await T0(e);if(!t.isFile()||t.isSymbolicLink())throw new ja("state_corrupt","A persisted file is not a regular file.");return await O0(e,"utf8")}catch(t){if(rt(t,"ENOENT"))return;throw t}}async function Fw(e,t){try{return await iW(e,t)}catch(n){if(rt(n,"ENOENT"))return;throw n}}function E0(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return rW.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var rW,ja;var Rc=S(()=>{dt();$a();qa();rW=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);ja=class ja extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as aW}from"fs/promises";import{dirname as sW,resolve as cW}from"path";import{fileURLToPath as lW}from"url";async function k0(e=Ba){let t=JSON.parse(await aW(e,"utf8")),n=Fe(uW,t);if(n===void 0)throw new Do("manifest_invalid","The public package manifest is invalid.");return n}async function Tc(e=Ba){let t=(await k0(e)).version,n=Fe(fc,t);if(n===void 0)throw new Do("manifest_invalid","The public package manifest version is invalid.");return n}async function I0(e=Ba){let t=await Tc(e),n=Fe(pc,t);if(n===void 0)throw new Do("manifest_invalid","The public package manifest must use a canonical stable release version.");return n}async function dW(e=Ba){let n=(await Tc(e)).split("-",1)[0],r=Fe($b,n);if(r===void 0)throw new Do("manifest_invalid","The public package manifest must use a canonical release base version.");return r}async function od(e=Ba){return await Tc(e)}async function Lw(e,t,n=Ba){let r=await k0(n),o=await I0(n),i=pW(e,o);if(!t)await Ha(n,{...r,version:i});return{previous:o,next:i}}function pW(e,t){if(e!=="patch"&&e!=="minor"){if(Fe(pc,e)===void 0)throw new Do("version_invalid","The version target is invalid.");return e}try{return jb(e,t)}catch(n){throw new Do("version_invalid",n instanceof Error?n.message:"The current version is invalid.")}}var uW,Ba,Do;var id=S(()=>{dt();Nt();qa();Rc();uW=X((e)=>_0(e)&&e.name==="holycodex"&&Fe(fc,e.version)!==void 0),Ba=cW(sW(lW(import.meta.url)),"../package.json");Do=class Do extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as fW}from"crypto";import{lstat as Dw,readFile as qw,rm as ph}from"fs/promises";import{join as Bt,relative as A0}from"path";async function mh(e,t,n=[],r="standard",o,i={}){let a=Wa(t,r,{...i,...o===void 0?{}:{windowsGitBashExecutable:o}}),s=Bt(e,"holycodex","agents",a),c=qo(t,r).map((d)=>({path:Bt(s,`${d.name}.toml`),contents:Oc(d,{...i,...o===void 0?{}:{windowsGitBashExecutable:o}})})),l=new Map(n.map((d)=>[Bt(e,d.path),d])),u=[];for(let d of c){let p=await Va(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 Qt(p)!==f.digest&&p!==d.contents)u.push(Bw(d.path,"replace",{present:!0,digest:await Qt(p)},{present:!0,digest:await Qt(d.contents)},"The managed native role file changed outside the previous HolyCodex transaction."))}return u}async function P0(e,t){let n=Bt(e,"agents"),r=Bt(e,"holycodex","agents"),o=[];for(let i of t){let a=Bt(e,i.path);if(!Fi(e,a)||!Fi(n,a)&&!Fi(r,a)&&a!==Bt(e,"config.toml"))continue;let s=await Va(a);if(s!==void 0&&await Qt(s)!==i.digest)o.push({...Bw(a,"remove",{present:!0,digest:await Qt(s)},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}return o}function qo(e,t="standard"){let n=Wr(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:Qb(o),description:t_(o),taskInstruction:e_(o),permissions:n_(o),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function Wa(e,t="standard",n={}){let r=qo(e,t).map((o)=>`${o.name}\x00${Oc(o,n)}`).join("\x00");return fW("sha256").update(r).digest("hex").slice(0,20)}function ad(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function Uw(e,t="standard"){let n=Wr(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 $w(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!K.requiresDelegation||!K.assignmentStartAndDispatchPrecedeDelegableExecution||!K.trivialWorkRequiresDelegation||!K.preparatoryAndExploratoryWorkRequiresDelegation||K.genericDirectWorkFallback||K.directExecutionExceptions!==K.rootOwnedAuthority||!K.codeReviewRequiredForImplementation||!K.codeReviewRequiredBeforeVcs||!K.externalVerificationMustBeTerminal||!K.concreteSpecialistDispatchRequired||!K.roleFamiliesAreLabelsOnly||!K.missingConcreteRouteIsBlocker||!K.normalSpawnRequiresExplicitForkTurns||K.normalSpawnForkTurns!=="none"||!K.normalSpawnUsesConcreteRegisteredAgentType||!K.assignmentContextIsTaskSpecificOnly||!K.configuredRouteModelAndEffortPreserved||K.normalProgressMessages||K.normalHeartbeatMessages||K.normalIntermediateEvidence||!K.userUpdatesUsefulOrImportantOnly||!K.routinePerToolOrSubagentNarrationForbidden||!K.routineStatusOnlyChatterForbidden||!K.fixedCadenceUserUpdatesForbidden||!K.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!K.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!K.materialUserUpdateKinds.includes("release_milestones")||!K.outOfBoundaryRequiresNewAssignment||!K.longestPracticalEventWait||!K.busyPollingForbidden||!K.statusOnlyCoordinationLoopsForbidden||!K.batchIndependentLifecycleActions||!K.releaseLeavesAfterAcceptedOutcome||K.routineWaitTool!=="collaboration.wait_agent"||!Number.isSafeInteger(K.routineWaitMaximumTimeoutMs)||K.routineWaitMaximumTimeoutMs<=0||!K.routineWaitUsesMaximumRuntimeTimeout||!K.earlySpecialistCompletionWakesWait||!K.collectiveMailboxIncludesRelevantAgents||!K.idleTimeoutRepeatsMaximumWait||!K.shortRoutineWaitsForbidden||!K.evidenceFirstConciseStructuredReports||K.specialistReportFields.length===0||K.rootLargeReadsOnlyFor.length===0||!K.stableFactsReused||!K.duplicatePolicyForbidden||!K.stableBoundedComponentScopesAreCanonical||!K.lifecycleWorkerOwnsDeterministicApi||K.registeredSpecialistAgentTypes!==Vr||K.forbiddenGenericAgentTypes!==Dm)throw Error("The Root orchestration policy is incomplete.");let n=[`You are the HolyCodex Root/session orchestrator. Never perform delegable work yourself. Root may directly perform only ${K.rootOwnedAuthority.map((r)=>hW[r]).join("; ")}, within approval and capability boundaries.`,`Start a bounded Assignment and dispatch the exact concrete registered Role.task agent_type before every delegable action, including trivial, preparatory, and exploratory work: ${K.delegableActions.map((r)=>gW[r]).join("; ")}. Registered targets: ${K.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are role-family labels only. Generic built-in agent_type values ${K.forbiddenGenericAgentTypes.join(", ")} are forbidden. If no matching route exists, return needs_root_input.`,"Before each spawn, derive the exact Role.task target and complete configuration from the active HolyCodex profile, service tier, and selected capabilities. Verify the registration resolves to its canonical role file and that the name, model, reasoning effort, service tier, full developer instructions, shell/environment policy, capability settings, and permissions match; pass every supported configuration field explicitly. Never inherit Root settings, substitute a generic route, or trust remembered route data. Recheck resumed threads. If the complete route cannot be verified and passed, stop with needs_root_input before spawning.",`For normal specialist spawns, set fork_turns: "${K.normalSpawnForkTurns}". Give each specialist a self-contained Assignment with objective, bounded scope, constraints, dependencies, acceptance criteria, and evidence needed for acceptance.`,"Use holycodex-agent semantic operations for Intent, optional Plan, and Assignment state. Do not edit TOON state. Root owns material decisions, integration acceptance, lifecycle, and completion; return out-of-boundary work to Root for a new Assignment.","Honor explicit user instructions within hard safety, authority, capability, and lifecycle boundaries. Make routine safe, reversible, in-scope choices and carry authorized work through its requested terminal state. Ask for material unresolved choices, genuine approval boundaries, user-owned credential entry, or outcome-changing blockers.","Dispatch independent non-overlapping Assignments concurrently; order dependencies and serialize writes to a shared seam. Do not request specialist progress. Accept terminal evidence and resolve material contradictions before integration.","Browser Use and Computer Use execution are specialist-owned. Root decides when interface work is needed, assigns bounded authorized work to a specialist with the capability, and accepts terminal evidence without operating the browser or computer. If the required capability is disabled or unavailable on the current surface, stop with needs_root_input and report the blocker without substituting another provider or route.","Use writing-instructions for model-facing contracts. Keep each meaning with one authoritative owner and add only the missing semantic delta for the receiver.",`Patch quality: ${Iu}`,"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.",xW,`${Mu.rule} ${yW}`,"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(SW());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.");if(t.windowsGitBashExecutable!==void 0)n.push(Hw(t.windowsGitBashExecutable));return n.join(`
37
- `)}function SW(){if(!wi.repositoryAndUserRequirementsPrecedePluginDefaults||!wi.specialistsOwnInspectionImplementationAndRenderedAcceptance||!wi.rootAcceptsTerminalVisualEvidence||!wi.sourceChangesInvalidateRenderEvidence||!wi.specialistReportsIncludeObservableRenderedEvidence||wi.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`For a user-visible frontend task, ${Ao.frontend.applicability.map(({skillId:n,appliesWhen:r})=>`${r} uses ${n}`).join("; ")}. Follow the repository stack, design system, and user requirements. Specialists inspect, implement, render, interact, and repair; Root accepts their current observable visual and interaction evidence, assigns discrepancies, and requires fresh evidence after relevant source changes. Check responsive layout, accessibility, and core interactions in proportion to the change.`}async function jw(e,t,n=[],r="standard",o,i,a=[],s={}){let c=Wa(t,r,{...s,...o===void 0?{}:{windowsGitBashExecutable:o}}),l=Bt(e,"holycodex","agents",c),u=[],d=[],p=qo(t,r).map((b)=>({path:Bt(l,`${b.name}.toml`),contents:Oc(b,{...s,...o===void 0?{}:{windowsGitBashExecutable:o}})})),f=new Map(n.map((b)=>[Bt(e,b.path),b])),m=new Map,y=new Set,g=new Set,w=new Map;for(let b of p){let I=await Va(b.path);m.set(b.path,I);let O=a.find((_)=>_.path===b.path&&_.action==="replace"&&_.key===void 0);if(O!==void 0){let _=wW(O);if(_===void 0||I===void 0||await Qt(I)!==_)throw Error(`The native role conflict changed after review; review the latest file and retry: ${b.path}`);if(w.set(b.path,_),O.decision==="keep")g.add(b.path);else y.add(b.path)}let v=f.get(b.path);if(I!==void 0&&v===void 0&&I!==b.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${b.path}`);if(I!==void 0&&v!==void 0){let _=await Qt(I);if(_!==v.digest&&I!==b.contents){let k=Bw(b.path,"replace",{present:!0,digest:_},{present:!0,digest:await Qt(b.contents)},"The managed native role file changed outside the previous HolyCodex transaction."),P=O===void 0?await i?.(k):O.decision==="keep"?"decline":"accept";if(P==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${b.path}`);if(P==="accept"||P==="decline"){let N=await Qt(I),U=await Va(b.path);if(U===void 0||await Qt(U)!==N)throw Error(`The native role conflict changed after review; review the latest file and retry: ${b.path}`);if(w.set(b.path,N),P==="accept")y.add(b.path);else g.add(b.path)}}}}let A=[];try{for(let v of p){let _=m.get(v.path),k=f.get(v.path),P=w.get(v.path);if(P!==void 0){let N=await Va(v.path);if(N===void 0||await Qt(N)!==P)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`)}if(g.has(v.path)){if(k!==void 0)u.push(v.path),A.push(k);continue}if(_!==void 0&&k!==void 0){if(await Qt(_)!==k.digest&&_!==v.contents&&!y.has(v.path)){u.push(v.path),A.push({path:A0(e,v.path).replaceAll("\\","/"),digest:k.digest});continue}}if(_===void 0||_!==v.contents)await Gn(v.path,v.contents),d.push({path:v.path,previous:_,installedDigest:await Qt(v.contents)});A.push({path:A0(e,v.path).replaceAll("\\","/"),digest:await Qt(v.contents)})}let b=Bt(e,"agents","root.toml"),I=await Va(b),O=await M0(b);if(O==="preserved")u.push(b);if(O==="removed"&&I!==void 0)d.push({path:b,previous:I,installedDigest:void 0});for(let v of n){let _=Bt(e,v.path);if(!p.some((k)=>k.path===_))A.push(v)}return{managed_artifacts:A,preserved:u,rollback:d}}catch(b){throw await hh(d).catch(()=>{return}),b}}async function hh(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await Va(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await Qt(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await ph(r.path,{force:!1}).catch((a)=>{if(!rt(a,"ENOENT"))throw a}),t.push(r.path);else await Gn(r.path,r.previous)}return{removed:t,preserved:n}}async function gh(e,t,n=new Set){let r=[],o=[],i=Bt(e,"agents"),a=Bt(e,"holycodex","agents");for(let l of t){let u=Bt(e,l.path);if(!Fi(e,u)||!Fi(i,u)&&!Fi(a,u)&&u!==Bt(e,"config.toml")){o.push(u);continue}try{await Lo(u);let d=await Dw(u);if(d.isSymbolicLink()||!d.isFile()){o.push(u);continue}let p=await qw(u);if(await Qt(p)!==l.digest){if(n.has(u)){await ph(u,{force:!1}),r.push(u);continue}o.push(u);continue}await ph(u,{force:!1}),r.push(u)}catch(d){if(!rt(d,"ENOENT"))o.push(u)}}let s=Bt(e,"agents","root.toml"),c=await M0(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);return{removed:r,preserved:o}}function Oc(e,t={}){let n=[mW,e.taskInstruction,...e.permissions.filesystem==="workspace-write"||e.name==="Reviewer.code"||e.name==="Reviewer.artifact"?[`Patch quality: ${Iu}`]:[],...t.windowsGitBashExecutable===void 0?[]:[Hw(t.windowsGitBashExecutable)],...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(fh(e))}`,'approval_policy = "never"','web_search = "live"',`developer_instructions = ${JSON.stringify(n)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent = false","",...fh(e)==="workspace-write"?["[sandbox_workspace_write]","network_access = true"]:[],""].join(`
39
- `)}function Hw(e){if(e===void 0||e.trim().length===0)throw Error("Git Bash executable is required.");return`On Windows, run all shell actions in the verified Git for Windows Bash environment at ${JSON.stringify(e)}. If that environment is unavailable or inactive, stop and report the mismatch; never fall back to another shell.`}function fh(e){return e.permissions.filesystem}function yh(e,t){return t.sandbox_mode===fh(e)&&t.default_permissions===void 0&&(fh(e)==="workspace-write"?Ne(t,"sandbox_workspace_write.network_access")===!0:Ne(t,"sandbox_workspace_write.network_access")===void 0)}function bW(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 Cc(e){return _W.has(e)}async function M0(e){try{await Lo(e);let t=await Dw(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await qw(e,"utf8");if(!Cc(n))return"preserved";return await ph(e,{force:!1}),"removed"}catch(t){if(rt(t,"ENOENT"))return"absent";throw t}}async function Va(e){try{await Lo(e);let t=await Dw(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await qw(e))}catch(t){if(rt(t,"ENOENT"))return;throw t}}async function Qt(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 Bw(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 wW(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var mW,hW,gW,yW="After implementation, reach a Reviewer.code fixed point, run Worker.validation, then integrate and perform VCS writes. Review repairs invalidate earlier validation.",xW,_W;var xh=S(()=>{_c();dt();$a();Rc();mW=[`Execute one bounded Assignment through its acceptance criteria. ${Mu.rule} Return out-of-boundary work or material decisions 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.`,`Return only one compact, evidence-first terminal outcome (${K.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${K.specialistReportFields.join(", ")}.`].join(" "),hW={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"},gW={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"},xW=`Wait for specialist results with ${K.routineWaitTool} at timeout_ms=${K.routineWaitMaximumTimeoutMs}; repeat after an idle timeout. Do not poll status or send routine progress messages. Release specialist leaves after accepting their terminal outcomes.`;_W=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)=>bW(e,t,n))))});import{access as vW,readFile as RW,readdir as TW}from"fs/promises";import{join as Vw}from"path";class za{adapter;observedIdentities={};constructor(e){if("run"in e){let t=ch({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await hw({environment:e}),n=ch({executable:t.path,environment:mw(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new za(n)}async list(){try{return await this.adapter.list()}catch(e){throw sd("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw sd("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw sd("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw sd("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw sd("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=Gr(t,i),s=fr(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 Sh{codexHome;observedIdentities={};constructor(e){this.codexHome=e}async status(e){let t=await RW(Vw(this.codexHome,"config.toml"),"utf8"),n=globalThis.Bun;if(!n?.TOML?.parse)throw Error("A TOML parser is unavailable.");let r=Fe(Ma,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=Wb(c),d=(l.length>0?l:[c]).flatMap((g)=>{if(i===void 0||!Object.hasOwn(i,g))return[];let w=i?.[g],A=typeof w==="object"&&w!==null&&!Array.isArray(w)?w.enabled:void 0;return[{id:g,enabled:A}]});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 OW(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 OW(e,t){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let o=Vw(e,"plugins","cache",n.slice(r+1),n.slice(0,r));try{let i=await TW(o,{withFileTypes:!0,encoding:"utf8"});for(let a of i){if(!a.isDirectory())continue;try{return await vW(Vw(o,a.name,".codex-plugin","plugin.json")),!0}catch(s){if(!N0(s))throw s}}}catch(i){if(N0(i))continue;throw i}}return!1}function N0(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function sd(e,t,n){if(t instanceof Yr)return t;let o=(t instanceof Ee?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 Yr(i,a,t,n===void 0?{}:{plugin_id:n})}var Yr;var cd=S(()=>{_c();dt();qa();Yr=class Yr 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 Kw(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=EW(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=Ww(o.slice(1,-1).trim()),CW(t,n);continue}let i=q0(o);if(i<1)throw Error("TOML assignment is invalid.");let a=Ww(o.slice(0,i).trim()),s=bh(o.slice(i+1).trim());D0(t,[...n,...a],s)}return t}function Jw(e){let t=[];return L0(e,[],t),t.join(`
41
- `)}function L0(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(Gw(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(F0).join(".")}]`)}for(let[i,a]of r)n.push(`${F0(i)} = ${U0(a)}`);for(let[i,a]of o)L0(a,[...t,i],n)}function bh(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?[]:zw(t,",").map((n)=>bh(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 zw(t,",")){let o=q0(r);if(o<1)throw Error("TOML inline table entry is invalid.");D0(n,Ww(r.slice(0,o).trim()),bh(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 Ww(e){let t=zw(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("'")?bh(n):n)}function D0(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(Gw(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 CW(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(Gw(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function zw(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 q0(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 EW(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 Gw(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function F0(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function U0(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(U0).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{execFile as kW}from"child_process";import{access as IW,readFile as AW,realpath as PW}from"fs/promises";import{posix as MW,win32 as NW}from"path";import{promisify as FW}from"util";function Za(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:kc,run:async(t,n)=>{try{let r=await LW(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 Ga(e){let t=Fn(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(ld(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(ld(t,"bunx")||ld(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(ld(t,"npx")||t.endsWith("/npx-cli.js")||ld(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function Xa(e,t){if(e.platform!=="win32")return{status:"not_applicable"};let n=await $0(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 pe("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 $0(e);if(o===void 0)throw new pe("git_bash_unavailable",`Git for Windows was installed, but ${Ja} could not be verified. Repair Git for Windows and retry.`);return{status:"healthy",path:o,installed:!0}}async function _h(e,t,n){let r=await Zw(e);if(r!==void 0){let o=Ga(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},i=n?.ownership==="holycodex"&&typeof n.identity==="string"&&await Ic(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(Ec(e))return $W(e,t,n);return UW(e,t,n)}async function Yw(e,t){let n=await Zw(e);if(n!==void 0){let i=Ga(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&await Ic(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=Ec(e)?{launcher:"bunx",family:"bun",executable:"bun"}:Ga(e.environment);if(r===void 0)throw new pe("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let o=r.family==="bun"&&Ec(e)?await ud(e):await dd(e,r);if(o===void 0)throw new pe("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:o.version,executable:o.executable,ownership:Xw(t,r,o),identity:o.identity}}async function Zw(e){let t=await V0(e.environment,e.platform,e.files??kc);if(t===void 0)return;let n=await e.run(t,["--version"]),r=n.exitCode===0?Ya(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}}async function DW(e){if(await Zw(e)!==void 0)return;if(Ec(e)){await qW(e);return}let t=Ga(e.environment);if(t===void 0)throw new pe("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 pe("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})}async function qW(e){let t=e.files??kc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if(KW(n.stderr))return;throw new pe("context7_unavailable","Bun's managed global installation could not be located before managed changes.",{stderr:n.stderr.slice(0,512)})}let r=en(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 pe("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:Ka(g)})}let l;try{await t.access(a)}catch(g){if(zW(g))return;throw new pe("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:Ka(g)})}try{l=await t.readText(s)}catch(g){throw new pe("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:Ka(g)})}let u;try{u=JSON.parse(l)}catch(g){throw new pe("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:Ka(g)})}if(typeof u.version!=="string"||Ya(u.version)!==u.version)throw new pe("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let d=W0(u);if(d===void 0)throw new pe("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 pe("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:Ka(g)})}if(!pd(f,a,e.platform)||!Fn(m).startsWith(`${Fn(f)}/`))throw new pe("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 pe("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:Ka(g)})}let y=await e.run(c,["--version"]);if(y.exitCode!==0||Ya(y.stdout)!==u.version)throw new pe("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:y.stderr.slice(0,512)})}async function UW(e,t,n){let r=Ga(e.environment);if(r===void 0)throw new pe("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await dd(e,r),i=await z0(e,r);if(i===void 0)throw new pe("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=Xw(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=H0(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new pe("context7_install_failed",`${r.family} could not install ${_r}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new pe("context7_unavailable",`${_r} is not owned by the ${r.family} global installation.`);let s=await dd(e,r);if(s===void 0)throw new pe("context7_verification_failed",`${_r} could not be verified in the ${r.family} global installation.`);if(s.version!==i)throw new pe("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 $W(e,t,n){let r={launcher:"bunx",family:"bun",executable:"bun"},o=await ud(e),i=await z0(e,r);if(i===void 0)throw new pe("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=Xw(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=await e.run(e.processPath,["add","-g",_r]);if(l.exitCode!==0)throw new pe("context7_install_failed",`Bun could not install ${_r} in its global installation.`,{stderr:l.stderr.slice(0,512)})}else if(o===void 0)throw new pe("context7_unavailable",`${_r} is not present in Bun's exact global installation.`);let s=await ud(e);if(s===void 0)throw new pe("context7_verification_failed",`${_r} could not be verified in Bun's exact global installation.`);if(s.version!==i)throw new pe("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 ud(e){let t=e.files??kc,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=en(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"||Ya(a.version)!==a.version)return;let s=W0(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(!pd(u,i,e.platform)||!Fn(d).startsWith(`${Fn(u)}/`))return;let f=await e.run(l,["--version"]);if(f.exitCode!==0||Ya(f.stdout)!==a.version)return;return{version:a.version,executable:l,identity:await B0({launcher:"bunx",family:"bun",executable:"bun"},u,d,p,a)}}function Ec(e){let t=en(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function Xw(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(!Qw(r)||r!==n.identity)return"user";return"holycodex"}async function fd(e,t){if(Ec(e))return jW(e,t);return HW(e,t)}async function jW(e,t){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n;try{n=await ud(e)}catch{return!1}if(n===void 0||n.version!==t.version||!await Ic(e,n.executable,t.executable)||!Qw(t.identity)||n.identity!==t.identity)return!1;let r=await e.run(e.processPath,["remove","-g","ctx7"]);if(r.exitCode!==0)throw new pe("context7_remove_failed","Bun could not remove ctx7.",{stderr:r.stderr.slice(0,512)});if(await ud(e)!==void 0)throw new pe("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0}async function HW(e,t){if(t?.ownership!=="holycodex")return!1;let n=Ga(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await dd(e,n)}catch(a){if(a instanceof pe&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!await Ic(e,r.executable,t.executable)||!Qw(t.identity)||r.identity!==t.identity)return!1;let o=BW(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new pe("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await dd(e,n)!==void 0)throw new pe("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof pe&&a.code==="context7_remove_failed")throw a;throw new pe("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function H0(e){switch(e){case"bun":return{executable:"bun",args:["add","-g",_r]};case"npm":return{executable:"npm",args:["install","--global",_r]};case"pnpm":return{executable:"pnpm",args:["add","--global",_r]}}}function BW(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 $0(e){if(await j0(e.run,Ja,e.platform))return Ja;for(let t of(e.environment.PATH??"").split(";")){if(t.length===0)continue;let n=en(e.platform).join(t,"bash.exe");if(await j0(e.run,n,e.platform))return n}return}async function j0(e,t,n){let r=GW(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 dd(e,t){let n=e.files??kc,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"?en(e.platform).join(o,"node_modules","ctx7"):t.family==="pnpm"?await JW(e,t):en(e.platform).join(en(e.platform).dirname(o),"install","global","node_modules","ctx7");if(i===void 0)return;let a;try{a=JSON.parse(await n.readText(en(e.platform).join(i,"package.json")))}catch{return}if(typeof a.version!=="string")return;let s=typeof a.bin==="string"?a.bin:ev(a.bin)&&typeof a.bin.ctx7==="string"?a.bin.ctx7:void 0;if(s===void 0)return;let c=en(e.platform).resolve(i,s),l,u;try{if(await n.access(c),l=await n.realpath(i),u=await n.realpath(c),!Fn(u).startsWith(`${Fn(l)}/`))return}catch{return}let d=VW(o,t.family,e.platform),p;try{await n.access(d),p=await n.realpath(d)}catch{return}let f=await V0(e.environment,e.platform,n);if(f!==void 0&&!pd(await WW(n,f),p,e.platform))throw new pe("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||Ya(m.stdout)!==a.version)return;return{version:a.version,executable:d,identity:await B0(t,l,u,p,a)}}async function B0(e,t,n,r,o){return await yr("context7-installation",[gr({manager:e.family,package_root:Fn(t),package_executable:Fn(n),shim:Fn(r),package:o})])}function Qw(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function V0(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=en(t).join(i,a);try{return await n.access(s),s}catch{}}}return}function VW(e,t,n){if(n==="win32")return en(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?en(n).join(e,"bin","ctx7"):en(n).join(e,"ctx7")}async function WW(e,t){try{return await e.realpath(t)}catch{return t}}function Ya(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function W0(e){return typeof e.bin==="string"?e.bin:ev(e.bin)&&typeof e.bin.ctx7==="string"?e.bin.ctx7:void 0}function Ka(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function zW(e){return ev(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(Ka(e))}function KW(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 JW(e,t){let n=await e.run(t.executable,["root","--global"]),r=n.stdout.trim();return n.exitCode===0&&r.length>0?en(e.platform).join(r,"ctx7"):void 0}async function z0(e,t){let n=await e.run(t.family==="bun"&&Ec(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return Ya(n.stdout)}function GW(e,t){let n=en(t),r=n.dirname(e),o=Fn(r).endsWith("/usr/bin")?n.resolve(r,"..",".."):n.resolve(r,"..");return n.resolve(o,"cmd","git.exe")}function ld(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function pd(e,t,n){let r=en(n),o=r.resolve(e),i=r.resolve(t);return n==="win32"?Fn(o)===Fn(i):o===i}async function Ic(e,t,n){if(pd(t,n,e.platform))return!0;let r=e.files??kc;try{let[o,i]=await Promise.all([r.realpath(t),r.realpath(n)]);return pd(o,i,e.platform)}catch{return!1}}function en(e){return e==="win32"?NW:MW}function Fn(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function ev(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Ja="C:\\Program Files\\Git\\bin\\bash.exe",_r="ctx7@latest",LW,kc,pe;var wh=S(()=>{dt();LW=FW(kW),kc={access:IW,readText:(e)=>AW(e,"utf8"),realpath:PW};pe=class pe extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as vh,rmdir as nv}from"fs/promises";import{join as YW}from"path";async function rv(e={},t=process.env){let n=br(e,t),r={};try{await Ua(n.codexHome),await Ua(n.stateRoot),r.paths=es({state_root:n.stateRoot})}catch(u){r.paths=Et(["path_symlink"],{error:Ln(u)})}let o=await Li(n).catch((u)=>{r.configuration=Et(["state_corrupt"],{error:Ln(u)});return}),[i,a]=await Promise.all([wr(n.preparingRecord,o).catch((u)=>{r.transaction=Et(["state_corrupt"],{path:n.preparingRecord,error:Ln(u)});return}),wr(n.conflictedRecord,o).catch((u)=>{r.transaction=Et(["state_corrupt"],{path:n.conflictedRecord,error:Ln(u)});return})]);if(r.transaction?.status!=="failed"&&(i!==void 0||a!==void 0)){let u=Oh(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=Et(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=Et(["configuration_missing"]);else if(await Nc(o))r.configuration=es({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=Et(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await oz(n,o),r.native_roles=await iz(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])=>d.selected&&d.status!=="healthy");if(u)r.capabilities=Et(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status})}let s=e.runtime??Za(t);try{let u=await Xa(s,!1);r.git_bash=u.status==="missing"?Et(["git_bash_missing"]):es(u.status==="healthy"?{path:u.path}:{})}catch(u){r.git_bash=Et(["git_bash_unavailable"],{error:Ln(u)})}try{let u=await Yw(s,o?.tooling?.context7);r.context7=es({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:Ln(u)}}}try{let u=await ot(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&Cc(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=Et(["native_role_invalid"],{error:Ln(u)})}let c=e.officialPluginManager;if(o&&c?.status){let u=[...new Set([an,...mc({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??[]])];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?es({status:d,observed_identities:f}):Et(["native_plugin_disagreement"],{missing:p,status:d,observed_identities:f})}catch(d){r.native_plugins=Et(["native_plugin_status_failed"],{error:Ln(d)})}}else r.native_plugins=Et(["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 ov(e={},t=process.env){let n=br(e,t);await Ua(n.codexHome),await Ua(n.stateRoot);let r=await Li(n);if(r!==void 0&&!await Nc(r))throw new E("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([wr(n.preparingRecord,r),wr(n.conflictedRecord,r)]);sv(r,o,i);let a=G0(r,o,i);if(a===void 0)return[];let s=Sn(await ot(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await Sr(s,a.managed_config,{schema:a.managed_config.schema,installId:a.managed_config.installId});for(let u of[...l.preservedKeys,...l.unresolvedKeys])c.push({path:n.configFile,key:u,action:"remove"})}if(a.plugin_config!==void 0){let l=await Pc(s,a.plugin_config);for(let u of l.preserved)c.push({path:n.configFile,key:u==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"})}if(a.provider_config!==void 0){let l=await Mc(s,a.provider_config,new Set(iv(a)));for(let u of l.preserved)c.push({path:n.configFile,key:`plugins."${u}"`,action:"remove"})}return c.push(...await P0(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[Qa(l),l])).values()]}async function md(e={},t=process.env){let n=br(e,t);await Ua(n.codexHome),await Ua(n.stateRoot);let r=await Li(n);if(r&&!await Nc(r))throw new E("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([wr(n.preparingRecord,r),wr(n.conflictedRecord,r)]);sv(r,o,i);let a=G0(r,o,i);tv(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(iv(a)),c=[],l=[],u=[],d=!1;if(a===void 0)return tv(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let p=await ov(e,t),f=await rz(e,p),m=await ot(n.configFile),y=Sn(m),g=a?.managed_config;if(g){let O=await Sr(y,g,{schema:g.schema,installId:g.installId});if(O.preservedKeys.length>0||O.unresolvedKeys.length>0){let _=[...O.preservedKeys,...O.unresolvedKeys].map((k)=>({path:n.configFile,key:k,action:"remove"}));for(let k of _)if(f.has(Qa(k)))y=Jr(y,k.key)}}if(a?.plugin_config){let O=await Pc(y,a.plugin_config);if(O.preserved.length>0){let v=O.preserved.map((_)=>({path:n.configFile,key:_==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let _ of O.preserved){let k=v.find((P)=>P.key===(_==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(k===void 0||!f.has(Qa(k)))continue;y=Jr(y,_==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let O=await Mc(y,a.provider_config,s);if(O.preserved.length>0){let v=O.preserved.map((_)=>({path:n.configFile,key:`plugins."${_}"`,action:"remove"}));for(let _ of O.preserved){let k=v.find((P)=>P.key===`plugins."${_}"`);if(k===void 0||!f.has(Qa(k)))continue;y=Jr(y,`plugins."${_}"`)}}}let w;try{w=e.officialPluginManager??await za.discover({...t,CODEX_HOME:n.codexHome})}catch(O){throw new E("capability_denied","Native Codex plugin removal is unavailable.",O,{recovery:"Install or expose Codex, then retry."})}if(w===void 0||!w.remove||!w.list)throw new E("capability_denied","Native Codex plugin removal and readback are unavailable.");let A,b=a;try{let O=y,v=g;if(v){let _=await Sr(O,v,{schema:v.schema,installId:v.installId}),k=[..._.preservedKeys,..._.unresolvedKeys];if(k.filter((N)=>!f.has(Qa({path:n.configFile,key:N,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Zr(n,a??Ac()),{removed:c,preserved:l,reasons:u};if(O=_.document,k.length>0){let N=new Set(k);v={..._.state,managed:Object.fromEntries(Object.entries(_.state.managed).filter(([U])=>!N.has(U)))}}else v=_.state}if(a?.plugin_config){let _=await Pc(O,a.plugin_config,{allowBeforeState:!0});if(_.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Zr(n,a),{removed:c,preserved:l,reasons:u};O=_.document}if(a?.provider_config){let _=await Mc(O,a.provider_config,s,{allowBeforeState:!0});if(_.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Zr(n,a),{removed:c,preserved:l,reasons:u};O=_.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)A=v===void 0?{document:O}:{document:O,state:v};if(A!==void 0){if(Object.keys(A.document).length===0&&m===void 0)await vh(n.configFile,{force:!1});else await Gn(n.configFile,Ch(A.document));b={...a,managed_config:A.state},await Zr(n,b),d=!0}}catch(O){if(O instanceof E)throw await Zr(n,b??Ac()),O;return l.push(n.configFile),u.push("managed_config_write_failed"),await Zr(n,b??Ac()),{removed:c,preserved:l,reasons:u}}let I=await gh(n.codexHome,a?.managed_artifacts??[],new Set(p.filter((O)=>O.key===void 0&&f.has(Qa(O))).map((O)=>O.path)));if(c.push(...I.removed),l.push(...I.preserved),I.preserved.length>0)u.push("managed_artifact_changed");c.push(...await XW(n.roleRoot,a?.managed_artifacts??[]));for(let O of s)try{let v=await w.list(),_=az(v,O);if(_?.entry.installed!==!0)continue;let k=_.entry.pluginId;await w.remove(k);let P=await w.list();if(Gr(P,O)?.entry?.installed===!0||[...P.installed,...P.available].some((ke)=>ke.pluginId===O&&ke.installed))throw new E("capability_denied",`Codex still reports ${O} after removal.`);c.push(O)}catch(v){throw u.push("native_plugin_remove_failed"),await Zr(n,b??Ac()),new E("capability_denied",`Codex native plugin removal did not converge for ${O}: ${Ln(v)}`,v)}try{if(await fd(e.runtime??Za(t),a.tooling?.context7))c.push("ctx7")}catch(O){throw u.push("context7_remove_failed"),await Zr(n,b??Ac()),new E("capability_denied",`Context7 removal did not converge: ${Ln(O)}`,O)}if(r)try{await vh(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(O){if(!rt(O,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await Zr(n,a??r),{removed:c,preserved:l,reasons:u}}if(l.length===0)try{await vh(n.installOptions,{force:!1}),c.push(n.installOptions)}catch(O){if(!rt(O,"ENOENT"))l.push(n.installOptions),u.push("state_remove_failed"),await Zr(n,a??r??Ac())}if(l.length===0)for(let[O,v]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0||d]]){if(!v)continue;try{await sz(O),c.push(O)}catch{l.push(O),u.push("state_remove_failed")}}if(l.length===0)try{await nv(n.roleRoot),c.push(n.roleRoot)}catch(O){if(!rt(O,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await nv(n.stateRoot),c.push(n.stateRoot)}catch(O){if(rt(O,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return tv(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 XW(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=YW(e,o);try{await nv(i),r.push(i)}catch(a){if(!rt(a,"ENOENT")&&!rt(a,"ENOTEMPTY")&&!rt(a,"EEXIST"))throw a}}return r}async function QW(e={},t=process.env,n={}){let r=br(e,t),o=await Li(r),[i,a]=await Promise.all([wr(r.preparingRecord,o),wr(r.conflictedRecord,o)]);if(o!==void 0&&!await Nc(o))throw new E("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});av(o,i,a);let s=J0(o,i,a),c=s??o;if(c===void 0)throw new E("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l=await Th(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:ez(c)}:tz(hd(l)),d=n.options===void 0?u:sn(n.options),p={profile:d.profile??u.profile,tier:d.tier??u.tier,optional:{...u.optional,...d.optional},officialPlugins:d.officialPlugins??u.officialPlugins},f=!nz(p,u),m;try{m=await od()}catch(_){throw new E("upgrade_failed","The running HolyCodex version is unavailable.",_)}let y=m.split("-",1)[0]===c.version.split("-",1)[0]&&m.includes("-dev.")!==c.version.includes("-dev."),g=y?0:Eu(m,c.version);if(g<0)throw new E("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 w=c.managed_config?.managed["features.context_management"]!==void 0,A=c.managed_config?.managed[Ci[0]]!==void 0,b=[];if(n.dryRun===!0){let _=Sn(await ot(r.configFile));if(c.managed_config!==void 0)for(let P of Object.keys(c.managed_config.managed)){if(!Na(P))continue;if((await La(_,c.managed_config,P)).status!=="unchanged")b.push({path:r.configFile,key:P,action:"replace"})}if(c.plugin_config!==void 0){let P=await Pc(_,c.plugin_config);for(let N of P.preserved){let U=N==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";b.push({path:r.configFile,key:U,action:"replace"})}}if(c.provider_config!==void 0){let P=await Mc(_,c.provider_config,new Set(iv(c)));for(let N of P.preserved)b.push({path:r.configFile,key:`plugins."${N}"`,action:"replace"})}let k=await mh(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 P of k)b.push(P)}let I=c.tooling===void 0,O=c.tooling===void 0?["record missing"]:[];try{let _=e.runtime??Za(t);if((await Xa(_,!1)).status==="missing")O.push("Git Bash unavailable");let P;try{P=await Yw(_,c.tooling?.context7)}catch(U){if(c.tooling?.context7!==void 0||!cz(U))throw U}let N=c.tooling?.context7;if(N?.manager!==P?.manager)O.push("Context7 manager changed");if(N?.version!==P?.version)O.push("Context7 version changed");if(N?.executable===void 0?P?.executable!==void 0:P?.executable===void 0||!await Ic(_,N.executable,P.executable))O.push("Context7 executable changed");I||=O.length>0}catch(_){I=!0;let k=typeof _==="object"&&_!==null&&"code"in _&&typeof _.code==="string"?_.code:_ instanceof Error?_.name:"inspection failed";O.push(`inspection failed (${k})`)}let v=[...g>0||y?["version"]:[],...f?["installation options"]:[],...l===void 0?["installation options migration"]:[],...w?["context-management configuration migration"]:[],...A?["auto-compaction configuration cleanup"]:[],...g>0||w||A?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...I?[`shared tooling reconciliation (${O.join(", ")})`]:[],...b.map((_)=>`conflict: ${_.path}${_.key===void 0?"":` (${_.key})`} -> ${_.action}`)];if(v.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:m,changes:[],record:o,preserved:[],warnings:[],conflicts:b};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:m,changes:v,record:o,preserved:[],warnings:[],conflicts:b};try{let _=await ts(p,e,t);return{status:"upgraded",from_version:c.version,to_version:m,changes:v,record:_.record,preserved:_.preserved,warnings:_.warnings}}catch(_){if(_ instanceof E)throw _;throw new E("upgrade_failed",`HolyCodex upgrade failed: ${Ln(_)}`,_)}}function ez(e){let t=new Set(mc(e.optional_selections));return(e.official_plugins??[]).filter((n)=>!K0(n)&&!t.has(n))}function tz(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!K0(t))}}}function K0(e){let t=e.slice(0,e.lastIndexOf("@"));return ZW.has(t)}function nz(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 rz(e,t){let n=new Set;for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(Qa(r));continue}if(o==="decline")continue;throw new E("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 Qa(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function oz(e,t){if(!t.managed_config)return Et(["incomplete_install_state"]);try{let n=Sn(await ot(e.configFile)),r=yd(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:Ct.frontend,security:Ct.security,...t.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:t.tooling.git_bash.path}:{}}),o=[];for(let i of Object.keys(r))if((await La(n,t.managed_config,i)).status!=="unchanged")o.push(i);return o.length===0?es({managed_keys:Object.keys(r).length}):Et(["changed_holycodex_config"],{keys:o})}catch(n){return Et(["config_unreadable"],{error:Ln(n)})}}async function iz(e,t,n,r,o={browserUse:!1,computerUse:!1}){try{let i=Sn(await ot(e.configFile)),a=[],s=Wa(t,n,{...o,...r===void 0?{}:{windowsGitBashExecutable:r}});for(let l of qo(t,n)){let u=Ne(i,`agents."${l.name}".config_file`),d=Fa(e.configFile,ad(l.name,s)).replaceAll("\\","/");if(typeof u!=="string"||Fa(e.configFile,u).replaceAll("\\","/")!==d){a.push(`${l.name}:registration`);continue}let p=await ot(d);if(p===void 0){a.push(`${l.name}:missing`);continue}if(p!==Oc(l,{...o,...r===void 0?{}:{windowsGitBashExecutable:r}})){a.push(`${l.name}:changed`);continue}let f=Sn(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")||!yh(l,f)||f.approval_policy!=="never"||f.web_search!==(l.permissions.network?"live":"disabled")||Ne(f,"agents.enabled")!==!1||Ne(f,"features.multi_agent")!==!1||Object.keys(f.features??{}).some((m)=>m!=="multi_agent"))a.push(`${l.name}:malformed`)}let c=await ot(`${e.codexHome}/agents/root.toml`);if(c!==void 0&&Cc(c))a.push("root:stale");return a.length===0?es({role_root:e.roleRoot,agent_types:qo(t,n).map((l)=>l.name)}):Et(["native_role_disagreement"],{roles:a})}catch(i){return Et(["native_role_invalid"],{error:Ln(i)})}}async function Zr(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(Fe(Mi,n)!==void 0)await Ha(e.conflictedRecord,xn(n))}function J0(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||gd(r,e)))}function G0(e,t,n){return J0(e,t,n)??e}function Ac(){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)];let t=(e?.plugin_snapshot??[]).filter((o)=>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"?[an]:[],r=(e?.provider_config??[]).filter((o)=>o.before.presence==="absent"&&o.after.presence==="present").map((o)=>o.plugin_id);return[...new Set([...t,...n,...r])]}function az(e,t){let n=Gr(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 es(e){return{status:"healthy",reasons:[],details:e}}function Et(e,t={}){return{status:"failed",reasons:e,details:t}}async function sz(e){await vh(e,{force:!1}).catch((t)=>{if(!rt(t,"ENOENT"))throw t})}function cz(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function Ln(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function tv(e,t){try{e.onProgress?.(t)}catch{}}var ZW;var Rh=S(()=>{_c();dt();xd();Xu();id();xh();cd();$a();qa();Rc();wh();ZW=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{rm as fv}from"fs/promises";function sn(e){let t=Fe(uh,e);if(t===void 0)throw new E("install_failed","The installation options are invalid.");return t}async function Th(e){let t=await ot(e.installOptions);return rF(t,e.installOptions)}function rF(e,t){if(e===void 0)return;let n;try{n=Kw(e)}catch(i){throw new E("state_corrupt","The HolyCodex install options are not valid TOML.",i,{path:t})}let r=Fe(nd,n);if(r!==void 0)return r;let o=Fe(g0,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 E("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}async function oF(e,t){if(Fe(nd,t)===void 0)throw new E("state_corrupt","The HolyCodex install options are invalid.");await Gn(e.installOptions,Jw(t))}function hd(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]}}async function iF(e={},t=process.env){let n=br(e,t),r=await Th(n);if(r!==void 0)return hd(r);let o=await Li(n);if(o===void 0)return{};return{profile:o.profile,tier:o.tier,optional:o.optional_selections,officialPlugins:mv(o)}}function aF(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)]}}function gd(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function Oh(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})=>gd(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?o&&!i?"incompatible":"orphaned":gd(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 av(e,t,n){let r=Oh(e,t,n);if(r.filter((i)=>i.relation==="stale"||i.relation==="incompatible").length>0)throw new E("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,sF(r));return r}function sv(e,t,n){let r=Oh(e,t,n);if(e===void 0&&r.some((o)=>o.relation==="incompatible"))throw new E("state_corrupt","HolyCodex has ambiguous transaction state and cannot recover safely.",void 0,sF(r));return r}function sF(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 ts(e={},t={},n=process.env){if(Fe(td,e)===void 0)throw new E("install_failed","The installation options are invalid.");let r=br(t,n),o=await ot(r.installOptions),i=await ot(r.activeRecord),a=rF(o,r.installOptions),s=a===void 0?void 0:hd(a);vr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let c=await Li(r);if(c!==void 0&&!await Nc(c))throw new E("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:r.activeRecord});let l=await wr(r.preparingRecord,c),u=await wr(r.conflictedRecord,c);av(c,l,u);let d=[u,l].find((L)=>L!==void 0&&(c===void 0||gd(L,c)));if(d!==void 0){await Promise.resolve().then(() => Rh());let Z=await md(t,n);if(Z.preserved.length>0||Z.reasons.length>0)throw new E("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:Z.preserved.join(","),reasons:Z.reasons.join(",")});return await ts({profile:e.profile??s?.profile??d.profile,tier:e.tier??s?.tier??d.tier,optional:{browser_use:e.optional?.browser_use??s?.optional?.browser_use??d.optional_selections.browser_use,computer_use:e.optional?.computer_use??s?.optional?.computer_use??d.optional_selections.computer_use,sites:e.optional?.sites??s?.optional?.sites??d.optional_selections.sites},officialPlugins:e.officialPlugins??s?.officialPlugins??mv(d)},t,n)}let p=Tz(e.profile??s?.profile,c?.profile),f=Oz(e.tier??s?.tier,c?.tier),m=s?.optional,y=pv(m,e.optional),g=Cz(y,c?.optional_selections),w=pv(pv(c?.explicit_optional_selections,m),e.optional),A=e.officialPlugins??s?.officialPlugins??mv(c),b=t.runtime??Za(n),I=await Xa(b,!1),O=await _h(b,!1,c?.tooling?.context7).then(()=>!0,()=>!1),v=I,_,k,P=[...new Set(mc(cF(g),A).map((L)=>fr(L)??L))],N;try{N=t.officialPluginManager??await za.discover({...n,CODEX_HOME:r.codexHome})}catch(L){throw new E("capability_denied","Native Codex plugin installation is unavailable.",L,{recovery:"Install or expose Codex, then retry."})}if(!N.addMarketplace||!N.add||!N.list)throw new E("install_failed","Native Codex plugin installation and verification are unavailable.");let U;try{U=await N.list()}catch(L){throw new E("capability_denied","Native Codex plugin state could not be read safely.",L)}let ke=P.filter((L)=>{if(!L.endsWith("@openai-curated"))return!1;let Z=Rr(U,L);return!(Z?.installed&&Z.enabled)});vr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let pt=c?.install_id??crypto.randomUUID().replaceAll("-",""),kt=await od(),bn=c!==void 0&&c.version!==kt&&c.owned_plugins?.includes(an)===!0?new Set([an]):new Set,Je=new Set(c?.owned_plugins??[]),St=new Set([an,...P]),Ft=[...Je].filter((L)=>!St.has(L));if(Ft.length>0&&N.remove===void 0)throw new E("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:Ft.join(",")});let Xr=(t.now?.()??new Date).toISOString(),Uc=await ot(r.configFile),Qr=Sn(Uc),is=await Eh(Qr),Uh=c?.plugin_config?.before??is,eo=Uh,as=t.resolveConflicts!==void 0,ss=[],$c=[],jc=[];if(c?.plugin_config!==void 0){if($c=["preference","marketplace"].filter((Z)=>{let V=is[Z].digest;return V!==c.plugin_config?.after[Z].digest&&V!==c.plugin_config?.before[Z].digest}).map((Z)=>{let V=Z==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",Oe=is[Z],it=Z==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:bd};return Di({path:r.configFile,key:V,action:"replace",category:"config-key",target:V,existing:Oe.safe_value??{presence:Oe.presence},desired:it,explanation:`The managed ${V} entry changed outside the previous HolyCodex transaction.`})}),as)ss.push(...$c)}let $h=[...new Set([...P,...(c?.provider_config??[]).map((L)=>L.plugin_id),...c?.owned_plugins??[]])].filter((L)=>L!==an),$i=await kh(Qr,$h);if(c?.provider_config!==void 0){let L=new Set(c.owned_plugins??[]);if(jc=$i.filter((V)=>{if(!L.has(V.plugin_id))return!1;let Oe=c.provider_config?.find((it)=>it.plugin_id===V.plugin_id);return Oe!==void 0&&V.before.digest!==Oe.after.digest&&V.before.digest!==Oe.before.digest}).map((V)=>{let Oe=`plugins."${V.plugin_id}"`;return Di({path:r.configFile,key:Oe,action:"replace",category:"config-key",target:Oe,existing:V.before.safe_value??{presence:V.before.presence},desired:{kind:"boolean",value:!0},explanation:`The managed provider plugin entry ${V.plugin_id} changed outside the previous transaction.`})}),as)ss.push(...jc)}let jh=$i.map((L)=>{let Z=c?.provider_config?.find((V)=>V.plugin_id===L.plugin_id);return Z===void 0?L:{plugin_id:L.plugin_id,before:Z.before,after:Z.before}}),Od=jh,Cd=c?.managed_config??Jm({schema:Rn,installId:pt}),Av=await lv(Qr,Cd,c),Pv=await dv(Av.document,Av.state),Mv=await uv(Pv.document,Pv.state),{document:to,state:Tr}=Mv;gz(to,Tr);let Hh=yd(p,f,{browserUse:g.browser_use,computerUse:g.computer_use,frontend:Ct.frontend,security:Ct.security,...b.platform==="win32"?{windowsGitBashExecutable:I.status==="healthy"?I.path:Ja}:{}}),cs;if(c!==void 0){cs=yd(c.profile,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use,frontend:Ct.frontend,security:Ct.security,...c.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:c.tooling.git_bash.path}:{}});let L=Im(c.version.split("-",1)[0]);for(let Z of Vr){let V=c.managed_artifacts.find(({path:Oe})=>Oe.endsWith(`/${Z}.toml`));cs[`agents."${Z}".config_file`]=V?.path??`holycodex/agents/${Z}.toml`}if(Eu(L,uz)<0)cs.model="gpt-6-astra",cs.model_reasoning_effort=c.profile==="low"?"low":c.profile==="default"?"medium":"high";delete cs.developer_instructions}let Bh=await hz(to,Tr,Hh,cs),ls;try{ls=await Sc(to,Tr,Bh,{schema:Rn,installId:pt})}catch(L){if(L instanceof E)throw L;throw new E("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",L,{recovery:"Converge the conflicting Codex setting, then retry."})}let Hc=[];if(ls.driftedKeys.length>0)Hc=ls.driftedKeys.map((L)=>{let Z=Tr.managed[L],V=Ne(to,L),Oe=Hh[L];return Di({path:r.configFile,key:L,action:"replace",category:"config-key",target:L,existing:V??Z?.lastManagedValue,desired:Oe,explanation:`The managed Codex setting ${L} changed outside the previous transaction.`})});if(as)ss.push(...Hc);let Bc;try{Bc=await mh(r.codexHome,p,c?.managed_artifacts,f,b.platform==="win32"?I.status==="healthy"?I.path:Ja:void 0,{browserUse:g.browser_use,computerUse:g.computer_use})}catch(L){throw new E("install_failed",Ah(L),L)}if(as)ss.push(...Bc.map(Di));let Ed=[...$c,...jc,...Hc,...Bc.map(Di)],us=await tF(t,as?ss:Ed,!0),Nv=[],Vc={...Bh},kd=Tr.managed,Fv=async()=>{Nv=Bc.map((wn)=>{let bt=Di(wn),we=us.decisions.get(bt.identity);return we===void 0?bt:{...bt,decision:we}});let L=await Z0(to,to,Uh,jh,is,$i,$c,jc,us.decisions,P),Z=L.document;eo=L.pluginConfigBefore,Od=L.providerConfigBefore;let V={...Tr.managed},Oe={...Bh};for(let wn of Hc){let bt=wn.key;if(bt===void 0)continue;let we=bt,Zn=us.decisions.get(wn.identity);if(Zn!=="keep"&&Zn!=="replace")throw new E("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:bt});let ji=V[we],vn=Hh[we];if(ji===void 0||vn===void 0)throw new E("state_corrupt","The managed conflict cannot be verified.",void 0,{path:r.configFile,key:bt});let ds=Ne(to,we);if(Zn==="replace")Z=Oi(Z,we,vn),V[we]={...ji,lastManagedValue:await on(we,vn)};else if(ds===void 0)delete Oe[we],delete V[we];else delete Oe[we],V[we]={...ji,lastManagedValue:await on(we,ds)}}if(ls=await Sc(Z,{...Tr,managed:V},Oe,{schema:Rn,installId:pt}),ls.driftedKeys.length>0)throw new E("state_corrupt","The accepted managed conflicts did not converge.");Vc=Oe;let it={...Tr.managed};for(let wn of Hc){let bt=wn.key;if(bt===void 0)continue;let we=Ne(to,bt),Zn=it[bt];if(Zn!==void 0&&we===void 0)delete it[bt];else if(Zn!==void 0&&we!==void 0)it[bt]={...Zn,lastManagedValue:await on(bt,we)}}kd=it};await Fv();let Lv=()=>Ed.map((L)=>{let Z=Di(L),V=us.decisions.get(Z.identity);return V===void 0?Z:{...Z,decision:V}}),Dv=(L)=>Object.fromEntries(["config-key","native-plugin","role-asset"].flatMap((Z)=>{let V=L.filter((Oe)=>Oe.category===Z).length;return V===0?[]:[[Z,V]]})),Id=Lv(),qv=Dv(Id),IF=Ez(I,O,U,P);if(t.reviewInstall!==void 0)while(!0){let L=await t.reviewInstall({operation:c===void 0?"install":"upgrade",...c===void 0?{}:{fromVersion:c.version},toVersion:kt,profile:p,tier:f,capabilities:{browser_use:g.browser_use,computer_use:g.computer_use,sites:g.sites},additionalPlugins:[...A],conflicts:Id,conflictCounts:qv,tools:IF});if(L.action==="cancel")throw new E("confirmation_required","Install review was cancelled.");if(L.action==="resolve"){if(Ed.length===0)throw new E("confirmation_required","There are no managed conflicts to resolve.");us=await tF(t,as?ss:Ed,!0),await Fv(),Id=Lv(),qv=Dv(Id);continue}if(L.action==="change"){if(L.request===void 0)throw new E("confirmation_required","Changing install options requires a revised request.");return await ts(L.request,t,n)}if(L.action==="apply")break;throw new E("confirmation_required","Unknown install review action.")}let Vh={owner:"holycodex",schema_epoch:Rn,install_id:pt,version:kt,digest:c?.digest??"0".repeat(64),profile:p,tier:f,optional_selections:g,explicit_optional_selections:w,official_plugins:P,capability_state:Ph(g),managed_artifacts:c?.managed_artifacts??[],installed_at:Xr,status:"preparing",step:"validated",managed_config:Cd,plugin_snapshot:[],plugin_config:{plugin_id:an,before:eo,after:eo},provider_config:Od,owned_plugins:[...Je],...c?.tooling===void 0?{}:{tooling:c.tooling}};await rd(r.stateRoot),await Yn(r.preparingRecord,Vh);let Wc=[],no,Uv=!1,$v=new Set,Wh=new Set,Ad=new Set,_n=new Set(Je),zh=new Set(Je),Kh=new Set,fe=Vh,jv=!1,Or,zc=ls.state,Hv=!1,Bv=!1;try{try{v=await Xa(b,!0)}catch(le){if(le instanceof pe)throw new E("capability_denied",le.message,le,le.details);throw le}try{_=await _h(b,!0,c?.tooling?.context7)}catch(le){k=`Optional ctx7 is unavailable: ${Ah(le)}`}let L=_??c?.tooling?.context7,Z={git_bash:v,...L===void 0?{}:{context7:L}},V={...Vh,tooling:Z};if(fe=V,await Yn(r.preparingRecord,fe),N.ensureOfficialMarketplace!==void 0&&ke.length>0)try{await N.ensureOfficialMarketplace(ke)}catch(le){throw new E("capability_denied",`The selected official Codex provider marketplace is unavailable: ${Ah(le)}`,le,{recovery:"Check Codex network and marketplace policy, then retry."})}try{Wc=await yz({list:()=>N.list()},[...new Set([an,...P,...Je])])}catch(le){throw new E("capability_denied","Native Codex plugin state could not be read safely.",le)}V={...V,plugin_snapshot:Wc},fe=V,await Yn(r.preparingRecord,fe);let Oe=Sn(await ot(r.configFile));await mz(Oe,is,$i);let it=await lv(Oe,Cd,c),wn=await dv(it.document,it.state);Or=(await uv(wn.document,wn.state)).document,await Q0(Or,to,{...Tr,managed:kd},Vc),vr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await rd(r.roleRoot),no=await jw(r.codexHome,p,c?.managed_artifacts,f,v.status==="healthy"?v.path:void 0,Bc.length===0?t.resolveConflict:void 0,Nv,{browserUse:g.browser_use,computerUse:g.computer_use}),fe={...V,step:"roles_prepared",managed_artifacts:no.managed_artifacts},await Yn(r.preparingRecord,fe),vr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),vr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),jv=!0;let we=Or;if(we===void 0)throw new E("state_corrupt","The pre-mutation configuration baseline is missing.");we=Uo(we,"plugins",ns,{enabled:!0}),we=Uo(we,"marketplaces",Lc,{source_type:"git",source:bd});for(let le of P)we=Uo(we,"plugins",le,{enabled:!0});let Zn=await Eh(we),vn=(await kh(we,$h)).map((le)=>({plugin_id:le.plugin_id,before:$i.find((ft)=>ft.plugin_id===le.plugin_id)?.before??le.before,after:le.before}));fe={...fe,plugin_config:{plugin_id:an,before:eo,after:Zn},provider_config:vn},await Yn(r.preparingRecord,fe),await N.addMarketplace(lz),await wz({list:()=>N.list(),add:(le)=>N.add(le)},[an,...P],bn,async(le,ft)=>{if(ft==="new")$v.add(le),_n.add(le),zh.add(le),fe={...fe,owned_plugins:[..._n]};else Kh.add(le),_n.add(le),zh.add(le),fe={...fe,owned_plugins:[..._n]};await Yn(r.preparingRecord,fe)}),fe={...fe,step:"plugins_installed"},await Yn(r.preparingRecord,fe),vr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let Pd=await ot(r.configFile),AF=Sn(Pd),Vv=await lv(AF,Cd,c),Wv=await dv(Vv.document,Vv.state),PF=await uv(Wv.document,Wv.state);if(Or===void 0)throw new E("state_corrupt","The pre-mutation configuration baseline is missing.");let Jh=await Z0(PF.document,Or,Uh,jh,is,$i,$c,jc,us.decisions,P),Hi=Jh.document;for(let le of Object.keys(kd)){let ft=le,ro=Ne(Or,ft);Hi=ro===void 0?Jr(Hi,ft):Oi(Hi,ft,ro)}eo=Jh.pluginConfigBefore,Od=Jh.providerConfigBefore;let Md=await Eh(Hi),zv=await kh(Hi,$h),Kv=zv.map((le)=>({plugin_id:le.plugin_id,before:Od.find((ft)=>ft.plugin_id===le.plugin_id)?.before??le.before,after:le.before})),Jv=zv.map((le)=>({plugin_id:le.plugin_id,before:$i.find((ft)=>ft.plugin_id===le.plugin_id)?.before??le.before,after:le.before}));fe={...fe,plugin_config:{plugin_id:an,before:eo,after:Md},provider_config:Jv};let Gv={};for(let[le,ft]of Object.entries(kd)){let ro=le,Xv=Ne(Or,ro);Gv[ro]={...ft,...Xv===void 0?{}:{lastManagedValue:await on(ro,Xv)}}}let Yv={...Tr,managed:Gv};await Q0(Hi,Or,Yv,Vc);let Nd=await Sc(Hi,Yv,Vc,{schema:Rn,installId:pt});if(Nd.driftedKeys.length>0)throw new E("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Nd.driftedKeys.join(",")});if(vr(t,{stage:"config",status:"started",message:"Configuring Root"}),zc=Nd.state,fe={...fe,managed_config:zc,plugin_config:{plugin_id:an,before:eo,after:Md},provider_config:Jv},await ot(r.configFile)!==Pd)throw new E("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:r.configFile});if(await Gn(r.configFile,Ch(Nd.document)),Uv=!0,fe={...fe,step:"config_published"},await Yn(r.preparingRecord,fe),Ft.length>0)await vz({list:()=>N.list(),remove:(ft)=>N.remove(ft)},Ft,async(ft,ro)=>{if(ro==="removed")Wh.add(ft),_n.delete(ft);else if(ro==="absent")_n.delete(ft);else Ad.add(ft);fe={...fe,owned_plugins:[..._n]},await Yn(r.preparingRecord,fe)});vr(t,{stage:"config",status:"completed",message:"Root configuration published"}),vr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await Sz(r,p,f,{browserUse:g.browser_use,computerUse:g.computer_use,frontend:Ct.frontend,security:Ct.security,...v.status==="healthy"?{windowsGitBashExecutable:v.path}:{}},zc,no.preserved,Vc),vr(t,{stage:"verification",status:"completed",message:"Installation verified"});let Zv=Ph(g),MF=await Mh({owner:"holycodex",install_id:pt,version:kt,profile:p,tier:f,optional_selections:g,explicit_optional_selections:w,official_plugins:P,capability_state:Zv,managed_artifacts:no.managed_artifacts,managed_config:zc,plugin_config:{plugin_id:an,before:eo,after:Md},provider_config:Kv,plugin_snapshot:Wc,owned_plugins:[..._n],tooling:Z}),Gh={owner:"holycodex",schema_epoch:Rn,install_id:pt,version:kt,digest:MF,profile:p,tier:f,optional_selections:g,explicit_optional_selections:w,official_plugins:P,capability_state:Zv,managed_artifacts:no.managed_artifacts,installed_at:Xr,status:"active",step:"active",managed_config:zc,plugin_snapshot:Wc,plugin_config:{plugin_id:an,before:eo,after:Md},provider_config:Kv,owned_plugins:[..._n],tooling:Z};if(Fe(vc,Gh)===void 0)throw new E("state_corrupt","The HolyCodex configuration is invalid.");return Hv=!0,await Ha(r.activeRecord,xn(Gh)),Bv=!0,await oF(r,aF(p,f,g,A)),await Ih(r.preparingRecord),await Ih(r.conflictedRecord),vr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Gh,optional_plugins:P,preserved:no.preserved,warnings:[...no.preserved.length===0?[]:["modified managed files were preserved"],...k===void 0?[]:[k]]}}catch(L){let Z=[];if(Hv)try{if(i===void 0)await fv(r.activeRecord,{force:!1}).catch((V)=>{if(!rt(V,"ENOENT"))throw V});else await Gn(r.activeRecord,i)}catch{Z.push("active_record")}if(Bv)try{if(o===void 0)await fv(r.installOptions,{force:!1}).catch((V)=>{if(!rt(V,"ENOENT"))throw V});else await Gn(r.installOptions,o)}catch{Z.push("install_options")}if(jv||Uv)try{if(Or!==void 0)await xz(r.configFile,fe,Or,zh)}catch{Z.push("config")}if(no!==void 0)try{if((await hh(no.rollback)).preserved.length>0)Z.push("roles")}catch{Z.push("roles")}if(Kh.size>0)Z.push(...[...Kh].map((V)=>`plugin:${V}`));for(let V of $v)try{await N.remove?.(V)}catch{Z.push(`plugin:${V}`)}for(let V of new Set([...Wh,...Ad]))try{await Rz({list:()=>N.list(),add:(Oe)=>N.add(Oe)},V,Wc.find((Oe)=>Oe.plugin_id===V)?.status),Wh.delete(V),Ad.delete(V),_n.add(V),fe={...fe,owned_plugins:[..._n]},await Yn(r.preparingRecord,fe)}catch{_n.add(V),Ad.add(V),fe={...fe,owned_plugins:[..._n]},await Yn(r.preparingRecord,fe).catch(()=>{return}),Z.push(`plugin:${V}`)}if(_?.ownership==="holycodex"&&c?.tooling?.context7?.ownership!=="holycodex")try{if(!await fd(b,_))Z.push("context7")}catch{Z.push("context7")}if(Z.length>0){try{let Oe=Sn(await ot(r.configFile)),it=fe.plugin_config,wn=await Eh(Oe),bt=it===void 0?void 0:{...it,after:{preference:wn.preference.digest===it.before.preference.digest?it.before.preference:it.after.preference,marketplace:wn.marketplace.digest===it.before.marketplace.digest?it.before.marketplace:it.after.marketplace}},we=fe.provider_config,Zn=await kh(Oe,we?.map((vn)=>vn.plugin_id)??[]),ji=we?.map((vn)=>{let ds=Zn.find((Pd)=>Pd.plugin_id===vn.plugin_id);return ds!==void 0&&ds.before.digest===vn.before.digest?{...vn,after:vn.before}:vn});fe={...fe,...bt===void 0?{}:{plugin_config:bt},...ji===void 0?{}:{provider_config:ji}}}catch{}let V=!1;try{await Yn(r.conflictedRecord,{...fe,step:"conflicted",status:"conflicted"}),V=!0}catch{}if(V)await Ih(r.preparingRecord).catch(()=>{return})}else await Ih(r.preparingRecord).catch(()=>{return});if(L instanceof Jn)throw L;if(L instanceof E)throw L;throw new E(L instanceof Yr||L instanceof jo?"capability_denied":"install_failed",Ah(L),L,Z.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function Li(e){let t=await Fw(e.activeRecord,Qu);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:Fe(vc,t);if(o!==void 0)return o;let i=Fe(y0,t);if(i===void 0)throw new E("state_corrupt","The HolyCodex configuration is invalid.");if(!await lF(i))throw new E("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 E("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=Fm(a)}catch(U){throw new E("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,U,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([U])=>U!=="plan")):i,{optional_selections:l,explicit_optional_selections:u}=i,d={browser_use:l.browser_use??Yt.browser_use,computer_use:l.computer_use,sites:l.sites??Yt.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:Ph(d,new Map([["browser_use","missing"],["sites","missing"]])),m=(i.official_plugins??[]).filter((U)=>!Sd(U)),y=i.owned_plugins?.filter((U)=>!Sd(U)),g=i.provider_config?.filter((U)=>!Sd(U.plugin_id)),w=i.plugin_snapshot?.filter((U)=>!Sd(U.plugin_id)),{optional_selections:A,explicit_optional_selections:b,capability_state:I,official_plugins:O,owned_plugins:v,provider_config:_,plugin_snapshot:k,...P}=c,N={...P,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},...w===void 0?{}:{plugin_snapshot:w},digest:await Mh({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},...w===void 0?{}:{plugin_snapshot:w},...y===void 0?{}:{owned_plugins:y},...i.tooling===void 0?{}:{tooling:i.tooling}})};return nF.set(N,i.digest),N}async function wr(e,t){let n=await Fw(e,Qu);if(n===void 0)return;let r=Fe(Mi,n);if(r!==void 0)return r;let o=Fe(b0,n);if(o===void 0)throw new E("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 E("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e});let s;try{s=Fm(a)}catch(P){throw new E("state_corrupt","The persisted transaction profile requires an explicit replacement.",P,{path:e,profile:a})}let{optional_selections:c,explicit_optional_selections:l}=i,u={browser_use:c.browser_use??Yt.browser_use,computer_use:c.computer_use??!1,sites:c.sites??Yt.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:Ph(u,new Map([["browser_use","missing"],["sites","missing"]])),{plan:m,profile:y,optional_selections:g,explicit_optional_selections:w,capability_state:A,...b}=i,I=typeof b.digest==="string"?b.digest:void 0,O=t===void 0?void 0:nF.get(t),v=t!==void 0&&b.install_id===t.install_id&&(I===t.digest||O!==void 0&&I===O)?t.digest:I,_={...b,profile:s,optional_selections:u,explicit_optional_selections:d,...f===void 0?{}:{capability_state:f},...v===void 0?{}:{digest:v}},k=Fe(Mi,_);if(k===void 0)throw new E("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e});return k}function cF(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites}}function Sn(e){if(e===void 0||e.trim().length===0)return{};try{let t=globalThis.Bun,n=t?.TOML?.parse?t.TOML.parse(e):Kw(e),r=Fe(Ma,n);if(r===void 0)throw Error("TOML document contains unsupported values.");return r}catch(t){throw new E("state_corrupt","The Codex config.toml is not valid TOML.",t)}}function Ch(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):Jw(e)).trimEnd()}
42
- `}catch(t){throw new E("install_failed","The merged Codex configuration is not writable.",t)}}async function Eh(e){return{preference:await rs(e,"plugins",ns),marketplace:await rs(e,"marketplaces",Lc)}}async function kh(e,t){return await Promise.all(t.map(async(n)=>{let r=await rs(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 Pc(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",ns],["marketplace","marketplaces",Lc]]){let u=t.before[s],d=t.after[s],p=await rs(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=hv(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=Uo(r,c,l,fz(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function Mc(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 rs(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=hv(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=Uo(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 Y0(e,t,n,r,o,i){if(o.presence!=="present"||o.safe_value!==void 0)return{document:e,restored:!1};let a=await rs(e,n,r);if(a.digest===o.digest||a.digest!==i.digest)return{document:e,restored:!1};let s=_d(t,n,r);if(s===void 0)return{document:e,restored:!1};return{document:Uo(e,n,r,s),restored:!0}}async function rs(e,t,n){let r=_d(e,t,n),o=await yr("holycodex-plugin-config",[gr(xn({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=pz(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function _d(e,t,n){let r=e[t];if(!Fc(r))return;return r[n]}function pz(e,t){if(!Fc(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!==bd)return;return{kind:"marketplace",source_type:"git",source:bd}}function fz(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function Uo(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!Fc(i))throw new E("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function hv(e,t,n){let r=e[t];if(!Fc(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 Fc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function mz(e,t,n){let r=[{parent:"plugins",key:ns,expected:t.preference},{parent:"marketplaces",key:Lc,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 rs(e,o,i)).digest!==a.digest)throw new E("confirmation_required","Plugin configuration changed after preflight; review the latest configuration and retry.",void 0,{key:`${o}.${i}`})}async function Z0(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 E("state_corrupt","A plugin configuration conflict has no identity.");let y=c.get(m);if(y!=="keep"&&y!=="replace")throw new E("confirmation_required",`Plugin configuration conflict resolution is incomplete for ${f.key??m}.`);let g=f.key==='plugins."holycodex@holycodex"'?"preference":"marketplace",w=o[g];if(y==="keep"){let A=_d(t,"plugins",ns);if(g==="preference"&&Fc(A)&&A.enabled===!1)throw new E("confirmation_required","Keeping disabled HolyCodex config would disable the selected plugin.");u=X0(u,t,f.key),d={...d,[g]:w};continue}u=Uo(u,g==="preference"?"plugins":"marketplaces",g==="preference"?ns:Lc,g==="preference"?{enabled:!0}:{source_type:"git",source:bd})}for(let f of s){let{identity:m,key:y}=f;if(m===void 0||y===void 0)throw new E("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 E("state_corrupt",`The provider configuration conflict key ${y} is invalid.`);let w=c.get(m);if(w!=="keep"&&w!=="replace")throw new E("confirmation_required",`Provider configuration conflict resolution is incomplete for ${y}.`);let A=i.find((b)=>b.plugin_id===g);if(A===void 0)throw new E("state_corrupt",`The provider configuration entry ${g} is missing.`);if(w==="keep"){let b=_d(t,"plugins",g);if(l.includes(g)&&Fc(b)&&b.enabled===!1)throw new E("confirmation_required",`Keeping disabled config would disable selected plugin ${g}.`);u=X0(u,t,y),p=p.map((I)=>I.plugin_id===g?{plugin_id:g,before:A.before,after:A.before}:I);continue}u=Uo(u,"plugins",g,{enabled:!0})}return{document:u,pluginConfigBefore:d,providerConfigBefore:p}}function X0(e,t,n){if(n===void 0)throw new E("state_corrupt","A configuration conflict has no key.");if(n.startsWith('plugins."')&&n.endsWith('"')){let o=n.slice(9,-1),i=_d(t,"plugins",o);return i===void 0?hv(e,"plugins",o):Uo(e,"plugins",o,i)}let r=Ne(t,n);return r===void 0?Jr(e,n):Oi(e,n,r)}async function hz(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 on(a,c);if(JSON.stringify(l)===JSON.stringify(s.lastManagedValue))continue;let u=Ne(e,a);if(typeof u!=="string"&&typeof u!=="number"&&typeof u!=="boolean")continue;let d=await on(a,u);if(JSON.stringify(d)===JSON.stringify(s.lastManagedValue))delete o[a]}return o}function yd(e,t,n=!1){let r=Uw(e,t),o=typeof n==="boolean"?{}:n,i={browserUse:o.browserUse??Yt.browser_use,computerUse:typeof n==="boolean"?n:o.computerUse??Yt.computer_use,...o.windowsGitBashExecutable===void 0?{}:{windowsGitBashExecutable:o.windowsGitBashExecutable}},a=Wa(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:$w({...typeof n==="boolean"?{computerUse:n}:n,rootModel:r.model}),suppress_unstable_features_warning:!0,"features.multi_agent":!0,"features.context_management.experimental_mode":!0};for(let c of Vr)s[`agents."${c}".config_file`]=ad(c,a);return s}async function Q0(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await La(e,n,a)).status==="drifted")o.push(a);continue}let c=Ne(t,a),l=Ne(e,a),u=xn(c===void 0?null:c),d=xn(l===void 0?null:l);if(Pn(u)!==Pn(d))o.push(a)}if(o.length>0)throw new E("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function lv(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 Sr(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new E("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=Ne(i,u);if(typeof d!=="string")continue;let p=d.replaceAll("\\","/").replace(/^\.\//u,"");if(p===`agents/${c}.toml`||p===`holycodex/agents/${c}.toml`)i=Jr(i,u)}return{document:i,state:a}}async function uv(e,t){let n=t.managed[cv];if(n===void 0)return{document:e,state:t};let r=await Sr(e,{...t,managed:{[cv]:n}},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>i!==cv));return{document:r.document,state:{...t,managed:o}}}async function dv(e,t){let n=Object.fromEntries(Object.entries(t.managed).filter(([i])=>Ci.includes(i)));if(Object.keys(n).length===0)return{document:e,state:t};let r=await Sr(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 gz(e,t){if(Ne(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new E("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function yz(e,t){let n=await e.list();return t.map((r)=>{let o=Rr(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function Yn(e,t){if(Fe(Mi,t)===void 0)throw new E("state_corrupt","The HolyCodex transaction state is invalid.");await Ha(e,xn(t))}async function Ih(e){await fv(e,{force:!1}).catch((t)=>{if(!rt(t,"ENOENT"))throw t})}async function xz(e,t,n,r){let o=await ot(e);if(o===void 0)return;let i=Sn(o),a={},s=0;for(let[p,f]of Object.entries(t.managed_config.managed)){let m=p,y=Ne(n,m),g=y===void 0?void 0:await on(m,y);if(JSON.stringify(g??null)===JSON.stringify(f.lastManagedValue))continue;if(y!==void 0&&g?.kind==="digest"){let w=Ne(i,m);if(w!==void 0&&JSON.stringify(await on(m,w))===JSON.stringify(f.lastManagedValue))i=Oi(i,m,y),s+=1;continue}a[p]={...f,originalValue:g??{kind:"absent"}}}let c=await Sr(i,{...t.managed_config,managed:a},{schema:Rn,installId:t.install_id});i=c.document;let l=t.plugin_config===void 0?void 0:await Pc(i,t.plugin_config,{allowBeforeState:!0});if(l!==void 0)i=l.document;let u=t.provider_config===void 0?void 0:await Mc(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",ns],["marketplace","marketplaces",Lc]]){let y=await Y0(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 Y0(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 Gn(e,Ch(i))}async function Sz(e,t,n,r,o,i=[],a=yd(t,n,r)){let s=await ot(e.configFile),c=Sn(s),l=a;for(let[m,y]of Object.entries(l)){let g=Ne(c,m);if(m==="developer_instructions"){if(typeof g!=="string"||g!==y||await bz(m,g)!==o.managed[m]?.lastManagedValue.value)throw new E("install_failed","The effective Root instructions did not converge.")}else if(g!==y)throw new E("install_failed",`The effective Codex setting ${m} did not converge.`)}let u={browserUse:r.browserUse??Yt.browser_use,computerUse:r.computerUse,...r.windowsGitBashExecutable===void 0?{}:{windowsGitBashExecutable:r.windowsGitBashExecutable}},d=Wa(t,n,u),p=qo(t,n);for(let m of p){let y=`agents."${m.name}".config_file`,g=Ne(c,y);if(typeof g!=="string")throw new E("install_failed",`The ${m.name} registration is missing.`);let w=ad(m.name,d),A=Fa(e.configFile,w),b=A.replaceAll("\\","/");if(Fa(e.configFile,g).replaceAll("\\","/")!==b)throw new E("install_failed",`The ${m.name} registration is stale (expected ${w}; received ${g}).`);let O=await ot(A);if(O===void 0)throw new E("install_failed",`The ${m.name} role file is missing.`);if(i.some((_)=>_.replaceAll("\\","/")===b))throw new E("install_failed",`The ${m.name} role file was kept after a conflict and cannot be activated.`);let v=Sn(O);if(v.name!==m.name||typeof v.description!=="string"||typeof v.model!=="string"||typeof v.model_reasoning_effort!=="string"||typeof v.service_tier!=="string"||typeof v.developer_instructions!=="string"||!yh(m,v)||v.approval_policy!=="never"||v.web_search!==(m.permissions.network?"live":"disabled")||v.tool_output_token_limit!==void 0||Ne(v,"agents.enabled")!==!1||Ne(v,"features.multi_agent")!==!1||Object.keys(v.features??{}).some((_)=>_!=="multi_agent"))throw new E("install_failed",`The ${m.name} role file is malformed.`)}let f=await ot(`${e.codexHome}/agents/root.toml`);if(f!==void 0&&Cc(f))throw new E("install_failed","A stale HolyCodex Root role remains installed.")}async function bz(e,t){return await yr("holycodex-managed-config-value",[gr({keyPath:e,value:t})])}function pv(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 _z(e){return["browser_use","computer_use","sites"].find((t)=>Ao[t].pluginIds.includes(e))}function mv(e){return(e?.official_plugins??[]).filter((t)=>{if(Sd(t))return!1;let n=_z(t);return n===void 0||e?.optional_selections[n]!==!0})}function Sd(e){let t=e.slice(0,e.lastIndexOf("@"));return dz.has(t)}async function wz(e,t,n=new Set,r){for(let o of t){let i=n.has(o),a;try{a=Rr(await e.list(),o)}catch(l){throw $o("list",l,o)}if(a?.installed&&!a.enabled)throw new jo("uncertain",`${o} is disabled`);let s=i||!(a?.installed&&a.enabled);if(s)try{await e.add(o)}catch(l){try{let u=Rr(await e.list(),o);if(i||!eF(a,u))await r?.(o,"uncertain")}catch{await r?.(o,"uncertain")}throw $o("add",l,o)}let c;try{c=Rr(await e.list(),o)}catch(l){if(s)await r?.(o,"uncertain");throw $o("list",l,o)}if(!c?.installed){if(s&&(i||!eF(a,c)))await r?.(o,"uncertain");throw new jo("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 jo("uncertain",`${o} is disabled after add`)}}}async function vz(e,t,n){for(let r of t){let o;try{o=Rr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),$o("list",a,r)}if(!(o?.installed??!1)){await n?.(r,"absent");continue}try{await e.remove(r)}catch(a){try{if(!(Rr(await e.list(),r)?.installed??!1))await n?.(r,"removed");else await n?.(r,"uncertain")}catch{await n?.(r,"uncertain")}throw $o("remove",a,r)}let i;try{i=Rr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),$o("list",a,r)}if(i?.installed)throw await n?.(r,"uncertain"),new jo("uncertain",`${r} is still installed after remove`);await n?.(r,"removed")}}async function Rz(e,t,n){if(n!=="installed"&&n!=="disabled")throw new jo("uncertain",`${t} has no proven prior installed state`);let r=n==="installed",o;try{o=Rr(await e.list(),t)}catch(a){throw $o("list",a,t)}if(o?.installed&&o.enabled===r)return;try{await e.add(t)}catch(a){throw $o("add",a,t)}let i;try{i=Rr(await e.list(),t)}catch(a){throw $o("list",a,t)}if(!i?.installed)throw new jo("missing",`${t} is not installed after restore`);if(i.enabled!==r)throw new jo("uncertain",`${t} did not regain its prior ${r?"enabled":"disabled"} state`)}function eF(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function $o(e,t,n){if(t instanceof Yr)return t;return new Yr(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 Rr(e,t){let n=Gr(e,t);if(n!==void 0)return n.entry;let r=fr(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function Tz(e,t){let n=e??t??"default";if(!Wr(n).ok)throw new E("install_failed","Unknown profile.");return n}function Oz(e,t){let n=e??t??"standard";if(Fe(Mo,n)===void 0)throw new E("install_failed","The tier is not supported.");return n}function Cz(e,t){let n=t?cF(t):Yt,r=zb(e,n);return{browser_use:r.browser_use,computer_use:r.computer_use,sites:r.sites,coding:!0}}function Ph(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:[...Ao[r].pluginIds]};return[r,a]}))}async function Mh(e){let{profile:t,plan:n,...r}=e,o=n===void 0?{...r,profile:t}:{...r,plan:n};return await yr("install-record",[gr(xn(o))])}async function Nc(e){return await lF(e)}async function lF(e){return await Mh({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 Ah(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function Ez(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=Rr(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 Di(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}`;return{...e,identity:r,category:t,target:n,defaultDecision:e.defaultDecision??"replace",validDecisions:e.validDecisions??["keep","replace","cancel"],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 tF(e,t,n=!1){let r=t.map(Di),o=new Map;if(r.length===0)return{accepted:[],decisions:o};if(e.resolveConflicts!==void 0){let a=await e.resolveConflicts(r);for(let s of r){let c=s.identity,l=a[c];if(l!=="keep"&&l!=="replace"&&l!=="cancel")throw new E("confirmation_required","Every managed conflict must have a valid decision before installation.",void 0,{identity:c});if(l==="cancel")throw new E("confirmation_required","Conflict resolution was cancelled.",void 0,{identity:c});o.set(c,l)}return{accepted:r.filter((s)=>o.get(s.identity)==="replace"),decisions:o}}let i=[];for(let a of r){let s=await e.resolveConflict?.(a);if(s==="accept"){i.push(a),o.set(a.identity,"replace");continue}if(s==="decline"&&n){o.set(a.identity,"keep");continue}throw new E("confirmation_required",s==="cancel"?"Conflict resolution was cancelled.":"HolyCodex-owned changes require confirmation before replacement.",void 0,{path:a.path,...a.key===void 0?{}:{key:a.key},action:a.action,resolution:s??"unavailable"})}return{accepted:i,decisions:o}}function vr(e,t){try{e.onProgress?.(t)}catch{}}var lz="davidbasilefilho/holycodex",an="holycodex@holycodex",uz="0.16.8",nF,bd="https://github.com/davidbasilefilho/holycodex.git",ns="holycodex@holycodex",Lc="holycodex",dz,cv,jo,E;var xd=S(()=>{_c();dt();Xu();id();xh();cd();$a();qa();Rc();wh();qa();nF=new WeakMap;dz=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]),cv=Ci[0];jo=class jo extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};E=class E 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 xK}from"readline/promises";dt();dt();dt();var x_=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."}]),AN=new Set(["codex-home","profile","tier","add-plugin"]),aB=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","sites","no-sites","browser-use","no-browser-use"]);class tt extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Hm(e){if(e.length===0)throw new tt("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 Hm(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new tt("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 tt("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 tt("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!AN.has(u)&&!aB.has(u))throw new tt("invalid_argument","Unknown option.",{option:`--${c}`});if(AN.has(u)){let d=l??e[o+1];if(d===void 0||d.length===0||d.startsWith("-"))throw new tt("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 tt("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 tt("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new tt("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return sB(t,n,r),{command:t,positionals:n,options:r}}function sB(e,t,n){let r=lB(e);for(let s of Object.keys(n))if(!r.has(s))throw new tt("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 tt("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!Wr(i).ok){let s=cB[i];if(s!==void 0)throw new tt("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 tt("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new tt("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 tt("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 tt("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove"].includes(e)&&n.yes===!1)throw new tt("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 tt("invalid_argument",`Installation options are not valid for ${e}.`)}var cB={"plus-low":"low",plus:"default","plus-high":"high"};function lB(e){switch(e){case"install":return new Set([...x_.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 uB=`HolyCodex
33
+ schema (${r._tag}): ${r}`;return o},mP=(e)=>wi("Invalid Argument",e),hP=(e)=>wi("Unsupported key schema",void 0,void 0,e),gP=(e)=>wi("Unsupported literal",`literal value: ${Ar(e)}`),BS=(e)=>wi("Duplicate index signature",`${e} index signature`),yP,xP,VS=(e)=>wi("Duplicate property signature transformation",`Duplicate key ${Ar(e)}`),WS=(e)=>wi("Duplicate property signature",`Duplicate key ${Ar(e)}`);var zS=S(()=>{tt();et();bu();yP=wi("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),xP=wi("Invalid element","A required element cannot follow an optional element. ts(1257)")});var bP,_P,wP,vP,RP,TP,OP;var CP=S(()=>{bP=Symbol.for("effect/SchemaId/DateFromSelf"),_P=Symbol.for("effect/SchemaId/GreaterThan"),wP=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),vP=Symbol.for("effect/SchemaId/Int"),RP=Symbol.for("effect/SchemaId/MinLength"),TP=Symbol.for("effect/SchemaId/MaxLength"),OP=Symbol.for("effect/SchemaId/MinItems")});class sc{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(jr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:Ze(this.annotations)}}}class Na{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Le(jr(this),()=>Ar(this.literal))}toJSON(){return{_tag:this._tag,literal:zo(this.literal)?String(this.literal):this.literal,annotations:Ze(this.annotations)}}}class ym{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Le(jr(this),()=>Ar(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:Ze(this.annotations)}}}class UP{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class jP{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class HP{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class BP{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class VP{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class zP{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class JP{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class YP{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class XP{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class QP{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class tM{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return dr(this)}toJSON(){return{_tag:this._tag,annotations:Ze(this.annotations)}}}class cc{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:Ze(this.annotations)}}toString(){return String(this.type)}}class vu{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(xP)}toString(){return Le(jr(this),()=>lH(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:Ze(this.annotations)}}}class lc{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,rM(e))this.parameter=e;else throw Error(yP)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class Hr{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(WS(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=Rb(t[i].parameter);if(bm(a)){if(o.string)throw Error(BS("string"));o.string=!0}else if(eM(a)){if(o.symbol)throw Error(BS("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Le(jr(this),()=>uH(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:Ze(this.annotations)}}}class on{types;annotations;static make=(e,t)=>_m(e)?new on(e,t):e.length===1?e[0]:Sm;static unify=(e,t)=>on.make(fH(oM(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Le(jr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:Ze(this.annotations)}}}class wm{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=Su(e)}toString(){return jr(this).pipe(Qn(()=>tr(JR(this.f)(),(e)=>jr(e))),Le(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=KS.get(e);if(t)return t;return KS.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:Ze(this.annotations)},KS.set(e,t),t}}class Ru{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return _u(this).pipe(Le(()=>ct(lM(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Tu(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:Ze(this.annotations)}}}class Sb{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(jr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:Ze(this.annotations)}}}class bb{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class _b{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(VS(o));t[o]=!0;let i=r.to;if(n[i])throw Error(VS(i));n[i]=!0}}}function zn(e,t){let n=!1,r=ia(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 xH(e){return ct(ub(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Ar(n)}>`).join("")})}var kP,GS,IP,YS,fm,mm,yn,hm,Po,ZS,XS,QS,eb,tb,nb,AP,rb,ob,ib,ab,sb,cb,lb,Yt,ub,PP,MP,db,pb,_u,fb,NP,FP,LP,DP,qP,mb,nH,hb=(e)=>ZR(nH(e),(t)=>t===!0),gb,rH,oH=(e)=>Qn(rH(e),()=>_u(e)),wu=(e)=>(t)=>t._tag===e,gm,$P,xm,iH,Sm,yb,WP,KP,bm,GP,ZP,aH,sH,eM,cH,vi,nM=(e)=>e.map((t)=>t.type),lH=(e)=>{let t=e.elements.map(String).join(", ");return eT(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}>`}})},Tt,rM=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return rM(e.from)}return!1},EP=(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}; ${EP(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${EP(e.indexSignatures)} }`;else return"{}"},dH,pH,oM=(e)=>Sl(e,(t)=>xb(t)?oM(t.types):[t]),fH=(e)=>{let t=dH(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[WP];case"UnknownKeyword":return[yb];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=pH[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},iM=(e,t)=>e.map(t),_m=(e)=>e.length>1,xb,KS,Tu,vm,Ou=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[mm];let o={...r,...t},i=mb(e);if(De(i))o[cb]=Ou(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},mH="[\\s\\S]*?",hH="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",aM=(e,t)=>{switch(e._tag){case"Literal":return Zs(String(e.literal));case"StringKeyword":return mH;case"NumberKeyword":return hH;case"TemplateLiteral":return sM(e,t,!1);case"Union":return e.types.map((n)=>aM(n,t)).join("|")}},gH=(e,t,n,r)=>{if(xb(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},sM=(e,t,n)=>{let r="";if(e.head!==""){let o=Zs(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=aM(o.type,t);if(r+=gH(o.type,i,t,n),o.literal!==""){let a=Zs(o.literal);r+=t&&n?`(${a})`:a}}return r},cM=(e)=>new RegExp(`^${sM(e,!1,!0)}$`),wb=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new lc(i,t,!0));break;case"Literal":if(qt(i.literal)||Tn(i.literal))n.push(new Tt(i.literal,t,!1,!0));else throw Error(gP(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new Tt(s,t,!1,!0));break}case"UniqueSymbol":n.push(new Tt(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(hP(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},vb=(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},yH,Rt=(e)=>{switch(e._tag){case"Declaration":{let t=zn(e.typeParameters,Rt);return t===e.typeParameters?e:new sc(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=zn(e.elements,(o)=>{let i=Rt(o.type);return i===o.type?o:new vi(i,o.isOptional)}),n=nM(e.rest),r=zn(n,Rt);return t===e.elements&&r===n?e:new vu(t,r.map((o)=>new cc(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=zn(e.propertySignatures,(r)=>{let o=Rt(r.type);return o===r.type?r:new Tt(r.name,o,r.isOptional,r.isReadonly)}),n=zn(e.indexSignatures,(r)=>{let o=Rt(r.type);return o===r.type?r:new lc(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new Hr(t,n,e.annotations)}case"Union":{let t=zn(e.types,Rt);return t===e.types?e:on.make(t,e.annotations)}case"Suspend":return new wm(()=>Rt(e.f()),e.annotations);case"Refinement":{let t=Rt(e.from);return t===e.from?e:new Ru(t,e.filter,e.annotations)}case"Transformation":{let t=yH(e);return Rt(t!==void 0?Ou(e.to,t):e.to)}}return e},JS=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return JS(e.from);case"Suspend":return JS(e.f())}},Ur=(e,t)=>{switch(e._tag){case"Declaration":{let n=zn(e.typeParameters,(r)=>Ur(r,t));return n===e.typeParameters?e:new sc(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=zn(e.elements,(i)=>{let a=Ur(i.type,t);return a===i.type?i:new vi(a,i.isOptional)}),r=nM(e.rest),o=zn(r,(i)=>Ur(i,t));return n===e.elements&&o===r?e:new vu(n,o.map((i)=>new cc(i)),e.isReadonly)}case"TypeLiteral":{let n=zn(e.propertySignatures,(o)=>{let i=Ur(o.type,t);return i===o.type?o:new Tt(o.name,i,o.isOptional,o.isReadonly)}),r=zn(e.indexSignatures,(o)=>{let i=Ur(o.type,t);return i===o.type?o:new lc(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new Hr(n,r)}case"Union":{let n=zn(e.types,(r)=>Ur(r,t));return n===e.types?e:on.make(n)}case"Suspend":{let n=void 0,r=oH(e);if(De(r)){let o=t?"Bound":"";n={[gb]:`${r.value}Encoded${o}`}}return new wm(()=>Ur(e.f(),t),n)}case"Refinement":{let n=Ur(e.from,t);if(t){if(n===e.from)return e;if(JS(e.from)===void 0&&hb(e))return new Ru(n,e.filter,e.annotations);return n}else return n}case"Transformation":return Ur(e.from,t)}return e},Rm=(e)=>Ur(e,!1),Ze=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},Rb=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return Rb(e.from)}},dr=(e)=>Le(jr(e),()=>e._tag),lM=(e)=>db(e).pipe(Qn(()=>fb(e)),Qn(()=>pb(e)),er((t)=>t+xH(e))),jr=(e)=>Qn(_u(e),()=>lM(e));var Tb=S(()=>{tt();ee();et();zS();bu();ou();lt();ep();Ee();Mx();kP=Symbol.for("effect/annotation/TypeConstructor"),GS=Symbol.for("effect/annotation/Brand"),IP=Symbol.for("effect/annotation/SchemaId"),YS=Symbol.for("effect/annotation/Message"),fm=Symbol.for("effect/annotation/MissingMessage"),mm=Symbol.for("effect/annotation/Identifier"),yn=Symbol.for("effect/annotation/Title"),hm=Symbol.for("effect/annotation/AutoTitle"),Po=Symbol.for("effect/annotation/Description"),ZS=Symbol.for("effect/annotation/Examples"),XS=Symbol.for("effect/annotation/Default"),QS=Symbol.for("effect/annotation/JSONSchema"),eb=Symbol.for("effect/annotation/Arbitrary"),tb=Symbol.for("effect/annotation/Pretty"),nb=Symbol.for("effect/annotation/Equivalence"),AP=Symbol.for("effect/annotation/Documentation"),rb=Symbol.for("effect/annotation/Concurrency"),ob=Symbol.for("effect/annotation/Batching"),ib=Symbol.for("effect/annotation/ParseIssueTitle"),ab=Symbol.for("effect/annotation/ParseOptions"),sb=Symbol.for("effect/annotation/DecodingFallback"),cb=Symbol.for("effect/annotation/Surrogate"),lb=Symbol.for("effect/annotation/StableFilter"),Yt=h(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?Y(e.annotations[t]):B()),ub=Yt(GS),PP=Yt(YS),MP=Yt(fm),db=Yt(yn),pb=Yt(hm),_u=Yt(mm),fb=Yt(Po),NP=Yt(rb),FP=Yt(ob),LP=Yt(ib),DP=Yt(ab),qP=Yt(sb),mb=Yt(cb),nH=Yt(lb),gb=Symbol.for("effect/annotation/JSONIdentifier"),rH=Yt(gb);gm=wu("Literal"),$P=new Na(null);xm=new UP({[yn]:"undefined"});iH=new jP({[yn]:"void"});Sm=new HP({[yn]:"never"});yb=new BP({[yn]:"unknown"});WP=new VP({[yn]:"any"});KP=new zP({[yn]:"string",[Po]:"a string"}),bm=wu("StringKeyword");GP=new JP({[yn]:"number",[Po]:"a number"});ZP=new YP({[yn]:"boolean",[Po]:"a boolean"});aH=new XP({[yn]:"bigint",[Po]:"a bigint"});sH=new QP({[yn]:"symbol",[Po]:"a symbol"}),eM=wu("SymbolKeyword");cH=new tM({[yn]:"object",[Po]:"an object in the TypeScript meaning, i.e. the `object` type"});vi=class vi extends cc{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:Ze(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};Tt=class Tt extends vi{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:Ze(this.annotations)}}};dH=ho(Qd($r,(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})),pH={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};xb=wu("Union"),KS=te(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Tu=wu("Refinement"),vm={};yH=vb([ZS,XS,QS,eb,tb,nb])});class Ot{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class Eb{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class uc{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class Xe{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class Om{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Cm{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Kn{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class kb{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function pr(e){return e.sort(vH).map((t)=>t[1])}function kH(e){return fb(e).pipe(Qn(()=>db(e)),Qn(()=>pb(e)),Qn(()=>_u(e)),Le(()=>`{ ${e.from} | filter }`))}function IH(e){if(e.message!==void 0)return e.message;return`Expected ${Tu(e.ast)?kH(e.ast):String(e.ast)}, actual ${Ar(e.actual)}`}var dM,mM,Ab=(e)=>new mM({issue:e}),hM,gM,Sn,Mo,fr,Em,yM,xM=(e,t)=>{if(t===void 0||Tn(t))return e;if(e===void 0)return t;return{...e,...t}},SM=(e,t,n)=>{let r=Zt(e,t);return(o,i)=>r(o,xM(n,i))},SH=(e,t,n)=>{let r=SM(e,t,n);return(o,i)=>vg(r(o,i),Ab)},bM=(e,t)=>SM(e.ast,!0,t),km=(e,t)=>SH(Rt(e.ast),!0,t),bH,_H,Zt=(e,t)=>{let n=t?bH:_H,r=n.get(e);if(r)return r;let o=wH(e,t),i=DP(e),a=De(i)?(l,u)=>o(l,xM(u,i.value)):o,s=qP(e),c=t&&De(s)?(l,u)=>Eu(yM(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},Ob=(e)=>hn(NP(e)),Cb=(e)=>hn(FP(e)),wH=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=Zt(e.from,!0);return(r,o)=>{o=o??vm;let i=o?.errors==="all",a=Mo(yM(n(r,o),(s)=>{let c=new Om(e,r,"From",s);if(i&&hb(e)&&TM(s))return ct(e.filter(r,o,e),{onNone:()=>ie(c),onSome:(l)=>ie(new Xe(e,r,[c,new Om(e,r,"Predicate",l)]))});return ie(c)}),(s)=>ct(e.filter(s,o,e),{onNone:()=>ce(s),onSome:(c)=>ie(new Om(e,r,"Predicate",c))}));return Eu(a,e,r,o)}}else{let n=Zt(Rt(e),!0),r=Zt(wM(e.from),!1);return(o,i)=>Eu(Mo(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=RH(e.transformation,t),r=t?Zt(e.from,!0):Zt(e.to,!1),o=t?Zt(e.to,!0):Zt(e.from,!1);return(i,a)=>Eu(Mo(Em(r(i,a),(s)=>new Cm(e,i,t?"Encoded":"Type",s)),(s)=>Mo(Em(n(s,a??vm,e,i),(c)=>new Cm(e,i,"Transformation",c)),(c)=>Em(o(c,a),(l)=>new Cm(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)=>Eu(n(r,o??vm,e),e,r,o)}case"Literal":return xn(e,(n)=>n===e.literal);case"UniqueSymbol":return xn(e,(n)=>n===e.symbol);case"UndefinedKeyword":return xn(e,xR);case"NeverKeyword":return xn(e,SR);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return ce;case"StringKeyword":return xn(e,qt);case"NumberKeyword":return xn(e,Tn);case"BooleanKeyword":return xn(e,Yi);case"BigIntKeyword":return xn(e,zo);case"SymbolKeyword":return xn(e,Zi);case"ObjectKeyword":return xn(e,rn);case"Enums":return xn(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>bm(r.type)))return xn(e,(r)=>{if(!qt(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=cM(e);return xn(e,(r)=>qt(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>Zt(l.type,t)),r=e.rest.map((l)=>Zt(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=Ob(e),c=Cb(e);return(l,u)=>{if(!Ig(l))return ie(new Kn(e,l));let d=u?.errors==="all",p=[],f=0,m=[],y=l.length;for(let b=y;b<=i-1;b++){let A=new Ot(b,l,new uc(o[b-y]));if(d){p.push([f++,A]);continue}else return ie(new Xe(e,l,A,m))}if(e.rest.length===0)for(let b=e.elements.length;b<=y-1;b++){let A=new Ot(b,l,new Eb(l[b],`is unexpected, expected: ${a}`));if(d){p.push([f++,A]);continue}else return ie(new Xe(e,l,A,m))}let g=0,_=void 0;for(;g<n.length;g++)if(y<g+1){if(e.elements[g].isOptional)continue}else{let b=n[g],A=b(l[g],u);if(Sn(A)){if(Fe(A)){let O=new Ot(g,l,A.left);if(d){p.push([f++,O]);continue}else return ie(new Xe(e,l,O,pr(m)))}m.push([f++,A.right])}else{let O=f++,v=g;if(!_)_=[];_.push(({es:w,output:k})=>ur(Ma(A),(P)=>{if(Fe(P)){let L=new Ot(v,l,P.left);if(d)return w.push([O,L]),An;else return ie(new Xe(e,l,L,pr(k)))}return k.push([O,P.right]),An}))}}if(Me(r)){let[b,...A]=r;for(;g<y-A.length;g++){let O=b(l[g],u);if(Sn(O))if(Fe(O)){let v=new Ot(g,l,O.left);if(d){p.push([f++,v]);continue}else return ie(new Xe(e,l,v,pr(m)))}else m.push([f++,O.right]);else{let v=f++,w=g;if(!_)_=[];_.push(({es:k,output:P})=>ur(Ma(O),(L)=>{if(Fe(L)){let j=new Ot(w,l,L.left);if(d)return k.push([v,j]),An;else return ie(new Xe(e,l,j,pr(P)))}else return P.push([v,L.right]),An}))}}for(let O=0;O<A.length;O++){let v=g+O;if(y<v+1)continue;else{let w=A[O](l[v],u);if(Sn(w)){if(Fe(w)){let k=new Ot(v,l,w.left);if(d){p.push([f++,k]);continue}else return ie(new Xe(e,l,k,pr(m)))}m.push([f++,w.right])}else{let k=f++;if(!_)_=[];_.push(({es:P,output:L})=>ur(Ma(w),(j)=>{if(Fe(j)){let Ie=new Ot(v,l,j.left);if(d)return P.push([k,Ie]),An;else return ie(new Xe(e,l,Ie,pr(L)))}return L.push([k,j.right]),An}))}}}}let I=({es:b,output:A})=>Zo(b)?ie(new Xe(e,l,pr(b),pr(A))):ce(pr(A));if(_&&_.length>0){let b=_;return xu(()=>{let A={es:Rs(p),output:Rs(m)};return ur(yu(b,(O)=>O(A),{concurrency:s,batching:c,discard:!0}),()=>I(A))})}return I({output:m,es:p})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return xn(e,bR);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([Zt(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Zt(u.parameter,t),Zt(u.type,t),u.parameter]),a=on.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>Zi(u)?new ym(u):new Na(u)))),s=Zt(a,t),c=Ob(e),l=Cb(e);return(u,d)=>{if(!ag(u))return ie(new Kn(e,u));let p=d?.errors==="all",f=[],m=0,y=d?.onExcessProperty==="error",g=d?.onExcessProperty==="preserve",_={},I;if(y||g){I=Reflect.ownKeys(u);for(let v of I){let w=s(v,d);if(Sn(w)&&Fe(w))if(y){let k=new Ot(v,u,new Eb(u[v],`is unexpected, expected: ${String(a)}`));if(p){f.push([m++,k]);continue}else return ie(new Xe(e,u,k,_))}else _[v]=u[v]}}let b=void 0,A=d?.exact===!0;for(let v=0;v<n.length;v++){let w=n[v][1],k=w.name,P=Object.prototype.hasOwnProperty.call(u,k);if(!P){if(w.isOptional)continue;else if(A){let Ie=new Ot(k,u,new uc(w));if(p){f.push([m++,Ie]);continue}else return ie(new Xe(e,u,Ie,_))}}let L=n[v][0],j=L(u[k],d);if(Sn(j)){if(Fe(j)){let Ie=new Ot(k,u,P?j.left:new uc(w));if(p){f.push([m++,Ie]);continue}else return ie(new Xe(e,u,Ie,_))}_[k]=j.right}else{let Ie=m++,ft=k;if(!b)b=[];b.push(({es:It,output:wn})=>ur(Ma(j),(Je)=>{if(Fe(Je)){let bt=new Ot(ft,u,P?Je.left:new uc(w));if(p)return It.push([Ie,bt]),An;else return ie(new Xe(e,u,bt,wn))}return wn[ft]=Je.right,An}))}}for(let v=0;v<i.length;v++){let w=i[v],k=w[0],P=w[1],L=jS(u,w[2]);for(let j of L){let Ie=k(j,d);if(Sn(Ie)&&At(Ie)){let ft=P(u[j],d);if(Sn(ft)){if(Fe(ft)){let It=new Ot(j,u,ft.left);if(p){f.push([m++,It]);continue}else return ie(new Xe(e,u,It,_))}else if(!Object.prototype.hasOwnProperty.call(r,j))_[j]=ft.right}else{let It=m++,wn=j;if(!b)b=[];b.push(({es:Je,output:bt})=>ur(Ma(ft),(Lt)=>{if(Fe(Lt)){let eo=new Ot(wn,u,Lt.left);if(p)return Je.push([It,eo]),An;else return ie(new Xe(e,u,eo,bt))}else{if(!Object.prototype.hasOwnProperty.call(r,j))bt[j]=Lt.right;return An}}))}}}}let O=({es:v,output:w})=>{if(Zo(v))return ie(new Xe(e,u,pr(v),w));if(d?.propertyOrder==="original"){let k=I||Reflect.ownKeys(u);for(let L of o)if(k.indexOf(L)===-1)k.push(L);let P={};for(let L of k)if(Object.prototype.hasOwnProperty.call(w,L))P[L]=w[L];return ce(P)}return ce(w)};if(b&&b.length>0){let v=b;return xu(()=>{let w={es:Rs(f),output:Object.assign({},_)};return ur(yu(v,(k)=>k(w),{concurrency:c,batching:l,discard:!0}),()=>O(w))})}return O({es:f,output:_})}}case"Union":{let n=_M(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],Zt(e.types[l],t));let s=Ob(e)??1,c=Cb(e);return(l,u)=>{let d=[],p=0,f=[];if(o>0)if(sl(l))for(let g=0;g<o;g++){let _=r[g],I=n.keys[_].buckets;if(Object.prototype.hasOwnProperty.call(l,_)){let b=String(l[_]);if(Object.prototype.hasOwnProperty.call(I,b))f=f.concat(I[b]);else{let{candidates:A,literals:O}=n.keys[_],v=on.make(O),w=A.length===i?new Hr([new Tt(_,v,!1,!0)],[]):on.make(A);d.push([p++,new Xe(w,l,new Ot(_,l,new Kn(v,l[_])))])}}else{let{candidates:b,literals:A}=n.keys[_],O=new Tt(_,on.make(A),!1,!0),v=b.length===i?new Hr([O],[]):on.make(b);d.push([p++,new Xe(v,l,new Ot(_,l,new uc(O)))])}}else{let g=n.candidates.length===i?e:on.make(n.candidates);d.push([p++,new Kn(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 _=f[g],I=a.get(_)(l,u);if(Sn(I)&&(!m||m.length===0))if(At(I))return I;else d.push([p++,I.left]);else{let b=p++;if(!m)m=[];m.push((A)=>xu(()=>{if("finalResult"in A)return An;else return ur(Ma(I),(O)=>{if(At(O))A.finalResult=O;else A.es.push([b,O.left]);return An})}))}}let y=(g)=>Zo(g)?g.length===1&&g[0][1]._tag==="Type"?ie(g[0][1]):ie(new Xe(e,l,pr(g))):ie(new Kn(e,l));if(m&&m.length>0){let g=m;return xu(()=>{let _={es:Rs(d)};return ur(yu(g,(I)=>I(_),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in _)return _.finalResult;return y(_.es)})})}return y(d)}}case"Suspend":{let n=Su(()=>Zt(e.f(),t));return(r,o)=>n()(r,o)}}},xn=(e,t)=>(n)=>t(n)?ce(n):ie(new Kn(e,n)),Cu=(e,t)=>{switch(e._tag){case"Declaration":{let n=mb(e);if(De(n))return Cu(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?Rm(o.type):Rt(o.type);if(gm(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?Rm(o.type):Rt(o.type);if(gm(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return Cu(e.from,t);case"Suspend":return Cu(e.f(),t);case"Transformation":return Cu(t?e.from:e.to,t)}return[]},_M=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=Cu(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}},wM=(e)=>Tu(e)?wM(e.from):e,Eu=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(Sn(e))return e;let o=new cu,i=lP(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(sI(a))return ce(a.value);let s=a.cause;if(QC(s))return ie(s.error);return ie(new kb(t,n,eE(s)))}return ie(new kb(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,RH=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return ce;case"TypeLiteralTransformation":return(n)=>{let r=ce(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=fr(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}),ku,TH=(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},OH=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},CH=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},RM=(e)=>("ast"in e)?Y(e.ast):B(),Ib,EH=(e)=>RM(e).pipe(tr(PP),ct({onNone:()=>Ib,onSome:(t)=>{let n=t(e);if(qt(n))return ce({message:n,override:!1});if(aP(n))return um(n,(r)=>({message:r,override:!1}));if(qt(n.message))return ce({message:n.message,override:n.override});return um(n.message,(r)=>({message:r,override:n.override}))}})),Pb=(e)=>(t)=>t._tag===e,TM,pM,fM,Iu=(e)=>Mo(EH(e),(t)=>{if(t!==void 0)return!t.override&&(TM(e)||pM(e)&&e.kind==="From"||fM(e)&&e.kind!=="Transformation")?fM(e)||pM(e)?Iu(e.issue):Ib:ce(t.message);return Ib}),OM=(e)=>RM(e).pipe(tr(LP),GR((t)=>t(e)),hn),AH=(e)=>fr(Iu(e),(t)=>t??OM(e)??IH(e)),Tm=(e)=>OM(e)??String(e.ast),PH=(e)=>e.message??"is forbidden",MH=(e)=>e.message??"is unexpected",NH=(e)=>{let t=MP(e.ast);if(De(t)){let n=t.value();return qt(n)?ce(n):n}return ce(e.message??"is missing")},dc=(e)=>{switch(e._tag){case"Type":return fr(AH(e),an);case"Forbidden":return ce(an(Tm(e),[an(PH(e))]));case"Unexpected":return ce(an(MH(e)));case"Missing":return fr(NH(e),an);case"Transformation":return Mo(Iu(e),(t)=>{if(t!==void 0)return ce(an(t));return fr(dc(e.issue),(n)=>an(Tm(e),[an(OH(e.kind),[n])]))});case"Refinement":return Mo(Iu(e),(t)=>{if(t!==void 0)return ce(an(t));return fr(dc(e.issue),(n)=>an(Tm(e),[an(CH(e.kind),[n])]))});case"Pointer":return fr(dc(e.issue),(t)=>an(dm(e.path),[t]));case"Composite":return Mo(Iu(e),(t)=>{if(t!==void 0)return ce(an(t));let n=Tm(e);return HS(e.issues)?fr(yu(e.issues,dc),(r)=>an(n,r)):fr(dc(e.issues),(r)=>an(n,[r]))})}};var CM=S(()=>{tt();tE();WE();dP();mn();cI();ee();et();bu();lt();Ee();Jf();Tb();dM=Symbol.for("effect/Schema/ParseErrorTypeId");mM=class mM extends VE("ParseError"){[dM]=dM;get message(){return this.toString()}toString(){return ku.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[de](){return this.toJSON()}};hM=ce,gM=ie,Sn=wg,Mo=h(2,(e,t)=>Sn(e)?xl(e,{onLeft:ie,onRight:t}):ur(e,t)),fr=h(2,(e,t)=>Sn(e)?HR(e,t):um(e,t)),Em=h(2,(e,t)=>Sn(e)?Xd(e,t):cP(e,t)),yM=h(2,(e,t)=>Sn(e)?xl(e,{onLeft:t,onRight:ce}):sP(e,t)),bH=te(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),_H=te(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);ku={formatIssue:(e)=>fr(dc(e),TH),formatIssueSync:(e)=>{let t=ku.formatIssue(e);return Sn(t)?VR(t):uP(t)},formatError:(e)=>ku.formatIssue(e.issue),formatErrorSync:(e)=>ku.formatIssueSync(e.issue)},Ib=ce(void 0),TM=Pb("Composite"),pM=Pb("Refinement"),fM=Pb("Transformation")});var EM,kM;var IM=S(()=>{ee();Ee();EM=h((e)=>rn(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),kM=h((e)=>rn(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function Ht(e){return class{[Au]=AM;static ast=e;static annotations(n){return Ht(Br(this.ast,n))}static pipe(){return F(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Au]=AM}}function DH(e){return _m(e)?on.make(iM(e,(t)=>new Na(t))):new Na(e[0])}function qM(e,t=DH(e)){return class extends Ht(t){static annotations(r){return qM(this.literals,Br(this.ast,r))}static literals=[...e]}}function E(...e){return Me(e)?qM(e):Fb}function Nb(e,t){return class extends Ht(t){static annotations(r){return Nb(this.typeParameters,Br(this.ast,r))}static typeParameters=[...e]}}function UM(e,t=UH(e)){return class extends Ht(t){static annotations(r){return UM(this.members,Br(this.ast,r))}static members=[...e]}}function xe(...e){return _m(e)?UM(e):Me(e)?e[0]:Fb}function Im(e,t,n=HH(e,t)){return class extends Ht(n){static annotations(o){return Im(this.elements,this.rest,Br(this.ast,o))}static elements=[...e];static rest=[...t]}}function jM(...e){return Array.isArray(e[0])?Im(e[0],e.slice(1)):Im(e,[])}function HM(e,t){return class extends Im([],[e],t){static annotations(r){return HM(this.value,Br(this.ast,r))}static value=e}}class VM{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<${Mb(this.to.isOptional)}, ${this.to.type}, ${BH(this.from.fromKey)}, ${Mb(this.from.isOptional)}, ${this.from.type}>`}}function Ub(e,t,n=WH(e,t)){return class extends Ht(n){static annotations(o){return Ub(this.fields,this.records,Br(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=zH(e,{...o});return Vb(i)?a:km(this)(a)};static pick(...o){return T(EM(e,...o))}static omit(...o){return T(kM(e,...o))}}}function T(e,...t){return Ub(e,t)}function JM(e,t,n){return class extends Ub({},[{key:e,value:t}],n){static annotations(o){return JM(e,t,Br(this.ast,o))}static key=e;static value=t}}function GM(e,t){return class extends Ht(t){static annotations(r){return GM(this.from,Br(this.ast,r))}static make=(r,o)=>Vb(o)?r:km(this)(r);static from=e}}function YM(e,t,n){return class extends Ht(n){static annotations(o){return YM(this.from,this.filter,Br(this.ast,o))}static[KH]=e;static from=e;static filter=t;static make=(o,i)=>Vb(i)?o:km(this)(o)}}function We(e,t){return(n)=>{function r(i,a,s){return JH(e(i,a,s),s,i)}let o=new Ru(n.ast,r,Fa(t));return YM(n,r,o)}}function Vb(e){return Yi(e)?e:e?.disableValidation??!1}var Au,AM,PM,Fa=(e)=>{if(!e)return{};let t={...e};for(let n in PM)if(n in e){let r=PM[n];t[r]=e[n],delete t[n]}return t},Br=(e,t)=>Ou(e,Fa(t)),Am=(e,t)=>{let n=bM(e,t);return(r,o)=>Xd(n(r,o),Ab)},MM=(e)=>H(e,Au)&&rn(e[Au]),qH=(e,t,n)=>Nb(e,new sc(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(Ht)),(...r)=>t.encode(...r.map(Ht)),Fa(n))),$H=(e,t)=>{let n=()=>(o,i,a)=>e(o)?hM(o):gM(new Kn(a,o));return Nb([],new sc([],n,n,Fa(t)))},X=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return qH(n,r,o)}let e=arguments[0],t=arguments[1];return $H(e,t)},$M,Ct,Fb,Lb,D,bn,V,UH=(e)=>on.make(e.map((t)=>t.ast)),jH=(e)=>xe(e,$M),HH=(e,t)=>new vu(e.map((n)=>MM(n)?new vi(n.ast,!1):n.ast),t.map((n)=>MM(n)?new cc(n.ast):n.ast),!0),z=(e)=>HM(e),Mb=(e)=>e?'"?:"':'":"',Db,BM,BH=(e)=>{if(e===void 0)return"never";if(qt(e))return JSON.stringify(e);return String(e)},WM=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new Db(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new VM(e.from,new BM(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},zM,KM=(e)=>H(e,zM),qb,$b,R=(e)=>{let t=e.ast===xm||e.ast===Sm?xm:jH(e).ast;return new $b(new Db(t,!0,!0,{},void 0),e)},VH,WH=(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(KM(u)){let d=u.ast;switch(d._tag){case"PropertySignatureDeclaration":{let{type:p,isOptional:f,annotations:m}=d;i.push(new Tt(l,p,f,!0,VH(d))),a.push(new Tt(l,Rt(p),f,!0,m)),r.push(new Tt(l,p,f,!0,m));break}case"PropertySignatureTransformation":{let p=d.from.fromKey??l;i.push(new Tt(p,d.from.type,d.from.isOptional,!0,d.from.annotations)),a.push(new Tt(l,d.to.type,d.to.isOptional,!0,d.to.annotations)),s.push(new bb(p,l,d.decode,d.encode));break}}}else i.push(new Tt(l,u.ast,!1,!0)),a.push(new Tt(l,Rt(u.ast),!1,!0)),r.push(new Tt(l,u.ast,!1,!0))}if(Me(s)){let c=[],l=[];for(let u of t){let{indexSignatures:d,propertySignatures:p}=wb(u.key.ast,u.value.ast);p.forEach((f)=>{i.push(f),a.push(new Tt(f.name,Rt(f.type),f.isOptional,f.isReadonly,f.annotations))}),d.forEach((f)=>{c.push(f),l.push(new lc(f.parameter,Rt(f.type),f.isReadonly))})}return new Sb(new Hr(i,c,{[hm]:"Struct (Encoded side)"}),new Hr(a,l,{[hm]:"Struct (Type side)"}),new _b(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=wb(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new Hr(r,o)},zH=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&KM(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},Pm=(e)=>JM(e.key,e.value),Pu=(e,t)=>(n)=>{let r=ct(ub(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=Ou(n.ast,Fa({[GS]:r,...t}));return GM(n,o)},KH,NM=(e,t,n)=>{if(Yi(e))return e?B():Y(new Kn(t,n));if(qt(e))return Y(new Kn(t,n,e));if(e!==void 0){if("_tag"in e)return Y(e);let r=new Kn(t,n,e.message);return Y(Me(e.path)?new Ot(e.path,n,r):r)}return B()},JH=(e,t,n)=>{if(fP(e))return NM(e,t,n);if(Me(e)){let r=np(e,(o)=>NM(o,t,n));if(Me(r))return Y(r.length===1?r[0]:new Xe(t,n,r))}return B()},GH,jb=(e,t)=>(n)=>n.pipe(We((r)=>r.length<=e,{schemaId:GH,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),YH,pc=(e,t)=>(n)=>n.pipe(We((r)=>r.length>=e,{schemaId:YH,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),FM,Se=(e,t)=>(n)=>{let r=e.source;return n.pipe(We((o)=>(e.lastIndex=0,e.test(o)),{schemaId:FM,[FM]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},ZH,LM,XH,QH,Hb=(e,t)=>(n)=>n.pipe(We((r)=>r>e,{schemaId:QH,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),e1,ZM=(e,t)=>(n)=>n.pipe(We((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})),t1,Mm=(e)=>(t)=>t.pipe(We((n)=>Number.isSafeInteger(n),{schemaId:t1,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),Bb=(e)=>Hb(0,{title:"positive",...e}),Nm,n1,Vr=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(mP(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(We((o)=>o.length>=r,{schemaId:n1,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[lb]:!0,...t}))},DM,r1;var Ft=S(()=>{tt();mn();il();zS();CP();bu();lt();CM();Pe();Ee();Tb();IM();Au=Symbol.for("effect/Schema");AM={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},PM={typeConstructor:kP,schemaId:IP,message:YS,missingMessage:fm,identifier:mm,title:yn,description:Po,examples:ZS,default:XS,documentation:AP,jsonSchema:QS,arbitrary:eb,pretty:tb,equivalence:nb,concurrency:rb,batching:ob,parseIssueTitle:ib,parseOptions:ab,decodingFallback:sb};$M=class $M extends Ht(xm){};Ct=class Ct extends Ht($P){};Fb=class Fb extends Ht(Sm){};Lb=class Lb extends Ht(yb){};D=class D extends Ht(KP){};bn=class bn extends Ht(GP){};V=class V extends Ht(ZP){};Db=class Db extends vi{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=Mb(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};BM=class BM extends vi{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};zM=Symbol.for("effect/PropertySignature");qb=class qb{ast;[Au];[zM]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return F(this,arguments)}annotations(e){return new qb(WM(this.ast,Fa(e)))}toString(){return String(this.ast)}};$b=class $b extends qb{from;constructor(e,t){super(e);this.from=t}annotations(e){return new $b(WM(this.ast,Fa(e)),this.from)}};VH=vb([fm]);KH=Symbol.for("effect/SchemaId/Refine");GH=TP,YH=RP,FM=Symbol.for("effect/SchemaId/Pattern"),ZH=Symbol.for("effect/SchemaId/UUID"),LM=/^[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;XH=class XH extends D.pipe(Se(LM,{schemaId:ZH,identifier:"UUID",jsonSchema:{format:"uuid",pattern:LM.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};QH=_P,e1=wP,t1=vP;Nm=class Nm extends bn.pipe(Mm({identifier:"Int"})){};n1=OP,DM=bP;r1=class r1 extends X(Hd,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:DM,[DM]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>gR}){}});function Jn(e,t){return Am(e,o1)(t)}var o1;var fc=S(()=>{Ft();o1={onExcessProperty:"error"}});function nN(e){let t=Am(mc)(e);return At(t)?t.right:void 0}function Wb(e){return nN(e)!==void 0}function rN(e){return Wb(e)&&!e.includes("-")}function XM(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 i1(e){let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!rN(t))return!1;let[o,i,a,s]=n.split(".");return o==="dev"&&s===void 0&&XM(i)&&XM(a)}function Fm(e){let t=nN(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 Nu(e,t){let n=QM(e),r=QM(t),o=Mu(n.minor,r.minor);if(o!==0)return o;let i=Mu(n.patch,r.patch);if(i!==0)return i;return a1(n.suffix,r.suffix)}function Kb(e,t){let n=Fm(t);if(e!=="patch"&&e!=="minor"){if(!Wb(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 QM(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 Mu(e,t){let n=BigInt(e),r=BigInt(t);if(n<r)return-1;if(n>r)return 1;return 0}function a1(e,t){let n=eN(e),r=eN(t);if(n<r)return-1;if(n>r)return 1;if(e.kind==="numeric"&&t.kind==="numeric")return Mu(e.value,t.value);if(e.kind==="development"&&t.kind==="development"){let o=Mu(e.runNumber,t.runNumber);return o===0?Mu(e.runAttempt,t.runAttempt):o}return 0}function eN(e){if(e.kind==="development")return 0;if(e.kind==="base")return 1;return 2}var tN,mc,zb,oN,hc;var iN=S(()=>{mn();Ft();tN=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,mc=D.pipe(Se(tN));zb=D.pipe(We(rN));oN=D.pipe(We(i1)),hc=xe(mc,oN)});function Yb(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(Gb.includes(r)&&o==="openai-bundled"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:e};if(!cN(r)||!sN(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function mr(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(cN(n)&&sN(r))return`${n}@openai-curated`;if(Gb.includes(n)&&r==="openai-bundled")return`${n}@openai-bundled`;return}function Zb(e){let t=mr(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 sN(e){return aN.includes(e)}function cN(e){return Lm.includes(e)}function Xb(e,t){let n=t??Xt;return{browser_use:e?.browser_use??n.browser_use,computer_use:e?.computer_use??n.computer_use,sites:e?.sites??n.sites}}function gc(e,t=[]){let n=[...uN],r=new Set(n);for(let o of lN){if(!e[o])continue;for(let i of No[o].pluginIds)if(!r.has(i))r.add(i),n.push(i)}for(let o of t)if(!r.has(o))r.add(o),n.push(o);return n}var Fu,Jb,s1,c1,aN,Lm,Gb,Et,Ri,l1,u1,No,lN,d1,uN,p1,Xt;var Qb=S(()=>{Ft();Fu=E("browser_use","computer_use","frontend","security","sites"),Jb=E("browser_use","computer_use","sites"),s1=E("installed","disabled","missing","uncertain"),c1=E("healthy","missing","disabled","uncertain"),aN=Object.freeze(["openai-curated","openai-curated-remote"]),Lm=Object.freeze(["build-web-apps","codex-security"]),Gb=Object.freeze(["browser","computer-use","sites"]);Et=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),Ri=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([])}),l1=Ri.frontend,u1={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Et.frontend,semanticSkillIds:Object.freeze(Ri.frontend.map(({skillId:e})=>e)),applicability:Ri.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Et.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:Ri.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Et.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:Ri.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:["browser@openai-bundled"],defaultSelected:Et.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:Ri.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:Et.sites,migrationKey:"sites",semanticSkillIds:[],applicability:Ri.sites,ownership:"shared-preserve"}},No=Object.freeze(u1),lN=Object.freeze(["browser_use","computer_use","sites"]),d1=Object.freeze(["frontend","security"]),uN=Object.freeze([...No.frontend.pluginIds,...No.security.pluginIds]),p1=Object.freeze(["writing-instructions","babysit-ci"]),Xt=Object.freeze({browser_use:Et.browser_use,computer_use:Et.computer_use,sites:Et.sites})});function Wr(e){return T({identifier:E(e),label:D,requiresRootApproval:V})}function dN(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 pN(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var fN,f1,m1,e_,h1,mN,g1,y1,x1;var hN=S(()=>{Ft();fN=E("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"),f1=T({identifier:fN,label:D,requiresRootApproval:V});m1=T({localRepositoryEdit:Wr("local.repository.edit"),localRepositoryCheck:Wr("local.repository.check"),localRepositoryLint:Wr("local.repository.lint"),localRepositoryFormat:Wr("local.repository.format"),localRepositoryCommit:Wr("local.repository.commit"),externalRead:Wr("external.read"),specialistDispatch:Wr("specialist.dispatch"),versionControlServerMutation:Wr("vcs.server.mutation"),versionControlServerCiTrigger:Wr("vcs.server.ci-trigger"),unknownEffect:Wr("unknown.effect")}),e_={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}};Ir(e_);h1=E("never","root"),mN=Object.values(e_);g1=mN.filter((e)=>!e.requiresRootApproval),y1=mN.filter((e)=>e.requiresRootApproval),x1=Object.freeze({noRootApproval:`${pN(dN(g1))} actions do not require Root approval.`,rootApproval:`${pN(dN(y1))} require Root approval.`})});function Dm(e){let t=Jn(S1,e);if(Fe(t))return Gi(Qc("sha256 digest",t.left));return ms(t.right)}var hr,t_,q9,$9,U9,S1,b1,_1,w1,v1;var qm=S(()=>{mn();Ft();hs();fc();hr=D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),t_=D.pipe(Se(/^[0-9a-f]{64}$/u)),q9=hr.pipe(Pu("RunId")),$9=hr.pipe(Pu("ProjectId")),U9=hr.pipe(Pu("TrustId")),S1=t_.pipe(Pu("Sha256Digest"));b1=T({run_id:hr,objective_lineage:hr,parent_run_id:R(xe(hr,Ct))}),_1=T({project_id:hr,trust_id:hr,trust_digest:t_}),w1=T({project_id:hr,project_digest:t_}),v1=D.pipe(Se(/^state-[0-9]+\.[0-9]+$/u))});function Um(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 SN(e){return typeof e==="string"&&E1.has(e)}function I1(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!SN(t)||typeof n!=="string")return!1;return Du.get(t)?.tasks.some((r)=>r.name===n)===!0}function jm(e,t){return typeof t==="string"&&Du.get(e)?.tasks.some((n)=>n.name===t)===!0}function bN(e){return typeof e==="string"&&k1.has(e)}function i_(e){let t=`${e.role}.${e.task}`;if(!r_.has(t))throw Error("Unknown native specialist agent type.");return t}function a_(e){let t=Du.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return e.role==="Librarian"?`${T1} ${t.instruction}`:t.instruction}function s_(e){let t=Du.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function wN(e){let t=Du.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function c_(e){let n=wN(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 zr,gN,gr,Lo,R1,Lu="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.",Fo="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",T1="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.",O1,yN,C1,Do,Du,E1,n_,k1,xN,r_,o_,A1,P1,M1,N1,qu,La,_N,Kr,F1,Hm,vN,$m,L1,D1,q1,l_,$u,$1,Ti,U1,j1,K;var Uu=S(()=>{Ft();zr=E("low","default","high"),gN=E("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),gr=xe(zr,gN);Lo=E("standard","fast","fast-all"),R1=E("low","medium","high","xhigh","max"),O1=E("none"),yN=Object.freeze(["implementation","review","validation","integration","vcs"]),C1=E("read-only","workspace-write"),Do=[{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. ${Fo}`,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. ${Fo}`,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. ${Fo}`,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. ${Fo}`,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. ${Fo}`,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:`Observe the assigned CI or release gate for the Root-supplied exact ref or SHA until it reaches a terminal state; report the matching result and failure evidence. ${Fo}`,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. ${Fo}`,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:"plan",description:"Adversarial implementation-plan review specialist.",instruction:`Adversarially inspect the assigned implementation plan for missing requirements, invalid assumptions, unsafe ordering, unowned seams, and inadequate proof. Return actionable plan findings or a fixed-point verdict; do not implement the plan. ${Fo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{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}}];Ir(Do);Du=new Map(Do.map((e)=>[e.role,e])),E1=new Set(Do.map((e)=>e.role)),n_=Do.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),k1=new Set(n_),xN=n_.map((e)=>e.replace(":",".")),r_=new Set(xN);o_=X(SN),A1=X((e)=>jm("Explorer",e)),P1=X((e)=>jm("Librarian",e)),M1=X((e)=>jm("Worker",e)),N1=X((e)=>jm("Reviewer",e)),qu=X(I1),La=Object.freeze(n_.filter((e)=>bN(e))),_N=X(bN),Kr=Object.freeze(xN.filter((e)=>r_.has(e))),F1=X((e)=>typeof e==="string"&&r_.has(e)),Hm=Object.freeze(["worker","explorer","reviewer","librarian"]);vN=T({profile:zr,service_tier:R(Lo)}),$m=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects"]),L1=E(...$m),D1=E("delegated","root_direct","unavailable"),q1=E(...$m),l_=E("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),$u=Object.freeze({rule:"Use the smallest meaningful proof proportionate to changed behavior, scope, and risk, plus repository-required gates. Avoid redundant equivalent checks and speculative edge-case tests.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),$1=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}),Ti=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnInspectionImplementationAndRenderedAcceptance:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["specialist_implements","specialist_renders_and_interacts","specialist_judges_current_result","root_accepts_terminal_evidence","root_assigns_discrepancies","specialist_repairs","root_rerenders_and_retests"])}),U1=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),j1=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),K=Object.freeze({requiresDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:Kr,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:Hm,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:$m,rootOwnedAuthority:$m,requestUserInputGates:Object.freeze(["plan_approval","installation_profile_approval","remote_origin_server_vcs_mutation","public_publication_or_release","ambiguity_or_missing_material_input"]),surgicalMutationRule:Lu,phaseOrder:yN,phaseGates:Object.freeze({implementationLeavesTerminalBeforeReviewerCode:!0,reviewerCodeFixedPointBeforeWorkerValidation:!0,workerValidationBeforeRootIntegration:!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,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:$u,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Qt(e,t){return new st("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function u_(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw Qt(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw Qt(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw Qt(t,"invalid number");return r}case"undefined":throw Qt(t,"undefined is not JSON");case"bigint":throw Qt(t,"bigint is not JSON");case"function":throw Qt(t,"function is not JSON");case"symbol":throw Qt(t,"symbol is not JSON");case"object":break}if(n.has(e))throw Qt(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw Qt(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 Qt(`${t}[${s}]`,"sparse or accessor array item");a.push(u_(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 Qt(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw Qt(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Qt(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw Qt(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 Qt(`${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 Qt(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${u_(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function Pn(e){return u_(e,"$",new Set)}function yr(e){return new TextEncoder().encode(Pn(e))}function RN(e,t){if(e.length===0||e.includes("\x00"))throw new st("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 st("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 B1(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function xr(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new st("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",V1(RN(e,t)));return B1(new Uint8Array(r))}function V1(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var d_=S(()=>{hs();qm()});function CN(e){try{return Pn(e)!==void 0}catch{return!1}}function Vm(e){let t=Jn(NN,e);if(Fe(t))return Gi(Qc("CLI envelope",t.left));return ms(t.right)}var TN,ON,EN,W1,z1,p_="holycodex-specialist-outcome-2",Vt,yc,ju,K1,J1,G1,Y1,Z1,X1,Bm,Q1,eB,tB,nB,rB,kN,IN,AN,oB,PN,MN,NN;var f_=S(()=>{mn();Ft();d_();Qb();hs();qm();Uu();fc();TN=E("blocked","completed","failed","partial"),ON=xe(E("high","max","xhigh"),Ct);EN=X((e)=>CN(e)),W1=X((e)=>ng(e)&&!Array.isArray(e)&&CN(e)),z1=T({blocked:V,changed_files:z(D),confidence:bn,context_owner:xe(D,Ct),material_findings:z(D),needs_more_context:V,needs_root_decision:V,needs_verification:V,relevant_files:z(D),remaining_risk:z(D),reuse_recommended:V,status:TN,suggested_followup:xe(D,Ct),suggested_luna_effort:ON,suggested_specialist:xe(o_,Ct),verification:z(D),verification_passed:V}),Vt=D.pipe(pc(1)),yc=T({state:l_,evidence:z(Vt).pipe(Vr(1)),library:R(Vt),version:R(Vt)}),ju={protocol_version:E(p_),route:qu,evidence:z(Vt),context7:R(yc)},K1=T(ju),J1=T({...ju,status:E("completed"),summary:Vt}),G1=T({...ju,status:E("blocked"),reason:Vt,needs_root_decision:V}),Y1=T({...ju,status:E("partial"),summary:Vt,completed:z(Vt),remaining:z(Vt),needs_root_decision:V}),Z1=T({...ju,status:E("failed"),error:Vt}),X1=xe(J1,G1,Y1,Z1),Bm={protocol_version:E(p_),capability:Fu,route:xe(qu,Ct),evidence:z(Vt),context7:R(yc),data:EN},Q1=T({...Bm,status:E("completed"),summary:Vt}),eB=T({...Bm,status:E("blocked"),reason:Vt,needs_root_decision:V}),tB=T({...Bm,status:E("partial"),summary:Vt,completed:z(Vt),remaining:z(Vt),needs_root_decision:V}),nB=T({...Bm,status:E("failed"),error:Vt}),rB=xe(Q1,eB,tB,nB),kN=z(D),IN=D.pipe(Se(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),AN=E(so),oB=T({code:hr,message:D,details:W1}),PN=T({schema_version:AN,ok:E(!0),command:IN,data:EN,warnings:kN}),MN=T({schema_version:AN,ok:E(!1),command:IN,error:oB,warnings:kN}),NN=xe(PN,MN)});function iB(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:Hu,effort:n}}function cB(e){let t=sB.get(e);if(t===void 0)throw new st("catalog_invalid","A profile has no route effort policy.",{profile:e});return Do.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new st("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return iB(n.role,r.name,i)}))}function m_(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:Hu,defaultServiceTier:"standard",routes:cB(e.name)}}function lB(e){let t=["low","default","high"];if(e.length!==t.length)throw new st("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 st("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=o==="high"?g_:h_,a=o==="low"?"medium":"high";if(r.root.model!==i||r.root.effort!==a||r.specialistModel!==Hu)throw new st("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==La.length)throw new st("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let c of r.routes){if(s.has(c.key)||!aB.has(c.key)||c.model!==Hu||`${c.role}:${c.task}`!==c.key)throw new st("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(c.key)}if(s.size!==La.length)throw new st("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<La.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||FN[i.effort]<r)throw new st("catalog_invalid","Profile route effort is not monotonic.",{route:La[n]??"unknown"});r=FN[i.effort]}}}function Jr(e){let t=Jn(zr,e);if(Fe(t))return Gi(new st("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=DN.get(t.right);if(!n)return Gi(new st("invalid_profile","Unknown profile selection.",{profile:t.right}));return ms(n)}var g_="gpt-6-astra",h_="gpt-6-sol",Hu="gpt-6-luna",aB,FN,y_,sB,x_,LN,DN,uB;var qN=S(()=>{mn();hs();Uu();fc();aB=new Set(La),FN={low:0,medium:1,high:2,xhigh:3,max:4},y_=[{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:plan":"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:plan":"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:plan":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];Ir(y_);sB=new Map(y_.map((e)=>[e.profile,e]));x_=[m_({name:"low",rootModel:h_,rootEffort:"medium"}),m_({name:"default",rootModel:h_,rootEffort:"high"}),m_({name:"high",rootModel:g_,rootEffort:"high"})];lB(x_);Ir(x_);LN=x_,DN=new Map,uB=new Map;for(let e of LN){DN.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 pB}from"child_process";import{promisify as fB}from"util";var UN="holycodex-intent-1",jN="holycodex-plan-1",HN="holycodex-assignment-1",Wm="toon-4",Q,Sr,zm,BN,xc,Gn,dt,dZ,S_,Da,b_,__,mB,$N,hB,gB,w_,VN,WN,Bu,v_,yB,xB,pZ,SB="holycodex-work-state-transaction-1",fZ,mZ,bB,_B,wB,vB,RB,TB,OB,CB,hZ,EB,gZ;var zN=S(()=>{Ft();f_();Uu();fc();Q=D.pipe(We((e)=>e.trim().length>0)),Sr=D.pipe(Se(/^[a-z0-9][a-z0-9-]{0,95}$/u)),zm=D.pipe(Se(/^[a-f0-9]{64}$/u)),BN=D.pipe(Se(/^[a-f0-9]{40}$/u)),xc=Nm.pipe(ZM(1)),Gn=D.pipe(We((e)=>!Number.isNaN(Date.parse(e)))),dt=z(Q),dZ=T({pid:Nm.pipe(Hb(0)),token:Q}),S_=T({role:E("Explorer","Librarian","Worker","Reviewer"),task:Q}).pipe(We((e)=>Do.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),Da=T({kind:E("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:Q,result:R(E("passed","failed","observed","unknown"))}),b_=T({root:Q,git_common_dir:Q,initial_head:Q,expected_head:Q,expected_changes:dt,expected_status_digest:zm,integrated_commit:R(BN),updated_at:Gn}),__=E("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),mB=E("scoping","ready","executing","verifying","reviewing"),$N=T({required:V,status:E("not_required","missing","passed","failed","accepted","rejected"),evidence:z(Da)}),hB=T({schema_version:E(UN),toon_compatibility:E(Wm),id:Sr,slug:Sr,title:Q,goal:Q,acceptance_criteria:dt,state:__,revision:xc,plan_required:V,active_plan_revision:R(xc),active_plan_digest:R(zm),blockers:dt,resume_state:R(mB),verification:$N,review:$N,acceptance_met:V,root_readiness:V,evidence:z(Da),baseline:b_,created_at:Gn,updated_at:Gn}),gB=T({schema_version:E(jN),toon_compatibility:E(Wm),intent_id:Sr,revision:xc,predecessor_digest:R(zm),approach:Q,scope:dt,exclusions:dt,assignments:dt,dependencies:dt,architecture:dt,risks:dt,assumptions:dt,open_questions:dt,verification:dt,recovery:dt,updated_at:Gn}),w_=E("completed","blocked","needs_root_input","failed"),VN=E("pending","executing","completed","blocked","needs_root_input","failed","superseded"),WN=T({id:Sr,outcome:w_,started_at:Gn,finished_at:Gn,summary:Q,evidence:z(Da),context7:R(yc),blocker:R(Q),remaining_risk:dt}),Bu=zm,v_={schema_version:E(HN),toon_compatibility:E(Wm),intent_id:Sr,id:Sr,objective:Q,owner:S_,scope:dt,constraints:dt,exclusions:dt,dependencies:dt,acceptance_criteria:dt,status:VN,revision:xc,invocations:z(WN),active_invocation_id:R(Q),active_started_at:R(Gn),supersedes:R(Sr),superseded_by:R(Sr),supersession_reason:R(Q),supersession_provenance:R(Q),evidence:z(Da),blocker:R(Q),remaining_risk:dt,created_at:Gn,updated_at:Gn},yB=T(v_),xB=T({...v_,capability:Bu}),pZ=T({...v_,active_invocation_capability_verifier:R(Bu),active_invocation_capability:R(Bu)}),fZ=T({schema_version:E(SB),state:E("prepared","committed"),files:z(T({path:Q,previous:D,next:D})).pipe(Vr(1))}),mZ=T({schema_version:E("holycodex-intent-0"),id:Sr,slug:Sr,title:Q,goal:Q,acceptance_criteria:dt,state:__,revision:xc,baseline:b_,created_at:Gn,updated_at:Gn}),bB=T({title:Q,goal:Q,acceptanceCriteria:z(Q).pipe(Vr(1)),planRequired:R(V),verificationRequired:R(V),reviewRequired:R(V)}),_B=T({approach:Q,scope:R(z(Q)),exclusions:R(z(Q)),assignments:R(z(Q)),dependencies:R(z(Q)),architecture:R(z(Q)),risks:R(z(Q)),assumptions:R(z(Q)),openQuestions:R(z(Q)),verification:R(z(Q)),recovery:R(z(Q))}),wB=T({id:R(Q),objective:Q,owner:S_,scope:z(Q).pipe(Vr(1)),constraints:R(z(Q)),exclusions:R(z(Q)),dependencies:R(z(Q)),acceptanceCriteria:z(Q).pipe(Vr(1))}),vB=T({scope:z(Q).pipe(Vr(1))}),RB=T({scope:R(z(Q).pipe(Vr(1)))}),TB=T({replacementId:Sr,replacementRevision:R(xc),reason:Q,provenance:Q}),OB=T({commit:BN}),CB=T({invocationId:R(Q),capability:R(Bu),outcome:w_,startedAt:R(Q),summary:Q,scope:R(z(Q).pipe(Vr(1))),evidence:R(z(Da)),context7:R(yc),blocker:R(Q),remainingRisk:R(z(Q))}),hZ=T({invocationId:Q,startedAt:Gn,interruptionReason:Q}),EB=T({evidence:R(z(Da)),verification:R(E("passed","failed")),review:R(E("accepted","rejected")),acceptanceMet:R(V),rootReadiness:R(V),clearBlockers:R(V)}),gZ=fB(pB)});var pt=S(()=>{hR();hs();fc();iN();Qb();hN();qm();Uu();f_();qN();d_();zN()});function ue(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ze(e){try{return Pn(e),!0}catch{return!1}}function UB(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 GN(e){return{ok:!1,error:e}}function YN(e){return{ok:!0,value:e}}function Mn(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 qa(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return Mn(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>qa(n,t+1));if(ue(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=Mn(r,96);if(i.length>0)n[i]=qa(o,t+1)}return n}return"[redacted]"}function ZN(e){let t=qa(e);return ue(t)?t:{value:t}}function Ke(e,t,n){return new oe("invalid_external_data",`Invalid ${e}.`,{field:e,received:qa(t)},n===void 0?void 0:{cause:n})}function Ue(e,t,n){let r=Jn(e,t);if(Fe(r))throw Ke(n,t,String(r.left));return r.right}function XN(e,t){try{return Ue(e,t,"value"),!0}catch{return!1}}var C_,Ku=1048576,E_=65536,Nn,Ci,dX,qo,$B,oe;var Gr=S(()=>{pt();mn();Ft();C_=so;Nn=X((e)=>ze(e)),Ci=X((e)=>ue(e)&&ze(e)),dX=D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),qo=D.pipe(We((e)=>e.length>0&&e.length<=4096)),$B=bn.pipe(We((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=UB(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var k_,Ju,Gu,I_,A_,P_,M_="turn/completed";var Jm=S(()=>{k_=["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"],Ju=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],Gu=["item/permissions/requestApproval"],I_=["mcpServer/elicitation/request"],A_=["item/tool/call"],P_={method:"initialized"}});function Sc(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)=>Sc(n,t));return ue(e)&&Object.values(e).every((n)=>Sc(n,t))}finally{t.delete(e)}}function Yr(e){return ue(e)&&Sc(e)}function N_(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('"')?HB(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Kr.includes(c))throw Ke("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 Ke("TOML key path",e);if(t.some((i)=>i==="__proto__"||i==="constructor"||i==="prototype"))throw Ke("TOML key path",e);return t}function HB(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Ke("TOML quoted key",e)}function he(e,t){if(!Yr(e))throw Ke("TOML document",e);let n=e;for(let r of N_(t)){if(!Yr(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function Gm(e){if(Array.isArray(e))return e.map(Gm);if(ue(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Gm(n)]));return e}function Ym(e){return Gm(e)}function ki(e,t,n){if(!Yr(e)||!Sc(n))throw Ke("TOML write",{keyPath:t});let r=N_(t),o={...Ym(e)},i=o;for(let a of r.slice(0,-1)){let s=i[a];if(s!==void 0&&!Yr(s))throw Ke("TOML table path",t);let c=s===void 0?{}:{...s};i[a]=c,i=c}return i[r.at(-1)]=Gm(n),o}function br(e,t){if(!Yr(e))throw Ke("TOML document",e);let n=N_(t),r={...Ym(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!Yr(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(Yr(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function Ua(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 Kr.some((t)=>e===`agents."${t}".config_file`)}function Zm(e){return Ua(e)||Ii.includes(e)}function Ei(e){return typeof e==="string"&&VB.test(e)}function F_(e){return e==="gpt-6-astra"||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 WB(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function L_(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function D_(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function q_(e){if(!ue(e)||!D_(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return F_(e.value);case"number":return L_(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&eh(e.value);case"digest":return WB(e.value);default:return!1}}function QN(e,t){switch(U_(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-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 o0(e){return ue(e)&&e.kind==="absent"?Object.keys(e).length===1:q_(e)}function i0(e){return ue(e)&&D_(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Ei(e.schema)&&Ei(e.installId)&&Zm(e.keyPath)&&o0(e.originalValue)&&q_(e.lastManagedValue)&&QN(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||QN(e.keyPath,e.originalValue))}function bc(e){if(!ue(e)||!D_(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Ei(e.schema)||!Ei(e.installId)||!ue(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>Zm(t)&&i0(n)&&n.keyPath===t)}function Qm(e){if(!Ei(e.schema)||!Ei(e.installId))throw Ke("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 $_(e){if(!eh(e))throw Ke("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function ja(e,t){let n=$_(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 U_(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"||Ii.includes(e)||e==="sandbox_workspace_write.network_access")return"boolean";return"enum"}function zB(e,t){let n=U_(e);if(n==="number")return L_(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-sol"||t==="gpt-6-luna";return typeof t==="string"&&F_(t)}async function sn(e,t){if(!Zm(e)||!Sc(t))throw Ke("managed config value",{keyPath:e});let n=U_(e);if(n==="number"&&L_(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:$_(t)};if(n==="enum"&&typeof t==="string"&&F_(t))return{kind:n,value:t};return{kind:"digest",value:await xr("holycodex-managed-config-value",[yr({keyPath:e,value:t})])}}function KB(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function _c(e,t,n,r){if(!Yr(e)||!bc(t)||!Ei(r.schema)||!Ei(r.installId))throw Ke("managed runtime config",{});let o={...t.managed},i=Ym(e),a=[];for(let[c,l]of Object.entries(n)){if(!Ua(c)||typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Ke("managed config key",c);let u=c,d=t.managed[u],p=he(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(!zB(u,l))throw Ke("managed config value",{keyPath:u});i=ki(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(!bc(s))throw Ke("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function _r(e,t,n){if(!Yr(e)||!bc(t))throw Ke("managed runtime config",{});let r=Ym(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!Zm(c))throw Ke("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=he(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=br(r,u),i.push(u),delete o[u];else{let f=KB(l.originalValue);if(f===void 0){s.push(u),a.push(u);continue}r=ki(r,u,f),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function Ha(e,t,n){if(!Ua(n)||!bc(t))throw Ke("managed config key",n);let r=t.managed[n],o=he(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 jB,$a,e0,Ii,BB,t0,n0,r0,Xm,VB;var th=S(()=>{pt();pt();Ft();Gr();jB=X((e)=>Sc(e)),$a=X((e)=>Yr(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"],Ii=["model_auto_compact_token_limit","features.context_management"],BB=X((e)=>Ua(e));t0=X((e)=>q_(e)),n0=X((e)=>o0(e)),r0=X((e)=>i0(e)),Xm=X((e)=>bc(e)),VB=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function GB(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function a0(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)=>GB(e[i]))}function l0(e){if(!ue(e)||!ze(e))return!1;return a0(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||a0(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function nh(e){return ue(e)&&ze(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function u0(e){return ue(e)&&ze(e)&&nh(e.thread)}function XB(e){return ue(e)&&ze(e)&&typeof e.id==="string"}function Ai(e){return ue(e)&&ze(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function d0(e){return ue(e)&&ze(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||l0(e.usage))}function QB(e){return ue(e)&&ze(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>ue(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>ue(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(Gu.some((t)=>t===e))return"permissions";if(Ju.some((t)=>t===e))return"approval";if(I_.some((t)=>t===e))return"elicitation";if(A_.some((t)=>t===e))return"dynamic_tool";return"other"}var s0,Yu,c0,Zu,JB,j_,Xu,YB,rh,H_,B_,ZB,Qu,V_,W_,z_,K_,J_,G_,Y_,Z_,X_,Q_,ew,tw,nw,rw,ow,iw,aw,sw,cw,lw,uw,dw,pw,fw,mw,hw,gw,yw,_X,eV,wX;var xw=S(()=>{Ft();Gr();Jm();th();s0=D.pipe(Se(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),Yu=xe(D.pipe(pc(1)),bn.pipe(We((e)=>Number.isSafeInteger(e)))),c0=T({code:bn.pipe(We((e)=>Number.isSafeInteger(e))),message:D,data:R(Nn)}),Zu=xe(T({id:Yu,result:Nn}),T({id:Yu,error:c0})),JB=T({id:Yu,error:c0}),j_=T({method:s0,params:R(Nn)}),Xu=T({id:Yu,method:s0,params:R(Nn),trace:R(Nn)});YB=X(l0),rh=T({clientInfo:T({name:qo,version:qo,title:xe(qo,Ct)}),capabilities:xe(T({experimentalApi:V,requestAttestation:V,mcpServerOpenaiFormElicitation:R(V),optOutNotificationMethods:R(xe(z(D),Ct)),extensions:R(Ci)}),Ct)}),H_=X((e)=>ue(e)&&ze(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),B_=T({method:E("initialized")});ZB=X(nh);Qu=X((e)=>u0(e)||XB(e)),V_=Qu,W_=Qu,z_=X(Ai),K_=X((e)=>ue(e)&&ze(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),J_=X((e)=>u0(e)),G_=X((e)=>{if(!ue(e)||!ze(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>nh(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>nh(r));return t&&e.threads===void 0||n&&e.data===void 0}),Y_=X((e)=>ue(e)&&ze(e));Z_=X(Ai),X_=X(Ai),Q_=X(Ai),ew=X((e)=>ue(e)&&ze(e));tw=X((e)=>Ai(e)&&(Array.isArray(e.input)&&e.input.every((t)=>ze(t))||typeof e.prompt==="string"&&e.prompt.length>0)),nw=X((e)=>Ai(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>ze(t))),rw=X((e)=>ue(e)&&ze(e)&&(e.turn!==void 0&&d0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),ow=X((e)=>ue(e)&&ze(e)&&typeof e.turnId==="string"&&e.turnId.length>0),iw=X((e)=>Ai(e)&&typeof e.turnId==="string"&&e.turnId.length>0),aw=X((e)=>ue(e)&&ze(e)),sw=X((e)=>Ai(e)&&(e.turn!==void 0&&d0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),cw=X((e)=>ue(e)&&ze(e));lw=X((e)=>ue(e)&&ze(e)&&Array.isArray(e.data)&&e.data.every((t)=>QB(t))),uw=Ci,dw=Ci,pw=T({includeLayers:R(V),cwd:R(xe(D,Ct))}),fw=T({config:$a,origins:Ci,layers:xe(z(Ci),Ct)}),mw=Ci,hw=Ci,gw=X((e)=>ue(e)&&ze(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&ue(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),yw=Nn,_X=X((e)=>ue(e)&&ze(e)&&typeof e.kind==="string"&&typeof e.method==="string");eV=xe(E("stable","experimental","disabled"),V),wX=Pm({key:D,value:eV})});class oh{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??Ku,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=tV){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(rh,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",Y_,e,Qu)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",Z_,t,V_)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",X_,t,J_)}async listThreads(e={}){return this.action("thread/list",ew,e,G_)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",Q_,t,W_)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",z_,t,K_)}async startTurn(e){return this.action("turn/start",tw,e,rw)}async steerTurn(e){return this.action("turn/steer",nw,e,ow)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",iw,n,aw)}async listModels(e={}){return this.action("model/list",cw,e,lw)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",uw,e,dw)}async readConfig(e={}){return this.action("config/read",pw,e,fw)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",mw,e,hw)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Ue(rh,t,"initialize parameters"));return Ue(Nn,r,"initialize result")}let n=Ue(Xu,{id:1,method:e,params:t},"App Server method");if(!nV.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(Nn,e,"initialize parameters")),n=Ue(H_,t,"initialize result"),r=Ue(B_,P_,"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(Nn,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(j_,t);if(o!==void 0){this.handleNotification(o);return}throw Ke("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=oV(t.method);t.reject(new oe(r,`The App Server rejected ${t.method}: ${Mn(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:qa(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Ue(gw,{...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,Mn(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,Mn(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Ue(yw,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,Mn(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:rV(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===M_){let n=Ue(sw,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:ZN({params:qa(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 rV(e){let t=Mn(e);return t.length>0?t:"server request failed"}function oV(e){if(Gu.some((t)=>t===e))return"permission_denied";if(Ju.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var tV,nV;var Sw=S(()=>{Gr();Jm();xw();tV={clientInfo:{name:"holycodex",title:null,version:C_},capabilities:null},nV=new Set(k_)});import{isAbsolute as iV}from"path";function Pi(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 bw(e=process.env){return Object.freeze(Pi(e))}async function ih(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 ah(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 wc(e){return Mn(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}class sh{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!iV(e.executablePath))throw new oe("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??Ku,this.maxDiagnosticBytes=e.maxDiagnosticBytes??E_,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:Pi(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 ih(this.stderrStream,this.maxDiagnosticBytes),t=ah(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=wc(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var ch=S(()=>{Gr()});import{lstat as PX,mkdir as MX,readFile as aV,readdir as NX,realpath as sV,stat as cV}from"fs/promises";import{delimiter as lV,isAbsolute as LX,join as DX,relative as qX,resolve as f0}from"path";async function dV(e){let t=[];if(e.executablePath!==void 0)t.push(f0(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(lV).filter((i)=>i.length>0))for(let i of r)t.push(f0(o,i))}for(let n of t)try{let r=await cV(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await sV(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 pV(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 mV(Promise.all([ih(n.stdout,16384),ih(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=Mn(ah(r,"Codex version output"));if(i!==0||a.length===0){let s=wc(ah(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 fV(e){let t=await aV(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=Dm(r);if(!o.ok)throw new oe("discovery_failed","The Codex executable digest was invalid.");return o.value}async function _w(e={}){let t=await dV(e),n=Pi(e.environment),r=e.versionRunner?Mn(await e.versionRunner(t,n)):await pV(t,n);if(r.length===0)throw new oe("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await fV(t)}}async function mV(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))},uV)})])}finally{if(r!==void 0)clearTimeout(r)}}var uV=30000,HX;var m0=S(()=>{pt();Ft();Gr();ch();HX=T({exitCode:bn.pipe(We((e)=>Number.isSafeInteger(e))),stdout:D.pipe(jb(1048576)),stderr:D.pipe(jb(1048576))})});var hV="packages/codex/generated",gV,yV,ww,zX,KX;var h0=S(()=>{pt();Ft();Gr();gV=/^codex-cli \d+\.\d+\.\d+$/u,yV=/^codex-app-server-\d+\.\d+\.\d+$/u,ww=D.pipe(Se(/^[a-f0-9]{64}$/u)),zX=T({schema_version:E("holycodex-generated-v2"),artifact_root:E(hV),codex_cli_version:D.pipe(Se(gV)),codex_cli_digest:ww,protocol_epoch:D.pipe(Se(yV)),generator:T({command:jM(E("app-server"),E("generate-ts")),supported_surface:E("codex app-server generators")}),typescript_root:E("typescript"),files:T({count:bn.pipe(Mm(),Bb()),digest:ww})}),KX=T({path:D.pipe(pc(1)),size:bn.pipe(Mm(),Bb()),sha256:ww})});var xV;var g0=S(()=>{Ft();th();xV=T({owner:E("holycodex"),schema:D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});import{spawn as SV}from"child_process";import{lstat as Ni,mkdir as bV,mkdtemp as _V,readFile as wV,readdir as vV,realpath as vw,rename as RV,rm as TV,stat as QX}from"fs/promises";import{dirname as S0,isAbsolute as kw,join as Mi,relative as b0,resolve as lh,sep as _0}from"path";async function v0(e){let t=Nw(e.selectedPluginIds);if(t.length===0)return;if(C0(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new ge("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>Mw(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&dh(r,t))return r;let o=e.initializeRuntime??(()=>LV(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??Pw,c=e.pollIntervalMs??OV,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new ge("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&dh(u,t))return u;let d=s-(Date.now()-l);if(d<=0)break;await(e.sleep??qV)(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 ge&&s.code==="cancelled")throw s;a=s instanceof ge?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 R0({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 ge)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 R0(e){let t=Nw(e.selectedPluginIds);if(t.length===0)throw se("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(C0(e.timeoutMs,void 0),!kw(e.codexHome))throw se("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new ge("cancelled","Official Codex marketplace fallback was cancelled.");let n=Pi(e.environment),r=e.gitRunner??I0("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??Pw,i;try{i=await kV(r,o,e.signal)}catch(u){if(u instanceof ge)throw u;throw se("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,Aw[1]);if(await AV(a,e.codexHome),await Ni(s).catch((u)=>{if(rd(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 _V(Mi(a,".openai-plugins-stage-"));try{if(await Tw(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(Ba,l)}catch(m){if(DV(m))throw se("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",Ba,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await uh(l);let u=await T0(l,e.codexHome,t);if(u===void 0||!dh(u,t))throw se("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await IV(r,l,o,e.signal)!==i)throw se("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Ni(s).catch((m)=>{if(rd(m))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await RV(l,s);let f=await Mw(e.codexHome,e.selectedPluginIds);if(f===void 0||!dh(f,t))throw se("marketplace_invalid","The published official marketplace failed validation.");return f}catch(u){if(u instanceof ge)throw u;throw se("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await TV(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function kV(e,t,n){let r=await e.run(["ls-remote",Ba,"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 IV(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 AV(e,t){await Rw(t,e),await bV(e,{recursive:!0}),await Rw(t,e)}async function Rw(e,t){let n=lh(e),r=lh(t);while(!0){if((await Ni(r).catch((a)=>{if(rd(a))return;throw a}))?.isSymbolicLink())throw se("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=S0(r);if(i===r||i!==n&&!PV(n,i))throw se("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function PV(e,t){let n=b0(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${_0}`)&&!kw(n)}async function uh(e){let t=await Ni(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 vV(e,{withFileTypes:!0});for(let r of n){let o=Mi(e,r.name),i=await Ni(o);if(i.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await uh(o)}}async function Mw(e,t=[]){return await T0(Mi(e,...Aw),e,Nw(t))}async function T0(e,t,n=[]){if(t!==void 0)await Rw(t,e);let r=await Ni(e).catch((l)=>{if(rd(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 Tw(t,e);else await uh(e);if(t!==void 0)await uh(e);let o=await vw(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 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 Tw(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 wV(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=`${Aw.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!ue(e)||e.name!==nd)throw se("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");MV(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(!ue(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=NV(s);if(!FV(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:nd,source:Ba,rootPath:t,manifestPath:n,plugins:i}}function MV(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:ue(n)&&typeof n.url==="string"?n.url:void 0)!==Ba)throw se("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function NV(e){let t=e.source;if(typeof t==="string")return t;if(ue(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function FV(e){if(e===void 0||e.length===0||kw(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 Nw(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 se("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!E0(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function dh(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 LV(e){let t=Pi(e.environment),n;try{n=new sh({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new oh(n,{requestTimeoutMs:Math.min(e.timeoutMs??Pw,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 C0(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 Tw(e,t){let n=await vw(e),r=await vw(t),o=b0(n,r);if(o===""||o===".."||o.startsWith(`..${_0}`))throw se("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=lh(e),a=lh(t);while(!0){if((await Ni(a)).isSymbolicLink())throw se("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=S0(a);if(c===a)throw se("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 DV(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function qV(e){await new Promise((t)=>setTimeout(t,e))}function se(e,t,n){return new ge(e,t,n instanceof Error?{cause:wc(n.message)}:{})}function Zr(e,t){let n=mr(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=Yb(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 E0(e){return Lm.includes(e)}function k0(e){if(!XN(Cw,e))return GN(Ke("live official plugin list",e));return YN(Ue(Cw,e,"live official plugin list"))}function ph(e){let t=e.runner??I0(e.executable,{environment:e.environment??Pi(),...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 Rc("list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new ge("command_failed","Codex returned invalid plugin data.")}let a=k0(i);if(!a.ok)throw new ge("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 Rc("marketplace list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new ge("command_failed","Codex returned invalid marketplace data.")}if(!ue(i)||!Array.isArray(i.marketplaces))throw new ge("command_failed","Codex returned an invalid marketplace list.");return i.marketplaces.map((a)=>{if(!ue(a)||typeof a.name!=="string"||typeof a.root!=="string")throw new ge("command_failed","Codex returned an invalid marketplace entry.");let s=a.marketplaceSource;if(s===void 0)return{name:a.name,root:a.root};if(!ue(s)||typeof s.sourceType!=="string"||typeof s.source!=="string")throw new ge("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 ge("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await v0({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(td,o,"plugin marketplace source");if(a===nd||a===Ba)throw new ge("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.");if(a!==Iw)throw new ge("marketplace_invalid",`Unsupported managed marketplace source: ${a}.`);let s=await r(),c=y0(s,vc);if(c!==void 0)throw new ge("marketplace_invalid",c);if(s.find((f)=>f.name===vc)===void 0){let f=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(f.exitCode!==0)throw Rc("marketplace add",f,a)}else{let f=await t.run(["plugin","marketplace","upgrade",vc],i===void 0?void 0:{signal:i});if(f.exitCode!==0)throw Rc("marketplace upgrade",f,vc)}let u=await r(),d=y0(u,vc);if(d!==void 0)throw new ge("marketplace_invalid",d);let p=u.find((f)=>f.name===vc);if(p===void 0||!Ew(p.marketplaceSource))throw new ge("readback_mismatch","Codex did not report the canonical HolyCodex marketplace after installation or refresh.")},add:async(o,i)=>{let a=Ue(td,o,"official plugin id"),s=await t.run(["plugin","add",a,"--json"],i===void 0?void 0:{signal:i});if(s.exitCode!==0)throw Rc("add",s,a);let c=await n(),l=Zr(c,a),u=mr(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 ge("readback_mismatch",`Codex did not report ${a} after installation.`,{plugin_id:a});if(!p.installed)throw new ge("plugin_missing",`Codex reported ${a} as unavailable after installation.`,{plugin_id:a});if(!p.enabled)throw new ge("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(td,o,"official plugin id"),s=a;if(mr(a)===a){let d=await n(),p=Zr(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 Rc("remove",c,s);let l=await n(),u=[...l.installed,...l.available].find((d)=>d.pluginId===s);if(u?.installed)throw new ge("readback_mismatch",`Codex still reports ${a} after removal.`,{plugin_id:a,observed_plugin_id:u.pluginId})}}}function Rc(e,t,n){let r=wc(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new ge("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function y0(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&&!Ew(n[0].marketplaceSource)){let o=n[0].marketplaceSource?.source??"an unknown source";return`Codex marketplace ${t} points to ${o}, not the canonical HolyCodex source ${Iw}; resolve the conflict before installing.`}let r=e.find((o)=>o.name!==t&&Ew(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 Ew(e){return e?.sourceType==="git"&&(e.source===Iw||e.source==="https://github.com/davidbasilefilho/holycodex.git"||e.source==="https://github.com/davidbasilefilho/holycodex")}function I0(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 ge("cancelled","The Codex plugin command was cancelled.");let r=SV(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=x0(r.stdout,n.stdoutLimit),i=x0(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 ge("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 ge("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 ge)throw d;throw new ge("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function x0(e,t){if(e===null)return Promise.reject(new ge("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 ge("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new ge("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",Ba="https://github.com/openai/plugins.git",vc="holycodex",Iw="davidbasilefilho/holycodex",Aw,Pw=30000,OV=100,w0,CV,ed,td,EV,$V,Ow,Cw,ge;var Fw=S(()=>{pt();Ft();Sw();Gr();ch();Aw=["plugins","openai-plugins"],w0=D.pipe(Se(/^[a-z][a-z0-9._-]{1,63}$/u)),CV=D.pipe(Se(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),ed=z(D),td=D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),EV=T({name:w0,version:CV,description:qo,author:R(Nn),license:R(qo),homepage:R(qo),repository:R(qo),keywords:R(ed),skills:R(ed),commands:R(ed),hooks:R(ed),assets:R(ed),official:R(V)});$V=T({id:w0,selected:E(!0)}),Ow=T({pluginId:td,installed:V,enabled:V,name:R(xe(D,Ct)),marketplaceName:R(xe(D,Ct)),version:R(xe(D,Ct))},Pm({key:D,value:Lb})),Cw=T({installed:z(Ow),available:z(Ow)});ge=class ge extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});var Tc=S(()=>{Gr();Gr();Jm();xw();Sw();ch();m0();h0();g0();th();Fw();Fw()});function _n(e){if(!Oc(e))throw Error("The value is not JSON serializable.");return Pn(e),e}function Oc(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)=>Oc(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>Oc(n,t))}finally{t.delete(e)}}var od=S(()=>{pt()});function ke(e,t){let n=Jn(e,t);return At(n)?n.right:void 0}function $0(e){return ke(id,e)!==void 0}var id,VQ,jV,HV,ad,BV,Fi,VV,WV,zV,P0,sd,mh,M0,cd,N0,en,Lw,KV,JV,GV,YV,ZV,XV,QV,eW,tW,fh,nW,A0,rW,hh,Cc,oW,Dw,iW,qw,aW,F0,$w,Uw,Li,L0,sW,D0,cW,q0;var Va=S(()=>{Tc();pt();mn();Ft();od();id=X((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&Oc(e)),VQ=X(Oc),jV=hc,HV=D.pipe(Se(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),ad=D.pipe(Se(/^[0-9a-f]{64}$/u)),BV=D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Fi=D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),VV=D.pipe(We((e)=>!Number.isNaN(Date.parse(e)))),WV=T({path:D.pipe(Se(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:ad}),zV=T({browser_use:V,computer_use:V,sites:V,coding:E(!0)}),P0=T({browser_use:R(V),computer_use:R(V),sites:R(V)}),sd=T({profile:R(zr),tier:R(Lo),optional:R(P0),officialPlugins:R(z(Fi))}),mh=sd,M0=E("keep","remove","replace","cancel"),cd=T({schema_version:E(1),profile:zr,tier:Lo,capabilities:z(Jb),additional_plugins:z(Fi)}),N0=T({schema_version:E(1),profile:zr,tier:Lo,capabilities:z(Fu),additional_plugins:z(Fi)}),en=T({selected:V,status:E("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:z(Fi),reason:R(D)}),Lw=T({browser_use:en,computer_use:en,frontend:en,security:en,sites:en}),KV=T({browser_use:R(V),computer_use:V,frontend:V,security:V,sites:R(V),coding:E(!0),work:V}),JV=T({browser_use:R(V),computer_use:R(V),frontend:R(V),security:R(V),sites:R(V),work:R(V)}),GV=T({browser_use:R(en),computer_use:en,frontend:en,security:en,sites:R(en),work:en}),YV=T({computer_use:V,frontend:V,security:V,coding:E(!0)}),ZV=T({computer_use:R(V),frontend:R(V),security:R(V)}),XV=T({computer_use:en,frontend:en,security:en}),QV=xe(T({status:E("not_applicable")}),T({status:E("missing")}),T({status:E("healthy"),path:D,installed:V})),eW=T({manager:E("bun","npm","pnpm"),launcher:E("bunx","npx","pnpm dlx"),version:HV,executable:D,ownership:E("user","holycodex"),identity:R(ad)}),tW=T({git_bash:QV,context7:R(eW)}),fh=T({presence:E("absent","present"),digest:ad,safe_value:R(xe(T({kind:E("boolean"),value:V}),T({kind:E("marketplace"),source_type:E("git"),source:E("https://github.com/davidbasilefilho/holycodex.git")})))}),nW=T({plugin_id:E("holycodex@holycodex"),before:T({preference:fh,marketplace:fh}),after:T({preference:fh,marketplace:fh})}),A0=T({presence:E("absent","present"),digest:ad,safe_value:R(T({kind:E("boolean"),value:V}))}),rW=T({plugin_id:Fi,before:A0,after:A0}),hh={owner:E("holycodex"),schema_epoch:E(Rn),install_id:BV,version:jV,digest:ad,profile:zr,tier:Lo,optional_selections:zV,explicit_optional_selections:P0,official_plugins:R(z(Fi)),capability_state:R(Lw),managed_artifacts:z(WV),installed_at:VV,status:R(E("active")),step:R(E("active")),managed_config:R(Xm),plugin_snapshot:R(z(T({plugin_id:Fi,status:E("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:R(nW),provider_config:R(z(rW)),owned_plugins:R(z(Fi)),tooling:R(tW)},Cc=T(hh),oW=(({profile:e,...t})=>t)(hh),Dw={...hh,optional_selections:KV,explicit_optional_selections:JV,capability_state:R(GV)},iW=(({profile:e,...t})=>t)(Dw),qw={...hh,optional_selections:YV,explicit_optional_selections:ZV,capability_state:R(XV)},aW=(({profile:e,...t})=>t)(qw),F0=xe(T({...Dw,profile:gr}),T({...iW,plan:gr}),T({...oW,plan:gr}),T({...qw,profile:gr}),T({...aW,plan:gr})),$w=E("preparing","conflicted"),Uw=E("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),Li=T({...Cc.fields,status:$w,step:Uw}),L0={...Dw,status:$w,step:Uw},sW=(({profile:e,...t})=>t)(L0),D0={...qw,status:$w,step:Uw},cW=(({profile:e,...t})=>t)(D0),q0=xe(Li,T({...L0,profile:gr}),T({...sW,plan:gr}),T({...D0,profile:gr}),T({...cW,plan:gr}))});import{lstat as lW,mkdir as uW}from"fs/promises";import{homedir as dW}from"os";import{dirname as pW,join as Di,posix as U0,resolve as fW,sep as j0,win32 as H0}from"path";function wr(e={},t=process.env){let n=dW(),r=e.paths?.codexHome??t.CODEX_HOME??Di(n,".codex"),o=Hw(r,"CODEX_HOME"),i=Di(o,mW);return{codexHome:o,stateRoot:i,activeRecord:Di(i,hW),preparingRecord:Di(i,gW),conflictedRecord:Di(i,yW),installOptions:Di(i,xW),roleRoot:Di(i,"agents"),configFile:Di(o,"config.toml")}}function Hw(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||bW(e))throw new Yn("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?H0:U0,o=jw(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new Yn("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":j0).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new Yn("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new Yn("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function bW(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function ld(e){Hw(e,"owned path"),await $o(e),await uW(e,{recursive:!0}),await $o(e)}async function $o(e){let n=fW(e);while(!0){try{if((await lW(n)).isSymbolicLink())throw new Yn("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof Yn)throw o;if(!it(o,"ENOENT"))throw o}let r=pW(n);if(r===n)break;n=r}}async function Wa(e){await $o(e)}function qi(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?H0:U0,o=r.resolve(jw(e,n)),i=r.resolve(jw(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":j0}`)&&a!==".."&&!r.isAbsolute(a)}function jw(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function it(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var mW="holycodex",hW="active.json",gW="preparing.json",yW="conflicted.json",xW="install.toml",SW,Yn;var za=S(()=>{pt();SW=Rn;Yn=class Yn extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as B0,open as _W,readFile as V0,rename as wW,unlink as vW,writeFile as RW}from"fs/promises";import{dirname as TW}from"path";async function W0(e){let t;try{t=await _W(e,"r"),await t.sync()}catch(n){if(!z0(n))throw n}finally{await t?.close().catch(()=>{return})}}async function CW(e){await W0(e).catch((t)=>{if(!z0(t))throw t})}async function Ja(e,t){await Fn(e,`${Pn(t)}
36
+ `)}async function Fn(e,t){let n=TW(e);await ld(n),await $o(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await RW(r,t,{encoding:"utf8",mode:384}),await W0(r),await wW(r,e),await CW(n)}catch(o){throw await vW(r).catch(()=>{return}),o}}async function EW(e,t){let n=await B0(e);if(!n.isFile()||n.isSymbolicLink())throw new Ka("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await V0(e,"utf8"))}catch(i){throw new Ka("state_corrupt","A persisted file is not valid JSON.",i)}let o=ke(t,r);if(o===void 0)throw new Ka("state_corrupt","A persisted file failed schema validation.");return o}async function Qe(e){try{let t=await B0(e);if(!t.isFile()||t.isSymbolicLink())throw new Ka("state_corrupt","A persisted file is not a regular file.");return await V0(e,"utf8")}catch(t){if(it(t,"ENOENT"))return;throw t}}async function Bw(e,t){try{return await EW(e,t)}catch(n){if(it(n,"ENOENT"))return;throw n}}function z0(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return OW.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var OW,Ka;var Ec=S(()=>{pt();za();Va();OW=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);Ka=class Ka extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as kW}from"fs/promises";import{dirname as IW,resolve as AW}from"path";import{fileURLToPath as PW}from"url";async function K0(e=Ga){let t=JSON.parse(await kW(e,"utf8")),n=ke(MW,t);if(n===void 0)throw new Uo("manifest_invalid","The public package manifest is invalid.");return n}async function kc(e=Ga){let t=(await K0(e)).version,n=ke(hc,t);if(n===void 0)throw new Uo("manifest_invalid","The public package manifest version is invalid.");return n}async function J0(e=Ga){let t=await kc(e),n=ke(mc,t);if(n===void 0)throw new Uo("manifest_invalid","The public package manifest must use a canonical stable release version.");return n}async function NW(e=Ga){let n=(await kc(e)).split("-",1)[0],r=ke(zb,n);if(r===void 0)throw new Uo("manifest_invalid","The public package manifest must use a canonical release base version.");return r}async function ud(e=Ga){return await kc(e)}async function Vw(e,t,n=Ga){let r=await K0(n),o=await J0(n),i=FW(e,o);if(!t)await Ja(n,{...r,version:i});return{previous:o,next:i}}function FW(e,t){if(e!=="patch"&&e!=="minor"){if(ke(mc,e)===void 0)throw new Uo("version_invalid","The version target is invalid.");return e}try{return Kb(e,t)}catch(n){throw new Uo("version_invalid",n instanceof Error?n.message:"The current version is invalid.")}}var MW,Ga,Uo;var dd=S(()=>{pt();Ft();Va();Ec();MW=X((e)=>$0(e)&&e.name==="holycodex"&&ke(hc,e.version)!==void 0),Ga=AW(IW(PW(import.meta.url)),"../package.json");Uo=class Uo extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as LW}from"crypto";import{lstat as Ww,readFile as zw,rm as gh}from"fs/promises";import{join as Wt,relative as G0}from"path";async function xh(e,t,n=[],r="standard",o,i={}){let a=Za(t,r,{...i,...o===void 0?{}:{windowsGitBashExecutable:o}}),s=Wt(e,"holycodex","agents",a),c=jo(t,r).map((d)=>({path:Wt(s,`${d.name}.toml`),contents:Ic(d,{...i,...o===void 0?{}:{windowsGitBashExecutable:o}})})),l=new Map(n.map((d)=>[Wt(e,d.path),d])),u=[];for(let d of c){let p=await Ya(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 tn(p)!==f.digest&&p!==d.contents)u.push(Zw(d.path,"replace",{present:!0,digest:await tn(p)},{present:!0,digest:await tn(d.contents)},"The managed native role file changed outside the previous HolyCodex transaction."))}return u}async function Y0(e,t){let n=Wt(e,"agents"),r=Wt(e,"holycodex","agents"),o=[];for(let i of t){let a=Wt(e,i.path);if(!qi(e,a)||!qi(n,a)&&!qi(r,a)&&a!==Wt(e,"config.toml"))continue;let s=await Ya(a);if(s!==void 0&&await tn(s)!==i.digest)o.push({...Zw(a,"remove",{present:!0,digest:await tn(s)},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}return o}function jo(e,t="standard"){let n=Jr(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:i_(o),description:s_(o),taskInstruction:a_(o),permissions:c_(o),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function Za(e,t="standard",n={}){let r=jo(e,t).map((o)=>`${o.name}\x00${Ic(o,n)}`).join("\x00");return LW("sha256").update(r).digest("hex").slice(0,20)}function pd(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function Kw(e,t="standard"){let n=Jr(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 Jw(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!K.requiresDelegation||!K.assignmentStartAndDispatchPrecedeDelegableExecution||!K.trivialWorkRequiresDelegation||!K.preparatoryAndExploratoryWorkRequiresDelegation||K.genericDirectWorkFallback||K.directExecutionExceptions!==K.rootOwnedAuthority||!K.codeReviewRequiredForImplementation||!K.codeReviewRequiredBeforeVcs||!K.externalVerificationMustBeTerminal||!K.concreteSpecialistDispatchRequired||!K.roleFamiliesAreLabelsOnly||!K.missingConcreteRouteIsBlocker||!K.normalSpawnRequiresExplicitForkTurns||K.normalSpawnForkTurns!=="none"||!K.normalSpawnUsesConcreteRegisteredAgentType||!K.assignmentContextIsTaskSpecificOnly||!K.configuredRouteModelAndEffortPreserved||K.normalProgressMessages||K.normalHeartbeatMessages||K.normalIntermediateEvidence||!K.userUpdatesUsefulOrImportantOnly||!K.routinePerToolOrSubagentNarrationForbidden||!K.routineStatusOnlyChatterForbidden||!K.fixedCadenceUserUpdatesForbidden||!K.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!K.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!K.materialUserUpdateKinds.includes("release_milestones")||!K.outOfBoundaryRequiresNewAssignment||!K.longestPracticalEventWait||!K.busyPollingForbidden||!K.statusOnlyCoordinationLoopsForbidden||!K.batchIndependentLifecycleActions||!K.releaseLeavesAfterAcceptedOutcome||K.routineWaitTool!=="collaboration.wait_agent"||!Number.isSafeInteger(K.routineWaitMaximumTimeoutMs)||K.routineWaitMaximumTimeoutMs<=0||!K.routineWaitUsesMaximumRuntimeTimeout||!K.earlySpecialistCompletionWakesWait||!K.collectiveMailboxIncludesRelevantAgents||!K.idleTimeoutRepeatsMaximumWait||!K.shortRoutineWaitsForbidden||!K.evidenceFirstConciseStructuredReports||K.specialistReportFields.length===0||K.rootLargeReadsOnlyFor.length===0||!K.stableFactsReused||!K.duplicatePolicyForbidden||!K.stableBoundedComponentScopesAreCanonical||!K.lifecycleWorkerOwnsDeterministicApi||K.registeredSpecialistAgentTypes!==Kr||K.forbiddenGenericAgentTypes!==Hm)throw Error("The Root orchestration policy is incomplete.");let n=[`You are the HolyCodex Root/session orchestrator. Never perform delegable work yourself. Root may directly perform only ${K.rootOwnedAuthority.map((r)=>qW[r]).join("; ")}, within approval and capability boundaries.`,`Start a bounded Assignment and dispatch the exact concrete registered Role.task agent_type before every delegable action, including trivial, preparatory, and exploratory work: ${K.delegableActions.map((r)=>$W[r]).join("; ")}. Registered targets: ${K.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are role-family labels only. Generic built-in agent_type values ${K.forbiddenGenericAgentTypes.join(", ")} are forbidden. If no matching route exists, return needs_root_input.`,"Before each spawn, derive the exact Role.task target and complete configuration from the active HolyCodex profile, service tier, and selected capabilities. Verify the registration resolves to its canonical role file and that the name, model, reasoning effort, service tier, full developer instructions, shell/environment policy, capability settings, and permissions match; pass every supported configuration field explicitly. Never inherit Root settings, substitute a generic route, or trust remembered route data. Recheck resumed threads. If the complete route cannot be verified and passed, stop with needs_root_input before spawning.",`For normal specialist spawns, set fork_turns: "${K.normalSpawnForkTurns}". Give each specialist a self-contained Assignment with objective, bounded scope, constraints, dependencies, acceptance criteria, and evidence needed for acceptance.`,"Use holycodex-agent semantic operations for Intent, optional Plan, and Assignment state. Do not edit TOON state. Root owns material decisions, integration acceptance, lifecycle, and completion; return out-of-boundary work to Root for a new Assignment.","Honor explicit user instructions within hard safety, authority, capability, and lifecycle boundaries. Make routine safe, reversible, in-scope choices and carry authorized work through its requested terminal state. Ask for material unresolved choices, genuine approval boundaries, user-owned credential entry, or outcome-changing blockers.","Dispatch independent non-overlapping Assignments concurrently; order dependencies and serialize writes to a shared seam. Do not request specialist progress. Accept terminal evidence and resolve material contradictions before integration.","Browser Use and Computer Use execution are specialist-owned. Root decides when interface work is needed, assigns bounded authorized work to a specialist with the capability, and accepts terminal evidence without operating the browser or computer. If the required capability is disabled or unavailable on the current surface, stop with needs_root_input and report the blocker without substituting another provider or route.","Use writing-instructions for model-facing contracts. Keep each meaning with one authoritative owner and add only the missing semantic delta for the receiver.",`Patch quality: ${Lu}`,"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.",jW,`${$u.rule} ${UW}`,"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(HW());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.");if(t.windowsGitBashExecutable!==void 0)n.push(Yw(t.windowsGitBashExecutable));return n.join(`
37
+ `)}function HW(){if(!Ti.repositoryAndUserRequirementsPrecedePluginDefaults||!Ti.specialistsOwnInspectionImplementationAndRenderedAcceptance||!Ti.rootAcceptsTerminalVisualEvidence||!Ti.sourceChangesInvalidateRenderEvidence||!Ti.specialistReportsIncludeObservableRenderedEvidence||Ti.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`For a user-visible frontend task, ${No.frontend.applicability.map(({skillId:n,appliesWhen:r})=>`${r} uses ${n}`).join("; ")}. Follow the repository stack, design system, and user requirements. Specialists inspect, implement, render, interact, and repair; Root accepts their current observable visual and interaction evidence, assigns discrepancies, and requires fresh evidence after relevant source changes. Check responsive layout, accessibility, and core interactions in proportion to the change.`}async function Gw(e,t,n=[],r="standard",o,i,a=[],s={}){let c=Za(t,r,{...s,...o===void 0?{}:{windowsGitBashExecutable:o}}),l=Wt(e,"holycodex","agents",c),u=[],d=[],p=jo(t,r).map((b)=>({path:Wt(l,`${b.name}.toml`),contents:Ic(b,{...s,...o===void 0?{}:{windowsGitBashExecutable:o}})})),f=new Map(n.map((b)=>[Wt(e,b.path),b])),m=new Map,y=new Set,g=new Set,_=new Map;for(let b of p){let A=await Ya(b.path);m.set(b.path,A);let O=a.find((w)=>w.path===b.path&&w.action==="replace"&&w.key===void 0);if(O!==void 0){let w=WW(O);if(w===void 0||A===void 0||await tn(A)!==w)throw Error(`The native role conflict changed after review; review the latest file and retry: ${b.path}`);if(_.set(b.path,w),O.decision==="keep")g.add(b.path);else y.add(b.path)}let v=f.get(b.path);if(A!==void 0&&v===void 0&&A!==b.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${b.path}`);if(A!==void 0&&v!==void 0){let w=await tn(A);if(w!==v.digest&&A!==b.contents){let k=Zw(b.path,"replace",{present:!0,digest:w},{present:!0,digest:await tn(b.contents)},"The managed native role file changed outside the previous HolyCodex transaction."),P=O===void 0?await i?.(k):O.decision==="keep"?"decline":"accept";if(P==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${b.path}`);if(P==="accept"||P==="decline"){let L=await tn(A),j=await Ya(b.path);if(j===void 0||await tn(j)!==L)throw Error(`The native role conflict changed after review; review the latest file and retry: ${b.path}`);if(_.set(b.path,L),P==="accept")y.add(b.path);else g.add(b.path)}}}}let I=[];try{for(let v of p){let w=m.get(v.path),k=f.get(v.path),P=_.get(v.path);if(P!==void 0){let L=await Ya(v.path);if(L===void 0||await tn(L)!==P)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`)}if(g.has(v.path)){if(k!==void 0)u.push(v.path),I.push(k);continue}if(w!==void 0&&k!==void 0){if(await tn(w)!==k.digest&&w!==v.contents&&!y.has(v.path)){u.push(v.path),I.push({path:G0(e,v.path).replaceAll("\\","/"),digest:k.digest});continue}}if(w===void 0||w!==v.contents)await Fn(v.path,v.contents),d.push({path:v.path,previous:w,installedDigest:await tn(v.contents)});I.push({path:G0(e,v.path).replaceAll("\\","/"),digest:await tn(v.contents)})}let b=Wt(e,"agents","root.toml"),A=await Ya(b),O=await Z0(b);if(O==="preserved")u.push(b);if(O==="removed"&&A!==void 0)d.push({path:b,previous:A,installedDigest:void 0});for(let v of n){let w=Wt(e,v.path);if(!p.some((k)=>k.path===w))I.push(v)}return{managed_artifacts:I,preserved:u,rollback:d}}catch(b){throw await Sh(d).catch(()=>{return}),b}}async function Sh(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await Ya(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await tn(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await gh(r.path,{force:!1}).catch((a)=>{if(!it(a,"ENOENT"))throw a}),t.push(r.path);else await Fn(r.path,r.previous)}return{removed:t,preserved:n}}async function bh(e,t,n=new Set){let r=[],o=[],i=Wt(e,"agents"),a=Wt(e,"holycodex","agents");for(let l of t){let u=Wt(e,l.path);if(!qi(e,u)||!qi(i,u)&&!qi(a,u)&&u!==Wt(e,"config.toml")){o.push(u);continue}try{await $o(u);let d=await Ww(u);if(d.isSymbolicLink()||!d.isFile()){o.push(u);continue}let p=await zw(u);if(await tn(p)!==l.digest){if(n.has(u)){await gh(u,{force:!1}),r.push(u);continue}o.push(u);continue}await gh(u,{force:!1}),r.push(u)}catch(d){if(!it(d,"ENOENT"))o.push(u)}}let s=Wt(e,"agents","root.toml"),c=await Z0(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);return{removed:r,preserved:o}}function Ic(e,t={}){let n=[DW,e.taskInstruction,...e.permissions.filesystem==="workspace-write"||e.name==="Reviewer.code"||e.name==="Reviewer.artifact"?[`Patch quality: ${Lu}`]:[],...t.windowsGitBashExecutable===void 0?[]:[Yw(t.windowsGitBashExecutable)],...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(yh(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","",...yh(e)==="workspace-write"?["[sandbox_workspace_write]","network_access = true"]:[],""].join(`
39
+ `)}function Yw(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 yh(e){return e.permissions.filesystem}function _h(e,t){return t.sandbox_mode===yh(e)&&t.default_permissions===void 0&&(yh(e)==="workspace-write"?he(t,"sandbox_workspace_write.network_access")===!0:he(t,"sandbox_workspace_write.network_access")===void 0)}function BW(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 Ac(e){return VW.has(e)}async function Z0(e){try{await $o(e);let t=await Ww(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await zw(e,"utf8");if(!Ac(n))return"preserved";return await gh(e,{force:!1}),"removed"}catch(t){if(it(t,"ENOENT"))return"absent";throw t}}async function Ya(e){try{await $o(e);let t=await Ww(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await zw(e))}catch(t){if(it(t,"ENOENT"))return;throw t}}async function tn(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 Zw(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 WW(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var DW,qW,$W,UW="After implementation, reach a Reviewer.code fixed point, run Worker.validation, then integrate and perform VCS writes. Review repairs invalidate earlier validation.",jW,VW;var wh=S(()=>{Tc();pt();za();Ec();DW=[`Execute one bounded Assignment through its acceptance criteria. ${$u.rule} Return out-of-boundary work or material decisions 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.`,`Return only one compact, evidence-first terminal outcome (${K.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${K.specialistReportFields.join(", ")}.`].join(" "),qW={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"},$W={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"},jW=`Wait for specialist results with ${K.routineWaitTool} at timeout_ms=${K.routineWaitMaximumTimeoutMs}; repeat after an idle timeout. Do not poll status or send routine progress messages. Release specialist leaves after accepting their terminal outcomes.`;VW=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)=>BW(e,t,n))))});import{access as zW,readFile as KW,readdir as JW}from"fs/promises";import{join as Xw}from"path";class Xa{adapter;observedIdentities={};constructor(e){if("run"in e){let t=ph({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await _w({environment:e}),n=ph({executable:t.path,environment:bw(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new Xa(n)}async list(){try{return await this.adapter.list()}catch(e){throw fd("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw fd("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw fd("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw fd("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw fd("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=Zr(t,i),s=mr(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 vh{codexHome;observedIdentities={};constructor(e){this.codexHome=e}async status(e){let t=await KW(Xw(this.codexHome,"config.toml"),"utf8"),n=globalThis.Bun;if(!n?.TOML?.parse)throw Error("A TOML parser is unavailable.");let r=ke($a,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=Zb(c),d=(l.length>0?l:[c]).flatMap((g)=>{if(i===void 0||!Object.hasOwn(i,g))return[];let _=i?.[g],I=typeof _==="object"&&_!==null&&!Array.isArray(_)?_.enabled:void 0;return[{id:g,enabled:I}]});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 GW(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 GW(e,t){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let o=Xw(e,"plugins","cache",n.slice(r+1),n.slice(0,r));try{let i=await JW(o,{withFileTypes:!0,encoding:"utf8"});for(let a of i){if(!a.isDirectory())continue;try{return await zW(Xw(o,a.name,".codex-plugin","plugin.json")),!0}catch(s){if(!X0(s))throw s}}}catch(i){if(X0(i))continue;throw i}}return!1}function X0(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function fd(e,t,n){if(t instanceof Xr)return t;let o=(t instanceof ge?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 Xr(i,a,t,n===void 0?{}:{plugin_id:n})}var Xr;var md=S(()=>{Tc();pt();Va();Xr=class Xr 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 tv(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=ZW(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=Qw(o.slice(1,-1).trim()),YW(t,n);continue}let i=nF(o);if(i<1)throw Error("TOML assignment is invalid.");let a=Qw(o.slice(0,i).trim()),s=Rh(o.slice(i+1).trim());tF(t,[...n,...a],s)}return t}function nv(e){let t=[];return eF(e,[],t),t.join(`
41
+ `)}function eF(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(rv(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(Q0).join(".")}]`)}for(let[i,a]of r)n.push(`${Q0(i)} = ${rF(a)}`);for(let[i,a]of o)eF(a,[...t,i],n)}function Rh(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?[]:ev(t,",").map((n)=>Rh(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 ev(t,",")){let o=nF(r);if(o<1)throw Error("TOML inline table entry is invalid.");tF(n,Qw(r.slice(0,o).trim()),Rh(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 Qw(e){let t=ev(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("'")?Rh(n):n)}function tF(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(rv(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 YW(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(rv(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function ev(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 nF(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 ZW(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 rv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Q0(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function rF(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(rF).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{execFile as XW}from"child_process";import{access as QW,readFile as ez,realpath as tz}from"fs/promises";import{posix as nz,win32 as rz}from"path";import{promisify as oz}from"util";function rs(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:Mc,run:async(t,n)=>{try{let r=await iz(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 ts(e){let t=Ln(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(hd(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(hd(t,"bunx")||hd(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(hd(t,"npx")||t.endsWith("/npx-cli.js")||hd(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function os(e,t){if(e.platform!=="win32")return{status:"not_applicable"};let n=await oF(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 pe("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 oF(e);if(o===void 0)throw new pe("git_bash_unavailable",`Git for Windows was installed, but ${es} could not be verified. Repair Git for Windows and retry.`);return{status:"healthy",path:o,installed:!0}}async function Th(e,t,n){let r=await iv(e);if(r!==void 0){let o=ts(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},i=n?.ownership==="holycodex"&&typeof n.identity==="string"&&await Nc(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(Pc(e))return lz(e,t,n);return cz(e,t,n)}async function ov(e,t){let n=await iv(e);if(n!==void 0){let i=ts(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&await Nc(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=Pc(e)?{launcher:"bunx",family:"bun",executable:"bun"}:ts(e.environment);if(r===void 0)throw new pe("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let o=r.family==="bun"&&Pc(e)?await gd(e):await yd(e,r);if(o===void 0)throw new pe("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:o.version,executable:o.executable,ownership:av(t,r,o),identity:o.identity}}async function iv(e){let t=await cF(e.environment,e.platform,e.files??Mc);if(t===void 0)return;let n=await e.run(t,["--version"]),r=n.exitCode===0?ns(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}}async function az(e){if(await iv(e)!==void 0)return;if(Pc(e)){await sz(e);return}let t=ts(e.environment);if(t===void 0)throw new pe("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 pe("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})}async function sz(e){let t=e.files??Mc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if(gz(n.stderr))return;throw new pe("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 pe("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:Qa(g)})}let l;try{await t.access(a)}catch(g){if(hz(g))return;throw new pe("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:Qa(g)})}try{l=await t.readText(s)}catch(g){throw new pe("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:Qa(g)})}let u;try{u=JSON.parse(l)}catch(g){throw new pe("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:Qa(g)})}if(typeof u.version!=="string"||ns(u.version)!==u.version)throw new pe("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let d=lF(u);if(d===void 0)throw new pe("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 pe("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:Qa(g)})}if(!xd(f,a,e.platform)||!Ln(m).startsWith(`${Ln(f)}/`))throw new pe("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 pe("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:Qa(g)})}let y=await e.run(c,["--version"]);if(y.exitCode!==0||ns(y.stdout)!==u.version)throw new pe("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:y.stderr.slice(0,512)})}async function cz(e,t,n){let r=ts(e.environment);if(r===void 0)throw new pe("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await yd(e,r),i=await uF(e,r);if(i===void 0)throw new pe("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=av(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=aF(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new pe("context7_install_failed",`${r.family} could not install ${vr}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new pe("context7_unavailable",`${vr} is not owned by the ${r.family} global installation.`);let s=await yd(e,r);if(s===void 0)throw new pe("context7_verification_failed",`${vr} could not be verified in the ${r.family} global installation.`);if(s.version!==i)throw new pe("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 lz(e,t,n){let r={launcher:"bunx",family:"bun",executable:"bun"},o=await gd(e),i=await uF(e,r);if(i===void 0)throw new pe("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=av(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=await e.run(e.processPath,["add","-g",vr]);if(l.exitCode!==0)throw new pe("context7_install_failed",`Bun could not install ${vr} in its global installation.`,{stderr:l.stderr.slice(0,512)})}else if(o===void 0)throw new pe("context7_unavailable",`${vr} is not present in Bun's exact global installation.`);let s=await gd(e);if(s===void 0)throw new pe("context7_verification_failed",`${vr} could not be verified in Bun's exact global installation.`);if(s.version!==i)throw new pe("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 gd(e){let t=e.files??Mc,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"||ns(a.version)!==a.version)return;let s=lF(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(!xd(u,i,e.platform)||!Ln(d).startsWith(`${Ln(u)}/`))return;let f=await e.run(l,["--version"]);if(f.exitCode!==0||ns(f.stdout)!==a.version)return;return{version:a.version,executable:l,identity:await sF({launcher:"bunx",family:"bun",executable:"bun"},u,d,p,a)}}function Pc(e){let t=nn(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function av(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(!sv(r)||r!==n.identity)return"user";return"holycodex"}async function Sd(e,t){if(Pc(e))return uz(e,t);return dz(e,t)}async function uz(e,t){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n;try{n=await gd(e)}catch{return!1}if(n===void 0||n.version!==t.version||!await Nc(e,n.executable,t.executable)||!sv(t.identity)||n.identity!==t.identity)return!1;let r=await e.run(e.processPath,["remove","-g","ctx7"]);if(r.exitCode!==0)throw new pe("context7_remove_failed","Bun could not remove ctx7.",{stderr:r.stderr.slice(0,512)});if(await gd(e)!==void 0)throw new pe("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0}async function dz(e,t){if(t?.ownership!=="holycodex")return!1;let n=ts(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await yd(e,n)}catch(a){if(a instanceof pe&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!await Nc(e,r.executable,t.executable)||!sv(t.identity)||r.identity!==t.identity)return!1;let o=pz(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new pe("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await yd(e,n)!==void 0)throw new pe("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof pe&&a.code==="context7_remove_failed")throw a;throw new pe("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function aF(e){switch(e){case"bun":return{executable:"bun",args:["add","-g",vr]};case"npm":return{executable:"npm",args:["install","--global",vr]};case"pnpm":return{executable:"pnpm",args:["add","--global",vr]}}}function pz(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 oF(e){if(await iF(e.run,es,e.platform))return es;for(let t of(e.environment.PATH??"").split(";")){if(t.length===0)continue;let n=nn(e.platform).join(t,"bash.exe");if(await iF(e.run,n,e.platform))return n}return}async function iF(e,t,n){let r=xz(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 yd(e,t){let n=e.files??Mc,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 yz(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:cv(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),!Ln(u).startsWith(`${Ln(l)}/`))return}catch{return}let d=fz(o,t.family,e.platform),p;try{await n.access(d),p=await n.realpath(d)}catch{return}let f=await cF(e.environment,e.platform,n);if(f!==void 0&&!xd(await mz(n,f),p,e.platform))throw new pe("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||ns(m.stdout)!==a.version)return;return{version:a.version,executable:d,identity:await sF(t,l,u,p,a)}}async function sF(e,t,n,r,o){return await xr("context7-installation",[yr({manager:e.family,package_root:Ln(t),package_executable:Ln(n),shim:Ln(r),package:o})])}function sv(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function cF(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 fz(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 mz(e,t){try{return await e.realpath(t)}catch{return t}}function ns(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function lF(e){return typeof e.bin==="string"?e.bin:cv(e.bin)&&typeof e.bin.ctx7==="string"?e.bin.ctx7:void 0}function Qa(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function hz(e){return cv(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(Qa(e))}function gz(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 yz(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 uF(e,t){let n=await e.run(t.family==="bun"&&Pc(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return ns(n.stdout)}function xz(e,t){let n=nn(t),r=n.dirname(e),o=Ln(r).endsWith("/usr/bin")?n.resolve(r,"..",".."):n.resolve(r,"..");return n.resolve(o,"cmd","git.exe")}function hd(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function xd(e,t,n){let r=nn(n),o=r.resolve(e),i=r.resolve(t);return n==="win32"?Ln(o)===Ln(i):o===i}async function Nc(e,t,n){if(xd(t,n,e.platform))return!0;let r=e.files??Mc;try{let[o,i]=await Promise.all([r.realpath(t),r.realpath(n)]);return xd(o,i,e.platform)}catch{return!1}}function nn(e){return e==="win32"?rz:nz}function Ln(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function cv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var es="C:\\Program Files\\Git\\bin\\bash.exe",vr="ctx7@latest",iz,Mc,pe;var Oh=S(()=>{pt();iz=oz(XW),Mc={access:QW,readText:(e)=>ez(e,"utf8"),realpath:tz};pe=class pe extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as Ch,rmdir as dv}from"fs/promises";import{join as Sz}from"path";async function pv(e={},t=process.env){let n=wr(e,t),r={};try{await Wa(n.codexHome),await Wa(n.stateRoot),r.paths=as({state_root:n.stateRoot})}catch(u){r.paths=kt(["path_symlink"],{error:Dn(u)})}let o=await $i(n).catch((u)=>{r.configuration=kt(["state_corrupt"],{error:Dn(u)});return}),[i,a]=await Promise.all([Rr(n.preparingRecord,o).catch((u)=>{r.transaction=kt(["state_corrupt"],{path:n.preparingRecord,error:Dn(u)});return}),Rr(n.conflictedRecord,o).catch((u)=>{r.transaction=kt(["state_corrupt"],{path:n.conflictedRecord,error:Dn(u)});return})]);if(r.transaction?.status!=="failed"&&(i!==void 0||a!==void 0)){let u=Ih(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 qc(o))r.configuration=as({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 Ez(n,o),r.native_roles=await kz(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])=>d.selected&&d.status!=="healthy");if(u)r.capabilities=kt(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status})}let s=e.runtime??rs(t);try{let u=await os(s,!1);r.git_bash=u.status==="missing"?kt(["git_bash_missing"]):as(u.status==="healthy"?{path:u.path}:{})}catch(u){r.git_bash=kt(["git_bash_unavailable"],{error:Dn(u)})}try{let u=await ov(s,o?.tooling?.context7);r.context7=as({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:Dn(u)}}}try{let u=await Qe(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&Ac(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:Dn(u)})}let c=e.officialPluginManager;if(o&&c?.status){let u=[...new Set([ln,...gc({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??[]])];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?as({status:d,observed_identities:f}):kt(["native_plugin_disagreement"],{missing:p,status:d,observed_identities:f})}catch(d){r.native_plugins=kt(["native_plugin_status_failed"],{error:Dn(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 fv(e={},t=process.env){let n=wr(e,t);await Wa(n.codexHome),await Wa(n.stateRoot);let r=await $i(n);if(r!==void 0&&!await qc(r))throw new C("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([Rr(n.preparingRecord,r),Rr(n.conflictedRecord,r)]);gv(r,o,i);let a=fF(r,o,i);if(a===void 0)return[];let s=cn(await Qe(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await _r(s,a.managed_config,{schema:a.managed_config.schema,installId:a.managed_config.installId});for(let u of[...l.preservedKeys,...l.unresolvedKeys])c.push({path:n.configFile,key:u,action:"remove"})}if(a.plugin_config!==void 0){let l=await Lc(s,a.plugin_config);for(let u of l.preserved)c.push({path:n.configFile,key:u==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"})}if(a.provider_config!==void 0){let l=await Dc(s,a.provider_config,new Set(mv(a)));for(let u of l.preserved)c.push({path:n.configFile,key:`plugins."${u}"`,action:"remove"})}return c.push(...await Y0(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[is(l),l])).values()]}async function bd(e={},t=process.env){let n=wr(e,t);await Wa(n.codexHome),await Wa(n.stateRoot);let r=await $i(n);if(r&&!await qc(r))throw new C("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([Rr(n.preparingRecord,r),Rr(n.conflictedRecord,r)]);gv(r,o,i);let a=fF(r,o,i);uv(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(mv(a)),c=[],l=[],u=[],d=!1;if(a===void 0)return uv(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let p=await fv(e,t),f=await Cz(e,p),m=await Qe(n.configFile),y=cn(m),g=a?.managed_config;if(g){let O=await _r(y,g,{schema:g.schema,installId:g.installId});if(O.preservedKeys.length>0||O.unresolvedKeys.length>0){let w=[...O.preservedKeys,...O.unresolvedKeys].map((k)=>({path:n.configFile,key:k,action:"remove"}));for(let k of w)if(f.has(is(k)))y=br(y,k.key)}}if(a?.plugin_config){let O=await Lc(y,a.plugin_config);if(O.preserved.length>0){let v=O.preserved.map((w)=>({path:n.configFile,key:w==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let w of O.preserved){let k=v.find((P)=>P.key===(w==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(k===void 0||!f.has(is(k)))continue;y=br(y,w==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let O=await Dc(y,a.provider_config,s);if(O.preserved.length>0){let v=O.preserved.map((w)=>({path:n.configFile,key:`plugins."${w}"`,action:"remove"}));for(let w of O.preserved){let k=v.find((P)=>P.key===`plugins."${w}"`);if(k===void 0||!f.has(is(k)))continue;y=br(y,`plugins."${w}"`)}}}let _;try{_=e.officialPluginManager??await Xa.discover({...t,CODEX_HOME:n.codexHome})}catch(O){throw new C("capability_denied","Native Codex plugin removal is unavailable.",O,{recovery:"Install or expose Codex, then retry."})}if(_===void 0||!_.remove||!_.list)throw new C("capability_denied","Native Codex plugin removal and readback are unavailable.");let I,b=a;try{let O=y,v=g;if(v){let w=await _r(O,v,{schema:v.schema,installId:v.installId}),k=[...w.preservedKeys,...w.unresolvedKeys];if(k.filter((L)=>!f.has(is({path:n.configFile,key:L,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Qr(n,a??Fc()),{removed:c,preserved:l,reasons:u};if(O=w.document,k.length>0){let L=new Set(k);v={...w.state,managed:Object.fromEntries(Object.entries(w.state.managed).filter(([j])=>!L.has(j)))}}else v=w.state}if(a?.plugin_config){let w=await Lc(O,a.plugin_config,{allowBeforeState:!0});if(w.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Qr(n,a),{removed:c,preserved:l,reasons:u};O=w.document}if(a?.provider_config){let w=await Dc(O,a.provider_config,s,{allowBeforeState:!0});if(w.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Qr(n,a),{removed:c,preserved:l,reasons:u};O=w.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)I=v===void 0?{document:O}:{document:O,state:v};if(I!==void 0){if(Object.keys(I.document).length===0&&m===void 0)await Ch(n.configFile,{force:!1});else await Fn(n.configFile,vd(I.document));b={...a,managed_config:I.state},await Qr(n,b),d=!0}}catch(O){if(O instanceof C)throw await Qr(n,b??Fc()),O;return l.push(n.configFile),u.push("managed_config_write_failed"),await Qr(n,b??Fc()),{removed:c,preserved:l,reasons:u}}let A=await bh(n.codexHome,a?.managed_artifacts??[],new Set(p.filter((O)=>O.key===void 0&&f.has(is(O))).map((O)=>O.path)));if(c.push(...A.removed),l.push(...A.preserved),A.preserved.length>0)u.push("managed_artifact_changed");c.push(...await wz(n.roleRoot,a?.managed_artifacts??[]));for(let O of s)try{let v=await _.list(),w=Iz(v,O);if(w?.entry.installed!==!0)continue;let k=w.entry.pluginId;await _.remove(k);let P=await _.list();if(Zr(P,O)?.entry?.installed===!0||[...P.installed,...P.available].some((Ie)=>Ie.pluginId===O&&Ie.installed))throw new C("capability_denied",`Codex still reports ${O} after removal.`);if(I!==void 0)await _z(n,I.document,O);c.push(O)}catch(v){throw u.push("native_plugin_remove_failed"),await Qr(n,b??Fc()),new C("capability_denied",`Codex native plugin removal did not converge for ${O}: ${Dn(v)}`,v)}try{if(await Sd(e.runtime??rs(t),a.tooling?.context7))c.push("ctx7")}catch(O){throw u.push("context7_remove_failed"),await Qr(n,b??Fc()),new C("capability_denied",`Context7 removal did not converge: ${Dn(O)}`,O)}if(r)try{await Ch(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(O){if(!it(O,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await Qr(n,a??r),{removed:c,preserved:l,reasons:u}}if(l.length===0)try{await Ch(n.installOptions,{force:!1}),c.push(n.installOptions)}catch(O){if(!it(O,"ENOENT"))l.push(n.installOptions),u.push("state_remove_failed"),await Qr(n,a??r??Fc())}if(l.length===0)for(let[O,v]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0||d]]){if(!v)continue;try{await Az(O),c.push(O)}catch{l.push(O),u.push("state_remove_failed")}}if(l.length===0)try{await dv(n.roleRoot),c.push(n.roleRoot)}catch(O){if(!it(O,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await dv(n.stateRoot),c.push(n.stateRoot)}catch(O){if(it(O,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return uv(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 _z(e,t,n){let r=await Qe(e.configFile);if(r===void 0)return;let o=cn(r,e.configFile),i=o.plugins;if(!lv(i))return;let a=i[n];if(!lv(a)||Object.keys(a).length!==1||a.enabled!==!1)return;let s=t.plugins,c=lv(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 Fn(e.configFile,vd(u))}function lv(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=Sz(e,o);try{await dv(i),r.push(i)}catch(a){if(!it(a,"ENOENT")&&!it(a,"ENOTEMPTY")&&!it(a,"EEXIST"))throw a}}return r}async function vz(e={},t=process.env,n={}){let r=wr(e,t),o=await $i(r),[i,a]=await Promise.all([Rr(r.preparingRecord,o),Rr(r.conflictedRecord,o)]);if(o!==void 0&&!await qc(o))throw new C("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});hv(o,i,a);let s=pF(o,i,a),c=s??o;if(c===void 0)throw new C("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l=await kh(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:Rz(c)}:Tz(_d(l)),d=n.options===void 0?u:un(n.options),p={profile:d.profile??u.profile,tier:d.tier??u.tier,optional:{...u.optional,...d.optional},officialPlugins:d.officialPlugins??u.officialPlugins},f=!Oz(p,u),m;try{m=await ud()}catch(w){throw new C("upgrade_failed","The running HolyCodex version is unavailable.",w)}let y=m.split("-",1)[0]===c.version.split("-",1)[0]&&m.includes("-dev.")!==c.version.includes("-dev."),g=y?0:Nu(m,c.version);if(g<0)throw new C("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 _=c.managed_config?.managed["features.context_management"]!==void 0,I=c.managed_config?.managed[Ii[0]]!==void 0,b=[];if(n.dryRun===!0){let w=cn(await Qe(r.configFile));if(c.managed_config!==void 0)for(let P of Object.keys(c.managed_config.managed)){if(!Ua(P))continue;if((await Ha(w,c.managed_config,P)).status!=="unchanged")b.push({path:r.configFile,key:P,action:"replace"})}if(c.plugin_config!==void 0){let P=await Lc(w,c.plugin_config);for(let L of P.preserved){let j=L==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";b.push({path:r.configFile,key:j,action:"replace"})}}if(c.provider_config!==void 0){let P=await Dc(w,c.provider_config,new Set(mv(c)));for(let L of P.preserved)b.push({path:r.configFile,key:`plugins."${L}"`,action:"replace"})}let k=await xh(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 P of k)b.push(P)}let A=c.tooling===void 0,O=c.tooling===void 0?["record missing"]:[];try{let w=e.runtime??rs(t);if((await os(w,!1)).status==="missing")O.push("Git Bash unavailable");let P;try{P=await ov(w,c.tooling?.context7)}catch(j){if(c.tooling?.context7!==void 0||!Pz(j))throw j}let L=c.tooling?.context7;if(L?.manager!==P?.manager)O.push("Context7 manager changed");if(L?.version!==P?.version)O.push("Context7 version changed");if(L?.executable===void 0?P?.executable!==void 0:P?.executable===void 0||!await Nc(w,L.executable,P.executable))O.push("Context7 executable changed");A||=O.length>0}catch(w){A=!0;let k=typeof w==="object"&&w!==null&&"code"in w&&typeof w.code==="string"?w.code:w instanceof Error?w.name:"inspection failed";O.push(`inspection failed (${k})`)}let v=[...g>0||y?["version"]:[],...f?["installation options"]:[],...l===void 0?["installation options migration"]:[],..._?["context-management configuration migration"]:[],...I?["auto-compaction configuration cleanup"]:[],...g>0||_||I?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...A?[`shared tooling reconciliation (${O.join(", ")})`]:[],...b.map((w)=>`conflict: ${w.path}${w.key===void 0?"":` (${w.key})`} -> ${w.action}`)];if(v.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:m,changes:[],record:o,preserved:[],warnings:[],conflicts:b};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:m,changes:v,record:o,preserved:[],warnings:[],conflicts:b};try{let w=await ss(p,e,t);return{status:"upgraded",from_version:c.version,to_version:m,changes:v,record:w.record,preserved:w.preserved,warnings:w.warnings}}catch(w){if(w instanceof C)throw w;throw new C("upgrade_failed",`HolyCodex upgrade failed: ${Dn(w)}`,w)}}function Rz(e){let t=new Set(gc(e.optional_selections));return(e.official_plugins??[]).filter((n)=>!dF(n)&&!t.has(n))}function Tz(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!dF(t))}}}function dF(e){let t=e.slice(0,e.lastIndexOf("@"));return bz.has(t)}function Oz(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 Cz(e,t){let n=new Set;for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(is(r));continue}if(o==="decline")continue;throw new C("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 is(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function Ez(e,t){if(!t.managed_config)return kt(["incomplete_install_state"]);try{let n=cn(await Qe(e.configFile)),r=Rd(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:Et.frontend,security:Et.security,...t.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:t.tooling.git_bash.path}:{}}),o=[];for(let i of Object.keys(r))if((await Ha(n,t.managed_config,i)).status!=="unchanged")o.push(i);return o.length===0?as({managed_keys:Object.keys(r).length}):kt(["changed_holycodex_config"],{keys:o})}catch(n){return kt(["config_unreadable"],{error:Dn(n)})}}async function kz(e,t,n,r,o={browserUse:!1,computerUse:!1}){try{let i=cn(await Qe(e.configFile)),a=[],s=Za(t,n,{...o,...r===void 0?{}:{windowsGitBashExecutable:r}});for(let l of jo(t,n)){let u=he(i,`agents."${l.name}".config_file`),d=ja(e.configFile,pd(l.name,s)).replaceAll("\\","/");if(typeof u!=="string"||ja(e.configFile,u).replaceAll("\\","/")!==d){a.push(`${l.name}:registration`);continue}let p=await Qe(d);if(p===void 0){a.push(`${l.name}:missing`);continue}if(p!==Ic(l,{...o,...r===void 0?{}:{windowsGitBashExecutable:r}})){a.push(`${l.name}:changed`);continue}let f=cn(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")||!_h(l,f)||f.approval_policy!=="never"||f.web_search!==(l.permissions.network?"live":"disabled")||he(f,"agents.enabled")!==!1||he(f,"features.multi_agent")!==!1||he(f,"features.multi_agent_v2")!==!1||he(f,"features.agent_message_board")!==!1||he(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 Qe(`${e.codexHome}/agents/root.toml`);if(c!==void 0&&Ac(c))a.push("root:stale");return a.length===0?as({role_root:e.roleRoot,agent_types:jo(t,n).map((l)=>l.name)}):kt(["native_role_disagreement"],{roles:a})}catch(i){return kt(["native_role_invalid"],{error:Dn(i)})}}async function Qr(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(ke(Li,n)!==void 0)await Ja(e.conflictedRecord,_n(n))}function pF(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||wd(r,e)))}function fF(e,t,n){return pF(e,t,n)??e}function Fc(){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 mv(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)];let t=(e?.plugin_snapshot??[]).filter((o)=>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"?[ln]:[],r=(e?.provider_config??[]).filter((o)=>o.before.presence==="absent"&&o.after.presence==="present").map((o)=>o.plugin_id);return[...new Set([...t,...n,...r])]}function Iz(e,t){let n=Zr(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 as(e){return{status:"healthy",reasons:[],details:e}}function kt(e,t={}){return{status:"failed",reasons:e,details:t}}async function Az(e){await Ch(e,{force:!1}).catch((t)=>{if(!it(t,"ENOENT"))throw t})}function Pz(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function Dn(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function uv(e,t){try{e.onProgress?.(t)}catch{}}var bz;var Eh=S(()=>{Tc();pt();Td();od();dd();wh();md();za();Va();Ec();Oh();bz=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{rm as wv}from"fs/promises";function un(e){let t=ke(mh,e);if(t===void 0)throw new C("install_failed","The installation options are invalid.");return t}async function kh(e){let t=await Qe(e.installOptions);return _F(t,e.installOptions)}function _F(e,t){if(e===void 0)return;let n;try{n=tv(e)}catch(i){throw new C("state_corrupt","The HolyCodex install options are not valid TOML.",i,{path:t})}let r=ke(cd,n);if(r!==void 0)return r;let o=ke(N0,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 C("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}async function wF(e,t){if(ke(cd,t)===void 0)throw new C("state_corrupt","The HolyCodex install options are invalid.");await Fn(e.installOptions,nv(t))}function _d(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]}}async function vF(e={},t=process.env){let n=wr(e,t),r=await kh(n);if(r!==void 0)return _d(r);let o=await $i(n);if(o===void 0)return{};return{profile:o.profile,tier:o.tier,optional:o.optional_selections,officialPlugins:Rv(o)}}function RF(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)]}}function wd(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function Ih(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})=>wd(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?o&&!i?"incompatible":"orphaned":wd(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 hv(e,t,n){let r=Ih(e,t,n);if(r.filter((i)=>i.relation==="stale"||i.relation==="incompatible").length>0)throw new C("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,TF(r));return r}function gv(e,t,n){let r=Ih(e,t,n);if(e===void 0&&r.some((o)=>o.relation==="incompatible"))throw new C("state_corrupt","HolyCodex has ambiguous transaction state and cannot recover safely.",void 0,TF(r));return r}function TF(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 ss(e={},t={},n=process.env){if(ke(sd,e)===void 0)throw new C("install_failed","The installation options are invalid.");let r=wr(t,n),o=await Qe(r.installOptions),i=await Qe(r.activeRecord),a=_F(o,r.installOptions),s=a===void 0?void 0:_d(a);Tr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let c=await $i(r);if(c!==void 0&&!await qc(c))throw new C("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:r.activeRecord});let l=await Rr(r.preparingRecord,c),u=await Rr(r.conflictedRecord,c);hv(c,l,u);let d=[u,l].find((M)=>M!==void 0&&(c===void 0||wd(M,c)));if(d!==void 0){await Promise.resolve().then(() => Eh());let G=await bd(t,n);if(G.preserved.length>0||G.reasons.length>0)throw new C("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:G.preserved.join(","),reasons:G.reasons.join(",")});return await ss({profile:e.profile??s?.profile??d.profile,tier:e.tier??s?.tier??d.tier,optional:{browser_use:e.optional?.browser_use??s?.optional?.browser_use??d.optional_selections.browser_use,computer_use:e.optional?.computer_use??s?.optional?.computer_use??d.optional_selections.computer_use,sites:e.optional?.sites??s?.optional?.sites??d.optional_selections.sites},officialPlugins:e.officialPlugins??s?.officialPlugins??Rv(d)},t,n)}let p=nK(e.profile??s?.profile,c?.profile),f=rK(e.tier??s?.tier,c?.tier),m=s?.optional,y=_v(m,e.optional),g=oK(y,c?.optional_selections),_=_v(_v(c?.explicit_optional_selections,m),e.optional),I=e.officialPlugins??s?.officialPlugins??Rv(c),b=t.runtime??rs(n),A=await os(b,!1),O=await Th(b,!1,c?.tooling?.context7).then(()=>!0,()=>!1),v=A,w,k,P=[...new Set(gc(OF(g),I).map((M)=>mr(M)??M))],L;try{L=t.officialPluginManager??await Xa.discover({...n,CODEX_HOME:r.codexHome})}catch(M){throw new C("capability_denied","Native Codex plugin installation is unavailable.",M,{recovery:"Install or expose Codex, then retry."})}if(!L.addMarketplace||!L.add||!L.list)throw new C("install_failed","Native Codex plugin installation and verification are unavailable.");let j;try{j=await L.list()}catch(M){throw new C("capability_denied","Native Codex plugin state could not be read safely.",M)}let Ie=P.filter((M)=>{if(!M.endsWith("@openai-curated"))return!1;let G=Cr(j,M);return!(G?.installed&&G.enabled)});Tr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let ft=c?.install_id??crypto.randomUUID().replaceAll("-",""),It=await ud(),wn=c!==void 0&&c.version!==It&&c.owned_plugins?.includes(ln)===!0?new Set([ln]):new Set,Je=new Set(c?.owned_plugins??[]),bt=new Set([ln,...P]),Lt=[...Je].filter((M)=>!bt.has(M));if(Lt.length>0&&L.remove===void 0)throw new C("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:Lt.join(",")});let eo=(t.now?.()??new Date).toISOString(),to=Rd(p,f,{browserUse:g.browser_use,computerUse:g.computer_use,frontend:Et.frontend,security:Et.security,...b.platform==="win32"?{windowsGitBashExecutable:A.status==="healthy"?A.path:es}:{}}),Vi=await Qe(r.configFile),jv;try{jv=cn(Vi,r.configFile)}catch(M){if(M instanceof C&&M.code==="state_corrupt")await Hz(t,M,r.configFile);throw M}let Vh=c?.managed_config??Qm({schema:Rn,installId:ft}),Hv=await Mh(jv,Vh),Wh=await $z(t,r.configFile,Hv.document,['plugins."holycodex@holycodex"',"marketplaces.holycodex",...Object.keys(to)]),{document:Vc,conflicts:Wc,decisions:GF}=Wh,Wi=await Ah(Vc),zh=c?.plugin_config?.before??Wi,no=zh,us=t.resolveConflicts!==void 0,ds=[],zc=[],Kc=[];if(zc=["preference","marketplace"].filter((G)=>{let N=Wi[G].digest,ye=Wi[G],Ge=G==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:$c},Dt=ye.presence==="present"&&JSON.stringify(ye.safe_value)!==JSON.stringify(Ge),je=c?.plugin_config!==void 0&&N!==c.plugin_config.after[G].digest&&N!==c.plugin_config.before[G].digest;return Dt||je}).map((G)=>{let N=G==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",ye=Wi[G],Ge=G==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:$c};return Or({path:r.configFile,key:N,action:"replace",category:"config-key",target:N,existing:ye.safe_value??{presence:ye.presence},desired:Ge,explanation:`The existing ${N} entry does not match the HolyCodex plugin configuration.`,...G==="preference"&&hF(Vc,"plugins",Ui)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),us)ds.push(...zc);let Kh=[...new Set([...P,...(c?.provider_config??[]).map((M)=>M.plugin_id),...c?.owned_plugins??[]])].filter((M)=>M!==ln),zi=await Ph(Vc,Kh);{let M=new Set(c?.owned_plugins??[]);if(Kc=zi.filter((N)=>{let ye=c?.provider_config?.find((je)=>je.plugin_id===N.plugin_id),Ge=M.has(N.plugin_id)&&ye!==void 0&&N.before.digest!==ye.after.digest&&N.before.digest!==ye.before.digest,Dt=P.includes(N.plugin_id)&&N.before.presence==="present"&&N.before.safe_value?.value!==!0;return Ge||Dt}).map((N)=>{let ye=`plugins."${N.plugin_id}"`;return Or({path:r.configFile,key:ye,action:"replace",category:"config-key",target:ye,existing:N.before.safe_value??{presence:N.before.presence},desired:{kind:"boolean",value:!0},explanation:`The existing provider plugin entry ${N.plugin_id} does not match the selected plugin configuration.`,...P.includes(N.plugin_id)&&hF(Vc,"plugins",N.plugin_id)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),us)ds.push(...Kc)}let Jh=zi.map((M)=>{let G=c?.provider_config?.find((N)=>N.plugin_id===M.plugin_id);return G===void 0?M:{plugin_id:M.plugin_id,before:G.before,after:G.before}}),Pd=Jh,Bv=Hv.state,Vv=await Sv(Vc,Bv,c),Wv=await Mh(Vv.document,Vv.state),zv=await bv(Wv.document,Wv.state),{document:Er,state:Xn}=zv;Kz(Er,Xn);let ps;if(c!==void 0){ps=Rd(c.profile,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use,frontend:Et.frontend,security:Et.security,...c.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:c.tooling.git_bash.path}:{}});let M=Fm(c.version.split("-",1)[0]);for(let G of Kr){let N=c.managed_artifacts.find(({path:ye})=>ye.endsWith(`/${G}.toml`));ps[`agents."${G}".config_file`]=N?.path??`holycodex/agents/${G}.toml`}if(Nu(M,Nz)<0)ps.model="gpt-6-astra",ps.model_reasoning_effort=c.profile==="low"?"low":c.profile==="default"?"medium":"high";delete ps.developer_instructions}let Gh=await zz(Er,Xn,to,ps),fs;try{fs=await _c(Er,Xn,Gh,{schema:Rn,installId:ft})}catch(M){if(M instanceof C)throw M;throw new C("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",M,{recovery:"Converge the conflicting Codex setting, then retry."})}let Jc=[];if(fs.driftedKeys.length>0)Jc=fs.driftedKeys.map((M)=>{let G=Xn.managed[M],N=he(Er,M),ye=to[M];return Or({path:r.configFile,key:M,action:"replace",category:"config-key",target:M,existing:N??G?.lastManagedValue,desired:ye,explanation:`The managed Codex setting ${M} changed outside the previous transaction.`})});let Md=Object.entries(to).flatMap(([M,G])=>{let N=M;if(Xn.managed[N]!==void 0)return[];let ye=he(Er,N);if(ye===void 0||JSON.stringify(ye)===JSON.stringify(G))return[];return[Or({path:r.configFile,key:N,action:"replace",category:"config-key",target:N,existing:ye,desired:G,explanation:`The existing Codex setting ${N} is user-owned and differs from the HolyCodex install value.`,defaultDecision:"keep",validDecisions:["keep","replace","cancel"]})]});if(us)ds.push(...Md);if(us)ds.push(...Jc);let Gc;try{Gc=await xh(r.codexHome,p,c?.managed_artifacts,f,b.platform==="win32"?A.status==="healthy"?A.path:es:void 0,{browserUse:g.browser_use,computerUse:g.computer_use})}catch(M){throw new C("install_failed",Cd(M),M)}if(us)ds.push(...Gc.map(Or));let Nd=[...Wc,...zc,...Kc,...Md,...Jc,...Gc.map(Or)],YF=new Set(Wc.map((M)=>M.identity)),ZF=us?ds:Nd.filter((M)=>!YF.has(M.identity)),Kv=await Dh(t,ZF,!0),ro={...Kv,decisions:new Map([...GF,...Kv.decisions])},Jv=[],Yc={...Gh},Fd=Xn.managed,Gv=async()=>{Jv=Gc.map((Dt)=>{let je=Or(Dt),at=ro.decisions.get(je.identity);return at===void 0?je:{...je,decision:at}});let M=await gF(Er,Er,zh,Jh,Wi,zi,zc,Kc,ro.decisions,P),G=Fh(M.document,Wc,ro.decisions);no=M.pluginConfigBefore,Pd=M.providerConfigBefore;let N={...Xn.managed},ye={...Gh};for(let Dt of[...Md,...Jc]){let je=Dt.key;if(je===void 0)continue;let at=je,_t=ro.decisions.get(Dt.identity);if(_t!=="keep"&&_t!=="replace")throw new C("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:je});let io=N[at],qn=to[at];if(qn===void 0)throw new C("state_corrupt","The managed conflict cannot be verified.",void 0,{path:r.configFile,key:je});let Ki=he(Er,at);if(_t==="replace"){if(G=ki(G,at,qn),io!==void 0)N[at]={...io,lastManagedValue:await sn(at,qn)}}else{if(delete ye[at],io===void 0)continue;if(Ki===void 0){delete N[at];continue}N[at]={...io,lastManagedValue:await sn(at,Ki)}}}if(fs=await _c(G,{...Xn,managed:N},ye,{schema:Rn,installId:ft}),fs.driftedKeys.length>0)throw new C("state_corrupt","The accepted managed conflicts did not converge.");Yc=ye;let Ge={...Xn.managed};for(let Dt of[...Md,...Jc]){let je=Dt.key;if(je===void 0)continue;let at=he(Er,je),_t=Ge[je];if(_t!==void 0&&at===void 0)delete Ge[je];else if(_t!==void 0&&at!==void 0)Ge[je]={..._t,lastManagedValue:await sn(je,at)}}Fd=Ge};await Gv();let Yv=()=>Nd.map((M)=>{let G=Or(M),N=ro.decisions.get(G.identity);return N===void 0?G:{...G,decision:N}}),Zv=(M)=>Object.fromEntries(["config-key","invalid-config","native-plugin","role-asset"].flatMap((G)=>{let N=M.filter((ye)=>ye.category===G).length;return N===0?[]:[[G,N]]})),Ld=Yv(),Xv=Zv(Ld),XF=iK(A,O,j,P);if(t.reviewInstall!==void 0)while(!0){let M=await t.reviewInstall({operation:c===void 0?"install":"upgrade",...c===void 0?{}:{fromVersion:c.version},toVersion:It,profile:p,tier:f,capabilities:{browser_use:g.browser_use,computer_use:g.computer_use,sites:g.sites},additionalPlugins:[...I],conflicts:Ld,conflictCounts:Xv,tools:XF});if(M.action==="cancel")throw new C("confirmation_required","Install review was cancelled.");if(M.action==="resolve"){if(Nd.length===0)throw new C("confirmation_required","There are no managed conflicts to resolve.");ro=await Dh(t,Nd,!0),await Gv(),Ld=Yv(),Xv=Zv(Ld);continue}if(M.action==="change"){if(M.request===void 0)throw new C("confirmation_required","Changing install options requires a revised request.");return await ss(M.request,t,n)}if(M.action==="apply")break;throw new C("confirmation_required","Unknown install review action.")}let Yh={owner:"holycodex",schema_epoch:Rn,install_id:ft,version:It,digest:c?.digest??"0".repeat(64),profile:p,tier:f,optional_selections:g,explicit_optional_selections:_,official_plugins:P,capability_state:Lh(g),managed_artifacts:c?.managed_artifacts??[],installed_at:eo,status:"preparing",step:"validated",managed_config:Bv,plugin_snapshot:[],plugin_config:{plugin_id:ln,before:no,after:no},provider_config:Pd,owned_plugins:[...Je],...c?.tooling===void 0?{}:{tooling:c.tooling}};await ld(r.stateRoot),await Zn(r.preparingRecord,Yh);let Zc=[],oo,Qv=!1,eR=new Set,Zh=new Set,Dd=new Set,vn=new Set(Je),Xh=new Set(Je),Qh=new Set,fe=Yh,tR=!1,kr,Xc=fs.state,nR=!1,rR=!1;try{try{v=await os(b,!0)}catch(le){if(le instanceof pe)throw new C("capability_denied",le.message,le,le.details);throw le}try{w=await Th(b,!0,c?.tooling?.context7)}catch(le){k=`Optional ctx7 is unavailable: ${Cd(le)}`}let M=w??c?.tooling?.context7,G={git_bash:v,...M===void 0?{}:{context7:M}},N={...Yh,tooling:G};if(fe=N,await Zn(r.preparingRecord,fe),L.ensureOfficialMarketplace!==void 0&&Ie.length>0)try{await L.ensureOfficialMarketplace(Ie)}catch(le){throw new C("capability_denied",`The selected official Codex provider marketplace is unavailable: ${Cd(le)}`,le,{recovery:"Check Codex network and marketplace policy, then retry."})}try{Zc=await Jz({list:()=>L.list()},[...new Set([ln,...P,...Je])])}catch(le){throw new C("capability_denied","Native Codex plugin state could not be read safely.",le)}N={...N,plugin_snapshot:Zc},fe=N,await Zn(r.preparingRecord,fe);let ye=cn(await Qe(r.configFile),r.configFile),Ge=Fh(ye,Wc,ro.decisions);await Wz(Ge,Wi,zi);let Dt=await Sv(Ge,Vh,c),je=await Mh(Dt.document,Dt.state);kr=(await bv(je.document,je.state)).document,await xF(kr,Er,{...Xn,managed:Fd},Yc),Tr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await ld(r.roleRoot),oo=await Gw(r.codexHome,p,c?.managed_artifacts,f,v.status==="healthy"?v.path:void 0,Gc.length===0?t.resolveConflict:void 0,Jv,{browserUse:g.browser_use,computerUse:g.computer_use}),fe={...N,step:"roles_prepared",managed_artifacts:oo.managed_artifacts},await Zn(r.preparingRecord,fe),Tr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),Tr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),tR=!0;let _t=kr;if(_t===void 0)throw new C("state_corrupt","The pre-mutation configuration baseline is missing.");_t=Ho(_t,"plugins",Ui,{enabled:!0}),_t=Ho(_t,"marketplaces",jc,{source_type:"git",source:$c});for(let le of P)_t=Ho(_t,"plugins",le,{enabled:!0});let io=await Ah(_t),Ki=(await Ph(_t,Kh)).map((le)=>({plugin_id:le.plugin_id,before:zi.find((mt)=>mt.plugin_id===le.plugin_id)?.before??le.before,after:le.before}));fe={...fe,plugin_config:{plugin_id:ln,before:no,after:io},provider_config:Ki},await Zn(r.preparingRecord,fe),await L.addMarketplace(Mz),await Qz({list:()=>L.list(),add:(le)=>L.add(le)},[ln,...P],wn,async(le,mt)=>{if(mt==="new")eR.add(le),vn.add(le),Xh.add(le),fe={...fe,owned_plugins:[...vn]};else Qh.add(le),vn.add(le),Xh.add(le),fe={...fe,owned_plugins:[...vn]};await Zn(r.preparingRecord,fe)}),fe={...fe,step:"plugins_installed"},await Zn(r.preparingRecord,fe),Tr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let iR=await Qe(r.configFile),QF=cn(iR,r.configFile),eL=Fh(QF,Wc,ro.decisions),aR=await Sv(eL,Vh,c),sR=await Mh(aR.document,aR.state),tL=await bv(sR.document,sR.state);if(kr===void 0)throw new C("state_corrupt","The pre-mutation configuration baseline is missing.");let eg=await gF(tL.document,kr,zh,Jh,Wi,zi,zc,Kc,ro.decisions,P),Ji=eg.document;for(let le of Object.keys(Fd)){let mt=le,ao=he(kr,mt);Ji=ao===void 0?br(Ji,mt):ki(Ji,mt,ao)}no=eg.pluginConfigBefore,Pd=eg.providerConfigBefore;let qd=await Ah(Ji),cR=await Ph(Ji,Kh),lR=cR.map((le)=>({plugin_id:le.plugin_id,before:Pd.find((mt)=>mt.plugin_id===le.plugin_id)?.before??le.before,after:le.before})),uR=cR.map((le)=>({plugin_id:le.plugin_id,before:zi.find((mt)=>mt.plugin_id===le.plugin_id)?.before??le.before,after:le.before}));fe={...fe,plugin_config:{plugin_id:ln,before:no,after:qd},provider_config:uR};let dR={};for(let[le,mt]of Object.entries(Fd)){let ao=le,mR=he(kr,ao);dR[ao]={...mt,...mR===void 0?{}:{lastManagedValue:await sn(ao,mR)}}}let pR={...Xn,managed:dR};await xF(Ji,kr,pR,Yc);let $d=await _c(Ji,pR,Yc,{schema:Rn,installId:ft});if($d.driftedKeys.length>0)throw new C("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:$d.driftedKeys.join(",")});if(Tr(t,{stage:"config",status:"started",message:"Configuring Root"}),Xc=$d.state,fe={...fe,managed_config:Xc,plugin_config:{plugin_id:ln,before:no,after:qd},provider_config:uR},await Qe(r.configFile)!==iR)throw new C("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:r.configFile});if(await Fn(r.configFile,vd($d.document)),Qv=!0,fe={...fe,step:"config_published"},await Zn(r.preparingRecord,fe),Lt.length>0)await eK({list:()=>L.list(),remove:(mt)=>L.remove(mt)},Lt,async(mt,ao)=>{if(ao==="removed")Zh.add(mt),vn.delete(mt);else if(ao==="absent")vn.delete(mt);else Dd.add(mt);fe={...fe,owned_plugins:[...vn]},await Zn(r.preparingRecord,fe)});Tr(t,{stage:"config",status:"completed",message:"Root configuration published"}),Tr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await Yz(r,p,f,{browserUse:g.browser_use,computerUse:g.computer_use,frontend:Et.frontend,security:Et.security,...v.status==="healthy"?{windowsGitBashExecutable:v.path}:{}},Xc,oo.preserved,Yc),Tr(t,{stage:"verification",status:"completed",message:"Installation verified"});let fR=Lh(g),nL=await qh({owner:"holycodex",install_id:ft,version:It,profile:p,tier:f,optional_selections:g,explicit_optional_selections:_,official_plugins:P,capability_state:fR,managed_artifacts:oo.managed_artifacts,managed_config:Xc,plugin_config:{plugin_id:ln,before:no,after:qd},provider_config:lR,plugin_snapshot:Zc,owned_plugins:[...vn],tooling:G}),tg={owner:"holycodex",schema_epoch:Rn,install_id:ft,version:It,digest:nL,profile:p,tier:f,optional_selections:g,explicit_optional_selections:_,official_plugins:P,capability_state:fR,managed_artifacts:oo.managed_artifacts,installed_at:eo,status:"active",step:"active",managed_config:Xc,plugin_snapshot:Zc,plugin_config:{plugin_id:ln,before:no,after:qd},provider_config:lR,owned_plugins:[...vn],tooling:G};if(ke(Cc,tg)===void 0)throw new C("state_corrupt","The HolyCodex configuration is invalid.");return nR=!0,await Ja(r.activeRecord,_n(tg)),rR=!0,await wF(r,RF(p,f,g,I)),await Nh(r.preparingRecord),await Nh(r.conflictedRecord),Tr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:tg,optional_plugins:P,preserved:oo.preserved,warnings:[...oo.preserved.length===0?[]:["modified managed files were preserved"],...k===void 0?[]:[k]]}}catch(M){let G=[];if(nR)try{if(i===void 0)await wv(r.activeRecord,{force:!1}).catch((N)=>{if(!it(N,"ENOENT"))throw N});else await Fn(r.activeRecord,i)}catch{G.push("active_record")}if(rR)try{if(o===void 0)await wv(r.installOptions,{force:!1}).catch((N)=>{if(!it(N,"ENOENT"))throw N});else await Fn(r.installOptions,o)}catch{G.push("install_options")}if(tR||Qv)try{if(kr!==void 0)await Gz(r.configFile,fe,kr,Xh)}catch{G.push("config")}if(oo!==void 0)try{if((await Sh(oo.rollback)).preserved.length>0)G.push("roles")}catch{G.push("roles")}if(Qh.size>0)G.push(...[...Qh].map((N)=>`plugin:${N}`));for(let N of eR)try{await L.remove?.(N)}catch{G.push(`plugin:${N}`)}for(let N of new Set([...Zh,...Dd]))try{await tK({list:()=>L.list(),add:(ye)=>L.add(ye)},N,Zc.find((ye)=>ye.plugin_id===N)?.status),Zh.delete(N),Dd.delete(N),vn.add(N),fe={...fe,owned_plugins:[...vn]},await Zn(r.preparingRecord,fe)}catch{vn.add(N),Dd.add(N),fe={...fe,owned_plugins:[...vn]},await Zn(r.preparingRecord,fe).catch(()=>{return}),G.push(`plugin:${N}`)}if(w?.ownership==="holycodex"&&c?.tooling?.context7?.ownership!=="holycodex")try{if(!await Sd(b,w))G.push("context7")}catch{G.push("context7")}if(G.length>0){try{let ye=cn(await Qe(r.configFile),r.configFile),Ge=fe.plugin_config,Dt=await Ah(ye),je=Ge===void 0?void 0:{...Ge,after:{preference:Dt.preference.digest===Ge.before.preference.digest?Ge.before.preference:Ge.after.preference,marketplace:Dt.marketplace.digest===Ge.before.marketplace.digest?Ge.before.marketplace:Ge.after.marketplace}},at=fe.provider_config,_t=await Ph(ye,at?.map((qn)=>qn.plugin_id)??[]),io=at?.map((qn)=>{let Ki=_t.find((oR)=>oR.plugin_id===qn.plugin_id);return Ki!==void 0&&Ki.before.digest===qn.before.digest?{...qn,after:qn.before}:qn});fe={...fe,...je===void 0?{}:{plugin_config:je},...io===void 0?{}:{provider_config:io}}}catch{}let N=!1;try{await Zn(r.conflictedRecord,{...fe,step:"conflicted",status:"conflicted"}),N=!0}catch{}if(N)await Nh(r.preparingRecord).catch(()=>{return})}else await Nh(r.preparingRecord).catch(()=>{return});if(M instanceof Yn)throw M;if(M instanceof C)throw M;throw new C(M instanceof Xr||M instanceof Vo?"capability_denied":"install_failed",Cd(M),M,G.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function $i(e){let t=await Bw(e.activeRecord,id);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:ke(Cc,t);if(o!==void 0)return o;let i=ke(F0,t);if(i===void 0)throw new C("state_corrupt","The HolyCodex configuration is invalid.");if(!await CF(i))throw new C("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 C("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=Um(a)}catch(j){throw new C("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,j,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([j])=>j!=="plan")):i,{optional_selections:l,explicit_optional_selections:u}=i,d={browser_use:l.browser_use??Xt.browser_use,computer_use:l.computer_use,sites:l.sites??Xt.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:Lh(d,new Map([["browser_use","missing"],["sites","missing"]])),m=(i.official_plugins??[]).filter((j)=>!Od(j)),y=i.owned_plugins?.filter((j)=>!Od(j)),g=i.provider_config?.filter((j)=>!Od(j.plugin_id)),_=i.plugin_snapshot?.filter((j)=>!Od(j.plugin_id)),{optional_selections:I,explicit_optional_selections:b,capability_state:A,official_plugins:O,owned_plugins:v,provider_config:w,plugin_snapshot:k,...P}=c,L={...P,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},..._===void 0?{}:{plugin_snapshot:_},digest:await qh({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},..._===void 0?{}:{plugin_snapshot:_},...y===void 0?{}:{owned_plugins:y},...i.tooling===void 0?{}:{tooling:i.tooling}})};return bF.set(L,i.digest),L}async function Rr(e,t){let n=await Bw(e,id);if(n===void 0)return;let r=ke(Li,n);if(r!==void 0)return r;let o=ke(q0,n);if(o===void 0)throw new C("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 C("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e});let s;try{s=Um(a)}catch(P){throw new C("state_corrupt","The persisted transaction profile requires an explicit replacement.",P,{path:e,profile:a})}let{optional_selections:c,explicit_optional_selections:l}=i,u={browser_use:c.browser_use??Xt.browser_use,computer_use:c.computer_use??!1,sites:c.sites??Xt.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:Lh(u,new Map([["browser_use","missing"],["sites","missing"]])),{plan:m,profile:y,optional_selections:g,explicit_optional_selections:_,capability_state:I,...b}=i,A=typeof b.digest==="string"?b.digest:void 0,O=t===void 0?void 0:bF.get(t),v=t!==void 0&&b.install_id===t.install_id&&(A===t.digest||O!==void 0&&A===O)?t.digest:A,w={...b,profile:s,optional_selections:u,explicit_optional_selections:d,...f===void 0?{}:{capability_state:f},...v===void 0?{}:{digest:v}},k=ke(Li,w);if(k===void 0)throw new C("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e});return k}function OF(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites}}function cn(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):tv(e),o=ke($a,r);if(o===void 0){let i=vv(r),a=i===void 0?"an unsupported TOML value":`the TOML value ${i}`;throw new C("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 C)throw n;let r=Cd(n),o=Uz(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 C("state_corrupt",i,n,{path:t,parser_message:r,...o===void 0?{}:o,reason:"invalid_toml_syntax"})}}function vv(e,t=[]){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number")return Number.isFinite(e)?void 0:xv(t);if(Array.isArray(e)){for(let[n,r]of e.entries()){let o=vv(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 xv(t);for(let[r,o]of Object.entries(e)){let i=vv(o,[...t,r]);if(i!==void 0)return i}return}return xv(t)}function xv(e){return e.length===0?"<root>":e.join(".")}function Lz(e,t){let n=new Map;for(let r of t)for(let o of Dz(r)){let i=he(e,o);if(i!==void 0&&!ji(i))n.set(o,i)}return[...n].map(([r,o])=>({key:r,value:o}))}function Dz(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 qz(e,t){let n=JSON.stringify(t.value);return new C("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 $z(e,t,n,r){let o=Lz(n,r).map((a)=>{let s=qz(t,a);return Or({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 Dh(e,o,!0);return{document:Fh(n,o,i.decisions),conflicts:o,decisions:i.decisions}}function Fh(e,t,n){let r=e;for(let o of t){if(n.get(o.identity)!=="remove"||o.key===void 0)throw new C("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=he(r,o.key);if(a===void 0)continue;if(JSON.stringify(a)!==JSON.stringify(o.existing))throw new C("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=br(r,o.key)}return r}function Uz(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=jz(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
+ `,c+1);n=l<0?e.length:l}if(n===void 0)return;let a=e.slice(0,n).split(`
43
+ `).length,s=e.lastIndexOf(`
44
+ `,Math.max(0,n-1));return{offset:n,line:a,column:n-s}}function jz(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 Hz(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=Or({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 Dh(e,[i],!0)}catch{}}function vd(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):nv(e)).trimEnd()}
46
+ `}catch(t){throw new C("install_failed","The merged Codex configuration is not writable.",t)}}async function Ah(e){return{preference:await cs(e,"plugins",Ui),marketplace:await cs(e,"marketplaces",jc)}}async function Ph(e,t){return await Promise.all(t.map(async(n)=>{let r=await cs(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 Lc(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",Ui],["marketplace","marketplaces",jc]]){let u=t.before[s],d=t.after[s],p=await cs(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=Tv(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=Ho(r,c,l,Vz(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function Dc(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 cs(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=Tv(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=Ho(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 mF(e,t,n,r,o,i){if(o.presence!=="present"||o.safe_value!==void 0)return{document:e,restored:!1};let a=await cs(e,n,r);if(a.digest===o.digest||a.digest!==i.digest)return{document:e,restored:!1};let s=Uc(t,n,r);if(s===void 0)return{document:e,restored:!1};return{document:Ho(e,n,r,s),restored:!0}}async function cs(e,t,n){let r=Uc(e,t,n),o=await xr("holycodex-plugin-config",[yr(_n({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=Bz(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function Uc(e,t,n){let r=e[t];if(!ji(r))return;return r[n]}function hF(e,t,n){let r=Uc(e,t,n);return ji(r)&&r.enabled===!1}function Bz(e,t){if(!ji(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!==$c)return;return{kind:"marketplace",source_type:"git",source:$c}}function Vz(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function Ho(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!ji(i))throw new C("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function Tv(e,t,n){let r=e[t];if(!ji(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 ji(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function Wz(e,t,n){let r=[{parent:"plugins",key:Ui,expected:t.preference},{parent:"marketplaces",key:jc,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 cs(e,o,i)).digest!==a.digest)throw new C("confirmation_required","Plugin configuration changed after preflight; review the latest configuration and retry.",void 0,{key:`${o}.${i}`})}async function gF(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 C("state_corrupt","A plugin configuration conflict has no identity.");let y=c.get(m);if(y!=="keep"&&y!=="replace")throw new C("confirmation_required",`Plugin configuration conflict resolution is incomplete for ${f.key??m}.`);let g=f.key==='plugins."holycodex@holycodex"'?"preference":"marketplace",_=o[g];if(y==="keep"){let I=Uc(t,"plugins",Ui);if(g==="preference"&&ji(I)&&I.enabled===!1)throw new C("confirmation_required","Keeping disabled HolyCodex config would disable the selected plugin.");u=yF(u,t,f.key),d={...d,[g]:_};continue}u=Ho(u,g==="preference"?"plugins":"marketplaces",g==="preference"?Ui:jc,g==="preference"?{enabled:!0}:{source_type:"git",source:$c})}for(let f of s){let{identity:m,key:y}=f;if(m===void 0||y===void 0)throw new C("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 C("state_corrupt",`The provider configuration conflict key ${y} is invalid.`);let _=c.get(m);if(_!=="keep"&&_!=="replace")throw new C("confirmation_required",`Provider configuration conflict resolution is incomplete for ${y}.`);let I=i.find((b)=>b.plugin_id===g);if(I===void 0)throw new C("state_corrupt",`The provider configuration entry ${g} is missing.`);if(_==="keep"){let b=Uc(t,"plugins",g);if(l.includes(g)&&ji(b)&&b.enabled===!1)throw new C("confirmation_required",`Keeping disabled config would disable selected plugin ${g}.`);u=yF(u,t,y),p=p.map((A)=>A.plugin_id===g?{plugin_id:g,before:I.before,after:I.before}:A);continue}u=Ho(u,"plugins",g,{enabled:!0})}return{document:u,pluginConfigBefore:d,providerConfigBefore:p}}function yF(e,t,n){if(n===void 0)throw new C("state_corrupt","A configuration conflict has no key.");if(n.startsWith('plugins."')&&n.endsWith('"')){let o=n.slice(9,-1),i=Uc(t,"plugins",o);return i===void 0?Tv(e,"plugins",o):Ho(e,"plugins",o,i)}let r=he(t,n);return r===void 0?br(e,n):ki(e,n,r)}async function zz(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=he(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 Rd(e,t,n=!1){let r=Kw(e,t),o=typeof n==="boolean"?{}:n,i={browserUse:o.browserUse??Xt.browser_use,computerUse:typeof n==="boolean"?n:o.computerUse??Xt.computer_use,...o.windowsGitBashExecutable===void 0?{}:{windowsGitBashExecutable:o.windowsGitBashExecutable}},a=Za(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:Jw({...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 Kr)s[`agents."${c}".config_file`]=pd(c,a);return s}async function xF(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await Ha(e,n,a)).status==="drifted")o.push(a);continue}let c=he(t,a),l=he(e,a),u=_n(c===void 0?null:c),d=_n(l===void 0?null:l);if(Pn(u)!==Pn(d))o.push(a)}if(o.length>0)throw new C("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function Sv(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 _r(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new C("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=he(i,u);if(typeof d!=="string")continue;let p=d.replaceAll("\\","/").replace(/^\.\//u,"");if(p===`agents/${c}.toml`||p===`holycodex/agents/${c}.toml`)i=br(i,u)}return{document:i,state:a}}async function bv(e,t){let n=t.managed[yv];if(n===void 0)return{document:e,state:t};let r=await _r(e,{...t,managed:{[yv]:n}},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>i!==yv));return{document:r.document,state:{...t,managed:o}}}async function Mh(e,t){let n=Object.fromEntries(Object.entries(t.managed).filter(([i])=>Ii.includes(i)));if(Object.keys(n).length===0)return{document:e,state:t};let r=await _r(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 Kz(e,t){if(he(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new C("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function Jz(e,t){let n=await e.list();return t.map((r)=>{let o=Cr(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function Zn(e,t){if(ke(Li,t)===void 0)throw new C("state_corrupt","The HolyCodex transaction state is invalid.");await Ja(e,_n(t))}async function Nh(e){await wv(e,{force:!1}).catch((t)=>{if(!it(t,"ENOENT"))throw t})}async function Gz(e,t,n,r){let o=await Qe(e);if(o===void 0)return;let i=cn(o,e),a={},s=0;for(let[p,f]of Object.entries(t.managed_config.managed)){let m=p,y=he(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 _=he(i,m);if(_!==void 0&&JSON.stringify(await sn(m,_))===JSON.stringify(f.lastManagedValue))i=ki(i,m,y),s+=1;continue}a[p]={...f,originalValue:g??{kind:"absent"}}}let c=await _r(i,{...t.managed_config,managed:a},{schema:Rn,installId:t.install_id});i=c.document;let l=t.plugin_config===void 0?void 0:await Lc(i,t.plugin_config,{allowBeforeState:!0});if(l!==void 0)i=l.document;let u=t.provider_config===void 0?void 0:await Dc(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",Ui],["marketplace","marketplaces",jc]]){let y=await mF(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 mF(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 Fn(e,vd(i))}async function Yz(e,t,n,r,o,i=[],a=Rd(t,n,r)){let s=await Qe(e.configFile),c=cn(s,e.configFile),l=a;for(let[m,y]of Object.entries(l)){let g=he(c,m);if(m==="developer_instructions"){if(typeof g!=="string"||g!==y||await Zz(m,g)!==o.managed[m]?.lastManagedValue.value)throw new C("install_failed","The effective Root instructions did not converge.")}else if(g!==y)throw new C("install_failed",`The effective Codex setting ${m} did not converge.`)}let u={browserUse:r.browserUse??Xt.browser_use,computerUse:r.computerUse,...r.windowsGitBashExecutable===void 0?{}:{windowsGitBashExecutable:r.windowsGitBashExecutable}},d=Za(t,n,u),p=jo(t,n);for(let m of p){let y=`agents."${m.name}".config_file`,g=he(c,y);if(typeof g!=="string")throw new C("install_failed",`The ${m.name} registration is missing.`);let _=pd(m.name,d),I=ja(e.configFile,_),b=I.replaceAll("\\","/");if(ja(e.configFile,g).replaceAll("\\","/")!==b)throw new C("install_failed",`The ${m.name} registration is stale (expected ${_}; received ${g}).`);let O=await Qe(I);if(O===void 0)throw new C("install_failed",`The ${m.name} role file is missing.`);if(i.some((w)=>w.replaceAll("\\","/")===b))throw new C("install_failed",`The ${m.name} role file was kept after a conflict and cannot be activated.`);let v=cn(O,I);if(v.name!==m.name||typeof v.description!=="string"||typeof v.model!=="string"||typeof v.model_reasoning_effort!=="string"||typeof v.service_tier!=="string"||typeof v.developer_instructions!=="string"||!_h(m,v)||v.approval_policy!=="never"||v.web_search!==(m.permissions.network?"live":"disabled")||v.tool_output_token_limit!==void 0||he(v,"agents.enabled")!==!1||he(v,"features.multi_agent")!==!1||he(v,"features.multi_agent_v2")!==!1||he(v,"features.agent_message_board")!==!1||he(v,"features.context_management.experimental_mode")!==!0||Object.keys(v.features??{}).some((w)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(w)))throw new C("install_failed",`The ${m.name} role file is malformed.`)}let f=await Qe(`${e.codexHome}/agents/root.toml`);if(f!==void 0&&Ac(f))throw new C("install_failed","A stale HolyCodex Root role remains installed.")}async function Zz(e,t){return await xr("holycodex-managed-config-value",[yr({keyPath:e,value:t})])}function _v(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 Xz(e){return["browser_use","computer_use","sites"].find((t)=>No[t].pluginIds.includes(e))}function Rv(e){return(e?.official_plugins??[]).filter((t)=>{if(Od(t))return!1;let n=Xz(t);return n===void 0||e?.optional_selections[n]!==!0})}function Od(e){let t=e.slice(0,e.lastIndexOf("@"));return Fz.has(t)}async function Qz(e,t,n=new Set,r){for(let o of t){let i=n.has(o),a;try{a=Cr(await e.list(),o)}catch(l){throw Bo("list",l,o)}if(a?.installed&&!a.enabled)throw new Vo("uncertain",`${o} is disabled`);let s=i||!(a?.installed&&a.enabled);if(s)try{await e.add(o)}catch(l){try{let u=Cr(await e.list(),o);if(i||!SF(a,u))await r?.(o,"uncertain")}catch{await r?.(o,"uncertain")}throw Bo("add",l,o)}let c;try{c=Cr(await e.list(),o)}catch(l){if(s)await r?.(o,"uncertain");throw Bo("list",l,o)}if(!c?.installed){if(s&&(i||!SF(a,c)))await r?.(o,"uncertain");throw new Vo("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 Vo("uncertain",`${o} is disabled after add`)}}}async function eK(e,t,n){for(let r of t){let o;try{o=Cr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),Bo("list",a,r)}if(!(o?.installed??!1)){await n?.(r,"absent");continue}try{await e.remove(r)}catch(a){try{if(!(Cr(await e.list(),r)?.installed??!1))await n?.(r,"removed");else await n?.(r,"uncertain")}catch{await n?.(r,"uncertain")}throw Bo("remove",a,r)}let i;try{i=Cr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),Bo("list",a,r)}if(i?.installed)throw await n?.(r,"uncertain"),new Vo("uncertain",`${r} is still installed after remove`);await n?.(r,"removed")}}async function tK(e,t,n){if(n!=="installed"&&n!=="disabled")throw new Vo("uncertain",`${t} has no proven prior installed state`);let r=n==="installed",o;try{o=Cr(await e.list(),t)}catch(a){throw Bo("list",a,t)}if(o?.installed&&o.enabled===r)return;try{await e.add(t)}catch(a){throw Bo("add",a,t)}let i;try{i=Cr(await e.list(),t)}catch(a){throw Bo("list",a,t)}if(!i?.installed)throw new Vo("missing",`${t} is not installed after restore`);if(i.enabled!==r)throw new Vo("uncertain",`${t} did not regain its prior ${r?"enabled":"disabled"} state`)}function SF(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function Bo(e,t,n){if(t instanceof Xr)return t;return new Xr(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 Cr(e,t){let n=Zr(e,t);if(n!==void 0)return n.entry;let r=mr(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function nK(e,t){let n=e??t??"default";if(!Jr(n).ok)throw new C("install_failed","Unknown profile.");return n}function rK(e,t){let n=e??t??"standard";if(ke(Lo,n)===void 0)throw new C("install_failed","The tier is not supported.");return n}function oK(e,t){let n=t?OF(t):Xt,r=Xb(e,n);return{browser_use:r.browser_use,computer_use:r.computer_use,sites:r.sites,coding:!0}}function Lh(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:[...No[r].pluginIds]};return[r,a]}))}async function qh(e){let{profile:t,plan:n,...r}=e,o=n===void 0?{...r,profile:t}:{...r,plan:n};return await xr("install-record",[yr(_n(o))])}async function qc(e){return await CF(e)}async function CF(e){return await qh({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 Cd(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function iK(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=Cr(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 Or(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 Dh(e,t,n=!1){let r=t.map(Or),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 C)||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 C("confirmation_required",`${s.message} Conflicts: ${c}.`,s,{conflicts:c})}for(let s of r){let c=s.identity,l=ke(M0,a[c]);if(l===void 0||s.validDecisions?.includes(l)===!1){let u=s.validDecisions?.join(", ")??"keep, replace, cancel";throw new C("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 C("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 C("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 C("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 C("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 Tr(e,t){try{e.onProgress?.(t)}catch{}}var Mz="davidbasilefilho/holycodex",ln="holycodex@holycodex",Nz="0.16.8",bF,$c="https://github.com/davidbasilefilho/holycodex.git",Ui="holycodex@holycodex",jc="holycodex",Fz,yv,Vo,C;var Td=S(()=>{Tc();pt();od();dd();wh();md();za();Va();Ec();Oh();Va();bF=new WeakMap;Fz=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]),yv=Ii[0];Vo=class Vo extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};C=class C 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 GK}from"readline/promises";pt();pt();pt();var R_=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."}]),KN=new Set(["codex-home","profile","tier","add-plugin"]),kB=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","sites","no-sites","browser-use","no-browser-use"]);class rt extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Km(e){if(e.length===0)throw new rt("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 Km(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new rt("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 rt("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 rt("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!KN.has(u)&&!kB.has(u))throw new rt("invalid_argument","Unknown option.",{option:`--${c}`});if(KN.has(u)){let d=l??e[o+1];if(d===void 0||d.length===0||d.startsWith("-"))throw new rt("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 rt("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 rt("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new rt("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return IB(t,n,r),{command:t,positionals:n,options:r}}function IB(e,t,n){let r=PB(e);for(let s of Object.keys(n))if(!r.has(s))throw new rt("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 rt("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!Jr(i).ok){let s=AB[i];if(s!==void 0)throw new rt("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 rt("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new rt("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 rt("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 rt("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove"].includes(e)&&n.yes===!1)throw new rt("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 rt("invalid_argument",`Installation options are not valid for ${e}.`)}var AB={"plus-low":"low",plus:"default","plus-high":"high"};function PB(e){switch(e){case"install":return new Set([...R_.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 MB=`HolyCodex
43
47
 
44
48
  Usage:
45
49
  holycodex install [options]
@@ -53,7 +57,7 @@ Options:
53
57
  --json Emit one validated JSON envelope.
54
58
 
55
59
  Use --json for scripts. Install and remove use native Codex plugin management.
56
- `,dB=`Install HolyCodex through Codex native plugin management.
60
+ `,NB=`Install HolyCodex through Codex native plugin management.
57
61
 
58
62
  Usage:
59
63
  holycodex install [options]
@@ -70,7 +74,7 @@ Tier is independent service handling (CLI values are lowercase only):
70
74
  fast-all Fast service handling for Root and leaves.
71
75
 
72
76
  Options:
73
- ${x_.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
77
+ ${R_.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
74
78
  `)}
75
79
  --no-sites / --no-browser-use / --no-computer-use
76
80
  Disable the corresponding plugin.
@@ -82,47 +86,47 @@ On an interactive TTY, install opens one wizard and final review with Install,
82
86
  Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
83
87
  Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
84
88
  remains repeatable on the command line.
85
- `,pB=`Remove HolyCodex-owned state through Codex native plugin management.
89
+ `,FB=`Remove HolyCodex-owned state through Codex native plugin management.
86
90
 
87
91
  Usage:
88
92
  holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
89
93
 
90
94
  Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
91
95
  configuration are preserved; changed owned files are preserved for review.
92
- `,fB=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
96
+ `,LB=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
93
97
 
94
98
  Usage:
95
99
  holycodex doctor [--json] [--codex-home <absolute-path>]
96
- `,mB=`Read or update the canonical public package version.
100
+ `,DB=`Read or update the canonical public package version.
97
101
 
98
102
  Usage:
99
103
  holycodex version [<0.x.y[-n]|patch|minor>] [--dry-run] [--json]
100
104
  holycodex --version
101
105
  holycodex -v
102
- `;function qu(e){switch(e){case"install":return dB;case"remove":return pB;case"doctor":return fB;case"version":return mB;default:return uB}}function S_(e,t={}){let n=vi({...t,stream:"stdout"});return qu(e).split(`
103
- `).map((r)=>{if(r==="HolyCodex")return nt(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return nt(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>nt(o,"option",n)).replace(/<[^>]+>/gu,(o)=>nt(o,"argument",n))}).join(`
104
- `)}function Uu(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function $u(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 vi(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 b_={heading:"#7aa2f7",option:"#7dcfff",argument:"#a9b1d6",focus:"#7dcfff",enabled:"#9ece6a",disabled:"#a9b1d6",success:"#73daca",warning:"#e0af68",error:"#f7768e",hint:"#737aa2"};function nt(e,t,n){if(!n)return e;let r=t==="heading"||t==="focus"?"1;":"",o=b_[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`}dt();xd();var kz=["low","default","high"],Iz=["standard","fast","fast-all"],qi=["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 vi({stdoutIsTTY:t,env:e.env??process.env,stream:"stdout"})}function wd(...e){return e}function ne(e,t){return wd({text:e,...t===void 0?{}:{tone:t}})}function Az(e,t,n){let r=e.fg(b_[n])(t);return n==="heading"||n==="focus"?e.bold(r):r}function Fh(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(Az(e,a.text,a.tone))}if(i<t.length-1)r.push(...e.stringToStyledText(`
106
+ `;function Vu(e){switch(e){case"install":return NB;case"remove":return FB;case"doctor":return LB;case"version":return DB;default:return MB}}function T_(e,t={}){let n=Oi({...t,stream:"stdout"});return Vu(e).split(`
107
+ `).map((r)=>{if(r==="HolyCodex")return ot(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return ot(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>ot(o,"option",n)).replace(/<[^>]+>/gu,(o)=>ot(o,"argument",n))}).join(`
108
+ `)}function Wu(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function zu(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 Oi(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 O_={heading:"#7aa2f7",option:"#7dcfff",argument:"#a9b1d6",focus:"#7dcfff",enabled:"#9ece6a",disabled:"#a9b1d6",success:"#73daca",warning:"#e0af68",error:"#f7768e",hint:"#737aa2"};function ot(e,t,n){if(!n)return e;let r=t==="heading"||t==="focus"?"1;":"",o=O_[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`}pt();Td();var aK=["low","default","high"],sK=["standard","fast","fast-all"],Hi=["sites","browser_use","computer_use"];function Ov(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 Cv(e){let t=e.stdoutIsTTY??(e.stdout===void 0?process.stdout.isTTY===!0:e.stdout.isTTY===!0);return Oi({stdoutIsTTY:t,env:e.env??process.env,stream:"stdout"})}function Ed(...e){return e}function ne(e,t){return Ed({text:e,...t===void 0?{}:{tone:t}})}function cK(e,t,n){let r=e.fg(O_[n])(t);return n==="heading"||n==="focus"?e.bold(r):r}function Uh(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(cK(e,a.text,a.tone))}if(i<t.length-1)r.push(...e.stringToStyledText(`
105
109
  `).chunks)}),r.push(...e.stringToStyledText(`
106
- `).chunks),new e.StyledText(r)}async function Lh(e={},t={}){let n=sn(e),r=await import("@opentui/core"),o=wv(n),i=await r.createCliRenderer({...gv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=yv(t),s=new r.TextRenderable(i,{content:hF(r,o,0,a)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=0,f=!1,m=(A)=>{if(f)return;f=!0,i.keyInput.off("keypress",w),i.destroy(),c(A)},y=(A)=>{if(f)return;f=!0,i.keyInput.off("keypress",w),i.destroy(),l(A)},g=()=>{s.content=d?Hz(r,o,p,a):hF(r,o,u,a),i.requestRender()},w=(A)=>{try{let b=A.name.toLowerCase();if(A.ctrl===!0&&b==="c"){m({action:"cancel"});return}if(d){if(b==="escape"){d=!1,g();return}if(b==="up"||b==="k")p=(p+2)%3;else if(b==="down"||b==="j")p=(p+1)%3;else if(b==="return"||b==="enter"||b==="linefeed"){if(p===0)m({action:"install",request:wF(o)});else if(p===1)d=!1,u=0;else m({action:"cancel"});return}g();return}let I=_F(o,u,A);if(u=I.cursor,I.action==="cancel"){m({action:"cancel"});return}if(I.action==="review")d=!0,p=0;g()}catch(b){y(b)}};i.keyInput.on("keypress",w);try{i.start()}catch(A){y(A)}})}function xv(e,t={}){let n={};for(let r of e){let o=r.identity??`${r.path}:${r.key??""}:${r.action}`,i=r.validDecisions??["keep","replace","cancel"],a=t[o]??r.defaultDecision??"replace";n[o]=i.includes(a)?a:i.find((s)=>s==="keep"||s==="replace")??"keep"}return{conflicts:e,decisions:n}}function SF(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"||r==="A")return uF(e,"replace"),{cursor:t,action:"render"};if((o==="k"||r==="K")&&n.ctrl!==!0)return uF(e,"keep"),{cursor:t,action:"render"};if(o==="space")return Lz(e,t),{cursor:t,action:"render"};if(o==="left"||o==="right")Dz(e,t,o==="left"?-1:1);return{cursor:t,action:"render"}}function Pz(e,t=xv(e).decisions,n=0,r={}){let o=vi({...r,stream:"stdout"}),i={conflicts:e,decisions:{...t}},a=[nt("HolyCodex \xB7 resolve conflicts","heading",o),nt("Only changes discovered during preflight are shown.","hint",o),nt("\u2191/\u2193 or j/k navigate \u2190/\u2192 choose Space toggle A replace all K keep all","hint",o),nt("Enter continue Esc back Ctrl-C cancel","hint",o),""],s;if(e.forEach((c,l)=>{let u=c.category??"managed";if(u!==s){if(s!==void 0)a.push("");a.push(nt(_v(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(nt(`${m} ${f}`,l===n?"focus":"argument",o)),a.push(` ${nt(`decision: ${p}`,y,o)}`),a.push(` existing: ${Nh(c.existing)}`),a.push(` desired: ${Nh(c.desired)}`),c.explanation!==void 0)a.push(` ${nt(c.explanation,"hint",o)}`)}),e.length===0)a.push(nt("No conflicts require a decision.","success",o));return`${a.join(`
110
+ `).chunks),new e.StyledText(r)}async function jh(e={},t={}){let n=un(e),r=await import("@opentui/core"),o=Pv(n),i=await r.createCliRenderer({...Ov(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=Cv(t),s=new r.TextRenderable(i,{content:MF(r,o,0,a)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=0,f=!1,m=(I)=>{if(f)return;f=!0,i.keyInput.off("keypress",_),i.destroy(),c(I)},y=(I)=>{if(f)return;f=!0,i.keyInput.off("keypress",_),i.destroy(),l(I)},g=()=>{s.content=d?SK(r,o,p,a):MF(r,o,u,a),i.requestRender()},_=(I)=>{try{let b=I.name.toLowerCase();if(I.ctrl===!0&&b==="c"){m({action:"cancel"});return}if(d){if(b==="escape"){d=!1,g();return}if(b==="up"||b==="k")p=(p+2)%3;else if(b==="down"||b==="j")p=(p+1)%3;else if(b==="return"||b==="enter"||b==="linefeed"){if(p===0)m({action:"install",request:jF(o)});else if(p===1)d=!1,u=0;else m({action:"cancel"});return}g();return}let A=UF(o,u,I);if(u=A.cursor,A.action==="cancel"){m({action:"cancel"});return}if(A.action==="review")d=!0,p=0;g()}catch(b){y(b)}};i.keyInput.on("keypress",_);try{i.start()}catch(I){y(I)}})}function Ev(e,t={}){let n={};for(let r of e){let o=r.identity??`${r.path}:${r.key??""}:${r.action}`,i=r.validDecisions??["keep","replace","cancel"],a=t[o]??r.defaultDecision??"replace";n[o]=i.includes(a)?a:i.find((s)=>s==="keep"||s==="replace")??"keep"}return{conflicts:e,decisions:n}}function DF(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"||r==="A")return EF(e,"replace"),{cursor:t,action:"render"};if((o==="k"||r==="K")&&n.ctrl!==!0)return EF(e,"keep"),{cursor:t,action:"render"};if(o==="space")return fK(e,t),{cursor:t,action:"render"};if(o==="left"||o==="right")mK(e,t,o==="left"?-1:1);return{cursor:t,action:"render"}}function lK(e,t=Ev(e).decisions,n=0,r={}){let o=Oi({...r,stream:"stdout"}),i={conflicts:e,decisions:{...t}},a=[ot("HolyCodex \xB7 resolve conflicts","heading",o),ot("Only changes discovered during preflight are shown.","hint",o),ot("\u2191/\u2193 or j/k navigate \u2190/\u2192 choose Space toggle A replace all K keep all","hint",o),ot("Enter continue Esc back Ctrl-C cancel","hint",o),""],s;if(e.forEach((c,l)=>{let u=c.category??"managed";if(u!==s){if(s!==void 0)a.push("");a.push(ot(Av(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(ot(`${m} ${f}`,l===n?"focus":"argument",o)),a.push(` ${ot(`decision: ${p}`,y,o)}`),a.push(` existing: ${$h(c.existing)}`),a.push(` desired: ${$h(c.desired)}`),a.push(` choices: ${$F(c)}`),c.explanation!==void 0)a.push(` ${ot(c.explanation,"hint",o)}`)}),e.length===0)a.push(ot("No conflicts require a decision.","success",o));return`${a.join(`
107
111
  `)}
108
- `}async function Sv(e,t={},n={}){let r=await import("@opentui/core"),o=xv(e,n),i=await r.createCliRenderer({...gv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=yv(t),s=new r.TextRenderable(i,{content:yF(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=yF(r,o.conflicts,o.decisions,u,a),i.requestRender()},y=(g)=>{try{let w=SF(o,u,g);if(u=w.cursor,w.action==="continue")p({action:"continue",decisions:{...o.decisions}});else if(w.action==="back"||w.action==="cancel")p({action:w.action});else m()}catch(w){f(w)}};i.keyInput.on("keypress",y);try{i.start()}catch(g){f(g)}})}function Mz(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 Nz(e,t){let n=bv(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 bF(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:xF(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=xF(n,e,l,i),o.requestRender()},m=(y)=>{try{let g=Nz({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 w=bv(e)[l];d({action:w})}else f()}catch(g){p(g)}};o.keyInput.on("keypress",m);try{o.start()}catch(y){p(y)}})}function bv(e){return e.conflicts.length>0?["apply","change","resolve","cancel"]:["apply","change","cancel"]}function Fz(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 uF(e,t){for(let n of e.conflicts){if(!(n.validDecisions??["keep","replace","cancel"]).includes(t))continue;e.decisions[n.identity??`${n.path}:${n.key??""}:${n.action}`]=t}}function Lz(e,t){let n=e.conflicts[t];if(n===void 0)return;let r=n.identity??`${n.path}:${n.key??""}:${n.action}`,o=n.validDecisions??["keep","replace","cancel"],a=(e.decisions[r]??"keep")==="replace"?"keep":"replace";if(o.includes(a))e.decisions[r]=a}function Dz(e,t,n){let r=e.conflicts[t];if(r===void 0)return;let o=r.identity??`${r.path}:${r.key??""}:${r.action}`,i=(r.validDecisions??["keep","replace","cancel"]).filter((c)=>c==="keep"||c==="replace");if(i.length===0)return;let a=e.decisions[o]??i[0],s=i.indexOf(a);e.decisions[o]=i[(s+n+i.length)%i.length]??i[0]}function _v(e){return e.split(/[-_]/u).map((t)=>t.length===0?t:`${t[0].toUpperCase()}${t.slice(1)}`).join(" ")}function Nh(e){if(e===void 0)return"(unknown)";if(typeof e==="string")return e;try{return JSON.stringify(e)}catch{return"(unavailable)"}}function _F(e,t,n){let r=n.name.toLowerCase(),o=qi.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=vF(e.pluginInput),{cursor:t,action:"review"};if(t===o){if(r==="backspace")fF(e,-1);else if(r==="delete")fF(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")pF(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!zz(n.name))pF(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)Uz(e,t-2);else if(r==="left")dF(e,t,-1);else if(r==="right")dF(e,t,1);return{cursor:t,action:"render"}}function wF(e){let t={profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]};return sn(t)}function qz(e,t="install",n={}){let r=wv(sn(e));return $z(r,t==="install"?0:t==="change"?1:2,vi({...n,stream:"stdout"}))}function wv(e){let t={...Yt,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{browser_use:t.browser_use??Yt.browser_use,computer_use:t.computer_use??Yt.computer_use,sites:t.sites??Yt.sites},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function dF(e,t,n){if(t===0)e.profile=mF(kz,e.profile,n);else if(t===1)e.tier=mF(Iz,e.tier,n)}function Uz(e,t){let n=qi[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function pF(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function fF(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 mF(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function vF(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return sn({officialPlugins:t}),t}function $z(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[nt("HolyCodex \xB7 review","heading",n),nt("Review configuration","heading",n),nt("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",nt("CAPABILITIES","heading",n),...qi.map((i)=>` ${Dh(i)}: ${nt(Rv(e.optional[i]),e.optional[i]?"enabled":"disabled",n)}`),...vv(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((i,a)=>nt(`${a===t?"\u203A":" "} ${i}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
112
+ `}async function kv(e,t={},n={}){let r=await import("@opentui/core"),o=Ev(e,n),i=await r.createCliRenderer({...Ov(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=Cv(t),s=new r.TextRenderable(i,{content:FF(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=FF(r,o.conflicts,o.decisions,u,a),i.requestRender()},y=(g)=>{try{let _=DF(o,u,g);if(u=_.cursor,_.action==="continue")p({action:"continue",decisions:{...o.decisions}});else if(_.action==="back"||_.action==="cancel")p({action:_.action});else m()}catch(_){f(_)}};i.keyInput.on("keypress",y);try{i.start()}catch(g){f(g)}})}function uK(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 dK(e,t){let n=Iv(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 qF(e,t={}){let n=await import("@opentui/core"),r={review:e,selected:0},o=await n.createCliRenderer({...Ov(t),exitOnCtrlC:!0,clearOnShutdown:!0}),i=Cv(t),a=new n.TextRenderable(o,{content:LF(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=LF(n,e,l,i),o.requestRender()},m=(y)=>{try{let g=dK({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 _=Iv(e)[l];d({action:_})}else f()}catch(g){p(g)}};o.keyInput.on("keypress",m);try{o.start()}catch(y){p(y)}})}function Iv(e){return e.conflicts.length>0?["apply","change","resolve","cancel"]:["apply","change","cancel"]}function pK(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 EF(e,t){for(let n of e.conflicts){if(!(n.validDecisions??["keep","replace","cancel"]).includes(t))continue;e.decisions[n.identity??`${n.path}:${n.key??""}:${n.action}`]=t}}function fK(e,t){let n=e.conflicts[t];if(n===void 0)return;let r=n.identity??`${n.path}:${n.key??""}:${n.action}`,o=n.validDecisions??["keep","replace","cancel"],a=(e.decisions[r]??"keep")==="replace"?"keep":"replace";if(o.includes(a))e.decisions[r]=a}function mK(e,t,n){let r=e.conflicts[t];if(r===void 0)return;let o=r.identity??`${r.path}:${r.key??""}:${r.action}`,i=r.validDecisions??["keep","replace","cancel"];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 $F(e){return(e.validDecisions??["keep","replace","cancel"]).join(" | ")}function Av(e){return e.split(/[-_]/u).map((t)=>t.length===0?t:`${t[0].toUpperCase()}${t.slice(1)}`).join(" ")}function $h(e){if(e===void 0)return"(unknown)";if(typeof e==="string")return e;try{return JSON.stringify(e)}catch{return"(unavailable)"}}function UF(e,t,n){let r=n.name.toLowerCase(),o=Hi.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=HF(e.pluginInput),{cursor:t,action:"review"};if(t===o){if(r==="backspace")AF(e,-1);else if(r==="delete")AF(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")IF(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!vK(n.name))IF(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)gK(e,t-2);else if(r==="left")kF(e,t,-1);else if(r==="right")kF(e,t,1);return{cursor:t,action:"render"}}function jF(e){let t={profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]};return un(t)}function hK(e,t="install",n={}){let r=Pv(un(e));return yK(r,t==="install"?0:t==="change"?1:2,Oi({...n,stream:"stdout"}))}function Pv(e){let t={...Xt,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{browser_use:t.browser_use??Xt.browser_use,computer_use:t.computer_use??Xt.computer_use,sites:t.sites??Xt.sites},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function kF(e,t,n){if(t===0)e.profile=PF(aK,e.profile,n);else if(t===1)e.tier=PF(sK,e.tier,n)}function gK(e,t){let n=Hi[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function IF(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function AF(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 PF(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function HF(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return un({officialPlugins:t}),t}function yK(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[ot("HolyCodex \xB7 review","heading",n),ot("Review configuration","heading",n),ot("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",ot("CAPABILITIES","heading",n),...Hi.map((i)=>` ${Hh(i)}: ${ot(Nv(e.optional[i]),e.optional[i]?"enabled":"disabled",n)}`),...Mv(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((i,a)=>ot(`${a===t?"\u203A":" "} ${i}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
109
113
  `)}
110
- `}function hF(e,t,n,r){let o=qi.length+2,i=n<2?n===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":n<o?Wz(qi[n-2]):"Optional plugin IDs separated by spaces. Enter continues to review.",a=[ne("HolyCodex \xB7 install","heading"),ne("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint"),ne(""),ne("PROFILE","heading"),gF("Profile",t.profile,n===0),gF("Service tier",t.tier,n===1),ne(""),ne("OPTIONAL CAPABILITIES","heading"),...qi.map((s,c)=>jz(s,t.optional[s],n===c+2)),ne(""),ne("ADDITIONAL PLUGINS","heading"),...vv(`${n===o?"\u276F":" "} ${t.pluginInput||"(none)"}`).map((s)=>ne(s,n===o?"focus":"argument")),ne(""),ne(i,"hint")];return Fh(e,a,r)}function gF(e,t,n){return ne(`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`,n?"focus":"argument")}function jz(e,t,n){let r=t?"[x] enabled":"[ ] disabled";return ne(`${n?"\u276F":" "} ${Dh(e).padEnd(14)} ${r}`,n?"focus":t?"enabled":"disabled")}function Hz(e,t,n,r){let o=["Install","Change options / Redo","Cancel"],i=[ne("HolyCodex \xB7 review","heading"),ne("Review configuration","heading"),ne("\u2191/\u2193 choose Enter confirm Esc back","hint"),ne(""),ne(`Profile: ${t.profile}`),ne(`Service tier: ${t.tier}`),ne(""),ne("CAPABILITIES","heading"),...qi.map((a)=>wd({text:` ${Dh(a)}: `},{text:Rv(t.optional[a]),tone:t.optional[a]?"enabled":"disabled"})),...vv(` Additional plugins: ${t.plugins.length===0?"none":t.plugins.join(" ")}`).map((a)=>ne(a,"argument")),ne(""),...o.map((a,s)=>ne(`${s===n?"\u203A":" "} ${a}`,s===n?"focus":s===0?"success":s===1?"warning":"error"))];return Fh(e,i,r)}function yF(e,t,n,r,o){let i=[ne("HolyCodex \xB7 resolve conflicts","heading"),ne("Only changes discovered during preflight are shown.","hint"),ne("\u2191/\u2193 or j/k navigate \u2190/\u2192 choose Space toggle A replace all K keep all","hint"),ne("Enter continue Esc back Ctrl-C cancel","hint"),ne("")],a;if(t.forEach((s,c)=>{let l=s.category??"managed";if(l!==a)i.push(ne(_v(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(wd({text:`${f} ${p}`,tone:c===r?"focus":"argument"},{text:" decision: "},{text:d,tone:m}))}),t.length===0)i.push(ne("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(ne(`Focused conflict: ${c}`,"focus")),i.push(ne(` existing: ${Nh(s.existing)}`)),i.push(ne(` desired: ${Nh(s.desired)}`)),s.explanation!==void 0)i.push(ne(` ${s.explanation}`,"hint"))}}return Fh(e,i,o)}function xF(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=Mz(t),c=s.keep+s.replace,l=[ne(`HolyCodex \xB7 ${o} review`,"heading"),ne("Review the complete preflight plan before applying changes.","hint"),ne(`Version: ${i}`),ne(`Profile: ${t.profile}`),ne(`Service tier: ${t.tier}`),ne("CAPABILITIES","heading"),...qi.map((u)=>wd({text:` ${Dh(u)}: `},{text:Rv(t.capabilities[u]),tone:t.capabilities[u]?"enabled":"disabled"})),ne(` Additional plugins: ${t.additionalPlugins.length===0?"none":t.additionalPlugins.join(" ")}`,"argument"),ne(`CONFLICTS (${a})`,"heading"),...a===0?[ne(" none")]:Object.entries(t.conflictCounts).map(([u,d])=>ne(` ${_v(u)}: ${d}`)),...a===0?[]:[ne(`DECISIONS (${c})`,"heading"),ne(` Keep: ${s.keep}`),ne(` Replace: ${s.replace}`)],ne("PREREQUISITES","heading"),...t.tools.length===0?[ne(" none")]:t.tools.map((u)=>Bz(u)),ne("\u2191/\u2193 or j/k choose Enter select Esc back Ctrl-C cancel","hint"),...bv(t).map((u,d)=>ne(`${d===n?"\u203A":" "} ${Fz(u,t.operation)}`,d===n?"focus":u==="apply"?"success":u==="change"||u==="resolve"?"warning":"error"))];return Fh(e,l,r)}function Bz(e){let t=e.name.toLowerCase()==="context7",n=t?Vz(e.status):e.status,r=e.status==="ready"||e.status==="healthy"?"success":"warning",o=t||e.detail===void 0?"":` (${e.detail})`;return wd({text:` ${e.name}: `},{text:n,tone:r},...o.length===0?[]:[{text:o}])}function Vz(e){return e==="ready"?"Use available ctx7":"Attempt optional managed ctx7 install"}function Wz(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 vv(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 Dh(e){switch(e){case"sites":return"ChatGPT Sites";case"browser_use":return"Browser Use";case"computer_use":return"Computer Use"}}function Rv(e){return e?"enabled":"disabled"}function zz(e){let t=e.codePointAt(0)??0;return t<=31||t===127}xd();Xu();Rh();id();cd();$a();Rc();async function Cv(e,t={}){if(e.length===0||Uu(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:$u(e);return{envelope:RF(r===void 0?"help":`${r} help`,{help:qu(r)}),exitCode:0}}let n;try{n=Hm(e);let r=await TF(n,t);return{envelope:RF(n.command,r),exitCode:sK(n.command,r)}}catch(r){return aK(n?.command??lK(e),r)}}async function TF(e,t){switch(e.command){case"install":return xn(await Kz(e,t));case"doctor":{let n=Td(e,t),r=br(n,t.env);return xn(await rv({...n,officialPluginManager:n.officialPluginManager??new Sh(r.codexHome)},t.env))}case"remove":return xn(await Yz(e,t));case"version":return xn(await Zz(e,t));case"help":return{help:qu(e.positionals[0])};default:throw new qc("invalid_argument","Unknown command.")}}async function Kz(e,t){let n=Gz(e),r=await Jz(e,t,n);if("cancelled"in r)return r;return await ts(r,Td(e,t),t.env)}async function Jz(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await iF(Td(e,t),t.env),a=await(t.io?.installWizard??Lh)({...i,...n,...i.optional===void 0&&n.optional===void 0?{}:{optional:{...i.optional,...n.optional}}});if(a.action==="cancel")return{cancelled:!0};return sn(a.request)}let o=await OF(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new qc("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return sn(n)}function Gz(e){let t=Qz(e),n=eK(e),r=Xz(e),o=e.options["add-plugin"]===void 0?void 0:tK(e,"add-plugin");return sn({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o===void 0?{}:{officialPlugins:o}})}async function Yz(e,t){let n=await OF(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let o=(await ov(Td(e,t),t.env))[0];if(o!==void 0)throw new E("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 qc("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.")}return await md(Td(e,t),t.env)}async function Zz(e,t){let n=e.positionals[0];if(!n)return{version:await Tc()};return await Lw(n,e.options["dry-run"]===!0)}async function OF(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 CF(t,n)}async function CF(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 Xz(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 Qz(e){let t=e.options.profile;if(typeof t!=="string")return;let n=Wr(t);return n.ok?n.value.name:void 0}function eK(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function tK(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Td(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),uK(t,r,y.message)},a=new Map,s=(y,g)=>{for(let w of y){let A=Tv(w),b=g[A];if(b!==void 0)a.set(A,b)}return g},c=n.resolveConflict??(e.options.yes===!0?async()=>"accept":async(y)=>{let g=y.key===void 0?y.path:`${y.path} (${y.key})`,w=await CF(t,`${y.action==="remove"?"Remove":"Replace"} modified HolyCodex-owned state at ${g}?`);return w==="confirmed"?"accept":w==="cancelled"?"decline":"cancel"}),l=n.resolveConflicts??(e.options.yes===!0?async(y)=>Object.fromEntries(y.map((g)=>[g.identity??g.path,"replace"])):async(y)=>{if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)throw new E("confirmation_required","Managed conflicts require an interactive review or --yes.");let g=await Sv(y,{},Object.fromEntries(a));if(g.action==="back")return Object.fromEntries(y.map((w)=>{let A=Tv(w),b=a.get(A);return[A,b??rK(w)]}));if(g.action==="cancel")throw new E("confirmation_required","Conflict review was cancelled.");if(g.action==="continue")return g.decisions;throw new E("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 bF(y):void 0),f=p===void 0?void 0:async(y)=>{let g=oK(y,a),w=await p(iK(g));if(w.action!=="change")return w;if(w.request!==void 0)return{action:"change",request:sn(w.request)};if(!o)throw new E("confirmation_required","Changing install options requires an interactive review.");let A=await(t.io?.installWizard??Lh)(nK(g));if(A.action==="cancel")return{action:"cancel"};return{action:"change",request:sn(A.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 nK(e){return sn({profile:e.profile,tier:e.tier,optional:e.capabilities,officialPlugins:e.additionalPlugins})}function Tv(e){return e.identity??e.path}function rK(e){let t=e.defaultDecision??"replace";if(t==="keep"||t==="replace"||t==="cancel"){if(e.validDecisions===void 0||e.validDecisions.includes(t))return t}return e.validDecisions?.find((n)=>n==="keep"||n==="replace")??"keep"}function oK(e,t){if(t.size===0||e.conflicts.length===0)return e;return{...e,conflicts:e.conflicts.map((n)=>{let r=t.get(Tv(n));return r===void 0?n:{...n,decision:r}})}}function iK(e){let{fromVersion:t,...n}=e;return{...n,operation:"install"}}function RF(e,t){let n=Um({schema_version:oo,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new qc("internal_error","The success envelope failed validation.");return n.value}function aK(e,t){let n=cK(t),r=Um({schema_version:oo,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:oo,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 sK(e,t){return e==="doctor"&&Ui(t)&&t.healthy===!1?4:0}function cK(e){if(e instanceof tt)return{code:e.code,message:os(e.message),details:e.details,exitCode:1};if(e instanceof qc)return{code:e.code,message:os(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof Jn)return{code:"trust_boundary_failed",message:os(e.message),details:{},exitCode:4};if(e instanceof E){let t=e.code==="confirmation_required"?1:e.code==="capability_denied"?2:e.code==="state_corrupt"?4:3;return{code:e.code,message:os(e.message),details:e.details,exitCode:t}}if(e instanceof Yr){let t=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),n=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:t?"effect_uncertain":n?"capability_denied":"install_failed",message:os(e.message),details:e.details,exitCode:t?4:n?2:3}}if(e instanceof ja)return{code:e.code,message:os(e.message),details:{},exitCode:4};if(e instanceof Do)return{code:e.code,message:os(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:"The command failed unexpectedly.",details:{},exitCode:5};return{code:"internal_error",message:"The command failed unexpectedly.",details:{},exitCode:5}}function lK(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function os(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 Ui(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function uK(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${EF(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
111
- `)}function qh(e,t={}){let n=vi(t);if(e.envelope.ok){if(e.envelope.command==="version")return dK(e.envelope.data);if(e.envelope.command==="install")return pK(e.envelope.data,n);if(e.envelope.command==="remove")return fK(e.envelope.data,n);if(e.envelope.command==="doctor")return mK(e.envelope.data,n);return`${ye("\u2714","green",n)} ${ye(e.envelope.command,"heading",n)}
112
- ${hK(e.envelope.data,n)}`}let r=e.envelope.error,o=yK(r.code,e.envelope.command);return[`${ye("\u2716","red",n)} ${ye(e.envelope.command,"heading",n)}`,` ${ye(r.code,"red",n)}: ${r.message}`,...gK(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
113
- `)}function EF(e,t={}){return`${ye("\u2022","cyan",vi({...t,stream:"stderr"}))} ${e}`}function dK(e){if(Ui(e)&&typeof e.version==="string")return`holycodex ${e.version}
114
- `;if(Ui(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
114
+ `}function MF(e,t,n,r){let o=Hi.length+2,i=n<2?n===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":n<o?wK(Hi[n-2]):"Optional plugin IDs separated by spaces. Enter continues to review.",a=[ne("HolyCodex \xB7 install","heading"),ne("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint"),ne(""),ne("PROFILE","heading"),NF("Profile",t.profile,n===0),NF("Service tier",t.tier,n===1),ne(""),ne("OPTIONAL CAPABILITIES","heading"),...Hi.map((s,c)=>xK(s,t.optional[s],n===c+2)),ne(""),ne("ADDITIONAL PLUGINS","heading"),...Mv(`${n===o?"\u276F":" "} ${t.pluginInput||"(none)"}`).map((s)=>ne(s,n===o?"focus":"argument")),ne(""),ne(i,"hint")];return Uh(e,a,r)}function NF(e,t,n){return ne(`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`,n?"focus":"argument")}function xK(e,t,n){let r=t?"[x] enabled":"[ ] disabled";return ne(`${n?"\u276F":" "} ${Hh(e).padEnd(14)} ${r}`,n?"focus":t?"enabled":"disabled")}function SK(e,t,n,r){let o=["Install","Change options / Redo","Cancel"],i=[ne("HolyCodex \xB7 review","heading"),ne("Review configuration","heading"),ne("\u2191/\u2193 choose Enter confirm Esc back","hint"),ne(""),ne(`Profile: ${t.profile}`),ne(`Service tier: ${t.tier}`),ne(""),ne("CAPABILITIES","heading"),...Hi.map((a)=>Ed({text:` ${Hh(a)}: `},{text:Nv(t.optional[a]),tone:t.optional[a]?"enabled":"disabled"})),...Mv(` Additional plugins: ${t.plugins.length===0?"none":t.plugins.join(" ")}`).map((a)=>ne(a,"argument")),ne(""),...o.map((a,s)=>ne(`${s===n?"\u203A":" "} ${a}`,s===n?"focus":s===0?"success":s===1?"warning":"error"))];return Uh(e,i,r)}function FF(e,t,n,r,o){let i=[ne("HolyCodex \xB7 resolve conflicts","heading"),ne("Only changes discovered during preflight are shown.","hint"),ne("\u2191/\u2193 or j/k navigate \u2190/\u2192 choose Space toggle A replace all K keep all","hint"),ne("Enter continue Esc back Ctrl-C cancel","hint"),ne("")],a;if(t.forEach((s,c)=>{let l=s.category??"managed";if(l!==a)i.push(ne(Av(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(Ed({text:`${f} ${p}`,tone:c===r?"focus":"argument"},{text:" decision: "},{text:d,tone:m},{text:` choices: ${$F(s)}`,tone:"hint"}))}),t.length===0)i.push(ne("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(ne(`Focused conflict: ${c}`,"focus")),i.push(ne(` existing: ${$h(s.existing)}`)),i.push(ne(` desired: ${$h(s.desired)}`)),s.explanation!==void 0)i.push(ne(` ${s.explanation}`,"hint"))}}return Uh(e,i,o)}function LF(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=uK(t),c=s.keep+s.replace,l=[ne(`HolyCodex \xB7 ${o} review`,"heading"),ne("Review the complete preflight plan before applying changes.","hint"),ne(`Version: ${i}`),ne(`Profile: ${t.profile}`),ne(`Service tier: ${t.tier}`),ne("CAPABILITIES","heading"),...Hi.map((u)=>Ed({text:` ${Hh(u)}: `},{text:Nv(t.capabilities[u]),tone:t.capabilities[u]?"enabled":"disabled"})),ne(` Additional plugins: ${t.additionalPlugins.length===0?"none":t.additionalPlugins.join(" ")}`,"argument"),ne(`CONFLICTS (${a})`,"heading"),...a===0?[ne(" none")]:Object.entries(t.conflictCounts).map(([u,d])=>ne(` ${Av(u)}: ${d}`)),...a===0?[]:[ne(`DECISIONS (${c})`,"heading"),ne(` Keep: ${s.keep}`),ne(` Replace: ${s.replace}`)],ne("PREREQUISITES","heading"),...t.tools.length===0?[ne(" none")]:t.tools.map((u)=>bK(u)),ne("\u2191/\u2193 or j/k choose Enter select Esc back Ctrl-C cancel","hint"),...Iv(t).map((u,d)=>ne(`${d===n?"\u203A":" "} ${pK(u,t.operation)}`,d===n?"focus":u==="apply"?"success":u==="change"||u==="resolve"?"warning":"error"))];return Uh(e,l,r)}function bK(e){let t=e.name.toLowerCase()==="context7",n=t?_K(e.status):e.status,r=e.status==="ready"||e.status==="healthy"?"success":"warning",o=t||e.detail===void 0?"":` (${e.detail})`;return Ed({text:` ${e.name}: `},{text:n,tone:r},...o.length===0?[]:[{text:o}])}function _K(e){return e==="ready"?"Use available ctx7":"Attempt optional managed ctx7 install"}function wK(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 Mv(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 Hh(e){switch(e){case"sites":return"ChatGPT Sites";case"browser_use":return"Browser Use";case"computer_use":return"Computer Use"}}function Nv(e){return e?"enabled":"disabled"}function vK(e){let t=e.codePointAt(0)??0;return t<=31||t===127}Td();od();Eh();dd();md();za();Ec();async function Dv(e,t={}){if(e.length===0||Wu(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:zu(e);return{envelope:BF(r===void 0?"help":`${r} help`,{help:Vu(r)}),exitCode:0}}let n;try{n=Km(e);let r=await VF(n,t);return{envelope:BF(n.command,r),exitCode:qK(n.command,r)}}catch(r){return DK(n?.command??UK(e),r)}}async function VF(e,t){switch(e.command){case"install":return _n(await RK(e,t));case"doctor":{let n=Ad(e,t),r=wr(n,t.env);return _n(await pv({...n,officialPluginManager:n.officialPluginManager??new vh(r.codexHome)},t.env))}case"remove":return _n(await CK(e,t));case"version":return _n(await EK(e,t));case"help":return{help:Vu(e.positionals[0])};default:throw new Bc("invalid_argument","Unknown command.")}}async function RK(e,t){let n=OK(e),r=await TK(e,t,n);if("cancelled"in r)return r;return await ss(r,Ad(e,t),t.env)}async function TK(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await vF(Ad(e,t),t.env),a=await(t.io?.installWizard??jh)({...i,...n,...i.optional===void 0&&n.optional===void 0?{}:{optional:{...i.optional,...n.optional}}});if(a.action==="cancel")return{cancelled:!0};return un(a.request)}let o=await WF(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new Bc("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return un(n)}function OK(e){let t=IK(e),n=AK(e),r=kK(e),o=e.options["add-plugin"]===void 0?void 0:PK(e,"add-plugin");return un({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o===void 0?{}:{officialPlugins:o}})}async function CK(e,t){let n=await WF(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let o=(await fv(Ad(e,t),t.env))[0];if(o!==void 0)throw new C("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 Bc("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.")}return await bd(Ad(e,t),t.env)}async function EK(e,t){let n=e.positionals[0];if(!n)return{version:await kc()};return await Vw(n,e.options["dry-run"]===!0)}async function WF(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 zF(t,n)}async function zF(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 kK(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 IK(e){let t=e.options.profile;if(typeof t!=="string")return;let n=Jr(t);return n.ok?n.value.name:void 0}function AK(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function PK(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Ad(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),jK(t,r,y.message)},a=new Map,s=(y,g)=>{for(let _ of y){let I=Fv(_),b=g[I];if(b!==void 0)a.set(I,b)}return g},c=n.resolveConflict??(e.options.yes===!0?async()=>"accept":async(y)=>{let g=y.key===void 0?y.path:`${y.path} (${y.key})`,_=await zF(t,`${y.action==="remove"?"Remove":"Replace"} modified HolyCodex-owned state at ${g}?`);return _==="confirmed"?"accept":_==="cancelled"?"decline":"cancel"}),l=n.resolveConflicts??(e.options.yes===!0?async(y)=>{if(y.length>0){let g=y.map((_)=>`${_.key===void 0?_.path:`${_.path} (${_.key})`}: ${_.explanation??"user-owned state requires review"}`).join("; ");throw new C("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 C("confirmation_required","Managed conflicts require an interactive review or --yes.");let g=await kv(y,{},Object.fromEntries(a));if(g.action==="back")return Object.fromEntries(y.map((_)=>{let I=Fv(_),b=a.get(I);return[I,b??NK(_)]}));if(g.action==="cancel")throw new C("confirmation_required","Conflict review was cancelled.");if(g.action==="continue")return g.decisions;throw new C("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 qF(y):void 0),f=p===void 0?void 0:async(y)=>{let g=FK(y,a),_=await p(LK(g));if(_.action!=="change")return _;if(_.request!==void 0)return{action:"change",request:un(_.request)};if(!o)throw new C("confirmation_required","Changing install options requires an interactive review.");let I=await(t.io?.installWizard??jh)(MK(g));if(I.action==="cancel")return{action:"cancel"};return{action:"change",request:un(I.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 MK(e){return un({profile:e.profile,tier:e.tier,optional:e.capabilities,officialPlugins:e.additionalPlugins})}function Fv(e){return e.identity??e.path}function NK(e){let t=e.defaultDecision??"replace";if(t==="keep"||t==="replace"||t==="cancel"){if(e.validDecisions===void 0||e.validDecisions.includes(t))return t}return e.validDecisions?.find((n)=>n==="keep"||n==="replace")??"keep"}function FK(e,t){if(t.size===0||e.conflicts.length===0)return e;return{...e,conflicts:e.conflicts.map((n)=>{let r=t.get(Fv(n));return r===void 0?n:{...n,decision:r}})}}function LK(e){let{fromVersion:t,...n}=e;return{...n,operation:"install"}}function BF(e,t){let n=Vm({schema_version:so,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new Bc("internal_error","The success envelope failed validation.");return n.value}function DK(e,t){let n=$K(t),r=Vm({schema_version:so,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:so,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 qK(e,t){return e==="doctor"&&Bi(t)&&t.healthy===!1?4:0}function $K(e){if(e instanceof rt)return{code:e.code,message:ls(e.message),details:e.details,exitCode:1};if(e instanceof Bc)return{code:e.code,message:ls(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof Yn)return{code:"trust_boundary_failed",message:ls(e.message),details:{},exitCode:4};if(e instanceof C){let t=e,n=t.code==="confirmation_required"?1:t.code==="capability_denied"?2:t.code==="state_corrupt"?4:3;return{code:t.code,message:ls(t.message),details:t.details,exitCode:n}}if(e instanceof Xr){let t=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),n=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:t?"effect_uncertain":n?"capability_denied":"install_failed",message:ls(e.message),details:e.details,exitCode:t?4:n?2:3}}if(e instanceof Ka)return{code:e.code,message:ls(e.message),details:{},exitCode:4};if(e instanceof Uo)return{code:e.code,message:ls(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:"The command failed unexpectedly.",details:{},exitCode:5};return{code:"internal_error",message:"The command failed unexpectedly.",details:{},exitCode:5}}function UK(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function ls(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 Bi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function jK(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${KF(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
115
+ `)}function Bh(e,t={}){let n=Oi(t);if(e.envelope.ok){if(e.envelope.command==="version")return HK(e.envelope.data);if(e.envelope.command==="install")return BK(e.envelope.data,n);if(e.envelope.command==="remove")return VK(e.envelope.data,n);if(e.envelope.command==="doctor")return WK(e.envelope.data,n);return`${be("\u2714","green",n)} ${be(e.envelope.command,"heading",n)}
116
+ ${zK(e.envelope.data,n)}`}let r=e.envelope.error,o=JK(r.code,e.envelope.command);return[`${be("\u2716","red",n)} ${be(e.envelope.command,"heading",n)}`,` ${be(r.code,"red",n)}: ${r.message}`,...KK(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
117
+ `)}function KF(e,t={}){return`${be("\u2022","cyan",Oi({...t,stream:"stderr"}))} ${e}`}function HK(e){if(Bi(e)&&typeof e.version==="string")return`holycodex ${e.version}
118
+ `;if(Bi(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
115
119
  `}return`holycodex version completed
116
- `}function pK(e,t){if(Ev(e,"cancelled")===!0)return`${ye("\u21A9","cyan",t)} ${ye("install","heading",t)} cancelled
117
- `;let n=vd(e,"record"),r=Rd(n,"version")??"unknown",o=Rd(n,"profile")??"unknown",i=Rd(n,"tier")??"unknown",a=vd(n,"capability_state"),s=["frontend","security","sites","browser_use","computer_use"].filter((f)=>vd(a,f)?.selected===!0).map((f)=>{let m=Rd(vd(a,f),"status");return m===void 0||m==="healthy"?f:`${f} (${m})`}),c=Dc(e,"preserved"),l=Dc(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`${[`${ye("\u2714","green",t)} ${ye("install","heading",t)}`,` ${ye("version","option",t)}: ${r}`,` ${ye("profile","option",t)}: ${o}`,` ${ye("tier","option",t)}: ${i}`,` ${ye("capabilities","option",t)}: ${u}`,` ${ye("preserved","option",t)}: ${d}`,...l.map((f)=>` ${ye("warning","warning",t)}: ${kv(f)}`)].join(`
120
+ `}function BK(e,t){if(qv(e,"cancelled")===!0)return`${be("\u21A9","cyan",t)} ${be("install","heading",t)} cancelled
121
+ `;let n=kd(e,"record"),r=Id(n,"version")??"unknown",o=Id(n,"profile")??"unknown",i=Id(n,"tier")??"unknown",a=kd(n,"capability_state"),s=["frontend","security","sites","browser_use","computer_use"].filter((f)=>kd(a,f)?.selected===!0).map((f)=>{let m=Id(kd(a,f),"status");return m===void 0||m==="healthy"?f:`${f} (${m})`}),c=Hc(e,"preserved"),l=Hc(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`${[`${be("\u2714","green",t)} ${be("install","heading",t)}`,` ${be("version","option",t)}: ${r}`,` ${be("profile","option",t)}: ${o}`,` ${be("tier","option",t)}: ${i}`,` ${be("capabilities","option",t)}: ${u}`,` ${be("preserved","option",t)}: ${d}`,...l.map((f)=>` ${be("warning","warning",t)}: ${$v(f)}`)].join(`
118
122
  `)}
119
- `}function fK(e,t){if(Ev(e,"cancelled")===!0)return`${ye("\u21A9","cyan",t)} ${ye("remove","heading",t)} cancelled
120
- `;let n=Dc(e,"removed"),r=Dc(e,"preserved"),o=Dc(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`;return`${[`${ye("\u2714","green",t)} ${ye("remove","heading",t)}`,` ${ye("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${ye("preserved","option",t)}: ${i}`,...o.map((s)=>` ${ye("reason","option",t)}: ${kv(s)}`)].join(`
123
+ `}function VK(e,t){if(qv(e,"cancelled")===!0)return`${be("\u21A9","cyan",t)} ${be("remove","heading",t)} cancelled
124
+ `;let n=Hc(e,"removed"),r=Hc(e,"preserved"),o=Hc(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`;return`${[`${be("\u2714","green",t)} ${be("remove","heading",t)}`,` ${be("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${be("preserved","option",t)}: ${i}`,...o.map((s)=>` ${be("reason","option",t)}: ${$v(s)}`)].join(`
121
125
  `)}
122
- `}function mK(e,t){let n=Ev(e,"healthy")===!0,r=vd(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=Ui(l)?l:void 0,d=Rd(u,"status");if(d===void 0||d==="healthy")return[];let p=Dc(u,"reasons");return[` ${ye(c,"option",t)}: ${p.length===0?d:p.map(kv).join(", ")}`]});return`${[`${n?ye("\u2714","green",t):ye("\u2716","red",t)} ${ye("doctor","heading",t)}`,` ${ye("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${ye("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${ye("issues","option",t)}:`,...i]].join(`
126
+ `}function WK(e,t){let n=qv(e,"healthy")===!0,r=kd(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=Bi(l)?l:void 0,d=Id(u,"status");if(d===void 0||d==="healthy")return[];let p=Hc(u,"reasons");return[` ${be(c,"option",t)}: ${p.length===0?d:p.map($v).join(", ")}`]});return`${[`${n?be("\u2714","green",t):be("\u2716","red",t)} ${be("doctor","heading",t)}`,` ${be("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${be("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${be("issues","option",t)}:`,...i]].join(`
123
127
  `)}
124
- `}function vd(e,t){if(!Ui(e))return;return Ui(e[t])?e[t]:void 0}function Ev(e,t){return Ui(e)?e[t]:void 0}function Rd(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function Dc(e,t){if(!Ui(e)||!Array.isArray(e[t]))return[];return e[t]}function kv(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function hK(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${ye(Ov(e),"dim",t)}
125
- `;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([o])=>o.length));return`${n.map(([o,i])=>` ${ye(o.padEnd(r),"option",t)}: ${Ov(i)}`).join(`
128
+ `}function kd(e,t){if(!Bi(e))return;return Bi(e[t])?e[t]:void 0}function qv(e,t){return Bi(e)?e[t]:void 0}function Id(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function Hc(e,t){if(!Bi(e)||!Array.isArray(e[t]))return[];return e[t]}function $v(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function zK(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${be(Lv(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])=>` ${be(o.padEnd(r),"option",t)}: ${Lv(i)}`).join(`
126
130
  `)}
127
- `}function gK(e,t){return Object.entries(e).map(([n,r])=>` ${ye(n,"option",t)}: ${ye(Ov(r),"dim",t)}`)}function Ov(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function yK(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 ye(e,t,n){return nt(e,{red:"error",green:"success",cyan:"focus",dim:"hint",warning:"warning",heading:"heading",option:"option"}[t],n)}class qc extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function Iv(e=Bun.argv.slice(2),t=SK()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??bK(),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 Cv(e,n);if((e.length===0||Uu(e)||e[0]==="help")&&!kF(e))n.io?.writeStdout?.(S_($u(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(kF(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
128
- `);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 SK(){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=xK({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 kF(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*bK(){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}xd();Rh();id();$a();cd();wh();xh();var Yee="holycodex";if(import.meta.main)process.exitCode=await Iv();export{tt as ArgumentError,_r as CONTEXT7_SPEC,Xt as CapabilityInstallStateSchema,Ew as CapabilityStateRecordSchema,za as CodexOfficialPluginManager,uh as InstallOptionsSchema,vc as InstallRecordSchema,td as InstallRequestSchema,E as InstallerError,Yr as OfficialPluginManagerError,Jn as PathBoundaryError,nd as PersistedInstallOptionsSchema,Sh as ReadOnlyCodexPluginStatus,YV as STATE_SCHEMA,pe as ToolingError,Ja as WINDOWS_GIT_BASH,SF as applyConflictScreenKey,_F as applyWizardConfigurationKey,Nw as assertRootText,H0 as context7InstallCommand,Za as createInstallerRuntime,Ga as detectContext7Manager,rv as doctorHolyCodex,_h as ensureContext7,Xa as ensureGitBash,TF as executeCommand,Uu as helpRequested,qu as helpText,$u as helpTopic,ts as installHolyCodex,jw as installNativeAgents,Mh as installRecordDigest,hd as installRequestFromPersistedOptions,Yee as packageName,Hm as parseArgv,vF as parsePluginInput,Fi as pathWithin,aF as persistedOptionsForInstall,DW as preflightContext7,qo as projectNativeAgents,Uw as projectRootAgent,Ba as publicManifestPath,Li as readActiveInstallRecord,dW as readCanonicalBaseVersion,I0 as readCanonicalVersion,Th as readInstallOptions,od as readInstallationVersion,Tc as readPublicVersion,md as removeHolyCodex,gh as removeManagedNativeAgents,fd as removeOwnedContext7,Pz as renderConflictScreen,S_ as renderHelp,qh as renderHuman,qz as renderInstallWizardReview,Oc as renderNativeAgent,EF as renderProgress,br as resolveInstallerPaths,hh as rollbackNativeAgentInstall,$w as rootDeveloperInstructions,Iv as runBinary,Cv as runCli,Sv as runOpenTuiConflictResolver,Lh as runOpenTuiInstallWizard,xv as stateFromConflicts,wv as stateFromRequest,wF as toInstallOptions,Lw as updateCanonicalVersion,QW as upgradeHolyCodex,sn as validateInstallOptions,Hw as windowsGitBashShellDirective,oF as writeInstallOptions};
131
+ `}function KK(e,t){return Object.entries(e).map(([n,r])=>` ${be(n,"option",t)}: ${be(Lv(r),"dim",t)}`)}function Lv(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function JK(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 be(e,t,n){return ot(e,{red:"error",green:"success",cyan:"focus",dim:"hint",warning:"warning",heading:"heading",option:"option"}[t],n)}class Bc extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function Uv(e=Bun.argv.slice(2),t=YK()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??ZK(),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 Dv(e,n);if((e.length===0||Wu(e)||e[0]==="help")&&!JF(e))n.io?.writeStdout?.(T_(zu(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(JF(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
132
+ `);else if(r.envelope.ok)n.io?.writeStdout?.(Bh(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(Bh(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function YK(){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=GK({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 JF(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*ZK(){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}Td();Eh();dd();za();md();Oh();wh();var Cte="holycodex";if(import.meta.main)process.exitCode=await Uv();export{rt as ArgumentError,vr as CONTEXT7_SPEC,en as CapabilityInstallStateSchema,Lw as CapabilityStateRecordSchema,Xa as CodexOfficialPluginManager,mh as InstallOptionsSchema,Cc as InstallRecordSchema,sd as InstallRequestSchema,C as InstallerError,Xr as OfficialPluginManagerError,Yn as PathBoundaryError,cd as PersistedInstallOptionsSchema,vh as ReadOnlyCodexPluginStatus,SW as STATE_SCHEMA,pe as ToolingError,es as WINDOWS_GIT_BASH,DF as applyConflictScreenKey,UF as applyWizardConfigurationKey,Hw as assertRootText,aF as context7InstallCommand,rs as createInstallerRuntime,ts as detectContext7Manager,pv as doctorHolyCodex,Th as ensureContext7,os as ensureGitBash,VF as executeCommand,Wu as helpRequested,Vu as helpText,zu as helpTopic,ss as installHolyCodex,Gw as installNativeAgents,qh as installRecordDigest,_d as installRequestFromPersistedOptions,Cte as packageName,Km as parseArgv,HF as parsePluginInput,qi as pathWithin,RF as persistedOptionsForInstall,az as preflightContext7,jo as projectNativeAgents,Kw as projectRootAgent,Ga as publicManifestPath,$i as readActiveInstallRecord,NW as readCanonicalBaseVersion,J0 as readCanonicalVersion,kh as readInstallOptions,ud as readInstallationVersion,kc as readPublicVersion,bd as removeHolyCodex,bh as removeManagedNativeAgents,Sd as removeOwnedContext7,lK as renderConflictScreen,T_ as renderHelp,Bh as renderHuman,hK as renderInstallWizardReview,Ic as renderNativeAgent,KF as renderProgress,wr as resolveInstallerPaths,Sh as rollbackNativeAgentInstall,Jw as rootDeveloperInstructions,Uv as runBinary,Dv as runCli,kv as runOpenTuiConflictResolver,jh as runOpenTuiInstallWizard,Ev as stateFromConflicts,Pv as stateFromRequest,jF as toInstallOptions,Vw as updateCanonicalVersion,vz as upgradeHolyCodex,un as validateInstallOptions,Yw as windowsGitBashShellDirective,wF as writeInstallOptions};