holycodex 0.16.6 → 0.16.7-dev.86.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,52 +1,52 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var x=(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&&Rm(r.value))ir(r.value,t)}Object.freeze(e)}function Rm(e){return typeof e==="object"&&e!==null}var Pr="0.15",yn="state-0.16";var L_=()=>{};function Ea(e){return{ok:!0,value:e}}function ui(e){return{ok:!1,error:e}}function Js(e,t){return new We("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var We;var Oa=x(()=>{We=class We 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 y(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 Cm=(e)=>typeof e==="function",d=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)}}}},de=(e)=>e,Gs=(e)=>()=>e,Ys,ho,wu,Zs;var z=x(()=>{Ys=Gs(!0),ho=Gs(!1),wu=Gs(void 0),Zs=wu});var Qs=(e)=>(t,n)=>t===n||e(t,n),nN=(e,t)=>e===t,rN=()=>nN,oN,km,D_,q_=(e)=>Qs((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 ec=x(()=>{z();oN=rN(),km=d(2,(e,t)=>Qs((n,r)=>e(t(n),t(r)))),D_=km(oN,(e)=>e.getTime())});var tc,K=(e,t)=>{if(!tc)globalThis["effect/GlobalValue"]??=new Map,tc=globalThis["effect/GlobalValue"];if(!tc.has(e))tc.set(e,t());return tc.get(e)};var wt=(e)=>typeof e==="string",rn=(e)=>typeof e==="number",pi=(e)=>typeof e==="boolean",go=(e)=>typeof e==="bigint",di=(e)=>typeof e==="symbol",yo,U_=(e)=>e===void 0,$_=(e)=>!1,nc=(e)=>typeof e==="object"&&e!==null,Bt=(e)=>nc(e)||yo(e),N,rc,fi=(e)=>e===null||e===void 0,H_=(e)=>e!==null&&e!==void 0,Tu=(e)=>e instanceof Date,Am=(e)=>typeof e==="string"||N(e,Symbol.iterator),Im=(e)=>nc(e)&&!Array.isArray(e),j_=(e)=>N(e,"then")&&yo(e.then);var we=x(()=>{z();yo=Cm,N=d(2,(e,t)=>Bt(e)&&(t in e)),rc=d(2,(e,t)=>N(e,"_tag")&&e._tag===t)});var mi=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Mm{_state;constructor(e,t,n,r){if(fi(t)&&fi(e))t=Math.random()*4294967295>>>0,e=0;else if(fi(t))t=e,e=0;if(fi(r)&&fi(n))r=this._state?this._state[3]:aN,n=this._state?this._state[2]:iN;else if(fi(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),B_(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*uN+t)/lN}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;pN(this._state,e,t,sN,cN),B_(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 pN(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 B_(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 Nm(e){if(typeof e==="object"&&e!==null&&Pm in e)return e[Pm]();throw Error(mi("yieldWrapGet"))}var Ca,iN=335903614,aN=4150755663,sN=1481765933,cN=1284865837,lN=9007199254740992,uN=134217728,Pm,Mr,Jt,V_,dN,fN,vt,uV;var xo=x(()=>{we();Ca=class Ca{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 Ca(this.self)}};Pm=Symbol.for("effect/Utils/YieldWrap");Mr=class Mr{#e;constructor(e){this.#e=e}[Pm](){return this.#e}};Jt=K("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),V_={effect_internal_function:(e)=>e()},dN={effect_internal_function:(e)=>{try{return e()}finally{}}},fN=V_.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,vt=fN?V_.effect_internal_function:dN.effect_internal_function,uV=function*(){}.constructor});var Fm,D,I=(e)=>{if(Jt.enabled===!0)return 0;switch(typeof e){case"number":return Ou(e);case"bigint":return xe(e.toString(10));case"boolean":return xe(String(e));case"symbol":return xe(String(e));case"string":return xe(e);case"undefined":return xe("undefined");case"function":case"object":if(e===null)return xe("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return xe("Invalid Date");return I(e.toISOString())}else if(e instanceof URL)return I(e.href);else if(hN(e))return e[D]();else return oc(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},oc=(e)=>{if(!Fm.has(e))Fm.set(e,Ou(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Fm.get(e)},Q=(e)=>(t)=>t*53^e,Eu=(e)=>e&3221225471|e>>>1&1073741824,hN=(e)=>N(e,D),Ou=(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 Eu(t)},xe=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Eu(t)},gN=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=y(xe(t[r]),Q(I(e[t[r]])));return Eu(n)},Ru=(e)=>gN(e,Object.keys(e)),on=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=y(t,Q(I(e[n])));return Eu(t)},le=function(){if(arguments.length===1){let n=arguments[0];return function(r){return Object.defineProperty(n,D,{value(){return r},enumerable:!1}),r}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,D,{value(){return t},enumerable:!1}),t};var Le=x(()=>{z();we();xo();Fm=K(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),D=Symbol.for("effect/Hash")});function P(){if(arguments.length===1)return(e)=>Cu(e,arguments[0]);return Cu(arguments[0],arguments[1])}function Cu(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(ic(e)&&ic(t))if(I(e)===I(t)&&e[L](t))return!0;else return Jt.enabled&&Jt.tester?Jt.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(Jt.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>Cu(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)&&Cu(e[i],t[i])))return Jt.tester?Jt.tester(e,t):!1;return!0}}return Jt.tester?Jt.tester(e,t):!1}}return Jt.enabled&&Jt.tester?Jt.tester(e,t):!1}var L,ic=(e)=>N(e,L),ac=()=>P;var fe=x(()=>{Le();we();xo();L=Symbol.for("effect/Equal")});function yN(e){try{return e.toISOString()}catch{return"Invalid Date"}}function xN(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function sc(e){return wt(e)?JSON.stringify(e):String(e)}function ar(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":rn(n)?" ".repeat(n):n,i=(l)=>o.repeat(l),a=(l,u)=>{let p=l?.constructor;return p&&p!==Object.prototype.constructor&&p.name?`${p.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 Lm;if(r.add(l),!o||l.length<=1)return`[${l.map((f)=>c(f,u)).join(",")}]`;let p=l.map((f)=>c(f,u+1)).join(`,
3
+ var x=(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&&Rm(r.value))ir(r.value,t)}Object.freeze(e)}function Rm(e){return typeof e==="object"&&e!==null}var Mr="0.15",yn="state-0.16";var L_=()=>{};function Ta(e){return{ok:!0,value:e}}function pi(e){return{ok:!1,error:e}}function Js(e,t){return new Ke("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var Ke;var Ea=x(()=>{Ke=class Ke 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 y(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 Om=(e)=>typeof e==="function",d=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)}}}},de=(e)=>e,Gs=(e)=>()=>e,Ys,go,wu,Zs;var W=x(()=>{Ys=Gs(!0),go=Gs(!1),wu=Gs(void 0),Zs=wu});var Qs=(e)=>(t,n)=>t===n||e(t,n),rN=(e,t)=>e===t,oN=()=>rN,iN,Cm,D_,q_=(e)=>Qs((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 ec=x(()=>{W();iN=oN(),Cm=d(2,(e,t)=>Qs((n,r)=>e(t(n),t(r)))),D_=Cm(iN,(e)=>e.getTime())});var tc,K=(e,t)=>{if(!tc)globalThis["effect/GlobalValue"]??=new Map,tc=globalThis["effect/GlobalValue"];if(!tc.has(e))tc.set(e,t());return tc.get(e)};var wt=(e)=>typeof e==="string",rn=(e)=>typeof e==="number",di=(e)=>typeof e==="boolean",yo=(e)=>typeof e==="bigint",fi=(e)=>typeof e==="symbol",xo,U_=(e)=>e===void 0,$_=(e)=>!1,nc=(e)=>typeof e==="object"&&e!==null,Bt=(e)=>nc(e)||xo(e),N,rc,mi=(e)=>e===null||e===void 0,H_=(e)=>e!==null&&e!==void 0,Tu=(e)=>e instanceof Date,km=(e)=>typeof e==="string"||N(e,Symbol.iterator),Am=(e)=>nc(e)&&!Array.isArray(e),j_=(e)=>N(e,"then")&&xo(e.then);var we=x(()=>{W();xo=Om,N=d(2,(e,t)=>Bt(e)&&(t in e)),rc=d(2,(e,t)=>N(e,"_tag")&&e._tag===t)});var hi=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Pm{_state;constructor(e,t,n,r){if(mi(t)&&mi(e))t=Math.random()*4294967295>>>0,e=0;else if(mi(t))t=e,e=0;if(mi(r)&&mi(n))r=this._state?this._state[3]:sN,n=this._state?this._state[2]:aN;else if(mi(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),B_(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*pN+t)/uN}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;dN(this._state,e,t,cN,lN),B_(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 dN(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 B_(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 Mm(e){if(typeof e==="object"&&e!==null&&Im in e)return e[Im]();throw Error(hi("yieldWrapGet"))}var Oa,aN=335903614,sN=4150755663,cN=1481765933,lN=1284865837,uN=9007199254740992,pN=134217728,Im,Nr,Jt,V_,fN,mN,vt,mV;var So=x(()=>{we();Oa=class Oa{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 Oa(this.self)}};Im=Symbol.for("effect/Utils/YieldWrap");Nr=class Nr{#e;constructor(e){this.#e=e}[Im](){return this.#e}};Jt=K("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),V_={effect_internal_function:(e)=>e()},fN={effect_internal_function:(e)=>{try{return e()}finally{}}},mN=V_.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,vt=mN?V_.effect_internal_function:fN.effect_internal_function,mV=function*(){}.constructor});var Nm,q,I=(e)=>{if(Jt.enabled===!0)return 0;switch(typeof e){case"number":return Ru(e);case"bigint":return xe(e.toString(10));case"boolean":return xe(String(e));case"symbol":return xe(String(e));case"string":return xe(e);case"undefined":return xe("undefined");case"function":case"object":if(e===null)return xe("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return xe("Invalid Date");return I(e.toISOString())}else if(e instanceof URL)return I(e.href);else if(gN(e))return e[q]();else return oc(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},oc=(e)=>{if(!Nm.has(e))Nm.set(e,Ru(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Nm.get(e)},te=(e)=>(t)=>t*53^e,Eu=(e)=>e&3221225471|e>>>1&1073741824,gN=(e)=>N(e,q),Ru=(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 Eu(t)},xe=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Eu(t)},yN=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=y(xe(t[r]),te(I(e[t[r]])));return Eu(n)},Ou=(e)=>yN(e,Object.keys(e)),on=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=y(t,te(I(e[n])));return Eu(t)},le=function(){if(arguments.length===1){let n=arguments[0];return function(r){return Object.defineProperty(n,q,{value(){return r},enumerable:!1}),r}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,q,{value(){return t},enumerable:!1}),t};var Le=x(()=>{W();we();So();Nm=K(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),q=Symbol.for("effect/Hash")});function P(){if(arguments.length===1)return(e)=>Cu(e,arguments[0]);return Cu(arguments[0],arguments[1])}function Cu(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(ic(e)&&ic(t))if(I(e)===I(t)&&e[D](t))return!0;else return Jt.enabled&&Jt.tester?Jt.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(Jt.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>Cu(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)&&Cu(e[i],t[i])))return Jt.tester?Jt.tester(e,t):!1;return!0}}return Jt.tester?Jt.tester(e,t):!1}}return Jt.enabled&&Jt.tester?Jt.tester(e,t):!1}var D,ic=(e)=>N(e,D),ac=()=>P;var fe=x(()=>{Le();we();So();D=Symbol.for("effect/Equal")});function xN(e){try{return e.toISOString()}catch{return"Invalid Date"}}function SN(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function sc(e){return wt(e)?JSON.stringify(e):String(e)}function ar(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":rn(n)?" ".repeat(n):n,i=(l)=>o.repeat(l),a=(l,u)=>{let p=l?.constructor;return p&&p!==Object.prototype.constructor&&p.name?`${p.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 Fm;if(r.add(l),!o||l.length<=1)return`[${l.map((f)=>c(f,u)).join(",")}]`;let p=l.map((f)=>c(f,u+1)).join(`,
4
4
  `+i(u+1));return`[
5
5
  ${i(u+1)}${p}
6
- ${i(u)}]`}if(Tu(l))return yN(l);if(!t?.ignoreToString&&N(l,"toString")&&yo(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let p=xN(l);if(l instanceof Error&&l.cause)return`${p} (cause: ${c(l.cause,u)})`;return p}if(wt(l))return JSON.stringify(l);if(rn(l)||l==null||pi(l)||di(l))return String(l);if(go(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return Lm;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(Bt(l)){if(r.has(l))return Lm;r.add(l);let p=s(l);if(!o||p.length<=1){let h=`{${p.map((m)=>`${sc(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,h)}let f=`{
6
+ ${i(u)}]`}if(Tu(l))return xN(l);if(!t?.ignoreToString&&N(l,"toString")&&xo(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let p=SN(l);if(l instanceof Error&&l.cause)return`${p} (cause: ${c(l.cause,u)})`;return p}if(wt(l))return JSON.stringify(l);if(rn(l)||l==null||di(l)||fi(l))return String(l);if(yo(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return Fm;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(Bt(l)){if(r.has(l))return Fm;r.add(l);let p=s(l);if(!o||p.length<=1){let h=`{${p.map((m)=>`${sc(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,h)}let f=`{
7
7
  ${p.map((h)=>`${i(u+1)}${sc(h)}: ${c(l[h],u+1)}`).join(`,
8
8
  `)}
9
- ${i(u)}}`;return a(l,f)}return String(l)}return c(e,0)}var ie,me=(e)=>{try{if(N(e,"toJSON")&&yo(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(me)}catch{return{}}return W_(e)},Lm="[Circular]",Se=(e)=>JSON.stringify(e,null,2),xV,Nr=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?ku(e,t):String(e)}catch{return String(e)}},ku=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(hi.fiberRefs!==void 0&&z_(i)?i[Dm](hi.fiberRefs):i):i,t);return n=void 0,r},Dm,z_=(e)=>typeof e==="object"&&e!==null&&(Dm in e),hi,K_=(e,t)=>{let n=hi.fiberRefs;hi.fiberRefs=e;try{return t()}finally{hi.fiberRefs=n}},W_=(e)=>{if(z_(e)&&hi.fiberRefs!==void 0)return e[Dm](hi.fiberRefs);return e};var Be=x(()=>{we();ie=Symbol.for("nodejs.util.inspect.custom");xV={toJSON(){return me(this)},[ie](){return this.toJSON()},toString(){return Se(this.toJSON())}},Dm=Symbol.for("effect/Inspectable/Redactable"),hi=K("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var k=(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 Oe=()=>{};var yi="Async",xi="Commit",Gt="Failure",cc="OnFailure",ka="OnSuccess",Aa="OnSuccessAndFailure",Yt="Success",Au="Sync",J_="Tag",Si="UpdateRuntimeFlags",Ia="While",Pa="Iterator",Iu="WithRuntime",Ma="Yield",lc="RevertFlags";var SN="3.22.2",uc=()=>SN;var Y_,Z_,X_,Q_,So,bN,_N,Fr,pc,bo,Um,ew;var Lr=x(()=>{fe();Le();Oe();xo();Y_=Symbol.for("effect/Effect"),Z_=Symbol.for("effect/Stream"),X_=Symbol.for("effect/Sink"),Q_=Symbol.for("effect/Channel"),So={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:uc()},bN={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},_N={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},Fr={[Y_]:So,[Z_]:So,[X_]:bN,[Q_]:_N,[L](e){return this===e},[D](){return le(this,oc(this))},[Symbol.iterator](){return new Ca(new Mr(this))},pipe(){return k(this,arguments)}},pc={[D](){return le(this,Ru(this))},[L](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)&&P(this[r],e[r])))return!1;return!0}},bo={...Fr,_op:xi},Um={...bo,...pc},ew=function(){function e(){}return e.prototype=bo,e}()});var nw,rw,wN,vN,TN,$m=(e)=>N(e,nw),Hm=(e)=>e._tag==="None",jm=(e)=>e._tag==="Some",Pu,dc=(e)=>{let t=Object.create(wN);return t.value=e,t};var Bm=x(()=>{fe();Le();Be();we();Lr();nw=Symbol.for("effect/Option"),rw={...Fr,[nw]:{_A:(e)=>e},[ie](){return this.toJSON()},toString(){return Se(this.toJSON())}},wN=Object.assign(Object.create(rw),{_tag:"Some",_op:"Some",[L](e){return $m(e)&&jm(e)&&P(this.value,e.value)},[D](){return le(this,Q(I(this._tag))(I(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:me(this.value)}}}),vN=I("None"),TN=Object.assign(Object.create(rw),{_tag:"None",_op:"None",[L](e){return $m(e)&&Hm(e)},[D](){return vN},toJSON(){return{_id:"Option",_tag:this._tag}}}),Pu=Object.create(TN)});var Vm,iw,EN,ON,Mu=(e)=>N(e,Vm),zm=(e)=>e._tag==="Left",Km=(e)=>e._tag==="Right",aw=(e)=>{let t=Object.create(ON);return t.left=e,t},sw=(e)=>{let t=Object.create(EN);return t.right=e,t};var cw=x(()=>{fe();Le();Be();we();Lr();Vm=Symbol.for("effect/Either"),iw={...Fr,[Vm]:{_R:(e)=>e},[ie](){return this.toJSON()},toString(){return Se(this.toJSON())}},EN=Object.assign(Object.create(iw),{_tag:"Right",_op:"Right",[L](e){return Mu(e)&&Km(e)&&P(this.right,e.right)},[D](){return Q(I(this._tag))(I(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:me(this.right)}}}),ON=Object.assign(Object.create(iw),{_tag:"Left",_op:"Left",[L](e){return Mu(e)&&zm(e)&&P(this.left,e.left)},[D](){return Q(I(this._tag))(I(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:me(this.left)}}})});var ne,X,Wm,ke,kt,Nu,lw,fc,uw,Jm,pw;var an=x(()=>{z();cw();ne=sw,X=aw,Wm=Mu,ke=zm,kt=Km,Nu=d(2,(e,t)=>ke(e)?X(t(e.left)):ne(e.right)),lw=d(2,(e,t)=>kt(e)?ne(t(e.right)):X(e.left)),fc=d(2,(e,{onLeft:t,onRight:n})=>ke(e)?t(e.left):n(e.right)),uw=fc({onLeft:de,onRight:de}),Jm=d(2,(e,t)=>{if(kt(e))return e.right;throw t(e.left)}),pw=Jm(()=>Error("getOrThrow called on a Left"))});var Gm=(e)=>e.length>0;var dw=(e)=>(t,n)=>t===n?0:e(t,n),fw,Fu,Ym=(e)=>d(2,(t,n)=>e(t,n)===1);var Lu=x(()=>{z();fw=dw((e,t)=>e<t?-1:1),Fu=d(2,(e,t)=>dw((n,r)=>e(t(n),t(r))))});var F=()=>Pu,H,De,Ie,Je,Ae,Fn,mw,Dr=(e)=>e==null?F():H(e),Zt,hw=(e)=>(...t)=>{try{return H(e(...t))}catch{return F()}},Ln,Dn,gw,AN=(e)=>d(2,(t,n)=>De(t)?!1:e(t.value,n)),IN,yw,xw;var Ge=x(()=>{fe();z();Bm();H=dc,De=Hm,Ie=jm,Je=d(2,(e,{onNone:t,onSome:n})=>De(e)?t():n(e.value)),Ae=d(2,(e,t)=>De(e)?t():e.value),Fn=d(2,(e,t)=>De(e)?t():e),mw=d(2,(e,t)=>De(e)?H(t()):e),Zt=Ae(wu),Ln=d(2,(e,t)=>De(e)?F():H(t(e.value))),Dn=d(2,(e,t)=>De(e)?F():t(e.value)),gw=d(2,(e,t)=>De(e)?F():Dr(t(e.value))),IN=ac(),yw=AN(IN),xw=d(2,(e,t)=>De(e)?!1:t(e.value))});var Sw=(...e)=>e;var bw=()=>{};var bi=(e)=>Array(e),Xm,Pe=(e)=>Array.isArray(e)?e:Array.from(e),Qm=(e)=>Array.isArray(e)?e:[e],_w,Na,ww,eh,th,MN=(e)=>e.length===0,vw,_o,Re,Tw=(e,t)=>e<0||e>=t.length,NN=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),FN,nh,qr,rt,Ew=(e)=>Re(e)?H(rh(e)):F(),rh=(e)=>e[e.length-1],qn=(e)=>e.slice(1),LN=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},Ow,Rw,oh=(e)=>Array.from(e).reverse(),Ur,ih,Cw,DN,qN,UN,Fa=(e)=>e.slice(),$N,wo,$r=()=>[],At=(e)=>[e],Un,mc,Du,qu,La,ah=(e,t)=>{let n=[],r=e,o;while(Ie(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},vo,kw,sh=(e)=>kw(e,ac()),Hr;var Ve=x(()=>{fe();ec();z();Ge();bw();Xm=d(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}),_w=d(2,(e,{onEmpty:t,onNonEmpty:n})=>Re(e)?n(rt(e),qn(e)):t()),Na=d(2,(e,t)=>[t,...e]),ww=d(2,(e,t)=>[...e,t]),eh=d(2,(e,t)=>Pe(e).concat(Pe(t))),th=Array.isArray,vw=MN,_o=Gm,Re=Gm,FN=d(2,(e,t)=>{let n=Math.floor(t);return Tw(n,e)?F():H(e[n])}),nh=d(2,(e,t)=>{let n=Math.floor(t);if(Tw(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),qr=FN(0),rt=nh(0),Ow=d(2,(e,t)=>qN(e,LN(e,t))),Rw=d(2,(e,t)=>{let n=Pe(e);return n.slice(NN(t,n),n.length)}),Ur=d(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),ih=d(2,(e,t)=>Cw(e,t,Sw)),Cw=d(3,(e,t,n)=>{let r=Pe(e),o=Pe(t);if(Re(r)&&Re(o)){let i=[n(rt(r),rt(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[]}),DN=ac(),qN=d(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(Re(n)){if(r>=1)return UN(n,r);return[[],n]}return[n,[]]}),UN=d(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[Fa(e),[]]:[Na(e.slice(1,n),rt(e)),e.slice(n)]}),$N=d(3,(e,t,n)=>{let r=Pe(e),o=Pe(t);if(Re(r)){if(Re(o))return kw(n)(eh(r,o));return r}return o}),wo=d(2,(e,t)=>$N(e,t,DN)),Un=d(2,(e,t)=>e.map(t)),mc=d(2,(e,t)=>{if(vw(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}),Du=mc(de),qu=d(2,(e,t)=>{let n=Pe(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if(Ie(i))r.push(i.value)}return r}),La=d(3,(e,t,n)=>Pe(e).reduce((r,o,i)=>n(r,o,i),t)),vo=q_,kw=d(2,(e,t)=>{let n=Pe(e);if(Re(n)){let r=[rt(n)],o=qn(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),Hr=d(2,(e,t)=>Pe(e).join(t))});function VN(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 Iw,Pw,zN=(e)=>Qs((t,n)=>t.length===n.length&&jr(t).every((r,o)=>e(r,Da(n,o)))),KN,WN,lt=(e)=>{let t=Object.create(WN);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=sr,t.right=sr;break}case"ISingleton":{t.length=1,t.depth=0,t.left=sr,t.right=sr;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=sr,t.right=sr;break}}return t},Mw=(e)=>N(e,Iw),sr,Sn=()=>sr,hc=(...e)=>YN(e),ot=(e)=>lt({_tag:"ISingleton",a:e}),Uu=(e)=>Mw(e)?e:gc(Pe(e)),ch=(e,t,n)=>{switch(e.backing._tag){case"IArray":{VN(e.backing.array,0,t,n,e.length);break}case"IConcat":{ch(e.left,t,n),ch(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]=Da(e,r),r+=1,o+=1;break}}},JN=(e)=>{switch(e.backing._tag){case"IEmpty":return Pw;case"IArray":return e.backing.array;default:{let t=Array(e.length);return ch(e,t,0),e.backing={_tag:"IArray",array:t},e.left=sr,e.right=sr,e.depth=0,t}}},jr,GN=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return lt({_tag:"IArray",array:oh(e.backing.array)});case"IConcat":return lt({_tag:"IConcat",left:To(e.backing.right),right:To(e.backing.left)});case"ISlice":return gc(oh(jr(e)))}},To,gc=(e)=>e.length===0?Sn():e.length===1?ot(e[0]):lt({_tag:"IArray",array:e}),YN=(e)=>gc(e),Da,Nw,It,lh,sn,Fw=(e)=>e.length===0,$n=(e)=>e.length>0,uh=(e)=>Da(e,0),Hn,jn=(e)=>lh(e,1);var cr=x(()=>{Ve();fe();ec();z();Le();Be();Oe();we();Iw=Symbol.for("effect/Chunk");Pw=[],KN=zN(P),WN={[Iw]:{_A:(e)=>e},toString(){return Se(this.toJSON())},toJSON(){return{_id:"Chunk",values:jr(this).map(me)}},[ie](){return this.toJSON()},[L](e){return Mw(e)&&KN(this,e)},[D](){return le(this,on(jr(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return Pw[Symbol.iterator]();default:return jr(this)[Symbol.iterator]()}},pipe(){return k(this,arguments)}},sr=lt({_tag:"IEmpty"}),jr=JN,To=GN,Da=d(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?Da(e.left,t):Da(e.right,t-e.left.length);case"ISlice":return Da(e.backing.chunk,t+e.backing.offset)}}),Nw=d(2,(e,t)=>sn(e,ot(t))),It=d(2,(e,t)=>sn(ot(t),e)),lh=d(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return sr;else switch(e.backing._tag){case"ISlice":return lt({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return lh(e.right,t-e.left.length);return lt({_tag:"IConcat",left:lh(e.left,t),right:e.right})}default:return lt({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),sn=d(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 lt({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=sn(e.right,t);return lt({_tag:"IConcat",left:e.left,right:r})}else{let r=sn(e.right.right,t);if(r.depth===e.depth-3){let o=lt({_tag:"IConcat",left:e.right.left,right:r});return lt({_tag:"IConcat",left:e.left,right:o})}else{let o=lt({_tag:"IConcat",left:e.left,right:e.right.left});return lt({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=sn(e,t.left);return lt({_tag:"IConcat",left:r,right:t.right})}else{let r=sn(e,t.left.left);if(r.depth===t.depth-3){let o=lt({_tag:"IConcat",left:r,right:t.left.right});return lt({_tag:"IConcat",left:o,right:t.right})}else{let o=lt({_tag:"IConcat",left:t.left.right,right:t.right});return lt({_tag:"IConcat",left:r,right:o})}}}),Hn=uh});var Eo=5,ph,Lw,Dw,qw;var $u=x(()=>{ph=Math.pow(2,5),Lw=ph-1,Dw=ph/2,qw=ph/4});function ZN(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 Oo(e,t){return t>>>e&Lw}function Ro(e){return 1<<e}function Hu(e,t){return ZN(e&t-1)}var dh=x(()=>{$u()});var Uw=(e,t)=>({value:e,previous:t});function _i(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 fh(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 $w(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 Vr{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(F());if(De(a))return new Vr;return++i.value,new wi(e,r,o,a)}}function bn(e){return rc(e,"EmptyNode")}function QN(e){return bn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function ju(e,t){return bn(e)?!1:t===e.edit}class wi{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(P(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(De(s))return--i.value,new Vr;if(ju(this,e))return this.value=s,this;return new wi(e,r,o,s)}let a=n(F());if(De(a))return this;return++i.value,Hw(e,t,this.hash,this,r,new wi(e,r,o,a))}}class mh{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=ju(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 mh(e,this.hash,c):c[0]}let a=n(F());if(De(a))return this;return++i.value,Hw(e,t,this.hash,this,r,new wi(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&&P(i,u.key)){let p=u.value,f=o(p);if(f===p)return r;if(De(f))return--a.value,fh(e,l,r);return _i(e,l,new wi(t,n,i,f),r)}}let c=o(F());if(De(c))return r;return++a.value,_i(e,s,new wi(t,n,i,c),r)}}class qa{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=Oo(t,r),l=Ro(c),u=Hu(a,l),p=a&l,f=ju(this,e);if(!p){let w=new Vr().modify(e,t+Eo,n,r,o,i);if(!w)return this;return s.length>=Dw?t0(e,c,w,a,s):new qa(e,a|l,$w(f,u,w,s))}let h=s[u],m=h.modify(e,t+Eo,n,r,o,i);if(h===m)return this;let S=a,E;if(bn(m)){if(S&=~l,!S)return new Vr;if(s.length<=2&&QN(s[u^1]))return s[u^1];E=fh(f,u,s)}else E=_i(f,u,m,s);if(f)return this.mask=S,this.children=E,this;return new qa(e,S,E)}}class hh{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=Oo(t,r),l=s[c],u=(l||new Vr).modify(e,t+Eo,n,r,o,i);if(l===u)return this;let p=ju(this,e),f;if(bn(l)&&!bn(u))++a,f=_i(p,c,u,s);else if(!bn(l)&&bn(u)){if(--a,a<=qw)return e0(e,a,c,s);f=_i(p,c,new Vr,s)}else f=_i(p,c,u,s);if(p)return this.size=a,this.children=f,this;return new hh(e,a,f)}}function e0(e,t,n,r){let o=Array(t-1),i=0,a=0;for(let s=0,c=r.length;s<c;++s)if(s!==n){let l=r[s];if(l&&!bn(l))o[i++]=l,a|=1<<s}return new qa(e,a,o)}function t0(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 hh(e,s+1,i)}function n0(e,t,n,r,o,i){if(n===o)return new mh(e,n,[i,r]);let a=Oo(t,n),s=Oo(t,o);if(a===s)return(c)=>new qa(e,Ro(a)|Ro(s),[c]);else{let c=a<s?[r,i]:[i,r];return new qa(e,Ro(a)|Ro(s),c)}}function Hw(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=n0(e,s,n,r,o,i);if(typeof c==="function")a=Uw(c,a),s=s+Eo;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var jw=x(()=>{fe();Ge();we();dh();$u()});var Bw="effect/HashMap",Bu,o0,gh=(e,t,n,r)=>{let o=Object.create(o0);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},zu,Vu=(e)=>e?zw(e[0],e[1],e[2],e[3],e[4]):F(),Vw=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if(Ie(e.value))return H({value:t(e.key,e.value.value),cont:n});return Vu(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return zw(r.length,r,0,t,n)}default:return Vu(n)}},zw=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!bn(i))return Vw(i,r,[e,t,n,r,o])}return Vu(o)},i0,Ua=()=>i0,Kw=(e)=>{let t=Ju(Ua());for(let n of e)vi(t,n[0],n[1]);return Yw(t)},Ww=(e)=>N(e,Bu),Jw=(e)=>e&&bn(e._root),Gw,Ku,yh,vi,a0,Wu=(e)=>new zu(e,(t)=>t),yc=(e)=>e._size,Ju=(e)=>gh(!0,e._edit+1,e._root,e._size),Yw=(e)=>(e._editable=!1,e),Gu,Zw,Yu,Xw,xh,$a;var Sh=x(()=>{fe();z();z();Le();Be();Ge();Oe();we();dh();$u();jw();Bu=Symbol.for(Bw),o0={[Bu]:Bu,[Symbol.iterator](){return new zu(this,(e,t)=>[e,t])},[D](){let e=I(Bw);for(let t of this)e^=y(I(t[0]),Q(I(t[1])));return le(this,e)},[L](e){if(Ww(e)){if(e._size!==this._size)return!1;for(let t of this){let n=y(e,Ku(t[0],I(t[0])));if(De(n))return!1;else if(!P(t[1],n.value))return!1}return!0}return!1},toString(){return Se(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(me)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}};zu=class zu{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=Vw(this.map._root,this.f,void 0)}next(){if(De(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=Vu(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new zu(this.map,this.f)}};i0=gh(!1,0,new Vr,0),Gw=d(2,(e,t)=>Ku(e,t,I(t))),Ku=d(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return P(t,r.key)?r.value:F();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&&P(t,c.key))return c.value}}return F()}case"IndexedNode":{let i=Oo(o,n),a=Ro(i);if(r.mask&a){r=r.children[Hu(r.mask,a)],o+=Eo;break}return F()}case"ArrayNode":{if(r=r.children[Oo(o,n)],r){o+=Eo;break}return F()}default:return F()}}),yh=d(2,(e,t)=>Ie(Ku(e,t,I(t)))),vi=d(3,(e,t,n)=>Gu(e,t,()=>H(n))),a0=d(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:gh(e._editable,e._edit,t,n)}),Gu=d(3,(e,t,n)=>Zw(e,t,I(t),n)),Zw=d(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 y(e,a0(i,o.value))}),Yu=d(2,(e,t)=>Gu(e,t,F)),Xw=d(2,(e,t)=>$a(e,Ua(),(n,r,o)=>vi(n,o,t(r,o)))),xh=d(2,(e,t)=>$a(e,void 0,(n,r,o)=>t(r,o))),$a=d(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return Ie(r.value)?n(t,r.value.value,r.key):t;if(r._tag==="EmptyNode")return t;let o=[r.children],i;while(i=o.pop())for(let a=0,s=i.length;a<s;){let c=i[a++];if(c&&!bn(c))if(c._tag==="LeafNode"){if(Ie(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var ev="effect/HashSet",Zu,s0,Xu=(e)=>{let t=Object.create(s0);return t._keyMap=e,t},tv=(e)=>N(e,Zu),c0,xc=()=>c0,nv=(e)=>{let t=Qu(xc());for(let n of e)Ha(t,n);return ep(t)},rv=(...e)=>{let t=Qu(xc());for(let n of e)Ha(t,n);return ep(t)},ov,iv=(e)=>yc(e._keyMap),Qu=(e)=>Xu(Ju(e._keyMap)),ep=(e)=>(e._keyMap._editable=!1,e),bh,Ha,_h,av,sv,cv,lv;var uv=x(()=>{fe();z();Le();Be();Oe();we();Sh();Zu=Symbol.for(ev),s0={[Zu]:Zu,[Symbol.iterator](){return Wu(this._keyMap)},[D](){return le(this,Q(I(this._keyMap))(I(ev)))},[L](e){if(tv(e))return yc(this._keyMap)===yc(e._keyMap)&&P(this._keyMap,e._keyMap);return!1},toString(){return Se(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(me)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}},c0=Xu(Ua()),ov=d(2,(e,t)=>yh(e._keyMap,t)),bh=d(2,(e,t)=>{let n=Qu(e);return t(n),ep(n)}),Ha=d(2,(e,t)=>e._keyMap._editable?(vi(t,!0)(e._keyMap),e):Xu(vi(t,!0)(e._keyMap))),_h=d(2,(e,t)=>e._keyMap._editable?(Yu(t)(e._keyMap),e):Xu(Yu(t)(e._keyMap))),av=d(2,(e,t)=>bh(e,(n)=>{for(let r of t)_h(n,r)})),sv=d(2,(e,t)=>bh(xc(),(n)=>{cv(e,(r)=>Ha(n,r));for(let r of t)Ha(n,r)})),cv=d(2,(e,t)=>xh(e._keyMap,(n,r)=>t(r))),lv=d(3,(e,t,n)=>$a(e._keyMap,t,(r,o,i)=>n(r,i)))});var lr,pv,Ti,dv,Sc,Ei,wh,vh,zr,Oi;var Ri=x(()=>{uv();lr=xc,pv=nv,Ti=rv,dv=ov,Sc=iv,Ei=Ha,wh=_h,vh=av,zr=sv,Oi=lv});var Ba="Die",Co="Empty",ko="Fail",Ci="Interrupt",ki="Parallel",Ai="Sequential";var hv="effect/Cause",Oh,p0,Va,Kr,za=(e)=>{let t=Object.create(Va);return t._tag=ko,t.error=e,t},cn=(e)=>{let t=Object.create(Va);return t._tag=Ba,t.defect=e,t},Bn=(e)=>{let t=Object.create(Va);return t._tag=Ci,t.fiberId=e,t},Mi=(e,t)=>{let n=Object.create(Va);return n._tag=ki,n.left=e,n.right=t,n},Pt=(e,t)=>{let n=Object.create(Va);return n._tag=Ai,n.left=e,n.right=t,n},gv=(e)=>N(e,Oh),Rh=(e)=>e._tag===Co,yv=(e)=>e._tag===ko,tp=(e)=>{if(e._tag===Co)return!0;return Ii(e,!0,(t,n)=>{switch(n._tag){case Co:return H(t);case Ba:case ko:case Ci:return H(!1);default:return F()}})},np=(e)=>Ie(xv(e)),Ka=(e)=>ip(void 0,h0)(e),Ch=(e)=>To(Ii(e,Sn(),(t,n)=>n._tag===ko?H(y(t,It(n.error))):F())),kh=(e)=>To(Ii(e,Sn(),(t,n)=>n._tag===Ba?H(y(t,It(n.defect))):F())),Ah=(e)=>Ii(e,lr(),(t,n)=>n._tag===Ci?H(y(t,Ei(n.fiberId))):F()),Ih=(e)=>Ph(e,(t)=>t._tag===ko?H(t.error):F()),rp=(e)=>{let t=Ih(e);switch(t._tag){case"None":return ne(e);case"Some":return X(t.value)}},xv=(e)=>Ph(e,(t)=>t._tag===Ci?H(t.fiberId):F()),op=(e)=>Mh(e,{onEmpty:Kr,onFail:()=>Kr,onDie:cn,onInterrupt:Bn,onSequential:Pt,onParallel:Mi}),Sv=(e)=>Mh(e,{onEmpty:Kr,onFail:cn,onDie:cn,onInterrupt:Bn,onSequential:Pt,onParallel:Mi}),d0=(e,t)=>{let n=ot(e),r=ot(t);while($n(n)&&$n(r)){let[o,i]=y(Hn(n),Ii([lr(),Sn()],([c,l],u)=>{let[p,f]=Th(u);return H([y(c,zr(p)),y(l,sn(f))])})),[a,s]=y(Hn(r),Ii([lr(),Sn()],([c,l],u)=>{let[p,f]=Th(u);return H([y(c,zr(p)),y(l,sn(f))])}));if(!P(o,a))return!1;n=i,r=s}return!0},f0=(e)=>m0(ot(e),Sn()),m0=(e,t)=>{while(!0){let[n,r]=y(e,La([lr(),Sn()],([i,a],s)=>{let[c,l]=Th(s);return[y(i,zr(c)),y(a,sn(l))]})),o=Sc(n)>0?y(t,It(n)):t;if(Fw(r))return To(o);e=r,t=o}throw Error(mi("Cause.flattenCauseLoop"))},Ph,Th=(e)=>{let t=e,n=[],r=lr(),o=Sn();while(t!==void 0)switch(t._tag){case Co:{if(n.length===0)return[r,o];t=n.pop();break}case ko:{if(r=Ei(r,hc(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case Ba:{if(r=Ei(r,hc(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case Ci:{if(r=Ei(r,hc(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case Ai:{switch(t.left._tag){case Co:{t=t.right;break}case Ai:{t=Pt(t.left.left,Pt(t.left.right,t.right));break}case ki:{t=Mi(Pt(t.left.left,t.right),Pt(t.left.right,t.right));break}default:{o=It(o,t.right),t=t.left;break}}break}case ki:{n.push(t.right),t=t.left;break}}throw Error(mi("Cause.evaluateCauseLoop"))},h0,fv="SequentialCase",mv="ParallelCase",Mh,Ii,ip,Vn=(e,t)=>{if(Ka(e))return"All fibers interrupted without errors.";return bc(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
9
+ ${i(u)}}`;return a(l,f)}return String(l)}return c(e,0)}var ie,me=(e)=>{try{if(N(e,"toJSON")&&xo(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(me)}catch{return{}}return K_(e)},Fm="[Circular]",Se=(e)=>JSON.stringify(e,null,2),wV,Fr=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?ku(e,t):String(e)}catch{return String(e)}},ku=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(gi.fiberRefs!==void 0&&z_(i)?i[Lm](gi.fiberRefs):i):i,t);return n=void 0,r},Lm,z_=(e)=>typeof e==="object"&&e!==null&&(Lm in e),gi,W_=(e,t)=>{let n=gi.fiberRefs;gi.fiberRefs=e;try{return t()}finally{gi.fiberRefs=n}},K_=(e)=>{if(z_(e)&&gi.fiberRefs!==void 0)return e[Lm](gi.fiberRefs);return e};var Be=x(()=>{we();ie=Symbol.for("nodejs.util.inspect.custom");wV={toJSON(){return me(this)},[ie](){return this.toJSON()},toString(){return Se(this.toJSON())}},Lm=Symbol.for("effect/Inspectable/Redactable"),gi=K("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var k=(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 Re=()=>{};var xi="Async",Si="Commit",Gt="Failure",cc="OnFailure",Ca="OnSuccess",ka="OnSuccessAndFailure",Yt="Success",Au="Sync",J_="Tag",bi="UpdateRuntimeFlags",Aa="While",Ia="Iterator",Iu="WithRuntime",Pa="Yield",lc="RevertFlags";var bN="3.22.2",uc=()=>bN;var Y_,Z_,X_,Q_,bo,_N,wN,Lr,pc,_o,qm,ew;var Dr=x(()=>{fe();Le();Re();So();Y_=Symbol.for("effect/Effect"),Z_=Symbol.for("effect/Stream"),X_=Symbol.for("effect/Sink"),Q_=Symbol.for("effect/Channel"),bo={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:uc()},_N={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},wN={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},Lr={[Y_]:bo,[Z_]:bo,[X_]:_N,[Q_]:wN,[D](e){return this===e},[q](){return le(this,oc(this))},[Symbol.iterator](){return new Oa(new Nr(this))},pipe(){return k(this,arguments)}},pc={[q](){return le(this,Ou(this))},[D](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)&&P(this[r],e[r])))return!1;return!0}},_o={...Lr,_op:Si},qm={..._o,...pc},ew=function(){function e(){}return e.prototype=_o,e}()});var nw,rw,vN,TN,EN,Um=(e)=>N(e,nw),$m=(e)=>e._tag==="None",Hm=(e)=>e._tag==="Some",Pu,dc=(e)=>{let t=Object.create(vN);return t.value=e,t};var jm=x(()=>{fe();Le();Be();we();Dr();nw=Symbol.for("effect/Option"),rw={...Lr,[nw]:{_A:(e)=>e},[ie](){return this.toJSON()},toString(){return Se(this.toJSON())}},vN=Object.assign(Object.create(rw),{_tag:"Some",_op:"Some",[D](e){return Um(e)&&Hm(e)&&P(this.value,e.value)},[q](){return le(this,te(I(this._tag))(I(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:me(this.value)}}}),TN=I("None"),EN=Object.assign(Object.create(rw),{_tag:"None",_op:"None",[D](e){return Um(e)&&$m(e)},[q](){return TN},toJSON(){return{_id:"Option",_tag:this._tag}}}),Pu=Object.create(EN)});var Bm,iw,RN,ON,Mu=(e)=>N(e,Bm),Vm=(e)=>e._tag==="Left",zm=(e)=>e._tag==="Right",aw=(e)=>{let t=Object.create(ON);return t.left=e,t},sw=(e)=>{let t=Object.create(RN);return t.right=e,t};var cw=x(()=>{fe();Le();Be();we();Dr();Bm=Symbol.for("effect/Either"),iw={...Lr,[Bm]:{_R:(e)=>e},[ie](){return this.toJSON()},toString(){return Se(this.toJSON())}},RN=Object.assign(Object.create(iw),{_tag:"Right",_op:"Right",[D](e){return Mu(e)&&zm(e)&&P(this.right,e.right)},[q](){return te(I(this._tag))(I(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:me(this.right)}}}),ON=Object.assign(Object.create(iw),{_tag:"Left",_op:"Left",[D](e){return Mu(e)&&Vm(e)&&P(this.left,e.left)},[q](){return te(I(this._tag))(I(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:me(this.left)}}})});var re,Q,Wm,ke,kt,Nu,lw,fc,uw,Km,pw;var an=x(()=>{W();cw();re=sw,Q=aw,Wm=Mu,ke=Vm,kt=zm,Nu=d(2,(e,t)=>ke(e)?Q(t(e.left)):re(e.right)),lw=d(2,(e,t)=>kt(e)?re(t(e.right)):Q(e.left)),fc=d(2,(e,{onLeft:t,onRight:n})=>ke(e)?t(e.left):n(e.right)),uw=fc({onLeft:de,onRight:de}),Km=d(2,(e,t)=>{if(kt(e))return e.right;throw t(e.left)}),pw=Km(()=>Error("getOrThrow called on a Left"))});var Jm=(e)=>e.length>0;var dw=(e)=>(t,n)=>t===n?0:e(t,n),fw,Fu,Gm=(e)=>d(2,(t,n)=>e(t,n)===1);var Lu=x(()=>{W();fw=dw((e,t)=>e<t?-1:1),Fu=d(2,(e,t)=>dw((n,r)=>e(t(n),t(r))))});var F=()=>Pu,B,De,Ie,Je,Ae,Fn,mw,qr=(e)=>e==null?F():B(e),Zt,hw=(e)=>(...t)=>{try{return B(e(...t))}catch{return F()}},Ln,Dn,gw,IN=(e)=>d(2,(t,n)=>De(t)?!1:e(t.value,n)),PN,yw,xw;var Ge=x(()=>{fe();W();jm();B=dc,De=$m,Ie=Hm,Je=d(2,(e,{onNone:t,onSome:n})=>De(e)?t():n(e.value)),Ae=d(2,(e,t)=>De(e)?t():e.value),Fn=d(2,(e,t)=>De(e)?t():e),mw=d(2,(e,t)=>De(e)?B(t()):e),Zt=Ae(wu),Ln=d(2,(e,t)=>De(e)?F():B(t(e.value))),Dn=d(2,(e,t)=>De(e)?F():t(e.value)),gw=d(2,(e,t)=>De(e)?F():qr(t(e.value))),PN=ac(),yw=IN(PN),xw=d(2,(e,t)=>De(e)?!1:t(e.value))});var Sw=(...e)=>e;var bw=()=>{};var _i=(e)=>Array(e),Zm,Pe=(e)=>Array.isArray(e)?e:Array.from(e),Xm=(e)=>Array.isArray(e)?e:[e],_w,Ma,ww,Qm,eh,NN=(e)=>e.length===0,vw,wo,Oe,Tw=(e,t)=>e<0||e>=t.length,FN=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),LN,th,Ur,rt,Ew=(e)=>Oe(e)?B(nh(e)):F(),nh=(e)=>e[e.length-1],qn=(e)=>e.slice(1),DN=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},Rw,Ow,rh=(e)=>Array.from(e).reverse(),$r,oh,Cw,qN,UN,$N,Na=(e)=>e.slice(),HN,vo,Hr=()=>[],At=(e)=>[e],Un,mc,Du,qu,Fa,ih=(e,t)=>{let n=[],r=e,o;while(Ie(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},To,kw,ah=(e)=>kw(e,ac()),jr;var Ve=x(()=>{fe();ec();W();Ge();bw();Zm=d(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}),_w=d(2,(e,{onEmpty:t,onNonEmpty:n})=>Oe(e)?n(rt(e),qn(e)):t()),Ma=d(2,(e,t)=>[t,...e]),ww=d(2,(e,t)=>[...e,t]),Qm=d(2,(e,t)=>Pe(e).concat(Pe(t))),eh=Array.isArray,vw=NN,wo=Jm,Oe=Jm,LN=d(2,(e,t)=>{let n=Math.floor(t);return Tw(n,e)?F():B(e[n])}),th=d(2,(e,t)=>{let n=Math.floor(t);if(Tw(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),Ur=LN(0),rt=th(0),Rw=d(2,(e,t)=>UN(e,DN(e,t))),Ow=d(2,(e,t)=>{let n=Pe(e);return n.slice(FN(t,n),n.length)}),$r=d(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),oh=d(2,(e,t)=>Cw(e,t,Sw)),Cw=d(3,(e,t,n)=>{let r=Pe(e),o=Pe(t);if(Oe(r)&&Oe(o)){let i=[n(rt(r),rt(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[]}),qN=ac(),UN=d(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(Oe(n)){if(r>=1)return $N(n,r);return[[],n]}return[n,[]]}),$N=d(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[Na(e),[]]:[Ma(e.slice(1,n),rt(e)),e.slice(n)]}),HN=d(3,(e,t,n)=>{let r=Pe(e),o=Pe(t);if(Oe(r)){if(Oe(o))return kw(n)(Qm(r,o));return r}return o}),vo=d(2,(e,t)=>HN(e,t,qN)),Un=d(2,(e,t)=>e.map(t)),mc=d(2,(e,t)=>{if(vw(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}),Du=mc(de),qu=d(2,(e,t)=>{let n=Pe(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if(Ie(i))r.push(i.value)}return r}),Fa=d(3,(e,t,n)=>Pe(e).reduce((r,o,i)=>n(r,o,i),t)),To=q_,kw=d(2,(e,t)=>{let n=Pe(e);if(Oe(n)){let r=[rt(n)],o=qn(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),jr=d(2,(e,t)=>Pe(e).join(t))});function zN(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 Iw,Pw,WN=(e)=>Qs((t,n)=>t.length===n.length&&Br(t).every((r,o)=>e(r,La(n,o)))),KN,JN,lt=(e)=>{let t=Object.create(JN);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=sr,t.right=sr;break}case"ISingleton":{t.length=1,t.depth=0,t.left=sr,t.right=sr;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=sr,t.right=sr;break}}return t},Mw=(e)=>N(e,Iw),sr,Sn=()=>sr,hc=(...e)=>ZN(e),ot=(e)=>lt({_tag:"ISingleton",a:e}),Uu=(e)=>Mw(e)?e:gc(Pe(e)),sh=(e,t,n)=>{switch(e.backing._tag){case"IArray":{zN(e.backing.array,0,t,n,e.length);break}case"IConcat":{sh(e.left,t,n),sh(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]=La(e,r),r+=1,o+=1;break}}},GN=(e)=>{switch(e.backing._tag){case"IEmpty":return Pw;case"IArray":return e.backing.array;default:{let t=Array(e.length);return sh(e,t,0),e.backing={_tag:"IArray",array:t},e.left=sr,e.right=sr,e.depth=0,t}}},Br,YN=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return lt({_tag:"IArray",array:rh(e.backing.array)});case"IConcat":return lt({_tag:"IConcat",left:Eo(e.backing.right),right:Eo(e.backing.left)});case"ISlice":return gc(rh(Br(e)))}},Eo,gc=(e)=>e.length===0?Sn():e.length===1?ot(e[0]):lt({_tag:"IArray",array:e}),ZN=(e)=>gc(e),La,Nw,It,ch,sn,Fw=(e)=>e.length===0,$n=(e)=>e.length>0,lh=(e)=>La(e,0),Hn,jn=(e)=>ch(e,1);var cr=x(()=>{Ve();fe();ec();W();Le();Be();Re();we();Iw=Symbol.for("effect/Chunk");Pw=[],KN=WN(P),JN={[Iw]:{_A:(e)=>e},toString(){return Se(this.toJSON())},toJSON(){return{_id:"Chunk",values:Br(this).map(me)}},[ie](){return this.toJSON()},[D](e){return Mw(e)&&KN(this,e)},[q](){return le(this,on(Br(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return Pw[Symbol.iterator]();default:return Br(this)[Symbol.iterator]()}},pipe(){return k(this,arguments)}},sr=lt({_tag:"IEmpty"}),Br=GN,Eo=YN,La=d(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?La(e.left,t):La(e.right,t-e.left.length);case"ISlice":return La(e.backing.chunk,t+e.backing.offset)}}),Nw=d(2,(e,t)=>sn(e,ot(t))),It=d(2,(e,t)=>sn(ot(t),e)),ch=d(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return sr;else switch(e.backing._tag){case"ISlice":return lt({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return ch(e.right,t-e.left.length);return lt({_tag:"IConcat",left:ch(e.left,t),right:e.right})}default:return lt({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),sn=d(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 lt({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=sn(e.right,t);return lt({_tag:"IConcat",left:e.left,right:r})}else{let r=sn(e.right.right,t);if(r.depth===e.depth-3){let o=lt({_tag:"IConcat",left:e.right.left,right:r});return lt({_tag:"IConcat",left:e.left,right:o})}else{let o=lt({_tag:"IConcat",left:e.left,right:e.right.left});return lt({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=sn(e,t.left);return lt({_tag:"IConcat",left:r,right:t.right})}else{let r=sn(e,t.left.left);if(r.depth===t.depth-3){let o=lt({_tag:"IConcat",left:r,right:t.left.right});return lt({_tag:"IConcat",left:o,right:t.right})}else{let o=lt({_tag:"IConcat",left:t.left.right,right:t.right});return lt({_tag:"IConcat",left:r,right:o})}}}),Hn=lh});var Ro=5,uh,Lw,Dw,qw;var $u=x(()=>{uh=Math.pow(2,5),Lw=uh-1,Dw=uh/2,qw=uh/4});function XN(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 Oo(e,t){return t>>>e&Lw}function Co(e){return 1<<e}function Hu(e,t){return XN(e&t-1)}var ph=x(()=>{$u()});var Uw=(e,t)=>({value:e,previous:t});function wi(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 dh(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 $w(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 zr{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(F());if(De(a))return new zr;return++i.value,new vi(e,r,o,a)}}function bn(e){return rc(e,"EmptyNode")}function e0(e){return bn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function ju(e,t){return bn(e)?!1:t===e.edit}class vi{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(P(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(De(s))return--i.value,new zr;if(ju(this,e))return this.value=s,this;return new vi(e,r,o,s)}let a=n(F());if(De(a))return this;return++i.value,Hw(e,t,this.hash,this,r,new vi(e,r,o,a))}}class fh{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=ju(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 fh(e,this.hash,c):c[0]}let a=n(F());if(De(a))return this;return++i.value,Hw(e,t,this.hash,this,r,new vi(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&&P(i,u.key)){let p=u.value,f=o(p);if(f===p)return r;if(De(f))return--a.value,dh(e,l,r);return wi(e,l,new vi(t,n,i,f),r)}}let c=o(F());if(De(c))return r;return++a.value,wi(e,s,new vi(t,n,i,c),r)}}class Da{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=Oo(t,r),l=Co(c),u=Hu(a,l),p=a&l,f=ju(this,e);if(!p){let v=new zr().modify(e,t+Ro,n,r,o,i);if(!v)return this;return s.length>=Dw?n0(e,c,v,a,s):new Da(e,a|l,$w(f,u,v,s))}let h=s[u],m=h.modify(e,t+Ro,n,r,o,i);if(h===m)return this;let S=a,E;if(bn(m)){if(S&=~l,!S)return new zr;if(s.length<=2&&e0(s[u^1]))return s[u^1];E=dh(f,u,s)}else E=wi(f,u,m,s);if(f)return this.mask=S,this.children=E,this;return new Da(e,S,E)}}class mh{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=Oo(t,r),l=s[c],u=(l||new zr).modify(e,t+Ro,n,r,o,i);if(l===u)return this;let p=ju(this,e),f;if(bn(l)&&!bn(u))++a,f=wi(p,c,u,s);else if(!bn(l)&&bn(u)){if(--a,a<=qw)return t0(e,a,c,s);f=wi(p,c,new zr,s)}else f=wi(p,c,u,s);if(p)return this.size=a,this.children=f,this;return new mh(e,a,f)}}function t0(e,t,n,r){let o=Array(t-1),i=0,a=0;for(let s=0,c=r.length;s<c;++s)if(s!==n){let l=r[s];if(l&&!bn(l))o[i++]=l,a|=1<<s}return new Da(e,a,o)}function n0(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 mh(e,s+1,i)}function r0(e,t,n,r,o,i){if(n===o)return new fh(e,n,[i,r]);let a=Oo(t,n),s=Oo(t,o);if(a===s)return(c)=>new Da(e,Co(a)|Co(s),[c]);else{let c=a<s?[r,i]:[i,r];return new Da(e,Co(a)|Co(s),c)}}function Hw(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=r0(e,s,n,r,o,i);if(typeof c==="function")a=Uw(c,a),s=s+Ro;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var jw=x(()=>{fe();Ge();we();ph();$u()});var Bw="effect/HashMap",Bu,i0,hh=(e,t,n,r)=>{let o=Object.create(i0);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},zu,Vu=(e)=>e?zw(e[0],e[1],e[2],e[3],e[4]):F(),Vw=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if(Ie(e.value))return B({value:t(e.key,e.value.value),cont:n});return Vu(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return zw(r.length,r,0,t,n)}default:return Vu(n)}},zw=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!bn(i))return Vw(i,r,[e,t,n,r,o])}return Vu(o)},a0,qa=()=>a0,Ww=(e)=>{let t=Ju(qa());for(let n of e)Ti(t,n[0],n[1]);return Yw(t)},Kw=(e)=>N(e,Bu),Jw=(e)=>e&&bn(e._root),Gw,Wu,gh,Ti,s0,Ku=(e)=>new zu(e,(t)=>t),yc=(e)=>e._size,Ju=(e)=>hh(!0,e._edit+1,e._root,e._size),Yw=(e)=>(e._editable=!1,e),Gu,Zw,Yu,Xw,yh,Ua;var xh=x(()=>{fe();W();W();Le();Be();Ge();Re();we();ph();$u();jw();Bu=Symbol.for(Bw),i0={[Bu]:Bu,[Symbol.iterator](){return new zu(this,(e,t)=>[e,t])},[q](){let e=I(Bw);for(let t of this)e^=y(I(t[0]),te(I(t[1])));return le(this,e)},[D](e){if(Kw(e)){if(e._size!==this._size)return!1;for(let t of this){let n=y(e,Wu(t[0],I(t[0])));if(De(n))return!1;else if(!P(t[1],n.value))return!1}return!0}return!1},toString(){return Se(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(me)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}};zu=class zu{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=Vw(this.map._root,this.f,void 0)}next(){if(De(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=Vu(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new zu(this.map,this.f)}};a0=hh(!1,0,new zr,0),Gw=d(2,(e,t)=>Wu(e,t,I(t))),Wu=d(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return P(t,r.key)?r.value:F();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&&P(t,c.key))return c.value}}return F()}case"IndexedNode":{let i=Oo(o,n),a=Co(i);if(r.mask&a){r=r.children[Hu(r.mask,a)],o+=Ro;break}return F()}case"ArrayNode":{if(r=r.children[Oo(o,n)],r){o+=Ro;break}return F()}default:return F()}}),gh=d(2,(e,t)=>Ie(Wu(e,t,I(t)))),Ti=d(3,(e,t,n)=>Gu(e,t,()=>B(n))),s0=d(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:hh(e._editable,e._edit,t,n)}),Gu=d(3,(e,t,n)=>Zw(e,t,I(t),n)),Zw=d(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 y(e,s0(i,o.value))}),Yu=d(2,(e,t)=>Gu(e,t,F)),Xw=d(2,(e,t)=>Ua(e,qa(),(n,r,o)=>Ti(n,o,t(r,o)))),yh=d(2,(e,t)=>Ua(e,void 0,(n,r,o)=>t(r,o))),Ua=d(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return Ie(r.value)?n(t,r.value.value,r.key):t;if(r._tag==="EmptyNode")return t;let o=[r.children],i;while(i=o.pop())for(let a=0,s=i.length;a<s;){let c=i[a++];if(c&&!bn(c))if(c._tag==="LeafNode"){if(Ie(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var ev="effect/HashSet",Zu,c0,Xu=(e)=>{let t=Object.create(c0);return t._keyMap=e,t},tv=(e)=>N(e,Zu),l0,xc=()=>l0,nv=(e)=>{let t=Qu(xc());for(let n of e)$a(t,n);return ep(t)},rv=(...e)=>{let t=Qu(xc());for(let n of e)$a(t,n);return ep(t)},ov,iv=(e)=>yc(e._keyMap),Qu=(e)=>Xu(Ju(e._keyMap)),ep=(e)=>(e._keyMap._editable=!1,e),Sh,$a,bh,av,sv,cv,lv;var uv=x(()=>{fe();W();Le();Be();Re();we();xh();Zu=Symbol.for(ev),c0={[Zu]:Zu,[Symbol.iterator](){return Ku(this._keyMap)},[q](){return le(this,te(I(this._keyMap))(I(ev)))},[D](e){if(tv(e))return yc(this._keyMap)===yc(e._keyMap)&&P(this._keyMap,e._keyMap);return!1},toString(){return Se(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(me)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}},l0=Xu(qa()),ov=d(2,(e,t)=>gh(e._keyMap,t)),Sh=d(2,(e,t)=>{let n=Qu(e);return t(n),ep(n)}),$a=d(2,(e,t)=>e._keyMap._editable?(Ti(t,!0)(e._keyMap),e):Xu(Ti(t,!0)(e._keyMap))),bh=d(2,(e,t)=>e._keyMap._editable?(Yu(t)(e._keyMap),e):Xu(Yu(t)(e._keyMap))),av=d(2,(e,t)=>Sh(e,(n)=>{for(let r of t)bh(n,r)})),sv=d(2,(e,t)=>Sh(xc(),(n)=>{cv(e,(r)=>$a(n,r));for(let r of t)$a(n,r)})),cv=d(2,(e,t)=>yh(e._keyMap,(n,r)=>t(r))),lv=d(3,(e,t,n)=>Ua(e._keyMap,t,(r,o,i)=>n(r,i)))});var lr,pv,Ei,dv,Sc,Ri,_h,wh,Wr,Oi;var Ci=x(()=>{uv();lr=xc,pv=nv,Ei=rv,dv=ov,Sc=iv,Ri=$a,_h=bh,wh=av,Wr=sv,Oi=lv});var ja="Die",ko="Empty",Ao="Fail",ki="Interrupt",Ai="Parallel",Ii="Sequential";var hv="effect/Cause",Eh,d0,Ba,Kr,Va=(e)=>{let t=Object.create(Ba);return t._tag=Ao,t.error=e,t},cn=(e)=>{let t=Object.create(Ba);return t._tag=ja,t.defect=e,t},Bn=(e)=>{let t=Object.create(Ba);return t._tag=ki,t.fiberId=e,t},Ni=(e,t)=>{let n=Object.create(Ba);return n._tag=Ai,n.left=e,n.right=t,n},Pt=(e,t)=>{let n=Object.create(Ba);return n._tag=Ii,n.left=e,n.right=t,n},gv=(e)=>N(e,Eh),Rh=(e)=>e._tag===ko,yv=(e)=>e._tag===Ao,tp=(e)=>{if(e._tag===ko)return!0;return Pi(e,!0,(t,n)=>{switch(n._tag){case ko:return B(t);case ja:case Ao:case ki:return B(!1);default:return F()}})},np=(e)=>Ie(xv(e)),za=(e)=>ip(void 0,g0)(e),Oh=(e)=>Eo(Pi(e,Sn(),(t,n)=>n._tag===Ao?B(y(t,It(n.error))):F())),Ch=(e)=>Eo(Pi(e,Sn(),(t,n)=>n._tag===ja?B(y(t,It(n.defect))):F())),kh=(e)=>Pi(e,lr(),(t,n)=>n._tag===ki?B(y(t,Ri(n.fiberId))):F()),Ah=(e)=>Ih(e,(t)=>t._tag===Ao?B(t.error):F()),rp=(e)=>{let t=Ah(e);switch(t._tag){case"None":return re(e);case"Some":return Q(t.value)}},xv=(e)=>Ih(e,(t)=>t._tag===ki?B(t.fiberId):F()),op=(e)=>Ph(e,{onEmpty:Kr,onFail:()=>Kr,onDie:cn,onInterrupt:Bn,onSequential:Pt,onParallel:Ni}),Sv=(e)=>Ph(e,{onEmpty:Kr,onFail:cn,onDie:cn,onInterrupt:Bn,onSequential:Pt,onParallel:Ni}),f0=(e,t)=>{let n=ot(e),r=ot(t);while($n(n)&&$n(r)){let[o,i]=y(Hn(n),Pi([lr(),Sn()],([c,l],u)=>{let[p,f]=vh(u);return B([y(c,Wr(p)),y(l,sn(f))])})),[a,s]=y(Hn(r),Pi([lr(),Sn()],([c,l],u)=>{let[p,f]=vh(u);return B([y(c,Wr(p)),y(l,sn(f))])}));if(!P(o,a))return!1;n=i,r=s}return!0},m0=(e)=>h0(ot(e),Sn()),h0=(e,t)=>{while(!0){let[n,r]=y(e,Fa([lr(),Sn()],([i,a],s)=>{let[c,l]=vh(s);return[y(i,Wr(c)),y(a,sn(l))]})),o=Sc(n)>0?y(t,It(n)):t;if(Fw(r))return Eo(o);e=r,t=o}throw Error(hi("Cause.flattenCauseLoop"))},Ih,vh=(e)=>{let t=e,n=[],r=lr(),o=Sn();while(t!==void 0)switch(t._tag){case ko:{if(n.length===0)return[r,o];t=n.pop();break}case Ao:{if(r=Ri(r,hc(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case ja:{if(r=Ri(r,hc(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case ki:{if(r=Ri(r,hc(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case Ii:{switch(t.left._tag){case ko:{t=t.right;break}case Ii:{t=Pt(t.left.left,Pt(t.left.right,t.right));break}case Ai:{t=Ni(Pt(t.left.left,t.right),Pt(t.left.right,t.right));break}default:{o=It(o,t.right),t=t.left;break}}break}case Ai:{n.push(t.right),t=t.left;break}}throw Error(hi("Cause.evaluateCauseLoop"))},g0,fv="SequentialCase",mv="ParallelCase",Ph,Pi,ip,Vn=(e,t)=>{if(za(e))return"All fibers interrupted without errors.";return bc(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
10
  ${bv(n.cause," ")}
11
11
  }`}).join(`
12
12
  `)},bv=(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
15
  ${bv(e.cause,`${t} `)}
16
- ${t}}`;return r},Eh=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(g0(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:Eh(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(Pi in e)r.span=e[Pi];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=S0(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},g0=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(N(e,"toString")&&yo(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return ku(e)},y0,x0,S0=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
16
+ ${t}}`;return r},Th=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(y0(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:Th(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(Mi in e)r.span=e[Mi];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=b0(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},y0=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(N(e,"toString")&&xo(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return ku(e)},x0,S0,b0=(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=x0.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(y0),u=!1;for(let[,p]of l)u=!0,r.push(` at ${i.name} (${p})`);if(!u)r.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else r.push(` at ${i.name}`)}else r.push(` at ${i.name}`);i=Zt(i.parent),a++}}return r.join(`
19
- `)},Pi,bc=(e)=>ip(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[Eh(n)],failCase:(t,n)=>[Eh(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Wa=x(()=>{Ve();cr();an();fe();z();Le();Ri();Be();Ge();Oe();we();Oh=Symbol.for(hv),p0={_E:(e)=>e},Va={[Oh]:p0,[D](){return y(I(hv),Q(I(f0(this))),le(this))},[L](e){return gv(e)&&d0(this,e)},pipe(){return k(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:me(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:me(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:me(this.left),right:me(this.right)}}},toString(){return Vn(this)},[ie](){return this.toJSON()}},Kr=(()=>{let e=Object.create(Va);return e._tag=Co,e})(),Ph=d(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 Ai:case ki:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return F()}),h0={emptyCase:Ys,failCase:ho,dieCase:ho,interruptCase:Ys,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},Mh=d(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>ip(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)})),Ii=d(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=Ie(a)?a.value:r,o._tag){case Ai:{i.push(o.right),o=o.left;break}case ki:{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}),ip=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case Co:{o.push(ne(n.emptyCase(t)));break}case ko:{o.push(ne(n.failCase(t,a.error)));break}case Ba:{o.push(ne(n.dieCase(t,a.defect)));break}case Ci:{o.push(ne(n.interruptCase(t,a.fiberId)));break}case Ai:{r.push(a.right),r.push(a.left),o.push(X({_tag:fv}));break}case ki:{r.push(a.right),r.push(a.left),o.push(X({_tag:mv}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case fv:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case mv:{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()}),y0=/\((.*)\)/g,x0=K("effect/Tracer/spanToTrace",()=>new WeakMap),Pi=Symbol.for("effect/SpanAnnotation")});var _v,wc,b0="effect/STM",_0,wv,w0,vv=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(wv);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},Tv=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,w0),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},Fh,v0,Ao=(e)=>{let t=Object.create(v0);return t.unsafeMap=e,t},T0=(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=S0.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(x0),u=!1;for(let[,p]of l)u=!0,r.push(` at ${i.name} (${p})`);if(!u)r.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else r.push(` at ${i.name}`)}else r.push(` at ${i.name}`);i=Zt(i.parent),a++}}return r.join(`
19
+ `)},Mi,bc=(e)=>ip(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[Th(n)],failCase:(t,n)=>[Th(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Wa=x(()=>{Ve();cr();an();fe();W();Le();Ci();Be();Ge();Re();we();Eh=Symbol.for(hv),d0={_E:(e)=>e},Ba={[Eh]:d0,[q](){return y(I(hv),te(I(m0(this))),le(this))},[D](e){return gv(e)&&f0(this,e)},pipe(){return k(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:me(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:me(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:me(this.left),right:me(this.right)}}},toString(){return Vn(this)},[ie](){return this.toJSON()}},Kr=(()=>{let e=Object.create(Ba);return e._tag=ko,e})(),Ih=d(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 Ii:case Ai:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return F()}),g0={emptyCase:Ys,failCase:go,dieCase:go,interruptCase:Ys,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},Ph=d(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>ip(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)})),Pi=d(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=Ie(a)?a.value:r,o._tag){case Ii:{i.push(o.right),o=o.left;break}case Ai:{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}),ip=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case ko:{o.push(re(n.emptyCase(t)));break}case Ao:{o.push(re(n.failCase(t,a.error)));break}case ja:{o.push(re(n.dieCase(t,a.defect)));break}case ki:{o.push(re(n.interruptCase(t,a.fiberId)));break}case Ii:{r.push(a.right),r.push(a.left),o.push(Q({_tag:fv}));break}case Ai:{r.push(a.right),r.push(a.left),o.push(Q({_tag:mv}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case fv:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case mv:{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()}),x0=/\((.*)\)/g,S0=K("effect/Tracer/spanToTrace",()=>new WeakMap),Mi=Symbol.for("effect/SpanAnnotation")});var _v,wc,_0="effect/STM",w0,wv,v0,vv=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(wv);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},Tv=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,v0),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},Nh,T0,Io=(e)=>{let t=Object.create(T0);return t.unsafeMap=e,t},E0=(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},Ev=(e)=>N(e,Fh),Ov=(e)=>N(e,wc),E0,Rv=()=>E0,Lh=(e,t)=>Ao(new Map([[e.key,t]])),Cv,Nh,Dh=(e)=>{if(Nh.has(e.key))return Nh.get(e.key);let t=e.defaultValue();return Nh.set(e.key,t),t},kv=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Dh(t),qh,Av,Iv,Pv;var ap=x(()=>{fe();z();Le();Be();Oe();we();Lr();Bm();_v=Symbol.for("effect/Context/Tag"),wc=Symbol.for("effect/Context/Reference"),_0=Symbol.for(b0),wv={...Fr,_op:"Tag",[_0]:So,[_v]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return Se(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[ie](){return this.toJSON()},of(e){return e},context(e){return Lh(this,e)}},w0={...wv,[wc]:wc},Fh=Symbol.for("effect/Context"),v0={[Fh]:{_Services:(e)=>e},[L](e){if(Ev(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!P(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[D](){return le(this,Ou(this.unsafeMap.size))},pipe(){return k(this,arguments)},toString(){return Se(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(me)}},[ie](){return this.toJSON()}},E0=Ao(new Map),Cv=d(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),Ao(r)}),Nh=K("effect/Context/defaultValueCache",()=>new Map),qh=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(wc in t)return Dh(t);throw T0(t)}return e.unsafeMap.get(t.key)}),Av=qh,Iv=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return Ov(t)?dc(Dh(t)):Pu;return dc(e.unsafeMap.get(t.key))}),Pv=d(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return Ao(n)})});var Xt,Io,Nv,ur,vc,Tc,Po,Ec,Oc;var _n=x(()=>{ap();Xt=vv,Io=Rv,Nv=Lh,ur=Cv,vc=Av,Tc=qh,Po=Iv,Ec=Pv,Oc=Tv});var $h,Uv,Fv,sp,Hh,Lv,Dv,O0,Wr=(e)=>{if($v(e))return e;else if(rn(e))return cp(e);else if(go(e))return Uh(e);else if(Array.isArray(e)&&e.length===2&&e.every(rn)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return jh;if(e[0]===1/0||e[1]===1/0)return A0;return Uh(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(wt(e)){let t=O0.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return Uh(BigInt(r));case"micro":case"micros":return I0(BigInt(r));case"milli":case"millis":return cp(i);case"second":case"seconds":return P0(i);case"minute":case"minutes":return M0(i);case"hour":case"hours":return N0(i);case"day":case"days":return F0(i);case"week":case"weeks":return L0(i)}}}throw Error("Invalid DurationInput")},qv,R0,C0,pr=(e)=>{let t=Object.create(C0);if(rn(e))if(isNaN(e)||e<=0)t.value=qv;else if(!Number.isFinite(e))t.value=R0;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<=Uv)t.value=qv;else t.value={_tag:"Nanos",nanos:e};return t},$v=(e)=>N(e,$h),k0=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Uv;case"Infinity":return!1}},jh,A0,Uh=(e)=>pr(e),I0=(e)=>pr(e*Hh),cp=(e)=>pr(e),P0=(e)=>pr(e*1000),M0=(e)=>pr(e*60000),N0=(e)=>pr(e*3600000),F0=(e)=>pr(e*86400000),L0=(e)=>pr(e*604800000),lp=(e)=>U0(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),D0=(e)=>{let t=Wr(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))}},q0=(e)=>{let t=Wr(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/Dv),Number(t.value.nanos%Dv)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},U0,Bh,$0=(e,t)=>Bh(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),Hv,jv,H0,j0=(e)=>{let t=Wr(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=D0(t),r=n/Lv,o=r/Hh,i=o/sp,a=i/sp,s=a/Fv;return{days:Number(s),hours:Number(a%Fv),minutes:Number(i%sp),seconds:Number(o%sp),millis:Number(r%Hh),nanos:Number(n%Lv)}},B0=(e)=>{let t=Wr(e);if(t.value._tag==="Infinity")return"Infinity";if(k0(t))return"0";let n=j0(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 Vh=x(()=>{fe();z();Le();Be();Oe();we();$h=Symbol.for("effect/Duration"),Uv=BigInt(0),Fv=BigInt(24),sp=BigInt(60),Hh=BigInt(1000),Lv=BigInt(1e6),Dv=BigInt(1e9),O0=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,qv={_tag:"Millis",millis:0},R0={_tag:"Infinity"},C0={[$h]:$h,[D](){return le(this,Ru(this.value))},[L](e){return $v(e)&&H0(this,e)},toString(){return`Duration(${B0(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:q0(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}},jh=pr(0),A0=pr(1/0),U0=d(2,(e,t)=>{let n=Wr(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)}}),Bh=d(3,(e,t,n)=>{let r=Wr(e),o=Wr(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(lp(r),lp(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)}),Hv=d(2,(e,t)=>Bh(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),jv=d(2,(e,t)=>Bh(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),H0=d(2,(e,t)=>$0(Wr(e),Wr(t)))});var Vv,V0,up=(e)=>{let t=Object.create(V0);return t.current=e,t},Ja=(e)=>e.current,pp;var zh=x(()=>{z();Be();Oe();Vv=Symbol.for("effect/MutableRef"),V0={[Vv]:Vv,toString(){return Se(this.toJSON())},toJSON(){return{_id:"MutableRef",current:me(this.current)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}},pp=d(2,(e,t)=>(e.current=t,e))});var Wh="effect/FiberId",Ga,dp="None",Kh="Runtime",z0="Composite",K0,Wv,Jv,Gv,Jh=(e)=>N(e,Ga),fp=(e)=>{switch(e._tag){case dp:return lr();case Kh:return Ti(e.id);case z0:return y(fp(e.left),zr(fp(e.right)))}},Kv,mp=(e)=>Array.from(fp(e)).map((n)=>`#${n}`).join(","),Yv=()=>{let e=Ja(Kv);return y(Kv,pp(e+1)),new Jv(e,Date.now())};var Gh=x(()=>{fe();z();Le();Ri();Be();zh();we();Ga=Symbol.for(Wh),K0=xe(`${Wh}-${dp}`);Wv=class Wv{[Ga]=Ga;_tag=dp;id=-1;startTimeMillis=-1;[D](){return K0}[L](e){return Jh(e)&&e._tag===dp}toString(){return Se(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[ie](){return this.toJSON()}};Jv=class Jv{id;startTimeMillis;[Ga]=Ga;_tag=Kh;constructor(e,t){this.id=e,this.startTimeMillis=t}[D](){return le(this,xe(`${Wh}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[L](e){return Jh(e)&&e._tag===Kh&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Se(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[ie](){return this.toJSON()}};Gv=new Wv,Kv=K(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>up(0))});var wn,Xv,hp;var Ya=x(()=>{Gh();wn=Gv,Xv=mp,hp=Yv});var Za,Qv,eT,Yh,Zh,Xh,tT,nT,Qh;var gp=x(()=>{Sh();Za=Ua,Qv=Kw,eT=Jw,Yh=Gw,Zh=vi,Xh=Wu,tT=Gu,nT=Xw,Qh=$a});var Cc,tg=(e)=>Pe(e),W0=(e)=>km(vo(e),tg),J0,G0,yp=(e,t)=>{let n=Object.create(G0);return n.head=e,n.tail=t,n},Y0,Z0,rT,oT=(e)=>N(e,Cc),dr=(e)=>e._tag==="Nil",ng=(e)=>e._tag==="Cons",X0=()=>rT,Jr=(e,t)=>yp(e,t),Mo,kc=(e)=>yp(e,rT),iT,Q0,eF,aT,sT=(e)=>{let t=Mo(),n=e;while(!dr(n))t=Q0(t,n.head),n=n.tail;return t};var xp=x(()=>{Ve();fe();ec();z();Le();Be();Oe();we();Cc=Symbol.for("effect/List"),J0=W0(P),G0={[Cc]:Cc,_tag:"Cons",toString(){return Se(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:tg(this).map(me)}},[ie](){return this.toJSON()},[L](e){return oT(e)&&this._tag===e._tag&&J0(this,e)},[D](){return le(this,on(tg(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 k(this,arguments)}},Y0=xe("Nil"),Z0={[Cc]:Cc,_tag:"Nil",toString(){return Se(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[ie](){return this.toJSON()},[D](){return Y0},[L](e){return oT(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return k(this,arguments)}},rT=Object.create(Z0),Mo=X0,iT=d(2,(e,t)=>eF(t,e)),Q0=d(2,(e,t)=>Jr(t,e)),eF=d(2,(e,t)=>{if(dr(e))return t;else if(dr(t))return e;else{let n=yp(t.head,e),r=n,o=t.tail;while(!dr(o)){let i=yp(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),aT=d(3,(e,t,n)=>{let r=t,o=e;while(!dr(o))r=n(r,o.head),o=o.tail;return r})});var VK,Xa;var Sp=x(()=>{fe();Le();Lr();VK=Object.assign(Object.create(Array.prototype),{[D](){return le(this,on(this))},[L](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>P(t,e[n]));else return!1}}),Xa=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=pc,e}()});function cT(e){return e}var nF,Ic,rF,oF,og=()=>oF,iF,aF=(e,t)=>{let n=Object.create(iF);return n.first=e,n.second=t,n},sF,cF=(e,t)=>{let n=Object.create(sF);return n.key=e,n.service=t,n},lF,uF=(e)=>{let t=Object.create(lF);return t.key=e,t},pF,dF=(e,t)=>{let n=Object.create(pF);return n.key=e,n.update=t,n},lT=(e,t)=>{let n=new Map(e.unsafeMap),r=og();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!P(a,i))r=Ac(dF(o,()=>i))(r)}else n.delete(o),r=Ac(cF(o,i))(r);for(let[o]of n.entries())r=Ac(uF(o))(r);return r},Ac,uT;var pT=x(()=>{cr();fe();z();ap();Sp();nF=Symbol.for("effect/DifferContextPatch");Ic={...Xa.prototype,[nF]:{_Value:cT,_Patch:cT}},rF=Object.assign(Object.create(Ic),{_tag:"Empty"}),oF=Object.create(rF),iF=Object.assign(Object.create(Ic),{_tag:"AndThen"}),sF=Object.assign(Object.create(Ic),{_tag:"AddService"}),lF=Object.assign(Object.create(Ic),{_tag:"RemoveService"}),pF=Object.assign(Object.create(Ic),{_tag:"UpdateService"}),Ac=d(2,(e,t)=>aF(e,t)),uT=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=ot(e),o=new Map(t.unsafeMap);while($n(r)){let a=Hn(r),s=jn(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=It(It(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 Ao(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 Ao(i)})});function ig(e){return e}var mF,_p,hF,gF,ag=()=>gF,yF,xF=(e,t)=>{let n=Object.create(yF);return n.first=e,n.second=t,n},SF,bF=(e)=>{let t=Object.create(SF);return t.value=e,t},_F,wF=(e)=>{let t=Object.create(_F);return t.value=e,t},dT=(e,t)=>{let[n,r]=Oi([e,ag()],([o,i],a)=>{if(dv(a)(o))return[wh(a)(o),i];return[o,bp(bF(a))(i)]})(t);return Oi(r,(o,i)=>bp(wF(i))(o))(n)},bp,fT;var mT=x(()=>{cr();z();Ri();Sp();mF=Symbol.for("effect/DifferHashSetPatch");_p={...Xa.prototype,[mF]:{_Value:ig,_Key:ig,_Patch:ig}},hF=Object.assign(Object.create(_p),{_tag:"Empty"}),gF=Object.create(hF),yF=Object.assign(Object.create(_p),{_tag:"AndThen"}),SF=Object.assign(Object.create(_p),{_tag:"Add"}),_F=Object.assign(Object.create(_p),{_tag:"Remove"}),bp=d(2,(e,t)=>xF(e,t)),fT=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=ot(e);while($n(r)){let o=Hn(r),i=jn(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=It(o.first)(It(o.second)(i));break}case"Add":{n=Ei(o.value)(n),r=i;break}case"Remove":n=wh(o.value)(n),r=i}}return n})});function hT(e){return e}var TF,Mc,EF,OF,sg=()=>OF,RF,CF=(e,t)=>{let n=Object.create(RF);return n.first=e,n.second=t,n},kF,AF=(e)=>{let t=Object.create(kF);return t.values=e,t},IF,PF=(e,t)=>{let n=Object.create(IF);return n.from=e,n.until=t,n},MF,NF=(e,t)=>{let n=Object.create(MF);return n.index=e,n.patch=t,n},gT=(e)=>{let t=0,n=sg();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(!P(i,e.differ.empty))n=Pc(n,NF(t,i));t=t+1}if(t<e.oldValue.length)n=Pc(n,PF(0,t));if(t<e.newValue.length)n=Pc(n,AF(Rw(t)(e.newValue)));return n},Pc,yT;var xT=x(()=>{Ve();fe();z();Sp();TF=Symbol.for("effect/DifferReadonlyArrayPatch");Mc={...Xa.prototype,[TF]:{_Value:hT,_Patch:hT}},EF=Object.assign(Object.create(Mc),{_tag:"Empty"}),OF=Object.create(EF),RF=Object.assign(Object.create(Mc),{_tag:"AndThen"}),kF=Object.assign(Object.create(Mc),{_tag:"Append"}),IF=Object.assign(Object.create(Mc),{_tag:"Slice"}),MF=Object.assign(Object.create(Mc),{_tag:"Update"}),Pc=d(2,(e,t)=>CF(e,t)),yT=d(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=At(e);while(_o(o)){let i=rt(o),a=qn(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 ST,LF,No=(e)=>{let t=Object.create(LF);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},cg=()=>No({empty:og(),combine:(e,t)=>Ac(t)(e),diff:(e,t)=>lT(e,t),patch:(e,t)=>uT(t)(e)}),lg=()=>No({empty:ag(),combine:(e,t)=>bp(t)(e),diff:(e,t)=>dT(e,t),patch:(e,t)=>fT(t)(e)}),ug=(e)=>No({empty:sg(),combine:(t,n)=>Pc(t,n),diff:(t,n)=>gT({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>yT(t,n,e)}),wp=()=>bT((e,t)=>t),bT=(e)=>No({empty:de,combine:(t,n)=>{if(t===de)return n;if(n===de)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(P(t,n))return de;return Gs(n)},patch:(t,n)=>e(n,t(n))});var vp=x(()=>{fe();z();Oe();pT();mT();xT();ST=Symbol.for("effect/Differ"),LF={[ST]:{_P:de,_V:de},pipe(){return k(this,arguments)}}});var Nc=255,_T=8,Tp=(e)=>e&Nc,Ep=(e)=>e>>_T&Nc,Ni=(e,t)=>(e&Nc)+((t&e&Nc)<<_T),dg,wT=(e)=>Ni(e,e),vT=(e)=>Ni(e,0),TT,fg,ET=(e)=>~e>>>0&Nc;var mg=x(()=>{z();dg=Ni(0,0),TT=d(2,(e,t)=>Ni(Tp(e)&~t,Ep(e))),fg=d(2,(e,t)=>e|t)});var DF=0,Gr=1,RT=2,hg=4,Op=16,gg=32,CT=(e)=>Rp(e,gg),yg,Yr=(e)=>xg(e)&&!qF(e),xg=(e)=>Rp(e,Gr),Rp,Sg=(...e)=>e.reduce((t,n)=>t|n,0),kT,bg=(e)=>Rp(e,hg),qF=(e)=>Rp(e,Op),Fc,Lc,_g;var Dc=x(()=>{z();vp();mg();yg=d(2,(e,t)=>e|t),Rp=d(2,(e,t)=>(e&t)!==0),kT=Sg(DF),Fc=d(2,(e,t)=>Ni(e^t,t)),Lc=d(2,(e,t)=>e&(ET(Tp(t))|Ep(t))|Tp(t)&Ep(t)),_g=No({empty:dg,diff:(e,t)=>Fc(e,t),combine:(e,t)=>fg(t)(e),patch:(e,t)=>Lc(t,e)})});var AT,vg,Tg;var Eg=x(()=>{mg();AT=wT,vg=vT,Tg=TT});var Rg=(e,t)=>({_tag:"Par",left:e,right:t}),Cp=(e,t)=>({_tag:"Seq",left:e,right:t}),PT=(e)=>{let t=kc(e),n=Mo();while(!0){let[r,o]=aT(t,[MT(),Mo()],([i,a],s)=>{let[c,l]=UF(s);return[VF(i,c),iT(a,l)]});if(n=$F(n,r),dr(o))return sT(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},UF=(e)=>{let t=e,n=MT(),r=Mo(),o=Mo();while(!0)switch(t._tag){case"Empty":{if(dr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Jr(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=Rg(Cp(s,a),Cp(c,a));break}case"Seq":{let{left:s,right:c}=i;t=Cp(s,Cp(c,a));break}case"Single":{t=i,o=Jr(a,o);break}}break}case"Single":{if(n=BF(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")},$F=(e,t)=>{if(dr(e))return kc(Og(t));if(zF(t))return e;let n=ZF(e.head),r=KF(t);if(n.length===1&&r.length===1&&P(n[0],r[0]))return Jr(YF(e.head,Og(t)),e.tail);return Jr(Og(t),e)},HF,jF,kp,MT=()=>new kp(Za()),BF=(e,t)=>new kp(tT(e.map,t.dataSource,(n)=>mw(Ln(n,Nw(t.blockedRequest)),()=>ot(t.blockedRequest)))),VF=(e,t)=>new kp(Qh(e.map,t.map,(n,r,o)=>Zh(n,o,Je(Yh(n,o),{onNone:()=>r,onSome:(i)=>sn(r,i)})))),zF=(e)=>eT(e.map),KF=(e)=>Array.from(Xh(e.map)),Og=(e)=>GF(nT(e.map,(t)=>ot(t))),WF,JF,Cg,GF=(e)=>new Cg(e),YF=(e,t)=>new Cg(Qh(t.map,e.map,(n,r,o)=>Zh(n,o,Je(Yh(n,o),{onNone:()=>Sn(),onSome:(i)=>sn(i,r)})))),ZF=(e)=>Array.from(Xh(e.map)),NT=(e)=>Array.from(e.map);var FT=x(()=>{cr();fe();gp();xp();Ge();HF=Symbol.for("effect/RequestBlock/RequestBlockParallel"),jF={_R:(e)=>e};kp=class kp{map;[HF]=jF;constructor(e){this.map=e}};WF=Symbol.for("effect/RequestBlock/RequestBlockSequential"),JF={_R:(e)=>e};Cg=class Cg{map;[WF]=JF;constructor(e){this.map=e}}});var Qa="Pending",Ap="Done";var QF="effect/Deferred",DT,qT,UT=(e)=>({_tag:Qa,joiners:e}),$T=(e)=>({_tag:Ap,effect:e});var HT=x(()=>{DT=Symbol.for(QF),qT={_E:(e)=>e,_A:(e)=>e}});var es;var jT=x(()=>{es=class es{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 es(this.self)}}});class Pg{patch;op;_op=lc;constructor(e,t){this.patch=e,this.op=t}}var Mp=(e,t)=>{let n=new gt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},Ig=(e)=>{let t=new gt("RunBlocked");return t.effect_instruction_i0=e,t},Fo,gt,Mg,Ng,ts=(e)=>N(e,Fo),Tt=(e)=>{let t=new gt(Iu);return t.effect_instruction_i0=e,t},ZT,Zr,Xr=(e)=>Zr(e,void 0),Fg=function(){let e=new gt(xi);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(mi("you're not supposed to end up here"))}return e},qc=(e,t=wn)=>{let n=new gt(yi),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,jc(n,(o)=>ts(r)?r:it)},XT=(e,t=wn)=>Me(()=>qc(e,t)),Lo=(e,t=wn)=>Fg(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 gt(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=vt(()=>this.effect_instruction_i0(o,s.signal));else a=vt(()=>this.effect_instruction_i0(o));return a||s?jc(i,(c)=>{if(s)s.abort();return a??it}):i}),Uc,BT,Np=(e,t)=>{if(Ie(t))return new Proxy(e,{has(n,r){return r===Pi||r===BT||r in n},get(n,r){if(r===Pi)return t.value;if(r===BT)return e;return n[r]}});return e},Fp=(e)=>Bt(e)&&!(Pi in e)?Tt((t)=>Mt(cn(Np(e,Zp(t))))):Mt(cn(e)),Lg=(e)=>QT(()=>cn(new cL(e))),Fi=(e)=>ns(e,{onFailure:(t)=>he(X(t)),onSuccess:(t)=>he(ne(t))}),Do=(e)=>eE(e,{onFailure:Ce,onSuccess:Fe}),yt=(e)=>Bt(e)&&!(Pi in e)?Tt((t)=>Mt(za(Np(e,Zp(t))))):Mt(za(e)),Dg=(e)=>W(B(e),yt),Mt=(e)=>{let t=new Mg(Gt);return t.effect_instruction_i0=e,t},QT=(e)=>W(B(e),Mt),qg,$c=(e)=>Tt((t)=>e(t.id())),W,Ug=(e)=>{let t=new gt("OnStep");return t.effect_instruction_i0=e,t},Hc=(e)=>W(e,de),eE,vn,ns,Tn,Li,Lp=(e)=>{let t=new gt(Si);return t.effect_instruction_i0=AT(Gr),t.effect_instruction_i1=()=>e,t},ze,Dp,Di,rs,jc,he=(e)=>{let t=new Ng(Yt);return t.effect_instruction_i0=e,t},Me=(e)=>{let t=new gt(xi);return t.commit=e,t},B=(e)=>{let t=new gt(Au);return t.effect_instruction_i0=e,t},qp,$g=(e)=>Tt((t)=>{let n=t.getFiberRef(Pp),r=y(n,Ae(()=>t.scope()));return e($o(Pp,H(r)))}),Up=(e)=>{let t=new gt(Si);return t.effect_instruction_i0=vg(Gr),t.effect_instruction_i1=()=>e,t},qo=(e)=>Fg(e,function(){let t=new gt(Si);return t.effect_instruction_i0=vg(Gr),t.effect_instruction_i1=(n)=>xg(n)?vt(()=>this.effect_instruction_i0(Lp)):vt(()=>this.effect_instruction_i0(Up)),t}),it,Hg=(e)=>{let t=new gt(Si);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},Bc=(e)=>{let t=new gt(Ia);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},Vc=(e)=>{let t=new gt(Ma);return typeof e?.priority<"u"?pE(t,e.priority):t},$p,Hp,Uo,zc,tE=(e)=>W(qg,(t)=>y(e,Kc(t))),Kc,nE,rE,oE,jg,Bg,Vg,iE,aE,rL="effect/FiberRef",oL,iL,jp=(e)=>Tt((t)=>Fe(t.getFiberRef(e))),qi,kg,aL,$o,Et=(e,t)=>Ui(e,{differ:wp(),fork:t?.fork??de,join:t?.join}),sE=(e)=>{let t=lg();return Ui(e,{differ:t,fork:t.empty})},sL=(e)=>{let t=ug(wp());return Ui(e,{differ:t,fork:t.empty})},Bp=(e)=>{let t=cg();return Ui(e,{differ:t,fork:t.empty})},Ui=(e,t)=>({...bo,[oL]:iL,initial:e,commit(){return jp(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)}),cE=(e)=>Ui(e,{differ:_g,fork:_g.empty}),$i,os,zg,lE,Kg,uE,pE,dE,fE,mE,hE,Wc,Pp,Jc,Vp,zp,Kp=(e,t)=>e.addFinalizer(()=>Xr(t)),Wg=(e,t)=>e.close(t),is=(e,t)=>e.fork(t),Wp,Hi=(e,t)=>{class n extends Wp{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},VT,cL,Ag,_W,gE=(e)=>N(e,Ag),zT,lL,KT,Gc,WT,wW,JT,vW,GT,TW,YT,uL,as=(e)=>ts(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),Jg=(e)=>e._tag==="Success",yE,Yc=(e)=>yE(e,void 0),ji=(e,t)=>pL(e,t?.parallel?Mi:Pt),Gg=(e)=>Ce(cn(e)),Zc=(e)=>Ce(za(e)),Ce=(e)=>{let t=new Mg(Gt);return t.effect_instruction_i0=e,t},Yg=(e)=>Ce(Bn(e)),Ip,Jp,Fe=(e)=>{let t=new Ng(Yt);return t.effect_instruction_i0=e,t},En,Zg,pL=(e,t)=>{let n=Uu(e);if(!$n(n))return F();return y(jn(n),La(y(Hn(n),Ip(ot)),(r,o)=>y(r,Zg(o,{onSuccess:(i,a)=>y(i,It(a)),onFailure:t}))),Ip(To),Ip((r)=>jr(r)),H)},xE=(e)=>({...bo,[DT]:qT,state:up(UT([])),commit(){return Gp(this)},blockingOn:e}),Gp=(e)=>XT((t)=>{let n=Ja(e.state);switch(n._tag){case Ap:return t(n.effect);case Qa:return n.joiners.push(t),dL(e,t)}},e.blockingOn),Yp=(e,t)=>{let n=Ja(e.state);if(n._tag===Qa){pp(e.state,$T(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},dL=(e,t)=>B(()=>{let n=Ja(e.state);if(n._tag===Qa){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),fL,SE=()=>fL,Bi=(e)=>W(SE(),e),mL,Xg,Zp=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?H(t):F()};var at=x(()=>{Ve();cr();_n();an();fe();Ya();z();Le();gp();Be();xp();zh();Ge();Oe();we();Eg();xo();Wa();HT();vp();Lr();Dc();jT();Fo=Symbol.for("effect/Effect");gt=class gt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Fo]=So;constructor(e){this._op=e}[L](e){return this===e}[D](){return le(this,oc(this))}pipe(){return k(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:me(this.effect_instruction_i0),effect_instruction_i1:me(this.effect_instruction_i1),effect_instruction_i2:me(this.effect_instruction_i2)}}toString(){return Se(this.toJSON())}[ie](){return this.toJSON()}[Symbol.iterator](){return new es(new Mr(this))}};Mg=class Mg{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Fo]=So;constructor(e){this._op=e,this._tag=e}[L](e){return as(e)&&e._op==="Failure"&&P(this.effect_instruction_i0,e.effect_instruction_i0)}[D](){return y(xe(this._tag),Q(I(this.effect_instruction_i0)),le(this))}get cause(){return this.effect_instruction_i0}pipe(){return k(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return Se(this.toJSON())}[ie](){return this.toJSON()}[Symbol.iterator](){return new es(new Mr(this))}};Ng=class Ng{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Fo]=So;constructor(e){this._op=e,this._tag=e}[L](e){return as(e)&&e._op==="Success"&&P(this.effect_instruction_i0,e.effect_instruction_i0)}[D](){return y(xe(this._tag),Q(I(this.effect_instruction_i0)),le(this))}get value(){return this.effect_instruction_i0}pipe(){return k(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:me(this.value)}}toString(){return Se(this.toJSON())}[ie](){return this.toJSON()}[Symbol.iterator](){return new es(new Mr(this))}};ZT=d(3,(e,t,n)=>qo((r)=>W(e,(o)=>W(Do(Me(()=>r(t(o)))),(i)=>Me(()=>n(o,i)).pipe(vn({onFailure:(a)=>{switch(i._tag){case Gt:return Mt(Pt(i.effect_instruction_i0,a));case Yt:return Mt(a)}},onSuccess:()=>i})))))),Zr=d(2,(e,t)=>W(e,()=>he(t))),Uc=d(2,(e,t)=>ns(e,{onFailure:t,onSuccess:he})),BT=Symbol.for("effect/OriginalAnnotation"),qg=Tt((e)=>he(e.id())),W=d(2,(e,t)=>{let n=new gt(ka);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),eE=d(2,(e,t)=>vn(e,{onFailure:(n)=>he(t.onFailure(n)),onSuccess:(n)=>he(t.onSuccess(n))})),vn=d(2,(e,t)=>{let n=new gt(Aa);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),ns=d(2,(e,t)=>vn(e,{onFailure:(n)=>{if(kh(n).length>0)return Mt(Sv(n));let o=Ch(n);if(o.length>0)return t.onFailure(uh(o));return Mt(n)},onSuccess:t.onSuccess})),Tn=d(2,(e,t)=>Me(()=>{let n=Pe(e),r=bi(n.length),o=0;return Zr(Bc({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),Li=d(2,(e,t)=>Me(()=>{let n=Pe(e),r=0;return Bc({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),ze=d(2,(e,t)=>W(e,(n)=>B(()=>t(n)))),Dp=d(2,(e,t)=>ns(e,{onFailure:(n)=>Dg(()=>t.onFailure(n)),onSuccess:(n)=>B(()=>t.onSuccess(n))})),Di=d(2,(e,t)=>vn(e,{onFailure:(n)=>{let r=rp(n);switch(r._tag){case"Left":return Dg(()=>t(r.left));case"Right":return Mt(r.right)}},onSuccess:he})),rs=d(2,(e,t)=>qo((n)=>vn(n(e),{onFailure:(r)=>{let o=Ce(r);return vn(t(o),{onFailure:(i)=>Ce(Pt(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=Fe(r);return Uo(t(o),o)}}))),jc=d(2,(e,t)=>rs(e,Jp({onFailure:(n)=>Ka(n)?Xr(t(Ah(n))):it,onSuccess:()=>it}))),qp=d((e)=>e.length===3||e.length===2&&!(Bt(e[1])&&("onlyEffect"in e[1])),(e,t)=>W(e,(n)=>{let r=typeof t==="function"?t(n):t;if(ts(r))return Zr(r,n);else if(j_(r))return qc((o)=>{r.then((i)=>o(he(n)),(i)=>o(yt(new uL(i,"An unknown error occurred in Effect.tap"))))});return he(n)})),it=he(void 0),$p=d(2,(e,t)=>W(e,(n)=>ze(t,(r)=>[n,r]))),Hp=d(2,(e,t)=>W(e,(n)=>Zr(t,n))),Uo=d(2,(e,t)=>W(e,()=>t)),zc=XT(()=>{let e=setInterval(()=>{},2147483647);return B(()=>clearInterval(e))}),Kc=d(2,(e,t)=>W(e.interruptAsFork(t),()=>e.await)),nE={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return k(this,arguments)}},rE={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return k(this,arguments)}},oE={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return k(this,arguments)}},jg={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return k(this,arguments)}},Bg={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return k(this,arguments)}},Vg={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return k(this,arguments)}},iE={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return k(this,arguments)}},aE={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return k(this,arguments)}},oL=Symbol.for(rL),iL={_A:(e)=>e},qi=d(2,(e,t)=>W(jp(e),t)),kg=d(2,(e,t)=>aL(e,()=>[void 0,t])),aL=d(2,(e,t)=>Tt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),he(r)})),$o=d(3,(e,t,n)=>ZT(Hp(jp(t),kg(t,n)),()=>e,(r)=>kg(t,r))),$i=K(Symbol.for("effect/FiberRef/currentContext"),()=>Bp(Io())),os=K(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>Et(0)),zg=K(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>Et(2048)),lE=K(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>Et(Za())),Kg=K(Symbol.for("effect/FiberRef/currentLogLevel"),()=>Et(Bg)),uE=K(Symbol.for("effect/FiberRef/currentLogSpan"),()=>Et(Mo())),pE=d(2,(e,t)=>$o(e,os,t)),dE=K(Symbol.for("effect/FiberRef/currentConcurrency"),()=>Et("unbounded")),fE=K(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>Et(!0)),mE=K(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>Et(H(Vg))),hE=K(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>Et(H(jg))),Wc=K(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>sL($r())),Pp=K(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>Et(F(),{fork:()=>F(),join:(e,t)=>e})),Jc=K(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>Et(Kr,{fork:()=>Kr,join:(e,t)=>e})),Vp=Symbol.for("effect/Scope"),zp=Symbol.for("effect/CloseableScope"),Wp=function(){class e extends globalThis.Error{commit(){return yt(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[ie](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
22
+ `)}return t},Ev=(e)=>N(e,Nh),Rv=(e)=>N(e,wc),R0,Ov=()=>R0,Fh=(e,t)=>Io(new Map([[e.key,t]])),Cv,Mh,Lh=(e)=>{if(Mh.has(e.key))return Mh.get(e.key);let t=e.defaultValue();return Mh.set(e.key,t),t},kv=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Lh(t),Dh,Av,Iv,Pv;var ap=x(()=>{fe();W();Le();Be();Re();we();Dr();jm();_v=Symbol.for("effect/Context/Tag"),wc=Symbol.for("effect/Context/Reference"),w0=Symbol.for(_0),wv={...Lr,_op:"Tag",[w0]:bo,[_v]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return Se(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[ie](){return this.toJSON()},of(e){return e},context(e){return Fh(this,e)}},v0={...wv,[wc]:wc},Nh=Symbol.for("effect/Context"),T0={[Nh]:{_Services:(e)=>e},[D](e){if(Ev(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!P(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[q](){return le(this,Ru(this.unsafeMap.size))},pipe(){return k(this,arguments)},toString(){return Se(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(me)}},[ie](){return this.toJSON()}},R0=Io(new Map),Cv=d(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),Io(r)}),Mh=K("effect/Context/defaultValueCache",()=>new Map),Dh=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(wc in t)return Lh(t);throw E0(t)}return e.unsafeMap.get(t.key)}),Av=Dh,Iv=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return Rv(t)?dc(Lh(t)):Pu;return dc(e.unsafeMap.get(t.key))}),Pv=d(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return Io(n)})});var Xt,Po,Nv,ur,vc,Tc,Mo,Ec,Rc;var _n=x(()=>{ap();Xt=vv,Po=Ov,Nv=Fh,ur=Cv,vc=Av,Tc=Dh,Mo=Iv,Ec=Pv,Rc=Tv});var Uh,Uv,Fv,sp,$h,Lv,Dv,O0,Jr=(e)=>{if($v(e))return e;else if(rn(e))return cp(e);else if(yo(e))return qh(e);else if(Array.isArray(e)&&e.length===2&&e.every(rn)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return Hh;if(e[0]===1/0||e[1]===1/0)return I0;return qh(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(wt(e)){let t=O0.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return qh(BigInt(r));case"micro":case"micros":return P0(BigInt(r));case"milli":case"millis":return cp(i);case"second":case"seconds":return M0(i);case"minute":case"minutes":return N0(i);case"hour":case"hours":return F0(i);case"day":case"days":return L0(i);case"week":case"weeks":return D0(i)}}}throw Error("Invalid DurationInput")},qv,C0,k0,pr=(e)=>{let t=Object.create(k0);if(rn(e))if(isNaN(e)||e<=0)t.value=qv;else if(!Number.isFinite(e))t.value=C0;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<=Uv)t.value=qv;else t.value={_tag:"Nanos",nanos:e};return t},$v=(e)=>N(e,Uh),A0=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Uv;case"Infinity":return!1}},Hh,I0,qh=(e)=>pr(e),P0=(e)=>pr(e*$h),cp=(e)=>pr(e),M0=(e)=>pr(e*1000),N0=(e)=>pr(e*60000),F0=(e)=>pr(e*3600000),L0=(e)=>pr(e*86400000),D0=(e)=>pr(e*604800000),lp=(e)=>$0(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),q0=(e)=>{let t=Jr(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))}},U0=(e)=>{let t=Jr(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/Dv),Number(t.value.nanos%Dv)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},$0,jh,H0=(e,t)=>jh(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),Hv,jv,j0,B0=(e)=>{let t=Jr(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=q0(t),r=n/Lv,o=r/$h,i=o/sp,a=i/sp,s=a/Fv;return{days:Number(s),hours:Number(a%Fv),minutes:Number(i%sp),seconds:Number(o%sp),millis:Number(r%$h),nanos:Number(n%Lv)}},V0=(e)=>{let t=Jr(e);if(t.value._tag==="Infinity")return"Infinity";if(A0(t))return"0";let n=B0(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 Bh=x(()=>{fe();W();Le();Be();Re();we();Uh=Symbol.for("effect/Duration"),Uv=BigInt(0),Fv=BigInt(24),sp=BigInt(60),$h=BigInt(1000),Lv=BigInt(1e6),Dv=BigInt(1e9),O0=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,qv={_tag:"Millis",millis:0},C0={_tag:"Infinity"},k0={[Uh]:Uh,[q](){return le(this,Ou(this.value))},[D](e){return $v(e)&&j0(this,e)},toString(){return`Duration(${V0(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:U0(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}},Hh=pr(0),I0=pr(1/0),$0=d(2,(e,t)=>{let n=Jr(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)}}),jh=d(3,(e,t,n)=>{let r=Jr(e),o=Jr(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(lp(r),lp(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)}),Hv=d(2,(e,t)=>jh(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),jv=d(2,(e,t)=>jh(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),j0=d(2,(e,t)=>H0(Jr(e),Jr(t)))});var Vv,z0,up=(e)=>{let t=Object.create(z0);return t.current=e,t},Ka=(e)=>e.current,pp;var Vh=x(()=>{W();Be();Re();Vv=Symbol.for("effect/MutableRef"),z0={[Vv]:Vv,toString(){return Se(this.toJSON())},toJSON(){return{_id:"MutableRef",current:me(this.current)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}},pp=d(2,(e,t)=>(e.current=t,e))});var Wh="effect/FiberId",Ja,dp="None",zh="Runtime",W0="Composite",K0,Kv,Jv,Gv,Kh=(e)=>N(e,Ja),fp=(e)=>{switch(e._tag){case dp:return lr();case zh:return Ei(e.id);case W0:return y(fp(e.left),Wr(fp(e.right)))}},Wv,mp=(e)=>Array.from(fp(e)).map((n)=>`#${n}`).join(","),Yv=()=>{let e=Ka(Wv);return y(Wv,pp(e+1)),new Jv(e,Date.now())};var Jh=x(()=>{fe();W();Le();Ci();Be();Vh();we();Ja=Symbol.for(Wh),K0=xe(`${Wh}-${dp}`);Kv=class Kv{[Ja]=Ja;_tag=dp;id=-1;startTimeMillis=-1;[q](){return K0}[D](e){return Kh(e)&&e._tag===dp}toString(){return Se(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[ie](){return this.toJSON()}};Jv=class Jv{id;startTimeMillis;[Ja]=Ja;_tag=zh;constructor(e,t){this.id=e,this.startTimeMillis=t}[q](){return le(this,xe(`${Wh}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[D](e){return Kh(e)&&e._tag===zh&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Se(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[ie](){return this.toJSON()}};Gv=new Kv,Wv=K(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>up(0))});var wn,Xv,hp;var Ga=x(()=>{Jh();wn=Gv,Xv=mp,hp=Yv});var Ya,Qv,eT,Gh,Yh,Zh,tT,nT,Xh;var gp=x(()=>{xh();Ya=qa,Qv=Ww,eT=Jw,Gh=Gw,Yh=Ti,Zh=Ku,tT=Gu,nT=Xw,Xh=Ua});var Cc,eg=(e)=>Pe(e),J0=(e)=>Cm(To(e),eg),G0,Y0,yp=(e,t)=>{let n=Object.create(Y0);return n.head=e,n.tail=t,n},Z0,X0,rT,oT=(e)=>N(e,Cc),dr=(e)=>e._tag==="Nil",tg=(e)=>e._tag==="Cons",Q0=()=>rT,Gr=(e,t)=>yp(e,t),No,kc=(e)=>yp(e,rT),iT,eF,tF,aT,sT=(e)=>{let t=No(),n=e;while(!dr(n))t=eF(t,n.head),n=n.tail;return t};var xp=x(()=>{Ve();fe();ec();W();Le();Be();Re();we();Cc=Symbol.for("effect/List"),G0=J0(P),Y0={[Cc]:Cc,_tag:"Cons",toString(){return Se(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:eg(this).map(me)}},[ie](){return this.toJSON()},[D](e){return oT(e)&&this._tag===e._tag&&G0(this,e)},[q](){return le(this,on(eg(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 k(this,arguments)}},Z0=xe("Nil"),X0={[Cc]:Cc,_tag:"Nil",toString(){return Se(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[ie](){return this.toJSON()},[q](){return Z0},[D](e){return oT(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return k(this,arguments)}},rT=Object.create(X0),No=Q0,iT=d(2,(e,t)=>tF(t,e)),eF=d(2,(e,t)=>Gr(t,e)),tF=d(2,(e,t)=>{if(dr(e))return t;else if(dr(t))return e;else{let n=yp(t.head,e),r=n,o=t.tail;while(!dr(o)){let i=yp(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),aT=d(3,(e,t,n)=>{let r=t,o=e;while(!dr(o))r=n(r,o.head),o=o.tail;return r})});var JW,Za;var Sp=x(()=>{fe();Le();Dr();JW=Object.assign(Object.create(Array.prototype),{[q](){return le(this,on(this))},[D](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>P(t,e[n]));else return!1}}),Za=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=pc,e}()});function cT(e){return e}var rF,Ic,oF,iF,rg=()=>iF,aF,sF=(e,t)=>{let n=Object.create(aF);return n.first=e,n.second=t,n},cF,lF=(e,t)=>{let n=Object.create(cF);return n.key=e,n.service=t,n},uF,pF=(e)=>{let t=Object.create(uF);return t.key=e,t},dF,fF=(e,t)=>{let n=Object.create(dF);return n.key=e,n.update=t,n},lT=(e,t)=>{let n=new Map(e.unsafeMap),r=rg();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!P(a,i))r=Ac(fF(o,()=>i))(r)}else n.delete(o),r=Ac(lF(o,i))(r);for(let[o]of n.entries())r=Ac(pF(o))(r);return r},Ac,uT;var pT=x(()=>{cr();fe();W();ap();Sp();rF=Symbol.for("effect/DifferContextPatch");Ic={...Za.prototype,[rF]:{_Value:cT,_Patch:cT}},oF=Object.assign(Object.create(Ic),{_tag:"Empty"}),iF=Object.create(oF),aF=Object.assign(Object.create(Ic),{_tag:"AndThen"}),cF=Object.assign(Object.create(Ic),{_tag:"AddService"}),uF=Object.assign(Object.create(Ic),{_tag:"RemoveService"}),dF=Object.assign(Object.create(Ic),{_tag:"UpdateService"}),Ac=d(2,(e,t)=>sF(e,t)),uT=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=ot(e),o=new Map(t.unsafeMap);while($n(r)){let a=Hn(r),s=jn(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=It(It(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 Io(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 Io(i)})});function og(e){return e}var hF,_p,gF,yF,ig=()=>yF,xF,SF=(e,t)=>{let n=Object.create(xF);return n.first=e,n.second=t,n},bF,_F=(e)=>{let t=Object.create(bF);return t.value=e,t},wF,vF=(e)=>{let t=Object.create(wF);return t.value=e,t},dT=(e,t)=>{let[n,r]=Oi([e,ig()],([o,i],a)=>{if(dv(a)(o))return[_h(a)(o),i];return[o,bp(_F(a))(i)]})(t);return Oi(r,(o,i)=>bp(vF(i))(o))(n)},bp,fT;var mT=x(()=>{cr();W();Ci();Sp();hF=Symbol.for("effect/DifferHashSetPatch");_p={...Za.prototype,[hF]:{_Value:og,_Key:og,_Patch:og}},gF=Object.assign(Object.create(_p),{_tag:"Empty"}),yF=Object.create(gF),xF=Object.assign(Object.create(_p),{_tag:"AndThen"}),bF=Object.assign(Object.create(_p),{_tag:"Add"}),wF=Object.assign(Object.create(_p),{_tag:"Remove"}),bp=d(2,(e,t)=>SF(e,t)),fT=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=ot(e);while($n(r)){let o=Hn(r),i=jn(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=It(o.first)(It(o.second)(i));break}case"Add":{n=Ri(o.value)(n),r=i;break}case"Remove":n=_h(o.value)(n),r=i}}return n})});function hT(e){return e}var EF,Mc,RF,OF,ag=()=>OF,CF,kF=(e,t)=>{let n=Object.create(CF);return n.first=e,n.second=t,n},AF,IF=(e)=>{let t=Object.create(AF);return t.values=e,t},PF,MF=(e,t)=>{let n=Object.create(PF);return n.from=e,n.until=t,n},NF,FF=(e,t)=>{let n=Object.create(NF);return n.index=e,n.patch=t,n},gT=(e)=>{let t=0,n=ag();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(!P(i,e.differ.empty))n=Pc(n,FF(t,i));t=t+1}if(t<e.oldValue.length)n=Pc(n,MF(0,t));if(t<e.newValue.length)n=Pc(n,IF(Ow(t)(e.newValue)));return n},Pc,yT;var xT=x(()=>{Ve();fe();W();Sp();EF=Symbol.for("effect/DifferReadonlyArrayPatch");Mc={...Za.prototype,[EF]:{_Value:hT,_Patch:hT}},RF=Object.assign(Object.create(Mc),{_tag:"Empty"}),OF=Object.create(RF),CF=Object.assign(Object.create(Mc),{_tag:"AndThen"}),AF=Object.assign(Object.create(Mc),{_tag:"Append"}),PF=Object.assign(Object.create(Mc),{_tag:"Slice"}),NF=Object.assign(Object.create(Mc),{_tag:"Update"}),Pc=d(2,(e,t)=>kF(e,t)),yT=d(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=At(e);while(wo(o)){let i=rt(o),a=qn(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 ST,DF,Fo=(e)=>{let t=Object.create(DF);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},sg=()=>Fo({empty:rg(),combine:(e,t)=>Ac(t)(e),diff:(e,t)=>lT(e,t),patch:(e,t)=>uT(t)(e)}),cg=()=>Fo({empty:ig(),combine:(e,t)=>bp(t)(e),diff:(e,t)=>dT(e,t),patch:(e,t)=>fT(t)(e)}),lg=(e)=>Fo({empty:ag(),combine:(t,n)=>Pc(t,n),diff:(t,n)=>gT({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>yT(t,n,e)}),wp=()=>bT((e,t)=>t),bT=(e)=>Fo({empty:de,combine:(t,n)=>{if(t===de)return n;if(n===de)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(P(t,n))return de;return Gs(n)},patch:(t,n)=>e(n,t(n))});var vp=x(()=>{fe();W();Re();pT();mT();xT();ST=Symbol.for("effect/Differ"),DF={[ST]:{_P:de,_V:de},pipe(){return k(this,arguments)}}});var Nc=255,_T=8,Tp=(e)=>e&Nc,Ep=(e)=>e>>_T&Nc,Fi=(e,t)=>(e&Nc)+((t&e&Nc)<<_T),pg,wT=(e)=>Fi(e,e),vT=(e)=>Fi(e,0),TT,dg,ET=(e)=>~e>>>0&Nc;var fg=x(()=>{W();pg=Fi(0,0),TT=d(2,(e,t)=>Fi(Tp(e)&~t,Ep(e))),dg=d(2,(e,t)=>e|t)});var qF=0,Yr=1,OT=2,mg=4,Rp=16,hg=32,CT=(e)=>Op(e,hg),gg,Zr=(e)=>yg(e)&&!UF(e),yg=(e)=>Op(e,Yr),Op,xg=(...e)=>e.reduce((t,n)=>t|n,0),kT,Sg=(e)=>Op(e,mg),UF=(e)=>Op(e,Rp),Fc,Lc,bg;var Dc=x(()=>{W();vp();fg();gg=d(2,(e,t)=>e|t),Op=d(2,(e,t)=>(e&t)!==0),kT=xg(qF),Fc=d(2,(e,t)=>Fi(e^t,t)),Lc=d(2,(e,t)=>e&(ET(Tp(t))|Ep(t))|Tp(t)&Ep(t)),bg=Fo({empty:pg,diff:(e,t)=>Fc(e,t),combine:(e,t)=>dg(t)(e),patch:(e,t)=>Lc(t,e)})});var AT,wg,vg;var Tg=x(()=>{fg();AT=wT,wg=vT,vg=TT});var Rg=(e,t)=>({_tag:"Par",left:e,right:t}),Cp=(e,t)=>({_tag:"Seq",left:e,right:t}),PT=(e)=>{let t=kc(e),n=No();while(!0){let[r,o]=aT(t,[MT(),No()],([i,a],s)=>{let[c,l]=$F(s);return[zF(i,c),iT(a,l)]});if(n=HF(n,r),dr(o))return sT(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},$F=(e)=>{let t=e,n=MT(),r=No(),o=No();while(!0)switch(t._tag){case"Empty":{if(dr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Gr(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=Rg(Cp(s,a),Cp(c,a));break}case"Seq":{let{left:s,right:c}=i;t=Cp(s,Cp(c,a));break}case"Single":{t=i,o=Gr(a,o);break}}break}case"Single":{if(n=VF(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")},HF=(e,t)=>{if(dr(e))return kc(Eg(t));if(WF(t))return e;let n=XF(e.head),r=KF(t);if(n.length===1&&r.length===1&&P(n[0],r[0]))return Gr(ZF(e.head,Eg(t)),e.tail);return Gr(Eg(t),e)},jF,BF,kp,MT=()=>new kp(Ya()),VF=(e,t)=>new kp(tT(e.map,t.dataSource,(n)=>mw(Ln(n,Nw(t.blockedRequest)),()=>ot(t.blockedRequest)))),zF=(e,t)=>new kp(Xh(e.map,t.map,(n,r,o)=>Yh(n,o,Je(Gh(n,o),{onNone:()=>r,onSome:(i)=>sn(r,i)})))),WF=(e)=>eT(e.map),KF=(e)=>Array.from(Zh(e.map)),Eg=(e)=>YF(nT(e.map,(t)=>ot(t))),JF,GF,Og,YF=(e)=>new Og(e),ZF=(e,t)=>new Og(Xh(t.map,e.map,(n,r,o)=>Yh(n,o,Je(Gh(n,o),{onNone:()=>Sn(),onSome:(i)=>sn(i,r)})))),XF=(e)=>Array.from(Zh(e.map)),NT=(e)=>Array.from(e.map);var FT=x(()=>{cr();fe();gp();xp();Ge();jF=Symbol.for("effect/RequestBlock/RequestBlockParallel"),BF={_R:(e)=>e};kp=class kp{map;[jF]=BF;constructor(e){this.map=e}};JF=Symbol.for("effect/RequestBlock/RequestBlockSequential"),GF={_R:(e)=>e};Og=class Og{map;[JF]=GF;constructor(e){this.map=e}}});var Xa="Pending",Ap="Done";var eL="effect/Deferred",DT,qT,UT=(e)=>({_tag:Xa,joiners:e}),$T=(e)=>({_tag:Ap,effect:e});var HT=x(()=>{DT=Symbol.for(eL),qT={_E:(e)=>e,_A:(e)=>e}});var Qa;var jT=x(()=>{Qa=class Qa{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 Qa(this.self)}}});class Ig{patch;op;_op=lc;constructor(e,t){this.patch=e,this.op=t}}var Mp=(e,t)=>{let n=new gt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},Ag=(e)=>{let t=new gt("RunBlocked");return t.effect_instruction_i0=e,t},Lo,gt,Pg,Mg,es=(e)=>N(e,Lo),Tt=(e)=>{let t=new gt(Iu);return t.effect_instruction_i0=e,t},ZT,Xr,Qr=(e)=>Xr(e,void 0),Ng=function(){let e=new gt(Si);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(hi("you're not supposed to end up here"))}return e},qc=(e,t=wn)=>{let n=new gt(xi),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,jc(n,(o)=>es(r)?r:it)},XT=(e,t=wn)=>Me(()=>qc(e,t)),Do=(e,t=wn)=>Ng(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 gt(xi);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=vt(()=>this.effect_instruction_i0(o,s.signal));else a=vt(()=>this.effect_instruction_i0(o));return a||s?jc(i,(c)=>{if(s)s.abort();return a??it}):i}),Uc,BT,Np=(e,t)=>{if(Ie(t))return new Proxy(e,{has(n,r){return r===Mi||r===BT||r in n},get(n,r){if(r===Mi)return t.value;if(r===BT)return e;return n[r]}});return e},Fp=(e)=>Bt(e)&&!(Mi in e)?Tt((t)=>Mt(cn(Np(e,Zp(t))))):Mt(cn(e)),Fg=(e)=>QT(()=>cn(new lL(e))),Li=(e)=>ts(e,{onFailure:(t)=>he(Q(t)),onSuccess:(t)=>he(re(t))}),qo=(e)=>eE(e,{onFailure:Ce,onSuccess:Fe}),yt=(e)=>Bt(e)&&!(Mi in e)?Tt((t)=>Mt(Va(Np(e,Zp(t))))):Mt(Va(e)),Lg=(e)=>J(V(e),yt),Mt=(e)=>{let t=new Pg(Gt);return t.effect_instruction_i0=e,t},QT=(e)=>J(V(e),Mt),Dg,$c=(e)=>Tt((t)=>e(t.id())),J,qg=(e)=>{let t=new gt("OnStep");return t.effect_instruction_i0=e,t},Hc=(e)=>J(e,de),eE,vn,ts,Tn,Di,Lp=(e)=>{let t=new gt(bi);return t.effect_instruction_i0=AT(Yr),t.effect_instruction_i1=()=>e,t},ze,Dp,qi,ns,jc,he=(e)=>{let t=new Mg(Yt);return t.effect_instruction_i0=e,t},Me=(e)=>{let t=new gt(Si);return t.commit=e,t},V=(e)=>{let t=new gt(Au);return t.effect_instruction_i0=e,t},qp,Ug=(e)=>Tt((t)=>{let n=t.getFiberRef(Pp),r=y(n,Ae(()=>t.scope()));return e(Ho(Pp,B(r)))}),Up=(e)=>{let t=new gt(bi);return t.effect_instruction_i0=wg(Yr),t.effect_instruction_i1=()=>e,t},Uo=(e)=>Ng(e,function(){let t=new gt(bi);return t.effect_instruction_i0=wg(Yr),t.effect_instruction_i1=(n)=>yg(n)?vt(()=>this.effect_instruction_i0(Lp)):vt(()=>this.effect_instruction_i0(Up)),t}),it,$g=(e)=>{let t=new gt(bi);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},Bc=(e)=>{let t=new gt(Aa);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},Vc=(e)=>{let t=new gt(Pa);return typeof e?.priority<"u"?pE(t,e.priority):t},$p,Hp,$o,zc,tE=(e)=>J(Dg,(t)=>y(e,Wc(t))),Wc,nE,rE,oE,Hg,jg,Bg,iE,aE,oL="effect/FiberRef",iL,aL,jp=(e)=>Tt((t)=>Fe(t.getFiberRef(e))),Ui,Cg,sL,Ho,Et=(e,t)=>$i(e,{differ:wp(),fork:t?.fork??de,join:t?.join}),sE=(e)=>{let t=cg();return $i(e,{differ:t,fork:t.empty})},cL=(e)=>{let t=lg(wp());return $i(e,{differ:t,fork:t.empty})},Bp=(e)=>{let t=sg();return $i(e,{differ:t,fork:t.empty})},$i=(e,t)=>({..._o,[iL]:aL,initial:e,commit(){return jp(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)}),cE=(e)=>$i(e,{differ:bg,fork:bg.empty}),Hi,rs,Vg,lE,zg,uE,pE,dE,fE,mE,hE,Kc,Pp,Jc,Vp,zp,Wp=(e,t)=>e.addFinalizer(()=>Qr(t)),Wg=(e,t)=>e.close(t),os=(e,t)=>e.fork(t),Kp,ji=(e,t)=>{class n extends Kp{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},VT,lL,kg,EK,gE=(e)=>N(e,kg),zT,uL,WT,Gc,KT,RK,JT,OK,GT,CK,YT,pL,is=(e)=>es(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),Kg=(e)=>e._tag==="Success",yE,Yc=(e)=>yE(e,void 0),Bi=(e,t)=>dL(e,t?.parallel?Ni:Pt),Jg=(e)=>Ce(cn(e)),Zc=(e)=>Ce(Va(e)),Ce=(e)=>{let t=new Pg(Gt);return t.effect_instruction_i0=e,t},Gg=(e)=>Ce(Bn(e)),Ip,Jp,Fe=(e)=>{let t=new Mg(Yt);return t.effect_instruction_i0=e,t},En,Yg,dL=(e,t)=>{let n=Uu(e);if(!$n(n))return F();return y(jn(n),Fa(y(Hn(n),Ip(ot)),(r,o)=>y(r,Yg(o,{onSuccess:(i,a)=>y(i,It(a)),onFailure:t}))),Ip(Eo),Ip((r)=>Br(r)),B)},xE=(e)=>({..._o,[DT]:qT,state:up(UT([])),commit(){return Gp(this)},blockingOn:e}),Gp=(e)=>XT((t)=>{let n=Ka(e.state);switch(n._tag){case Ap:return t(n.effect);case Xa:return n.joiners.push(t),fL(e,t)}},e.blockingOn),Yp=(e,t)=>{let n=Ka(e.state);if(n._tag===Xa){pp(e.state,$T(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},fL=(e,t)=>V(()=>{let n=Ka(e.state);if(n._tag===Xa){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),mL,SE=()=>mL,Vi=(e)=>J(SE(),e),hL,Zg,Zp=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?B(t):F()};var at=x(()=>{Ve();cr();_n();an();fe();Ga();W();Le();gp();Be();xp();Vh();Ge();Re();we();Tg();So();Wa();HT();vp();Dr();Dc();jT();Lo=Symbol.for("effect/Effect");gt=class gt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Lo]=bo;constructor(e){this._op=e}[D](e){return this===e}[q](){return le(this,oc(this))}pipe(){return k(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:me(this.effect_instruction_i0),effect_instruction_i1:me(this.effect_instruction_i1),effect_instruction_i2:me(this.effect_instruction_i2)}}toString(){return Se(this.toJSON())}[ie](){return this.toJSON()}[Symbol.iterator](){return new Qa(new Nr(this))}};Pg=class Pg{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Lo]=bo;constructor(e){this._op=e,this._tag=e}[D](e){return is(e)&&e._op==="Failure"&&P(this.effect_instruction_i0,e.effect_instruction_i0)}[q](){return y(xe(this._tag),te(I(this.effect_instruction_i0)),le(this))}get cause(){return this.effect_instruction_i0}pipe(){return k(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return Se(this.toJSON())}[ie](){return this.toJSON()}[Symbol.iterator](){return new Qa(new Nr(this))}};Mg=class Mg{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Lo]=bo;constructor(e){this._op=e,this._tag=e}[D](e){return is(e)&&e._op==="Success"&&P(this.effect_instruction_i0,e.effect_instruction_i0)}[q](){return y(xe(this._tag),te(I(this.effect_instruction_i0)),le(this))}get value(){return this.effect_instruction_i0}pipe(){return k(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:me(this.value)}}toString(){return Se(this.toJSON())}[ie](){return this.toJSON()}[Symbol.iterator](){return new Qa(new Nr(this))}};ZT=d(3,(e,t,n)=>Uo((r)=>J(e,(o)=>J(qo(Me(()=>r(t(o)))),(i)=>Me(()=>n(o,i)).pipe(vn({onFailure:(a)=>{switch(i._tag){case Gt:return Mt(Pt(i.effect_instruction_i0,a));case Yt:return Mt(a)}},onSuccess:()=>i})))))),Xr=d(2,(e,t)=>J(e,()=>he(t))),Uc=d(2,(e,t)=>ts(e,{onFailure:t,onSuccess:he})),BT=Symbol.for("effect/OriginalAnnotation"),Dg=Tt((e)=>he(e.id())),J=d(2,(e,t)=>{let n=new gt(Ca);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),eE=d(2,(e,t)=>vn(e,{onFailure:(n)=>he(t.onFailure(n)),onSuccess:(n)=>he(t.onSuccess(n))})),vn=d(2,(e,t)=>{let n=new gt(ka);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),ts=d(2,(e,t)=>vn(e,{onFailure:(n)=>{if(Ch(n).length>0)return Mt(Sv(n));let o=Oh(n);if(o.length>0)return t.onFailure(lh(o));return Mt(n)},onSuccess:t.onSuccess})),Tn=d(2,(e,t)=>Me(()=>{let n=Pe(e),r=_i(n.length),o=0;return Xr(Bc({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),Di=d(2,(e,t)=>Me(()=>{let n=Pe(e),r=0;return Bc({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),ze=d(2,(e,t)=>J(e,(n)=>V(()=>t(n)))),Dp=d(2,(e,t)=>ts(e,{onFailure:(n)=>Lg(()=>t.onFailure(n)),onSuccess:(n)=>V(()=>t.onSuccess(n))})),qi=d(2,(e,t)=>vn(e,{onFailure:(n)=>{let r=rp(n);switch(r._tag){case"Left":return Lg(()=>t(r.left));case"Right":return Mt(r.right)}},onSuccess:he})),ns=d(2,(e,t)=>Uo((n)=>vn(n(e),{onFailure:(r)=>{let o=Ce(r);return vn(t(o),{onFailure:(i)=>Ce(Pt(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=Fe(r);return $o(t(o),o)}}))),jc=d(2,(e,t)=>ns(e,Jp({onFailure:(n)=>za(n)?Qr(t(kh(n))):it,onSuccess:()=>it}))),qp=d((e)=>e.length===3||e.length===2&&!(Bt(e[1])&&("onlyEffect"in e[1])),(e,t)=>J(e,(n)=>{let r=typeof t==="function"?t(n):t;if(es(r))return Xr(r,n);else if(j_(r))return qc((o)=>{r.then((i)=>o(he(n)),(i)=>o(yt(new pL(i,"An unknown error occurred in Effect.tap"))))});return he(n)})),it=he(void 0),$p=d(2,(e,t)=>J(e,(n)=>ze(t,(r)=>[n,r]))),Hp=d(2,(e,t)=>J(e,(n)=>Xr(t,n))),$o=d(2,(e,t)=>J(e,()=>t)),zc=XT(()=>{let e=setInterval(()=>{},2147483647);return V(()=>clearInterval(e))}),Wc=d(2,(e,t)=>J(e.interruptAsFork(t),()=>e.await)),nE={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return k(this,arguments)}},rE={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return k(this,arguments)}},oE={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return k(this,arguments)}},Hg={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return k(this,arguments)}},jg={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return k(this,arguments)}},Bg={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return k(this,arguments)}},iE={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return k(this,arguments)}},aE={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return k(this,arguments)}},iL=Symbol.for(oL),aL={_A:(e)=>e},Ui=d(2,(e,t)=>J(jp(e),t)),Cg=d(2,(e,t)=>sL(e,()=>[void 0,t])),sL=d(2,(e,t)=>Tt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),he(r)})),Ho=d(3,(e,t,n)=>ZT(Hp(jp(t),Cg(t,n)),()=>e,(r)=>Cg(t,r))),Hi=K(Symbol.for("effect/FiberRef/currentContext"),()=>Bp(Po())),rs=K(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>Et(0)),Vg=K(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>Et(2048)),lE=K(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>Et(Ya())),zg=K(Symbol.for("effect/FiberRef/currentLogLevel"),()=>Et(jg)),uE=K(Symbol.for("effect/FiberRef/currentLogSpan"),()=>Et(No())),pE=d(2,(e,t)=>Ho(e,rs,t)),dE=K(Symbol.for("effect/FiberRef/currentConcurrency"),()=>Et("unbounded")),fE=K(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>Et(!0)),mE=K(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>Et(B(Bg))),hE=K(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>Et(B(Hg))),Kc=K(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>cL(Hr())),Pp=K(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>Et(F(),{fork:()=>F(),join:(e,t)=>e})),Jc=K(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>Et(Kr,{fork:()=>Kr,join:(e,t)=>e})),Vp=Symbol.for("effect/Scope"),zp=Symbol.for("effect/CloseableScope"),Kp=function(){class e extends globalThis.Error{commit(){return yt(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[ie](){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 Vn(za(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,Um),e}(),VT=Symbol.for("effect/Cause/errors/RuntimeException"),cL=Hi({[VT]:VT},"RuntimeException"),Ag=Symbol.for("effect/Cause/errors/InterruptedException"),_W=Hi({[Ag]:Ag},"InterruptedException"),zT=Symbol.for("effect/Cause/errors/IllegalArgument"),lL=Hi({[zT]:zT},"IllegalArgumentException"),KT=Symbol.for("effect/Cause/errors/NoSuchElement"),Gc=Hi({[KT]:KT},"NoSuchElementException"),WT=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),wW=Hi({[WT]:WT},"InvalidPubSubCapacityException"),JT=Symbol.for("effect/Cause/errors/ExceededCapacityException"),vW=Hi({[JT]:JT},"ExceededCapacityException"),GT=Symbol.for("effect/Cause/errors/Timeout"),TW=Hi({[GT]:GT},"TimeoutException"),YT=Symbol.for("effect/Cause/errors/UnknownException"),uL=function(){class e extends Wp{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[YT]:YT,name:"UnknownException"}),e}(),yE=d(2,(e,t)=>{switch(e._tag){case Gt:return Ce(e.effect_instruction_i0);case Yt:return Fe(t)}}),Ip=d(2,(e,t)=>{switch(e._tag){case Gt:return Ce(e.effect_instruction_i0);case Yt:return Fe(t(e.effect_instruction_i0))}}),Jp=d(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case Gt:return t(e.effect_instruction_i0);case Yt:return n(e.effect_instruction_i0)}}),En=Fe(void 0),Zg=d(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case Gt:switch(t._tag){case Yt:return Ce(e.effect_instruction_i0);case Gt:return Ce(n(e.effect_instruction_i0,t.effect_instruction_i0))}case Yt:switch(t._tag){case Yt:return Fe(r(e.effect_instruction_i0,t.effect_instruction_i0));case Gt:return Ce(t.effect_instruction_i0)}}}),fL=Tt((e)=>Fe(e.currentContext)),mL=d(2,(e,t)=>$o($i,t)(e)),Xg=d(2,(e,t)=>Bi((n)=>mL(e,t(n))))});var bE,_E;var wE=x(()=>{Wa();bE=yv,_E=Vn});var Xp="And",Qp="Or",ed="InvalidData",td="MissingData",nd="SourceUnavailable",rd="Unsupported";var yL="effect/ConfigError",vE,ss,od=(e,t)=>{let n=Object.create(ss);return n._op=Xp,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},id=(e,t)=>{let n=Object.create(ss);return n._op=Qp,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},Qg=(e,t,n={pathDelim:"."})=>{let r=Object.create(ss);return r._op=ed,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${y(this.path,Hr(n.pathDelim))}: "${this.message}")`}}),r},fr=(e,t,n={pathDelim:"."})=>{let r=Object.create(ss);return r._op=td,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${y(this.path,Hr(n.pathDelim))}: "${this.message}")`}}),r},ey=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(ss);return o._op=nd,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${y(this.path,Hr(r.pathDelim))}: "${this.message}")`}}),o},ty=(e,t,n={pathDelim:"."})=>{let r=Object.create(ss);return r._op=rd,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${y(this.path,Hr(n.pathDelim))}: "${this.message}")`}}),r},Ho,TE;var ny=x(()=>{Ve();an();z();vE=Symbol.for(yL),ss={_tag:"ConfigError",[vE]:vE},Ho=d(2,(e,t)=>{switch(e._op){case Xp:return od(Ho(e.left,t),Ho(e.right,t));case Qp:return id(Ho(e.left,t),Ho(e.right,t));case ed:return Qg([...t,...e.path],e.message);case td:return fr([...t,...e.path],e.message);case nd:return ey([...t,...e.path],e.message,e.cause);case rd:return ty([...t,...e.path],e.message)}}),TE=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case Xp:{r.push(a.right),r.push(a.left),o.push(X({_op:"AndCase"}));break}case Qp:{r.push(a.right),r.push(a.left),o.push(X({_op:"OrCase"}));break}case ed:{o.push(ne(n.invalidDataCase(t,a.path,a.message)));break}case td:{o.push(ne(n.missingDataCase(t,a.path,a.message)));break}case nd:{o.push(ne(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case rd:{o.push(ne(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 xL="effect/Clock",OE,Xc,SL=2147483647,RE,CE,bL,kE,AE=()=>new kE;var ry=x(()=>{_n();Vh();z();at();OE=Symbol.for(xL),Xc=Xt("effect/Clock"),RE={unsafeSchedule(e,t){let n=lp(t);if(n>SL)return ho;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},CE=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))}}(),bL=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return CE;let t=CE()-e.bigint();return()=>t+e.bigint()}();kE=class kE{[OE]=OE;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return bL()}currentTimeMillis=B(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=B(()=>this.unsafeCurrentTimeNanos());scheduler(){return he(RE)}sleep(e){return Lo((t)=>{let n=RE.unsafeSchedule(()=>t(it),e);return Xr(B(n))})}}});var mr;var Qc=x(()=>{Lu();mr=fw});var cs=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var oy=()=>{};var ME,sd;var NE=x(()=>{Ve();an();z();xp();Ge();ny();ME={_tag:"Empty"},sd=d(2,(e,t)=>{let n=kc(t),r=e;while(ng(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Jr(o.first,Jr(o.second,n.tail));break}case"MapName":{r=Un(r,o.f),n=n.tail;break}case"Nested":{r=Na(r,o.name),n=n.tail;break}case"Unnested":{if(y(qr(r),yw(o.name)))r=qn(r),n=n.tail;else return X(fr(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return ne(r)})});var FE="Constant",LE="Fail",DE="Fallback",qE="Described",UE="Lazy",$E="MapOrFail",HE="Nested",jE="Primitive",BE="Redacted",VE="Sequence",zE="HashMap",KE="ZipWith";var cd=(e,t)=>[...e,...t],RL="effect/ConfigProvider",WE,GE,CL="effect/ConfigProviderFlat",JE,kL=(e)=>({[WE]:WE,pipe(){return k(this,arguments)},...e}),AL=(e)=>({[JE]:JE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),IL=(e)=>kL({load:(t)=>W(ln(e,$r(),t,!1),(n)=>Je(qr(n),{onNone:()=>yt(fr($r(),`Expected a single value having structure: ${t}`)),onSome:he})),flattened:e}),YE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>y(c,Hr(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return IL(AL({load:(c,l,u=!0)=>{let p=r(c),f=i(),h=p in f?H(f[p]):F();return y(h,Di(()=>fr(c,`Expected ${p} to exist in the process context`)),W((m)=>qL(m,c,l,n,u)))},enumerateChildren:(c)=>B(()=>{let l=i(),f=Object.keys(l).map((h)=>o(h.toUpperCase())).filter((h)=>{for(let m=0;m<c.length;m++){let S=y(c,nh(m)),E=h[m];if(E===void 0||S!==E)return!1}return!0}).flatMap((h)=>h.slice(c.length,c.length+1));return pv(f)}),patch:ME}))},PL=(e,t,n,r)=>{let o=ah(n.length,(c)=>c>=r.length?F():H([e(c),c+1])),i=ah(r.length,(c)=>c>=n.length?F():H([t(c),c+1])),a=cd(n,o),s=cd(r,i);return[a,s]},ML=(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},NL,FL=(e)=>TE(e,void 0,NL),ln=(e,t,n,r)=>{let o=n;switch(o._tag){case FE:return he(At(o.value));case qE:return Me(()=>ln(e,t,o.config,r));case LE:return yt(fr(t,o.message));case DE:return y(Me(()=>ln(e,t,o.first,r)),Uc((i)=>{if(o.condition(i))return y(ln(e,t,o.second,r),Uc((a)=>yt(id(i,a))));return yt(i)}));case UE:return Me(()=>ln(e,t,o.config(),r));case $E:return Me(()=>y(ln(e,t,o.original,r),W(Tn((i)=>y(o.mapOrFail(i),Di(Ho(ML(t,o.original))))))));case HE:return Me(()=>ln(e,cd(t,At(o.name)),o.config,r));case jE:return y(sd(t,e.patch),W((i)=>y(e.load(i,o,r),W((a)=>{if(a.length===0){let s=y(Ew(i),Ae(()=>"<n/a>"));return yt(fr([],`Expected ${o.description} with name ${s}`))}return he(a)}))));case BE:return Me(()=>y(ln(e,t,o.original,r),Di(FL),ze(Un(o.redact))));case VE:return y(sd(t,e.patch),W((i)=>y(e.enumerateChildren(i),W($L),W((a)=>{if(a.length===0)return Me(()=>ze(ln(e,t,o.config,!0),At));return y(Tn(a,(s)=>ln(e,ww(t,`[${s}]`),o.config,!0)),ze((s)=>{let c=Du(s);if(c.length===0)return At($r());return At(c)}))}))));case zE:return Me(()=>y(sd(t,e.patch),W((i)=>y(e.enumerateChildren(i),W((a)=>y(a,Tn((s)=>ln(e,cd(i,At(s)),o.valueConfig,r)),ze((s)=>{if(s.length===0)return At(Za());return y(UL(s),Un((c)=>Qv(ih(Pe(a),c))))})))))));case KE:return Me(()=>y(ln(e,t,o.left,r),Fi,W((i)=>y(ln(e,t,o.right,r),Fi,W((a)=>{if(ke(i)&&ke(a))return yt(od(i.left,a.left));if(ke(i)&&kt(a))return yt(i.left);if(kt(i)&&ke(a))return yt(a.left);if(kt(i)&&kt(a)){let s=y(t,Hr(".")),c=LL(t,s),[l,u]=PL(c,c,y(i.right,Un(ne)),y(a.right,Un(ne)));return y(l,ih(u),Tn(([p,f])=>y($p(p,f),ze(([h,m])=>o.zip(h,m)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},LL=(e,t)=>(n)=>X(fr(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),DL=(e,t)=>e.split(new RegExp(`\\s*${cs(t)}\\s*`)),qL=(e,t,n,r,o)=>{if(!o)return y(n.parse(e),Dp({onFailure:Ho(t),onSuccess:At}));return y(DL(e,r),Tn((i)=>n.parse(i.trim())),Di(Ho(t)))},UL=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),$L=(e)=>y(Tn(e,jL),Dp({onFailure:()=>$r(),onSuccess:Ur(mr)}),Fi,ze(uw)),HL,jL=(e)=>{let t=e.match(HL);if(t!==null){let n=t[2];return y(n!==void 0&&n.length>0?H(n):F(),Dn(BL))}return F()},BL=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?F():H(t)};var ZE=x(()=>{Ve();_n();an();z();gp();Ri();Qc();Ge();Oe();oy();ny();NE();at();WE=Symbol.for(RL),GE=Xt("effect/ConfigProvider"),JE=Symbol.for(CL),NL={andCase:(e,t,n)=>od(t,n),orCase:(e,t,n)=>id(t,n),invalidDataCase:(e,t)=>Qg(t,"<redacted>"),missingDataCase:(e,t)=>fr(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>ey(t,"<redacted>",r),unsupportedCase:(e,t)=>ty(t,"<redacted>")},HL=/^(\[(\d+)\])$/});var XE,ld,QE;var iy=x(()=>{_n();at();XE=Symbol.for("effect/Console"),ld=Xt("effect/Console"),QE={[XE]:XE,assert(e,...t){return B(()=>{console.assert(e,...t)})},clear:B(()=>{console.clear()}),count(e){return B(()=>{console.count(e)})},countReset(e){return B(()=>{console.countReset(e)})},debug(...e){return B(()=>{console.debug(...e)})},dir(e,t){return B(()=>{console.dir(e,t)})},dirxml(...e){return B(()=>{console.dirxml(...e)})},error(...e){return B(()=>{console.error(...e)})},group(e){return e?.collapsed?B(()=>console.groupCollapsed(e?.label)):B(()=>console.group(e?.label))},groupEnd:B(()=>{console.groupEnd()}),info(...e){return B(()=>{console.info(...e)})},log(...e){return B(()=>{console.log(...e)})},table(e,t){return B(()=>{console.table(e,t)})},time(e){return B(()=>console.time(e))},timeEnd(e){return B(()=>console.timeEnd(e))},timeLog(e,...t){return B(()=>{console.timeLog(e,...t)})},trace(...e){return B(()=>{console.trace(...e)})},warn(...e){return B(()=>{console.warn(...e)})},unsafe:console}});var KL="effect/Random",eO,tO,nO,WL=(e,t)=>Me(()=>y(B(()=>Array.from(e)),W((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return y(r,Li((o)=>y(t(o),ze((i)=>JL(n,o-1,i)))),Zr(Uu(n)))}))),JL=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},rO=(e)=>new nO(I(e));var oO=x(()=>{cr();_n();z();Le();xo();at();eO=Symbol.for(KL),tO=Xt("effect/Random");nO=class nO{seed;[eO]=eO;PRNG;constructor(e){this.seed=e,this.PRNG=new Mm(e)}get next(){return B(()=>this.PRNG.number())}get nextBoolean(){return ze(this.next,(e)=>e>0.5)}get nextInt(){return B(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return ze(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return B(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return WL(e,(t)=>this.nextIntBetween(0,t))}}});class sO{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:aO(32),this.spanId=aO(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 iO,YL=(e)=>({[iO]:iO,...e}),el,ud,aO,cO,lO;var pd=x(()=>{_n();z();iO=Symbol.for("effect/Tracer"),el=Xt("effect/Tracer"),ud=Xt("effect/ParentSpan"),aO=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();cO=YL({span:(e,t,n,r,o,i)=>new sO(e,t,n,r,o,i),context:(e)=>e()}),lO=Oc()("effect/Tracer/DisablePropagation",{defaultValue:ho})});var QL,tl;var uO=x(()=>{_n();z();ry();ZE();at();iy();oO();pd();QL=y(Io(),ur(Xc,AE()),ur(ld,QE),ur(tO,rO(Math.random())),ur(GE,YE()),ur(el,cO)),tl=K(Symbol.for("effect/DefaultServices/currentServices"),()=>Bp(QL))});var tD,pO=(e)=>{let t={BaseEffectError:class extends tD{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var dO=x(()=>{at();tD=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends Wp{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 fO,nD,sy;var cy=x(()=>{Lr();fO=Fr,nD=ew;sy=class sy extends nD{}});var hO="Sequential",gO="Parallel",rD="ParallelN",ls,yO,xO=(e)=>({_tag:rD,parallelism:e}),ly=(e)=>e._tag===hO,uy=(e)=>e._tag===gO;var dd=x(()=>{ls={_tag:hO},yO={_tag:gO}});var fd,md,hd;var SO=x(()=>{dd();fd=ls,md=yO,hd=xO});function bO(e){return new Qr(e)}function _O(){return bO(new Map)}var dy,Qr,iD=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(Re(i)&&Re(a)){let l=rt(i)[0],u=qn(i),p=rt(a)[0],f=rt(a)[1],h=qn(a);if(l.startTimeMillis<p.startTimeMillis)a=h,s=!0;else if(l.startTimeMillis>p.startTimeMillis)i=u;else if(l.id<p.id)a=h,s=!0;else if(l.id>p.id)i=u;else c=[f,s]}else c=[o.initial,!0];return c},my,hy,wO=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(P(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},nl,gy,jo,us,fy=(e,t,n,r)=>{let o=e.get(n)??[],i;if(Re(o)){let[a,s]=rt(o);if(a[L](t))if(P(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},vO;var gd=x(()=>{Ve();fe();z();Ge();Oe();dy=Symbol.for("effect/FiberRefs");Qr=class Qr{locals;[dy]=dy;constructor(e){this.locals=e}pipe(){return k(this,arguments)}};my=d(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][L](t)){if(!r.has(i)){if(P(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=iD(i,s,o);if(l){let u=i.diff(c,a),p=s[0][1],f=i.join(p,i.patch(u)(p));if(!P(p,f)){let h,m=s[0][0];if(m[L](t))h=[[m,f],...s.slice(1)];else h=[[t,f],...s];r.set(i,h)}}}}),new Qr(r)}),hy=d(2,(e,t)=>{let n=new Map;return wO(e,n,t),new Qr(n)}),nl=d(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new Qr(n)}),gy=d(2,(e,t)=>{if(!e.locals.has(t))return F();return H(rt(e.locals.get(t))[1])}),jo=d(2,(e,t)=>y(gy(e,t),Ae(()=>t.initial))),us=d(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new Qr(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return fy(o,t,n,r),new Qr(o)}),vO=d(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new Qr(new Map(t));let r=new Map(e.locals);if(n!==void 0)wO(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)fy(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{fy(r,a,o,s)})}),new Qr(r)})});var TO,EO,OO;var xy=x(()=>{gd();TO=jo,EO=vO,OO=_O});var CO="Empty",kO="Add",AO="Remove",IO="Update",PO="AndThen",MO,NO=(e,t)=>{let n=new Map(e.locals),r=MO;for(let[o,i]of t.locals.entries()){let a=rt(i)[1],s=n.get(o);if(s!==void 0){let c=rt(s)[1];if(!P(c,a))r=yd({_tag:IO,fiberRef:o,patch:o.diff(c,a)})(r)}else r=yd({_tag:kO,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=yd({_tag:AO,fiberRef:o})(r);return r},yd,FO;var LO=x(()=>{Ve();fe();z();gd();MO={_tag:CO},yd=d(2,(e,t)=>({_tag:PO,first:e,second:t})),FO=d(3,(e,t,n)=>{let r=n,o=At(e);while(Re(o)){let i=rt(o),a=qn(o);switch(i._tag){case CO:{o=a;break}case kO:{r=us(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case AO:{r=nl(r,i.fiberRef),o=a;break}case IO:{let s=jo(r,i.fiberRef);r=us(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case PO:{o=Na(i.first)(Na(i.second)(a));break}}}return r})});var DO,qO;var UO=x(()=>{LO();DO=NO,qO=FO});var Sd="effect/FiberStatus",Bo,xd="Done",$O="Running",HO="Suspended",cD,jO,BO,VO,zO,KO=(e)=>new BO(e),WO=(e,t)=>new VO(e,t),bd=(e)=>N(e,Bo),JO=(e)=>e._tag===xd;var GO=x(()=>{fe();z();Le();we();Bo=Symbol.for(Sd),cD=xe(`${Sd}-${xd}`);jO=class jO{[Bo]=Bo;_tag=xd;[D](){return cD}[L](e){return bd(e)&&e._tag===xd}};BO=class BO{runtimeFlags;[Bo]=Bo;_tag=$O;constructor(e){this.runtimeFlags=e}[D](){return y(I(Sd),Q(I(this._tag)),Q(I(this.runtimeFlags)),le(this))}[L](e){return bd(e)&&e._tag===$O&&this.runtimeFlags===e.runtimeFlags}};VO=class VO{runtimeFlags;blockingOn;[Bo]=Bo;_tag=HO;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[D](){return y(I(Sd),Q(I(this._tag)),Q(I(this.runtimeFlags)),Q(I(this.blockingOn)),le(this))}[L](e){return bd(e)&&e._tag===HO&&this.runtimeFlags===e.runtimeFlags&&P(this.blockingOn,e.blockingOn)}};zO=new jO});var YO,Sy,ZO,XO;var QO=x(()=>{GO();YO=zO,Sy=KO,ZO=WO,XO=JO});var pD,dD,fD,mD,hD,gD,yD,xD,SD,eR,tR=(e)=>{switch(e){case"All":return pD;case"Debug":return gD;case"Error":return fD;case"Fatal":return dD;case"Info":return hD;case"Trace":return yD;case"None":return xD;case"Warning":return mD}};var nR=x(()=>{z();at();Qc();Lu();pD=nE,dD=rE,fD=oE,mD=jg,hD=Bg,gD=Vg,yD=iE,xD=aE,SD=y(mr,Fu((e)=>e.ordinal)),eR=Ym(SD)});function kD(e){return _y("Micro.evaluate: Not implemented")}class Cy{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,LD(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(mR)}flush(){while(this.tasks.length>0)this.runTasks()}}var _D,wd,rR,wD,wy,aR,vD=(e,t=[])=>new aR(e,t),sR,TD=(e=[])=>new sR(e),ED=(e)=>e._tag==="Interrupt",oR,OD,cR,iR,lR,ut,by,ds,ps,vd,_d,RD,CD,Ed=(e)=>({...CD,[lR]:e.op,[by]:e.eval??kD,[ds]:e.contA,[ps]:e.contE,[vd]:e.ensure}),vy=(e)=>{let t=Ed(e);return function(){let n=Object.create(t);return n[ut]=e.single===!1?arguments:arguments[0],n}},uR=(e)=>{let t={...Ed(e),[wd]:wd,_tag:e.op,get[e.prop](){return this[ut]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[ut]}},[L](n){return ND(n)&&n._tag===e.op&&P(this[ut],n[ut])},[D](){return le(this,Q(xe(e.op))(I(this[ut])))}};return function(n){let r=Object.create(t);return r[ut]=n,r[ds]=void 0,r[ps]=void 0,r[vd]=void 0,r}},Ty,pR,AD,ID,PD,Ey,Td,MD,ND=(e)=>N(e,wd),dR,Oy,Ry,_y=(e)=>Oy(vD(e)),FD,LD,DD,fR,mR,Od,qD,UD,$D,hR,HD=(e)=>Ey((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(hR(!1)),t._interrupted)return Ry;return e}),jD=(e)=>Ey((t)=>{if(!t.interruptible)return e(de);return t.interruptible=!1,t._stack.push(hR(!0)),e(HD)}),gR=(e,t)=>{let n=new cR(Od.context(t?.scheduler??new Cy));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 yR=x(()=>{_n();cy();fe();z();Le();Be();ap();Oe();we();xo();_D=Symbol.for("effect/Micro"),wd=Symbol.for("effect/Micro/MicroExit"),rR=Symbol.for("effect/Micro/MicroCause"),wD={_E:de};wy=class wy extends globalThis.Error{_tag;traces;[rR];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 Vn(Va(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,qm),e}(),VT=Symbol.for("effect/Cause/errors/RuntimeException"),lL=ji({[VT]:VT},"RuntimeException"),kg=Symbol.for("effect/Cause/errors/InterruptedException"),EK=ji({[kg]:kg},"InterruptedException"),zT=Symbol.for("effect/Cause/errors/IllegalArgument"),uL=ji({[zT]:zT},"IllegalArgumentException"),WT=Symbol.for("effect/Cause/errors/NoSuchElement"),Gc=ji({[WT]:WT},"NoSuchElementException"),KT=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),RK=ji({[KT]:KT},"InvalidPubSubCapacityException"),JT=Symbol.for("effect/Cause/errors/ExceededCapacityException"),OK=ji({[JT]:JT},"ExceededCapacityException"),GT=Symbol.for("effect/Cause/errors/Timeout"),CK=ji({[GT]:GT},"TimeoutException"),YT=Symbol.for("effect/Cause/errors/UnknownException"),pL=function(){class e extends Kp{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[YT]:YT,name:"UnknownException"}),e}(),yE=d(2,(e,t)=>{switch(e._tag){case Gt:return Ce(e.effect_instruction_i0);case Yt:return Fe(t)}}),Ip=d(2,(e,t)=>{switch(e._tag){case Gt:return Ce(e.effect_instruction_i0);case Yt:return Fe(t(e.effect_instruction_i0))}}),Jp=d(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case Gt:return t(e.effect_instruction_i0);case Yt:return n(e.effect_instruction_i0)}}),En=Fe(void 0),Yg=d(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case Gt:switch(t._tag){case Yt:return Ce(e.effect_instruction_i0);case Gt:return Ce(n(e.effect_instruction_i0,t.effect_instruction_i0))}case Yt:switch(t._tag){case Yt:return Fe(r(e.effect_instruction_i0,t.effect_instruction_i0));case Gt:return Ce(t.effect_instruction_i0)}}}),mL=Tt((e)=>Fe(e.currentContext)),hL=d(2,(e,t)=>Ho(Hi,t)(e)),Zg=d(2,(e,t)=>Vi((n)=>hL(e,t(n))))});var bE,_E;var wE=x(()=>{Wa();bE=yv,_E=Vn});var Xp="And",Qp="Or",ed="InvalidData",td="MissingData",nd="SourceUnavailable",rd="Unsupported";var xL="effect/ConfigError",vE,as,od=(e,t)=>{let n=Object.create(as);return n._op=Xp,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},id=(e,t)=>{let n=Object.create(as);return n._op=Qp,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},Xg=(e,t,n={pathDelim:"."})=>{let r=Object.create(as);return r._op=ed,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${y(this.path,jr(n.pathDelim))}: "${this.message}")`}}),r},fr=(e,t,n={pathDelim:"."})=>{let r=Object.create(as);return r._op=td,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${y(this.path,jr(n.pathDelim))}: "${this.message}")`}}),r},Qg=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(as);return o._op=nd,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${y(this.path,jr(r.pathDelim))}: "${this.message}")`}}),o},ey=(e,t,n={pathDelim:"."})=>{let r=Object.create(as);return r._op=rd,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${y(this.path,jr(n.pathDelim))}: "${this.message}")`}}),r},jo,TE;var ty=x(()=>{Ve();an();W();vE=Symbol.for(xL),as={_tag:"ConfigError",[vE]:vE},jo=d(2,(e,t)=>{switch(e._op){case Xp:return od(jo(e.left,t),jo(e.right,t));case Qp:return id(jo(e.left,t),jo(e.right,t));case ed:return Xg([...t,...e.path],e.message);case td:return fr([...t,...e.path],e.message);case nd:return Qg([...t,...e.path],e.message,e.cause);case rd:return ey([...t,...e.path],e.message)}}),TE=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case Xp:{r.push(a.right),r.push(a.left),o.push(Q({_op:"AndCase"}));break}case Qp:{r.push(a.right),r.push(a.left),o.push(Q({_op:"OrCase"}));break}case ed:{o.push(re(n.invalidDataCase(t,a.path,a.message)));break}case td:{o.push(re(n.missingDataCase(t,a.path,a.message)));break}case nd:{o.push(re(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case rd:{o.push(re(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 SL="effect/Clock",RE,Xc,bL=2147483647,OE,CE,_L,kE,AE=()=>new kE;var ny=x(()=>{_n();Bh();W();at();RE=Symbol.for(SL),Xc=Xt("effect/Clock"),OE={unsafeSchedule(e,t){let n=lp(t);if(n>bL)return go;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},CE=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))}}(),_L=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return CE;let t=CE()-e.bigint();return()=>t+e.bigint()}();kE=class kE{[RE]=RE;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return _L()}currentTimeMillis=V(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=V(()=>this.unsafeCurrentTimeNanos());scheduler(){return he(OE)}sleep(e){return Do((t)=>{let n=OE.unsafeSchedule(()=>t(it),e);return Qr(V(n))})}}});var mr;var Qc=x(()=>{Lu();mr=fw});var ss=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var ry=()=>{};var ME,sd;var NE=x(()=>{Ve();an();W();xp();Ge();ty();ME={_tag:"Empty"},sd=d(2,(e,t)=>{let n=kc(t),r=e;while(tg(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Gr(o.first,Gr(o.second,n.tail));break}case"MapName":{r=Un(r,o.f),n=n.tail;break}case"Nested":{r=Ma(r,o.name),n=n.tail;break}case"Unnested":{if(y(Ur(r),yw(o.name)))r=qn(r),n=n.tail;else return Q(fr(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return re(r)})});var FE="Constant",LE="Fail",DE="Fallback",qE="Described",UE="Lazy",$E="MapOrFail",HE="Nested",jE="Primitive",BE="Redacted",VE="Sequence",zE="HashMap",WE="ZipWith";var cd=(e,t)=>[...e,...t],CL="effect/ConfigProvider",KE,GE,kL="effect/ConfigProviderFlat",JE,AL=(e)=>({[KE]:KE,pipe(){return k(this,arguments)},...e}),IL=(e)=>({[JE]:JE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),PL=(e)=>AL({load:(t)=>J(ln(e,Hr(),t,!1),(n)=>Je(Ur(n),{onNone:()=>yt(fr(Hr(),`Expected a single value having structure: ${t}`)),onSome:he})),flattened:e}),YE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>y(c,jr(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return PL(IL({load:(c,l,u=!0)=>{let p=r(c),f=i(),h=p in f?B(f[p]):F();return y(h,qi(()=>fr(c,`Expected ${p} to exist in the process context`)),J((m)=>UL(m,c,l,n,u)))},enumerateChildren:(c)=>V(()=>{let l=i(),f=Object.keys(l).map((h)=>o(h.toUpperCase())).filter((h)=>{for(let m=0;m<c.length;m++){let S=y(c,th(m)),E=h[m];if(E===void 0||S!==E)return!1}return!0}).flatMap((h)=>h.slice(c.length,c.length+1));return pv(f)}),patch:ME}))},ML=(e,t,n,r)=>{let o=ih(n.length,(c)=>c>=r.length?F():B([e(c),c+1])),i=ih(r.length,(c)=>c>=n.length?F():B([t(c),c+1])),a=cd(n,o),s=cd(r,i);return[a,s]},NL=(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},FL,LL=(e)=>TE(e,void 0,FL),ln=(e,t,n,r)=>{let o=n;switch(o._tag){case FE:return he(At(o.value));case qE:return Me(()=>ln(e,t,o.config,r));case LE:return yt(fr(t,o.message));case DE:return y(Me(()=>ln(e,t,o.first,r)),Uc((i)=>{if(o.condition(i))return y(ln(e,t,o.second,r),Uc((a)=>yt(id(i,a))));return yt(i)}));case UE:return Me(()=>ln(e,t,o.config(),r));case $E:return Me(()=>y(ln(e,t,o.original,r),J(Tn((i)=>y(o.mapOrFail(i),qi(jo(NL(t,o.original))))))));case HE:return Me(()=>ln(e,cd(t,At(o.name)),o.config,r));case jE:return y(sd(t,e.patch),J((i)=>y(e.load(i,o,r),J((a)=>{if(a.length===0){let s=y(Ew(i),Ae(()=>"<n/a>"));return yt(fr([],`Expected ${o.description} with name ${s}`))}return he(a)}))));case BE:return Me(()=>y(ln(e,t,o.original,r),qi(LL),ze(Un(o.redact))));case VE:return y(sd(t,e.patch),J((i)=>y(e.enumerateChildren(i),J(HL),J((a)=>{if(a.length===0)return Me(()=>ze(ln(e,t,o.config,!0),At));return y(Tn(a,(s)=>ln(e,ww(t,`[${s}]`),o.config,!0)),ze((s)=>{let c=Du(s);if(c.length===0)return At(Hr());return At(c)}))}))));case zE:return Me(()=>y(sd(t,e.patch),J((i)=>y(e.enumerateChildren(i),J((a)=>y(a,Tn((s)=>ln(e,cd(i,At(s)),o.valueConfig,r)),ze((s)=>{if(s.length===0)return At(Ya());return y($L(s),Un((c)=>Qv(oh(Pe(a),c))))})))))));case WE:return Me(()=>y(ln(e,t,o.left,r),Li,J((i)=>y(ln(e,t,o.right,r),Li,J((a)=>{if(ke(i)&&ke(a))return yt(od(i.left,a.left));if(ke(i)&&kt(a))return yt(i.left);if(kt(i)&&ke(a))return yt(a.left);if(kt(i)&&kt(a)){let s=y(t,jr(".")),c=DL(t,s),[l,u]=ML(c,c,y(i.right,Un(re)),y(a.right,Un(re)));return y(l,oh(u),Tn(([p,f])=>y($p(p,f),ze(([h,m])=>o.zip(h,m)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},DL=(e,t)=>(n)=>Q(fr(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),qL=(e,t)=>e.split(new RegExp(`\\s*${ss(t)}\\s*`)),UL=(e,t,n,r,o)=>{if(!o)return y(n.parse(e),Dp({onFailure:jo(t),onSuccess:At}));return y(qL(e,r),Tn((i)=>n.parse(i.trim())),qi(jo(t)))},$L=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),HL=(e)=>y(Tn(e,BL),Dp({onFailure:()=>Hr(),onSuccess:$r(mr)}),Li,ze(uw)),jL,BL=(e)=>{let t=e.match(jL);if(t!==null){let n=t[2];return y(n!==void 0&&n.length>0?B(n):F(),Dn(VL))}return F()},VL=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?F():B(t)};var ZE=x(()=>{Ve();_n();an();W();gp();Ci();Qc();Ge();Re();ry();ty();NE();at();KE=Symbol.for(CL),GE=Xt("effect/ConfigProvider"),JE=Symbol.for(kL),FL={andCase:(e,t,n)=>od(t,n),orCase:(e,t,n)=>id(t,n),invalidDataCase:(e,t)=>Xg(t,"<redacted>"),missingDataCase:(e,t)=>fr(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>Qg(t,"<redacted>",r),unsupportedCase:(e,t)=>ey(t,"<redacted>")},jL=/^(\[(\d+)\])$/});var XE,ld,QE;var oy=x(()=>{_n();at();XE=Symbol.for("effect/Console"),ld=Xt("effect/Console"),QE={[XE]:XE,assert(e,...t){return V(()=>{console.assert(e,...t)})},clear:V(()=>{console.clear()}),count(e){return V(()=>{console.count(e)})},countReset(e){return V(()=>{console.countReset(e)})},debug(...e){return V(()=>{console.debug(...e)})},dir(e,t){return V(()=>{console.dir(e,t)})},dirxml(...e){return V(()=>{console.dirxml(...e)})},error(...e){return V(()=>{console.error(...e)})},group(e){return e?.collapsed?V(()=>console.groupCollapsed(e?.label)):V(()=>console.group(e?.label))},groupEnd:V(()=>{console.groupEnd()}),info(...e){return V(()=>{console.info(...e)})},log(...e){return V(()=>{console.log(...e)})},table(e,t){return V(()=>{console.table(e,t)})},time(e){return V(()=>console.time(e))},timeEnd(e){return V(()=>console.timeEnd(e))},timeLog(e,...t){return V(()=>{console.timeLog(e,...t)})},trace(...e){return V(()=>{console.trace(...e)})},warn(...e){return V(()=>{console.warn(...e)})},unsafe:console}});var KL="effect/Random",eR,tR,nR,JL=(e,t)=>Me(()=>y(V(()=>Array.from(e)),J((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return y(r,Di((o)=>y(t(o),ze((i)=>GL(n,o-1,i)))),Xr(Uu(n)))}))),GL=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},rR=(e)=>new nR(I(e));var oR=x(()=>{cr();_n();W();Le();So();at();eR=Symbol.for(KL),tR=Xt("effect/Random");nR=class nR{seed;[eR]=eR;PRNG;constructor(e){this.seed=e,this.PRNG=new Pm(e)}get next(){return V(()=>this.PRNG.number())}get nextBoolean(){return ze(this.next,(e)=>e>0.5)}get nextInt(){return V(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return ze(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return V(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return JL(e,(t)=>this.nextIntBetween(0,t))}}});class sR{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:aR(32),this.spanId=aR(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 iR,ZL=(e)=>({[iR]:iR,...e}),el,ud,aR,cR,lR;var pd=x(()=>{_n();W();iR=Symbol.for("effect/Tracer"),el=Xt("effect/Tracer"),ud=Xt("effect/ParentSpan"),aR=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();cR=ZL({span:(e,t,n,r,o,i)=>new sR(e,t,n,r,o,i),context:(e)=>e()}),lR=Rc()("effect/Tracer/DisablePropagation",{defaultValue:go})});var eD,tl;var uR=x(()=>{_n();W();ny();ZE();at();oy();oR();pd();eD=y(Po(),ur(Xc,AE()),ur(ld,QE),ur(tR,rR(Math.random())),ur(GE,YE()),ur(el,cR)),tl=K(Symbol.for("effect/DefaultServices/currentServices"),()=>Bp(eD))});var nD,pR=(e)=>{let t={BaseEffectError:class extends nD{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var dR=x(()=>{at();nD=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends Kp{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 fR,rD,ay;var sy=x(()=>{Dr();fR=Lr,rD=ew;ay=class ay extends rD{}});var hR="Sequential",gR="Parallel",oD="ParallelN",cs,yR,xR=(e)=>({_tag:oD,parallelism:e}),cy=(e)=>e._tag===hR,ly=(e)=>e._tag===gR;var dd=x(()=>{cs={_tag:hR},yR={_tag:gR}});var fd,md,hd;var SR=x(()=>{dd();fd=cs,md=yR,hd=xR});function bR(e){return new eo(e)}function _R(){return bR(new Map)}var py,eo,aD=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(Oe(i)&&Oe(a)){let l=rt(i)[0],u=qn(i),p=rt(a)[0],f=rt(a)[1],h=qn(a);if(l.startTimeMillis<p.startTimeMillis)a=h,s=!0;else if(l.startTimeMillis>p.startTimeMillis)i=u;else if(l.id<p.id)a=h,s=!0;else if(l.id>p.id)i=u;else c=[f,s]}else c=[o.initial,!0];return c},fy,my,wR=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(P(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},nl,hy,Bo,ls,dy=(e,t,n,r)=>{let o=e.get(n)??[],i;if(Oe(o)){let[a,s]=rt(o);if(a[D](t))if(P(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},vR;var gd=x(()=>{Ve();fe();W();Ge();Re();py=Symbol.for("effect/FiberRefs");eo=class eo{locals;[py]=py;constructor(e){this.locals=e}pipe(){return k(this,arguments)}};fy=d(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][D](t)){if(!r.has(i)){if(P(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=aD(i,s,o);if(l){let u=i.diff(c,a),p=s[0][1],f=i.join(p,i.patch(u)(p));if(!P(p,f)){let h,m=s[0][0];if(m[D](t))h=[[m,f],...s.slice(1)];else h=[[t,f],...s];r.set(i,h)}}}}),new eo(r)}),my=d(2,(e,t)=>{let n=new Map;return wR(e,n,t),new eo(n)}),nl=d(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new eo(n)}),hy=d(2,(e,t)=>{if(!e.locals.has(t))return F();return B(rt(e.locals.get(t))[1])}),Bo=d(2,(e,t)=>y(hy(e,t),Ae(()=>t.initial))),ls=d(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new eo(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return dy(o,t,n,r),new eo(o)}),vR=d(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new eo(new Map(t));let r=new Map(e.locals);if(n!==void 0)wR(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)dy(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{dy(r,a,o,s)})}),new eo(r)})});var TR,ER,RR;var yy=x(()=>{gd();TR=Bo,ER=vR,RR=_R});var CR="Empty",kR="Add",AR="Remove",IR="Update",PR="AndThen",MR,NR=(e,t)=>{let n=new Map(e.locals),r=MR;for(let[o,i]of t.locals.entries()){let a=rt(i)[1],s=n.get(o);if(s!==void 0){let c=rt(s)[1];if(!P(c,a))r=yd({_tag:IR,fiberRef:o,patch:o.diff(c,a)})(r)}else r=yd({_tag:kR,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=yd({_tag:AR,fiberRef:o})(r);return r},yd,FR;var LR=x(()=>{Ve();fe();W();gd();MR={_tag:CR},yd=d(2,(e,t)=>({_tag:PR,first:e,second:t})),FR=d(3,(e,t,n)=>{let r=n,o=At(e);while(Oe(o)){let i=rt(o),a=qn(o);switch(i._tag){case CR:{o=a;break}case kR:{r=ls(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case AR:{r=nl(r,i.fiberRef),o=a;break}case IR:{let s=Bo(r,i.fiberRef);r=ls(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case PR:{o=Ma(i.first)(Ma(i.second)(a));break}}}return r})});var DR,qR;var UR=x(()=>{LR();DR=NR,qR=FR});var Sd="effect/FiberStatus",Vo,xd="Done",$R="Running",HR="Suspended",lD,jR,BR,VR,zR,WR=(e)=>new BR(e),KR=(e,t)=>new VR(e,t),bd=(e)=>N(e,Vo),JR=(e)=>e._tag===xd;var GR=x(()=>{fe();W();Le();we();Vo=Symbol.for(Sd),lD=xe(`${Sd}-${xd}`);jR=class jR{[Vo]=Vo;_tag=xd;[q](){return lD}[D](e){return bd(e)&&e._tag===xd}};BR=class BR{runtimeFlags;[Vo]=Vo;_tag=$R;constructor(e){this.runtimeFlags=e}[q](){return y(I(Sd),te(I(this._tag)),te(I(this.runtimeFlags)),le(this))}[D](e){return bd(e)&&e._tag===$R&&this.runtimeFlags===e.runtimeFlags}};VR=class VR{runtimeFlags;blockingOn;[Vo]=Vo;_tag=HR;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[q](){return y(I(Sd),te(I(this._tag)),te(I(this.runtimeFlags)),te(I(this.blockingOn)),le(this))}[D](e){return bd(e)&&e._tag===HR&&this.runtimeFlags===e.runtimeFlags&&P(this.blockingOn,e.blockingOn)}};zR=new jR});var YR,xy,ZR,XR;var QR=x(()=>{GR();YR=zR,xy=WR,ZR=KR,XR=JR});var dD,fD,mD,hD,gD,yD,xD,SD,bD,eO,tO=(e)=>{switch(e){case"All":return dD;case"Debug":return yD;case"Error":return mD;case"Fatal":return fD;case"Info":return gD;case"Trace":return xD;case"None":return SD;case"Warning":return hD}};var nO=x(()=>{W();at();Qc();Lu();dD=nE,fD=rE,mD=oE,hD=Hg,gD=jg,yD=Bg,xD=iE,SD=aE,bD=y(mr,Fu((e)=>e.ordinal)),eO=Gm(bD)});function AD(e){return by("Micro.evaluate: Not implemented")}class Oy{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,DD(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(mO)}flush(){while(this.tasks.length>0)this.runTasks()}}var wD,wd,rO,vD,_y,aO,TD=(e,t=[])=>new aO(e,t),sO,ED=(e=[])=>new sO(e),RD=(e)=>e._tag==="Interrupt",oO,OD,cO,iO,lO,ut,Sy,ps,us,vd,_d,CD,kD,Ed=(e)=>({...kD,[lO]:e.op,[Sy]:e.eval??AD,[ps]:e.contA,[us]:e.contE,[vd]:e.ensure}),wy=(e)=>{let t=Ed(e);return function(){let n=Object.create(t);return n[ut]=e.single===!1?arguments:arguments[0],n}},uO=(e)=>{let t={...Ed(e),[wd]:wd,_tag:e.op,get[e.prop](){return this[ut]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[ut]}},[D](n){return FD(n)&&n._tag===e.op&&P(this[ut],n[ut])},[q](){return le(this,te(xe(e.op))(I(this[ut])))}};return function(n){let r=Object.create(t);return r[ut]=n,r[ps]=void 0,r[us]=void 0,r[vd]=void 0,r}},vy,pO,ID,PD,MD,Ty,Td,ND,FD=(e)=>N(e,wd),dO,Ey,Ry,by=(e)=>Ey(TD(e)),LD,DD,qD,fO,mO,Rd,UD,$D,HD,hO,jD=(e)=>Ty((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(hO(!1)),t._interrupted)return Ry;return e}),BD=(e)=>Ty((t)=>{if(!t.interruptible)return e(de);return t.interruptible=!1,t._stack.push(hO(!0)),e(jD)}),gO=(e,t)=>{let n=new cO(Rd.context(t?.scheduler??new Oy));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 yO=x(()=>{_n();sy();fe();W();Le();Be();ap();Re();we();So();wD=Symbol.for("effect/Micro"),wd=Symbol.for("effect/Micro/MicroExit"),rO=Symbol.for("effect/Micro/MicroCause"),vD={_E:de};_y=class _y extends globalThis.Error{_tag;traces;[rO];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=Nr(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
28
+ `)}`:`${o}: ${i}`}else o=r,i=Fr(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
29
29
  ${n.join(`
30
- `)}`;super(i);this._tag=e,this.traces=n,this[rR]=wD,this.name=o,this.stack=a}pipe(){return k(this,arguments)}toString(){return this.stack}[ie](){return this.stack}};aR=class aR extends wy{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};sR=class sR extends wy{constructor(e=[]){super("Interrupt","interrupted",e)}};oR=Symbol.for("effect/Micro/MicroFiber"),OD={_A:de,_E:de};cR=class cR{context;interruptible;[oR];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[oR]=OD}getRef(e){return kv(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),Zs;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(Ry)}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===_d)return;let n=iR.interruptChildren&&iR.interruptChildren(this);if(n!==void 0)return this.evaluate(Td(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(Od).shouldYield(this)){t=!0;let r=n;n=Td(ID,()=>r)}if(n=n[by](this),n===_d){let r=this._yielded;if(wd in r)return this._yielded=void 0,r;return _d}}}catch(r){if(!N(n,by))return _y(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return _y(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[vd]&&t[vd](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,_d}children(){return this._children??=new Set}};iR=K("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),lR=Symbol.for("effect/Micro/identifier"),ut=Symbol.for("effect/Micro/args"),by=Symbol.for("effect/Micro/evaluate"),ds=Symbol.for("effect/Micro/successCont"),ps=Symbol.for("effect/Micro/failureCont"),vd=Symbol.for("effect/Micro/ensureCont"),_d=Symbol.for("effect/Micro/Yield"),RD={_A:de,_E:de,_R:de},CD={...fO,_op:"Micro",[_D]:RD,pipe(){return k(this,arguments)},[Symbol.iterator](){return new Ca(new Mr(this))},toJSON(){return{_id:"Micro",op:this[lR],...ut in this?{args:this[ut]}:void 0}},toString(){return Se(this)},[ie](){return Se(this)}};Ty=uR({op:"Success",prop:"value",eval(e){let t=e.getCont(ds);return t?t[ds](this[ut],e):e.yieldWith(this)}}),pR=uR({op:"Failure",prop:"cause",eval(e){let t=e.getCont(ps);while(ED(this[ut])&&t&&e.interruptible)t=e.getCont(ps);return t?t[ps](this[ut],e):e.yieldWith(this)}}),AD=vy({op:"Yield",eval(e){let t=!1;return e.getRef(Od).scheduleTask(()=>{if(t)return;e.evaluate(FD)},this[ut]??0),e.yieldWith(()=>{t=!0})}}),ID=AD(0),PD=Ty(void 0),Ey=vy({op:"WithMicroFiber",eval(e){return this[ut](e)}}),Td=d(2,(e,t)=>{let n=Object.create(MD);return n[ut]=e,n[ds]=t,n}),MD=Ed({op:"OnSuccess",eval(e){return e._stack.push(this),this[ut]}}),dR=Ty,Oy=pR,Ry=Oy(TD()),FD=dR(void 0),LD="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);DD=d(2,(e,t)=>Ey((n)=>{let r=n.context;return n.context=t(r),$D(e,()=>(n.context=r,PD))})),fR=d(2,(e,t)=>DD(e,Ec(t)));mR=class mR extends Oc()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};Od=class Od extends Oc()("effect/Micro/currentScheduler",{defaultValue:()=>new Cy}){};qD=d(2,(e,t)=>{let n=Object.create(UD);return n[ut]=e,n[ds]=t.onSuccess,n[ps]=t.onFailure,n}),UD=Ed({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[ut]}}),$D=d(2,(e,t)=>jD((n)=>qD(n(e),{onFailure:(r)=>Td(t(Oy(r)),()=>pR(r)),onSuccess:(r)=>Td(t(dR(r)),()=>Ty(r))}))),hR=vy({op:"SetInterruptible",ensure(e){if(e.interruptible=this[ut],e._interrupted&&e.interruptible)return()=>Ry}})});class Rd{scheduleDrain;running=!1;tasks=new ky;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 Rd(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new Rd(e),n.set(r,o);return o}}}class ky{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 xR{maxNextTickBeforeTimer;getRunner=Rd.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(zg)?e.getFiberRef(os):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class rl{tasks=new ky;deferred=!1;scheduleTask(e,t,n){if(this.deferred)SR.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(zg)?e.getFiberRef(os):!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 SR,Cd;var kd=x(()=>{at();SR=K(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new xR(2048));Cd=K(Symbol.for("effect/FiberRef/currentScheduler"),()=>Et(SR))});var Ad;var Ay=x(()=>{at();Ad=K(Symbol.for("effect/FiberRef/currentRequestMap"),()=>Et(new Map))});var Iy=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return qi(dE,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var _R=x(()=>{at()});var Py=(e)=>e.replace(/[\s="]/g,"_"),wR=(e)=>(t)=>`${Py(t.label)}=${e-t.startTime}ms`;var vR="effect/MetricLabel",My,TR,ER=(e,t)=>new TR(e,t),WD=(e)=>N(e,My);var OR=x(()=>{fe();Le();Oe();we();My=Symbol.for(vR);TR=class TR{key;value;[My]=My;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=xe(vR+this.key+this.value)}[D](){return this._hash}[L](e){return WD(e)&&this.key===e.key&&this.value===e.value}pipe(){return k(this,arguments)}}});var Ny;var RR=x(()=>{_n();Ge();pd();Ny=Dn((e)=>vc(e.context,lO)?e._tag==="Span"?Ny(e.parent):F():H(e))});var CR;var kR=x(()=>{at();CR=Jg});var Fy="InterruptSignal",Ly="Stateful",Dy="Resume",qy="YieldNow",Id=(e)=>({_tag:"InterruptSignal",cause:e}),fs=(e)=>({_tag:"Stateful",onFiber:e}),Vi=(e)=>({_tag:"Resume",effect:e}),AR=()=>({_tag:"YieldNow"});var QD="effect/FiberScope",Pd,PR,MR,NR=(e)=>new MR(e.id(),e),ol;var Uy=x(()=>{Ya();Pd=Symbol.for(QD);PR=class PR{[Pd]=Pd;fiberId=wn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};MR=class MR{fiberId;parent;[Pd]=Pd;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(fs((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};ol=K(Symbol.for("effect/FiberScope/Global"),()=>new PR)});var nq="effect/Fiber",$y,Hy,rq,oq="effect/Fiber",LR,Md=(e)=>Hp(Hc(e.await),e.inheritAll),iG,Vo="effect/FiberCurrent";var DR=x(()=>{Ya();Ge();Oe();at();Lr();$y=Symbol.for(nq),Hy={_E:(e)=>e,_A:(e)=>e},rq={[$y]:Hy,pipe(){return k(this,arguments)}},LR=Symbol.for(oq),iG={...bo,commit(){return Md(this)},...rq,id:()=>wn,await:zc,children:he([]),inheritAll:zc,poll:he(F()),interruptAsFork:()=>zc}});var aq="effect/Logger",qR,UR,Nd=(e)=>({[qR]:UR,log:e,pipe(){return k(this,arguments)}}),cG,sq,cq=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(sq)?m:e(m),u=(m,S)=>`${Py(m)}=${l(S)}`,p=(m,S)=>" "+u(m,S),f=u("timestamp",o.toISOString());f+=p("level",a.label),f+=p("fiber",mp(i));let h=Qm(s);for(let m=0;m<h.length;m++)f+=p("message",Nr(h[m],t));if(!Rh(r))f+=p("cause",Vn(r,{renderErrorCause:!0}));for(let m of c)f+=" "+wR(o.getTime())(m);for(let[m,S]of n)f+=p(m,Nr(S,t));return f},lq=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,$R,zi,lG,HR,uG,pG;var jR=x(()=>{Ve();z();Be();Oe();Wa();Gh();qR=Symbol.for(aq),UR={_Message:(e)=>e,_Output:(e)=>e},cG={[qR]:UR,log:Zs,pipe(){return k(this,arguments)}},sq=/^[^\s"=]*$/,$R=Nd(cq(lq)),zi={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},lG={None:[],All:[],Trace:[zi.gray],Debug:[zi.blue],Info:[zi.green],Warning:[zi.yellow],Error:[zi.red],Fatal:[zi.bgBrightRed,zi.black]},HR=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,uG=HR&&process.stdout.isTTY===!0,pG=HR||"Deno"in globalThis});var BR="effect/MetricBoundaries",jy,VR,pq=(e)=>N(e,jy),dq=(e)=>{let t=y(e,eh(ot(Number.POSITIVE_INFINITY)),sh);return new VR(t)},zR=(e)=>y(Xm(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),gc,dq);var KR=x(()=>{Ve();cr();fe();z();Le();Oe();we();jy=Symbol.for(BR);VR=class VR{values;[jy]=jy;constructor(e){this.values=e,this._hash=y(xe(BR),Q(on(this.values)))}_hash;[D](){return this._hash}[L](e){return pq(e)&&P(this.values,e.values)}pipe(){return k(this,arguments)}}});var mq="effect/MetricKeyType",WR,JR="effect/MetricKeyType/Counter",By,hq="effect/MetricKeyType/Frequency",gq,yq="effect/MetricKeyType/Gauge",xq,GR="effect/MetricKeyType/Histogram",Vy,Sq="effect/MetricKeyType/Summary",bq,YR,ZR,XR,QR=(e)=>new ZR(e?.incremental??!1,e?.bigint??!1),eC=(e)=>new XR(e),zy=(e)=>N(e,By),tC=(e)=>N(e,gq),nC=(e)=>N(e,xq),Ky=(e)=>N(e,Vy),rC=(e)=>N(e,bq);var Wy=x(()=>{fe();z();Le();Oe();we();WR=Symbol.for(mq),By=Symbol.for(JR),gq=Symbol.for(hq),xq=Symbol.for(yq),Vy=Symbol.for(GR),bq=Symbol.for(Sq),YR={_In:(e)=>e,_Out:(e)=>e};ZR=class ZR{incremental;bigint;[WR]=YR;[By]=By;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=xe(JR)}_hash;[D](){return this._hash}[L](e){return zy(e)}pipe(){return k(this,arguments)}};XR=class XR{boundaries;[WR]=YR;[Vy]=Vy;constructor(e){this.boundaries=e,this._hash=y(xe(GR),Q(I(this.boundaries)))}_hash;[D](){return this._hash}[L](e){return Ky(e)&&P(this.boundaries,e.boundaries)}pipe(){return k(this,arguments)}}});var _q="effect/MetricKey",iC,wq,vq,Fd,Tq=(e)=>N(e,iC),aC=(e,t)=>new Fd(e,QR(t),Dr(t?.description)),sC=(e,t,n)=>new Fd(e,eC(t),Dr(n)),cC;var lC=x(()=>{Ve();fe();z();Le();Ge();Oe();we();Wy();iC=Symbol.for(_q),wq={_Type:(e)=>e},vq=vo(P);Fd=class Fd{name;keyType;description;tags;[iC]=wq;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=y(xe(this.name+this.description),Q(I(this.keyType)),Q(on(this.tags)))}_hash;[D](){return this._hash}[L](e){return Tq(e)&&this.name===e.name&&P(this.keyType,e.keyType)&&P(this.description,e.description)&&vq(this.tags,e.tags)}pipe(){return k(this,arguments)}};cC=d(2,(e,t)=>t.length===0?e:new Fd(e.name,e.keyType,e.description,wo(e.tags,t)))});class pC{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 uC,Oq,Jy,dC=()=>{let e=Object.create(Oq);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},zo,Rq=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[L](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return H(a)}return F()},ms,hs,Cq=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[L](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var fC=x(()=>{fe();z();Le();Be();Ge();Oe();uC=Symbol.for("effect/MutableHashMap"),Oq={[uC]:uC,[Symbol.iterator](){return new Jy(this)},toString(){return Se(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(me)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}};Jy=class Jy{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 pC(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new Jy(this.self)}};zo=d(2,(e,t)=>{if(ic(t)===!1)return e.referential.has(t)?H(e.referential.get(t)):F();let n=t[D](),r=e.buckets.get(n);if(r===void 0)return F();return Rq(e,r,t)}),ms=d(2,(e,t)=>Ie(zo(e,t))),hs=d(3,(e,t,n)=>{if(ic(t)===!1)return e.referential.set(t,n),e;let r=t[D](),o=e.buckets.get(r);if(o===void 0)return e.buckets.set(r,[[t,n]]),e.bucketsSize++,e;return Cq(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var Aq="effect/MetricState",il,mC="effect/MetricState/Counter",Gy,hC="effect/MetricState/Frequency",Yy,gC="effect/MetricState/Gauge",Zy,yC="effect/MetricState/Histogram",Xy,xC="effect/MetricState/Summary",Qy,al,SC,Iq,bC,_C,wC,vC,TC=(e)=>new SC(e),EC=(e)=>new bC(e),OC=(e)=>new _C(e),RC=(e)=>new wC(e.buckets,e.count,e.min,e.max,e.sum),CC=(e)=>new vC(e.error,e.quantiles,e.count,e.min,e.max,e.sum),Pq=(e)=>N(e,Gy),Mq=(e)=>N(e,Yy),Nq=(e)=>N(e,Zy),Fq=(e)=>N(e,Xy),Lq=(e)=>N(e,Qy);var kC=x(()=>{Ve();fe();z();Le();Oe();we();il=Symbol.for(Aq),Gy=Symbol.for(mC),Yy=Symbol.for(hC),Zy=Symbol.for(gC),Xy=Symbol.for(yC),Qy=Symbol.for(xC),al={_A:(e)=>e};SC=class SC{count;[il]=al;[Gy]=Gy;constructor(e){this.count=e}[D](){return y(I(mC),Q(I(this.count)),le(this))}[L](e){return Pq(e)&&this.count===e.count}pipe(){return k(this,arguments)}};Iq=vo(P);bC=class bC{occurrences;[il]=al;[Yy]=Yy;constructor(e){this.occurrences=e}_hash;[D](){return y(xe(hC),Q(on(Pe(this.occurrences.entries()))),le(this))}[L](e){return Mq(e)&&Iq(Pe(this.occurrences.entries()),Pe(e.occurrences.entries()))}pipe(){return k(this,arguments)}};_C=class _C{value;[il]=al;[Zy]=Zy;constructor(e){this.value=e}[D](){return y(I(gC),Q(I(this.value)),le(this))}[L](e){return Nq(e)&&this.value===e.value}pipe(){return k(this,arguments)}};wC=class wC{buckets;count;min;max;sum;[il]=al;[Xy]=Xy;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[D](){return y(I(yC),Q(I(this.buckets)),Q(I(this.count)),Q(I(this.min)),Q(I(this.max)),Q(I(this.sum)),le(this))}[L](e){return Fq(e)&&P(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return k(this,arguments)}};vC=class vC{error;quantiles;count;min;max;sum;[il]=al;[Qy]=Qy;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}[D](){return y(I(xC),Q(I(this.error)),Q(I(this.quantiles)),Q(I(this.count)),Q(I(this.min)),Q(I(this.max)),Q(I(this.sum)),le(this))}[L](e){return Lq(e)&&this.error===e.error&&P(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return k(this,arguments)}}});var qq="effect/MetricHook",Uq,$q,sl=(e)=>({[Uq]:$q,pipe(){return k(this,arguments)},...e}),AC,PC=(e)=>{let t=e.keyType.bigint?AC:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=AC:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return sl({get:()=>TC(t),update:r,modify:r})},MC=(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 sl({get:()=>EC(t),update:n,modify:n})},NC=(e,t)=>{let n=t;return sl({get:()=>OC(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},FC=(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;y(t,Ur(mr),Un((p,f)=>{o[f]=p}));let l=(p)=>{let f=0,h=n;while(f!==h){let m=Math.floor(f+(h-f)/2),S=o[m];if(p<=S)h=m;else f=m;if(h===f+1)if(p<=o[f])h=f;else f=h}if(r[f]=r[f]+1,i=i+1,a=a+p,p<s)s=p;if(p>c)c=p},u=()=>{let p=bi(n),f=0;for(let h=0;h<n;h++){let m=o[h],S=r[h];f=f+S,p[h]=[m,f]}return p};return sl({get:()=>RC({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},LC=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=y(o,Ur(mr)),a=bi(r),s=0,c=0,l=0,u=0,p=0,f=(m)=>{let S=[],E=0;while(E!==r-1){let w=a[E];if(w!=null){let[b,g]=w,O=cp(m-b);if(jv(O,jh)&&Hv(O,n))S.push(g)}E=E+1}return Hq(t,i,Ur(S,mr))},h=(m,S)=>{if(r>0){s=s+1;let E=s%r;a[E]=[S,m]}u=c===0?m:Math.min(u,m),p=c===0?m:Math.max(p,m),c=c+1,l=l+m};return sl({get:()=>CC({error:t,quantiles:f(Date.now()),count:c,min:u,max:p,sum:l}),update:([m,S])=>h(m,S),modify:([m,S])=>h(m,S)})},Hq=(e,t,n)=>{let r=n.length;if(!Re(t))return $r();let o=t[0],i=t.slice(1),a=IC(e,r,F(),0,o,n),s=At(a);return i.forEach((c)=>{s.push(IC(e,r,a.value,a.consumed,c,a.rest))}),Un(s,(c)=>[c.quantile,c.value])},IC=(e,t,n,r,o,i)=>{let a=e,s=t,c=n,l=r,u=o,p=i,f=e,h=t,m=n,S=r,E=o,w=i;while(!0){if(!Re(p))return{quantile:u,value:F(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:H(rh(p)),consumed:l+p.length,rest:[]};let b=rt(p),g=Ow(p,(q)=>q===b),O=u*s,R=a/2*O,C=l+g[0].length,G=Math.abs(C-O);if(C<O-R){f=a,h=s,m=qr(p),S=C,E=u,w=g[1],a=f,s=h,c=m,l=S,u=E,p=w;continue}if(C>O+R){let q=De(c)?H(b):c;return{quantile:u,value:q,consumed:l,rest:p}}switch(c._tag){case"None":{f=a,h=s,m=qr(p),S=C,E=u,w=g[1],a=f,s=h,c=m,l=S,u=E,p=w;continue}case"Some":{let q=Math.abs(O-c.value);if(G<q){f=a,h=s,m=qr(p),S=C,E=u,w=g[1],a=f,s=h,c=m,l=S,u=E,p=w;continue}return{quantile:u,value:H(c.value),consumed:l,rest:p}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var DC=x(()=>{Ve();Vh();z();Qc();Ge();Oe();kC();Uq=Symbol.for(qq),$q={_In:(e)=>e,_Out:(e)=>e},AC=BigInt(0)});var Bq="effect/MetricPair",Vq,zq,qC=(e,t)=>({[Vq]:zq,metricKey:e,metricState:t,pipe(){return k(this,arguments)}});var UC=x(()=>{Oe();Vq=Symbol.for(Bq),zq={_Type:(e)=>e}});var Wq="effect/MetricRegistry",$C,HC,jC=()=>new HC;var BC=x(()=>{z();fC();Ge();DC();Wy();UC();$C=Symbol.for(Wq);HC=class HC{[$C]=$C;map=dC();snapshot(){let e=[];for(let[t,n]of this.map)e.push(qC(t,n.get()));return e}get(e){let t=y(this.map,zo(e),Zt);if(t==null){if(zy(e.keyType))return this.getCounter(e);if(nC(e.keyType))return this.getGauge(e);if(tC(e.keyType))return this.getFrequency(e);if(Ky(e.keyType))return this.getHistogram(e);if(rC(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=y(this.map,zo(e),Zt);if(t==null){let n=PC(e);if(!y(this.map,ms(e)))y(this.map,hs(e,n));t=n}return t}getFrequency(e){let t=y(this.map,zo(e),Zt);if(t==null){let n=MC(e);if(!y(this.map,ms(e)))y(this.map,hs(e,n));t=n}return t}getGauge(e){let t=y(this.map,zo(e),Zt);if(t==null){let n=NC(e,e.keyType.bigint?BigInt(0):0);if(!y(this.map,ms(e)))y(this.map,hs(e,n));t=n}return t}getHistogram(e){let t=y(this.map,zo(e),Zt);if(t==null){let n=FC(e);if(!y(this.map,ms(e)))y(this.map,hs(e,n));t=n}return t}getSummary(e){let t=y(this.map,zo(e),Zt);if(t==null){let n=LC(e);if(!y(this.map,ms(e)))y(this.map,hs(e,n));t=n}return t}}});var Gq="effect/Metric",Yq,Zq,VC,zC=function(e,t,n,r){let o=Object.assign((i)=>qp(i,(a)=>Qq(o,a)),{[Yq]:Zq,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return k(this,arguments)}});return o},cl=(e,t)=>KC(aC(e,t)),KC=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=VC.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=VC.get(cC(e,o)),n.set(o,i),i};return zC(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},WC=(e,t,n)=>KC(sC(e,t,n)),JC,Xq,Qq;var GC=x(()=>{Ve();z();Oe();at();lC();OR();BC();Yq=Symbol.for(Gq),Zq={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},VC=K(Symbol.for("effect/Metric/globalMetricRegistry"),()=>jC()),JC=d(3,(e,t,n)=>Xq(e,[ER(t,n)])),Xq=d(2,(e,t)=>zC(e.keyType,(n,r)=>e.unsafeUpdate(n,wo(t,r)),(n)=>e.unsafeValue(wo(t,n)),(n,r)=>e.unsafeModify(n,wo(t,r)))),Qq=d(2,(e,t)=>qi(Wc,(n)=>B(()=>e.unsafeUpdate(t,n))))});var tU="effect/Request",nU,rU,jG,YC;var ZC=x(()=>{z();Ay();at();Lr();nU=Symbol.for(tU),rU={_E:(e)=>e,_A:(e)=>e},jG={...pc,[nU]:rU},YC=d(2,(e,t)=>qi(Ad,(n)=>B(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,Yp(r.result,t)}})))});var oU="effect/Supervisor",Ld,ex,Dd,qd,tx=(e)=>N(e,Ld)&&rc(e,"Zip"),XC,iU=(e)=>new XC(e),Ki;var Ud=x(()=>{z();we();at();Ld=Symbol.for(oU),ex={_T:(e)=>e};Dd=class Dd{underlying;value0;[Ld]=ex;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 Dd(this,y(this.value,ze(e)))}zip(e){return new qd(this,e)}};qd=class qd{left;right;_tag="Zip";[Ld]=ex;constructor(e,t){this.left=e,this.right=t}get value(){return $p(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 Dd(this,y(this.value,ze(e)))}zip(e){return new qd(this,e)}};XC=class XC{effect;[Ld]=ex;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 Dd(this,y(this.value,ze(e)))}zip(e){return new qd(this,e)}onRun(e,t){return e()}};Ki=K("effect/Supervisor/none",()=>iU(it))});var QC;var ek=x(()=>{vp();QC=No});var tk="Empty",nk="AddSupervisor",rk="RemoveSupervisor",ok="AndThen",gs,$d=(e,t)=>({_tag:ok,first:e,second:t}),sU=(e,t)=>cU(t,ot(e)),cU=(e,t)=>{let n=e,r=t;while($n(r)){let o=Hn(r);switch(o._tag){case tk:{r=jn(r);break}case nk:{n=n.zip(o.supervisor),r=jn(r);break}case rk:{n=rx(n,o.supervisor),r=jn(r);break}case ok:{r=It(o.first)(It(o.second)(jn(r)));break}}}return n},rx=(e,t)=>{if(P(e,t))return Ki;else if(tx(e))return rx(e.left,t).zip(rx(e.right,t));else return e},Hd=(e)=>{if(P(e,Ki))return lr();else if(tx(e))return y(Hd(e.left),zr(Hd(e.right)));else return Ti(e)},lU=(e,t)=>{if(P(e,t))return gs;let n=Hd(e),r=Hd(t),o=y(r,vh(n),Oi(gs,(a,s)=>$d(a,{_tag:nk,supervisor:s}))),i=y(n,vh(r),Oi(gs,(a,s)=>$d(a,{_tag:rk,supervisor:s})));return $d(o,i)},ik;var ak=x(()=>{cr();ek();fe();z();Ri();Ud();gs={_tag:tk},ik=QC({empty:gs,patch:sU,combine:$d,diff:lU})});var SU,sk,bU,_U,wU,ll="Continue",vU="Done",ck="Yield",TU,jd=(e)=>{throw Error(`BUG: FiberRuntime - ${Nr(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},eo,to,ul,EU,OU=(e)=>Li(PT(e),(t)=>Wi(NT(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(jr(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return $o(HU(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),Ad,o)},!1,!1)),RU,Bd,CU,kU=(e)=>Nd((t)=>{let n=TO(t.context,tl);vc(n,ld).unsafe.log(e.log(t))}),AU,IU,PU,pk,dk=(e,t,n)=>Me(()=>{let r=Pe(e),o=Array(r.length);return Uo(Wi(r,(a,s)=>W(t(a,s),(c)=>B(()=>o[s]=c)),n,!1),he(o))}),Wi=(e,t,n,r,o)=>qo((i)=>$g((a)=>Tt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return it;let u=0,p=!1,f=o?Math.min(c.length,o):c.length,h=new Set,m=[],S=()=>h.forEach((q)=>{q.currentScheduler.scheduleTask(()=>{q.unsafeInterruptAsFork(s.id())},0,q)}),E=[],w=[],b=[],g=()=>{let q=m.filter(({exit:Y})=>Y._tag==="Failure").sort((Y,ce)=>Y.index<ce.index?-1:Y.index===ce.index?0:1).map(({exit:Y})=>Y);if(q.length===0)q.push(En);return q},O=(q,Y=!1)=>{let ce=Up(a(q)),oe=NU(ce,s,s.currentRuntimeFlags,ol);return s.currentScheduler.scheduleTask(()=>{if(Y)oe.unsafeInterruptAsFork(s.id());oe.resume(ce)},0,oe),oe},R=()=>{if(!r)l-=c.length,c=[];p=!0,S()},C=n?Ug:Do,G=O(Lo((q)=>{let Y=(oe,Te)=>{if(oe._op==="Blocked")b.push(oe);else if(m.push({index:Te,exit:oe}),oe._op==="Failure"&&!p)R()},ce=()=>{if(c.length>0){let oe=c.pop(),Te=u++,Ut=()=>{let tt=c.pop();return Te=u++,W(Vc(),()=>W(C(i(t(tt,Te))),$t))},$t=(tt)=>{if(c.length>0){if(Y(tt,Te),c.length>0)return Ut()}return he(tt)},Wt=W(C(i(t(oe,Te))),$t),et=O(Wt);if(E.push(et),h.add(et),p)et.currentScheduler.scheduleTask(()=>{et.unsafeInterruptAsFork(s.id())},0,et);et.addObserver((tt)=>{let Ht;if(tt._op==="Failure")Ht=tt;else Ht=tt.effect_instruction_i0;if(w.push(et),h.delete(et),Y(Ht,Te),m.length===l)q(he(Ae(ji(g(),{parallel:!0}),()=>En)));else if(b.length+m.length===l){let Pn=g(),uo=b.map((Mn)=>Mn.effect_instruction_i0).reduce(Rg);q(he(Mp(uo,Wi([Ae(ji(Pn,{parallel:!0}),()=>En),...b.map((Mn)=>Mn.effect_instruction_i1)],(Mn)=>Mn,n,!0,o))))}else ce()})}};for(let oe=0;oe<f;oe++)ce()}));return Xr(rs(Hc(i(Md(G))),Jp({onFailure:(q)=>{R();let Y=b.length+1,ce=Math.min(typeof o==="number"?o:b.length,b.length),oe=Array.from(b);return Lo((Te)=>{let Ut=[],$t=0,Wt=0,et=(Ht,Pn)=>(uo)=>{if(Ut[Ht]=uo,$t++,$t===Y)Te(Fe(Ce(q)));if(oe.length>0&&Pn)tt()},tt=()=>{O(oe.pop(),!0).addObserver(et(Wt,!0)),Wt++};G.addObserver(et(Wt,!1)),Wt++;for(let Ht=0;Ht<ce;Ht++)tt()})},onSuccess:()=>Tn(w,(q)=>q.inheritAll)})))}))),ox=(e,t,n,r)=>Me(()=>{let o=Pe(e),i=Array(o.length);return Uo(Wi(o,(s,c)=>ze(n(s,c),(l)=>i[c]=l),r,!1,t),he(i))}),sx=(e)=>FU(e,ol),MU=(e,t,n,r=null)=>{let o=fk(e,t,n,r);return o.resume(e),o},NU=(e,t,n,r=null)=>fk(e,t,n,r),fk=(e,t,n,r=null)=>{let o=hp(),i=t.getFiberRefs(),a=hy(i,o),s=new Bd(o,a,n),c=jo(a,$i),l=s.currentSupervisor;return l.onStart(c,e,H(t),s),s.addObserver((p)=>l.onEnd(p,s)),(r!==null?r:y(t.getFiberRef(Pp),Ae(()=>t.scope()))).add(n,s),s},FU=(e,t)=>Tt((n,r)=>he(MU(e,n,r.runtimeFlags,t))),ix=(e)=>Bi((t)=>Je(Po(t,pl),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return W(is(n,md),(r)=>cx(e,r))}}})),lk=(e)=>(t)=>Bi((n)=>Je(Po(n,pl),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return W(is(r,hd(e)),(o)=>cx(t,o))}})),ys=(e,t)=>(n)=>Bi((r)=>Je(Po(r,pl),{onNone:()=>n(de),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?ix:e._tag==="Sequential"?ax:lk(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(ix));case"Sequential":return i(n(ax));case"ParallelN":return i(n(lk(o.strategy.parallelism)))}}else return n(de)}})),ax=(e)=>Bi((t)=>Je(Po(t,pl),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return W(is(n,fd),(r)=>cx(e,r))}}})),pl,LU=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},DU,qU=(e=ls)=>{let t=Object.create(DU);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},cx,UU=(e)=>Ui(e,{differ:ik,fork:gs}),uk,$U,mk,HU=(e,t,n)=>$c((r)=>mk(W(sx(Lp(e)),(o)=>Lo((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"&&as(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&np(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(tE(o))}};o.addObserver((l)=>{c.forEach((u)=>u()),i(l)});let c=t.map((l,u)=>{let p=(f)=>{a[u]=f,s()};return l.listeners.addObserver(p),()=>l.listeners.removeObserver(p)});return s(),B(()=>{c.forEach((l)=>l())})})),Me(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return Li(o,(i)=>YC(i.request,Yg(r)))})));var lx=x(()=>{Ve();cr();_n();cy();SO();Ya();xy();UO();QO();z();Ri();Be();nR();yR();Ge();Oe();we();Eg();kd();xo();FT();Wa();ry();Ay();_R();RR();at();uO();iy();dd();DR();gd();Uy();jR();GC();KR();ZC();Dc();Dc();Ud();ak();pd();SU=cl("effect_fiber_started",{incremental:!0}),sk=cl("effect_fiber_active"),bU=cl("effect_fiber_successes",{incremental:!0}),_U=cl("effect_fiber_failures",{incremental:!0}),wU=JC(WC("effect_fiber_lifetimes",zR({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),TU={_E:(e)=>e,_A:(e)=>e},eo=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),to=K("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),ul={[ka]:(e,t,n)=>vt(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>Fe(Fe(n)),[Aa]:(e,t,n)=>vt(()=>t.effect_instruction_i2(n)),[lc]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),Yr(e.currentRuntimeFlags)&&e.isInterrupted())return Ce(e.getInterruptedCause());else return Fe(n)},[Ia]:(e,t,n)=>{if(vt(()=>t.effect_instruction_i2(n)),vt(()=>t.effect_instruction_i0()))return e.pushStack(t),vt(()=>t.effect_instruction_i1());else return it},[Pa]:(e,t,n)=>{while(!0){let r=vt(()=>t.effect_instruction_i0.next(n));if(r.done)return Fe(r.value);let o=Nm(r.value);if(!as(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},EU={[Fy]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),Yr(t)?Ce(r.cause):n),[Dy]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[Ly]:(e,t,n,r)=>(r.onFiber(e,Sy(t)),n),[qy]:(e,t,n,r)=>W(Vc(),()=>n)},RU=uc();Bd=class Bd extends sy{[$y]=Hy;[LR]=TU;_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,bg(n)){let r=this.getFiberRef(Wc);SU.unsafeUpdate(1,r),sk.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return Md(this)}id(){return this._fiberId}resume(e){this.tell(Vi(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(XO(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return NR(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(Jc)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return Me(()=>{let t=xE(this._fiberId);return this.tell(fs((n,r)=>{Yp(t,B(()=>e(n,r)))})),Gp(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return Lo((e)=>{let t=(n)=>e(he(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(fs((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),B(()=>this.tell(fs((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return Tt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=my(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(uk),c=y(Fc(o,s),Tg(Gr),Tg(Op));return Hg(c)})}get poll(){return B(()=>Dr(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return B(()=>this.tell(Id(Bn(e))))}unsafeInterruptAsFork(e){this.tell(Id(Bn(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(uk,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=nl(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=us(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(tl),this.currentTracer=this.currentDefaultServices.unsafeMap.get(el.key),this.currentSupervisor=this.getFiberRef($U),this.currentScheduler=this.getFiberRef(Cd),this.currentContext=this.getFiberRef($i),this.currentSpan=this.currentContext.unsafeMap.get(ud.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=ll,n=globalThis[Vo];globalThis[Vo]=this;try{while(t===ll)t=this._queue.length===0?vU:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Vo]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===ck)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(os),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=EU[r._tag](this,e,n,r)}return n}isInterrupted(){return!tp(this.getFiberRef(Jc))}addInterruptedCause(e){let t=this.getFiberRef(Jc);this.setFiberRef(Jc,Pt(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(Id(Bn(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return Bc({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Xr(r.value.await);else return B(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(bg(this.currentRuntimeFlags)){let t=this.getFiberRef(Wc),n=this.id().startTimeMillis,r=Date.now();switch(wU.unsafeUpdate(r-n,t),sk.unsafeUpdate(-1,t),e._tag){case Yt:{bU.unsafeUpdate(1,t);break}case Gt:{_U.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(mE);if(!Ka(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(PU)}log(e,t,n){let r=Ie(n)?n.value:this.getFiberRef(Kg),o=this.getFiberRef(CU);if(eR(o,r))return;let i=this.getFiberRef(uE),a=this.getFiberRef(lE),s=this.getLoggers(),c=this.getFiberRefs();if(Sc(s)>0){let l=vc(this.getFiberRef(tl),Xc),u=new Date(l.unsafeCurrentTimeMillis());K_(c,()=>{for(let p of s)p.log({fiberId:this.id(),logLevel:r,message:e,cause:t,context:c,spans:i,annotations:a,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case qy:return ck;case Fy:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Ce(e.cause)),this._asyncInterruptor=null;return ll}case Dy:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),ll;case Ly:return e.onFiber(this,this._exitValue!==null?YO:ZO(this.currentRuntimeFlags,this._asyncBlockingOn)),ll;default:return jd(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=Yr(this.currentRuntimeFlags)&&this.isInterrupted()?Ce(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===eo){let o=to.currentOp;if(to.currentOp=null,o._op===Ma)if(CT(this.currentRuntimeFlags))this.tell(AR()),this.tell(Vi(En)),t=null;else t=En;else if(o._op===yi)t=null}else{this.currentRuntimeFlags=y(this.currentRuntimeFlags,yg(Op));let o=this.interruptAllChildren();if(o!==null)t=W(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(Vi(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Vo];globalThis[Vo]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Vo]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(Vi(e))}startFork(e){this.tell(Vi(e))}patchRuntimeFlags(e,t){let n=Lc(e,t);return globalThis[Vo]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(Vi(o))};if(Yr(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(Mt(cn(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!==cc)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==ka&&e._op!==Ia&&e._op!==Pa)return e;e=this.popStack()}}[J_](e){return B(()=>Tc(this.currentContext,e))}["Left"](e){return yt(e.left)}["None"](e){return yt(new Gc)}["Right"](e){return Fe(e.right)}["Some"](e){return Fe(e.value)}["Micro"](e){return qc((t)=>{let n=t,r=gR(fR(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(Fe(o.value));switch(o.cause._tag){case"Interrupt":return n(Ce(Bn(wn)));case"Fail":return n(yt(o.cause.error));case"Die":return n(Fp(o.cause.defect))}}),qc((o)=>{n=(i)=>{o(it)},r.unsafeInterrupt()})})}[Au](e){let t=vt(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in ul))jd(n);return ul[n._op](this,n,t)}else return to.currentOp=Fe(t),eo}[Yt](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in ul))jd(n);return ul[n._op](this,n,t.effect_instruction_i0)}else return to.currentOp=t,eo}[Gt](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case cc:case Aa:if(!(Yr(this.currentRuntimeFlags)&&this.isInterrupted()))return vt(()=>n.effect_instruction_i1(t));else return Ce(op(t));case"OnStep":if(!(Yr(this.currentRuntimeFlags)&&this.isInterrupted()))return Fe(Ce(t));else return Ce(op(t));case lc:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),Yr(this.currentRuntimeFlags)&&this.isInterrupted())return Ce(Pt(t,this.getInterruptedCause()));else return Ce(t);default:jd(n)}else return to.currentOp=Ce(t),eo}[Iu](e){return vt(()=>e.effect_instruction_i0(this,Sy(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=DO(o.refs,t),s=Fc(o.flags,n);return Fe(Mp(e.effect_instruction_i0,Tt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(qO(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=Lc(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return qo((r)=>W(sx(Ig(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return OU(e.effect_instruction_i0)}[Si](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=Lc(n,t);if(Yr(r)&&this.isInterrupted())return Ce(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Fc(r,n);return this.pushStack(new Pg(o,e)),vt(()=>e.effect_instruction_i1(n))}else return En}[ka](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[cc](e){return this.pushStack(e),e.effect_instruction_i0}[Aa](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),to.currentOp=e,eo}[Ma](e){return this._isYielding=!1,to.currentOp=e,eo}[Ia](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return En}[Pa](e){return ul[Pa](this,e,void 0)}[xi](e){return vt(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&RT)!==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=W(Vc({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(RU!==t[Fo]._V){let n=this.getFiberRef(hE);if(n._tag==="Some"){let r=t[Fo]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${uc()}, 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`,Kr,n)}}return this[t._op](t)},this),t===eo){let n=to.currentOp;if(n._op===Ma||n._op===yi)return eo;return to.currentOp=null,n._op===Yt||n._op===Gt?n:Ce(cn(n))}}catch(n){if(t!==eo&&!N(t,"_op")||!(t._op in this))t=Lg(`Not a valid effect: ${Nr(t)}`);else if(gE(n))t=Ce(Pt(cn(n),Bn(wn)));else t=Fp(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};CU=K("effect/FiberRef/currentMinimumLogLevel",()=>Et(tR("Info"))),AU=K(Symbol.for("effect/Logger/defaultLogger"),()=>kU($R)),IU=K(Symbol.for("effect/Logger/tracerLogger"),()=>Nd(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=Ny(Po(jo(n,$i),ud));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=Tc(jo(n,tl),Xc),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=Xv(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=Vn(t,{renderErrorCause:!0});a.value.event(Nr(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),PU=K(Symbol.for("effect/FiberRef/currentLoggers"),()=>sE(Ti(AU,IU))),pk=d((e)=>Am(e[0]),(e,t,n)=>Tt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(fE);if(n?.discard)return Iy(n.concurrency,()=>ys(fd,n?.concurrentFinalizers)((i)=>o?Wi(e,(a,s)=>i(t(a,s)),!0,!1,1):Li(e,(a,s)=>i(t(a,s)))),()=>ys(md,n?.concurrentFinalizers)((i)=>Wi(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>ys(hd(i),n?.concurrentFinalizers)((a)=>Wi(e,(s,c)=>a(t(s,c)),o,!1,i)));return Iy(n?.concurrency,()=>ys(fd,n?.concurrentFinalizers)((i)=>o?ox(e,1,(a,s)=>i(t(a,s)),!0):Tn(e,(a,s)=>i(t(a,s)))),()=>ys(md,n?.concurrentFinalizers)((i)=>dk(e,(a,s)=>i(t(a,s)),o)),(i)=>ys(hd(i),n?.concurrentFinalizers)((a)=>ox(e,i,(s,c)=>a(t(s,c)),o)))})),pl=Xt("effect/Scope"),DU={[Vp]:Vp,[zp]:zp,pipe(){return k(this,arguments)},fork(e){return B(()=>{let t=qU(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),LU(t,(o)=>B(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return Me(()=>{if(this.state._tag==="Closed")return it;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return it;return ly(this.strategy)?y(Tn(t,(n)=>Do(n(e))),W((n)=>y(ji(n),Ln(Yc),Ae(()=>En)))):uy(this.strategy)?y(dk(t,(n)=>Do(n(e)),!1),W((n)=>y(ji(n,{parallel:!0}),Ln(Yc),Ae(()=>En)))):y(ox(t,this.strategy.parallelism,(n)=>Do(n(e)),!1),W((n)=>y(ji(n,{parallel:!0}),Ln(Yc),Ae(()=>En))))})},addFinalizer(e){return Me(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),it})}},cx=d(2,(e,t)=>Xg(e,Ec(Nv(pl,t)))),uk=cE(kT),$U=UU(Ki),mk=d(2,(e,t)=>qo((n)=>vn(n(e),{onFailure:(r)=>vn(t,{onFailure:(o)=>Mt(Pt(r,o)),onSuccess:()=>Mt(r)}),onSuccess:(r)=>Zr(t,r)})))});var gk,yk;var xk=x(()=>{at();gk=Wg,yk=is});class wk{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return k(this,arguments)}}var px=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},Sk,zU,bk,KU=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new bk(e);return Error.stackTraceLimit=t,n},ux,Vd,_k,WU=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new _k(e);return Error.stackTraceLimit=t,n},JU=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return Zc(t.left);case"Right":return Fe(t.right);case"Some":return Fe(t.value);case"None":return Zc(new Gc)}},GU,YU=(e)=>new wk(e.context,e.runtimeFlags,e.fiberRefs),ZU,vk,Tk,Ek;var Ok=x(()=>{_n();fe();Ya();xy();Be();Ge();Oe();kd();xk();Wa();at();dd();lx();Uy();Dc();Ud();Sk=px((e,t,n)=>{let r=hp(),o=[[$i,[[r,e.context]]]];if(n?.scheduler)o.push([Cd,[[r,n.scheduler]]]);let i=EO(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new Bd(r,i,e.runtimeFlags),s=t;if(n?.scope)s=W(yk(n.scope,ls),(l)=>Uo(Kp(l,$c((u)=>P(u,a.id())?it:Kc(a,u))),rs(t,(u)=>gk(l,u))));let c=a.currentSupervisor;if(c!==Ki)c.onStart(e.context,s,F(),a),a.addObserver((l)=>c.onEnd(l,a));if(ol.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),zU=px((e,t)=>{let n=GU(e)(t);if(n._tag==="Failure")throw WU(n.effect_instruction_i0);return n.effect_instruction_i0});bk=class bk 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}};ux=Symbol.for("effect/Runtime/FiberFailure"),Vd=Symbol.for("effect/Runtime/FiberFailure/Cause");_k=class _k extends Error{[ux];[Vd];constructor(e){let t=bc(e)[0];super(t?.message||"An error has occurred");if(this[ux]=ux,this[Vd]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[Vd].toJSON()}}toString(){return"(FiberFailure) "+Vn(this[Vd],{renderErrorCause:!0})}[ie](){return this.toString()}};GU=px((e,t)=>{let n=JU(t);if(n)return n;let r=new rl,o=Sk(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return Gg(Np(KU(o),Zp(o)))});ZU=Sg(Gr,gg,hg),vk=YU({context:Io(),runtimeFlags:ZU,fiberRefs:OO()}),Tk=Sk(vk),Ek=zU(vk)});var Rk,dl,fl,un,Ck,zd,kk,Ji,Kn,Ak,Ik;var Pk=x(()=>{at();lx();Ok();Rk=ts,dl=pk,fl=Me,un=it,Ck=Uc,zd=ze,kk=Di,Ji=Fi,Kn=W,Ak=Tk,Ik=Ek});var dx=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return dx(e,t.from)}},ml=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},fx=(e)=>Array.isArray(e),Nk=(e)=>!Array.isArray(e),Mk=(e)=>`[${sc(e)}]`,Kd=(e)=>fx(e)?e.map(Mk).join(""):Mk(e);var hl=x(()=>{Be()});var Ko=(e,t,n,r)=>{let o=e;if(n&&Re(n))o+=`
31
- at path: ${Kd(n)}`;if(t!==void 0)o+=`
30
+ `)}`;super(i);this._tag=e,this.traces=n,this[rO]=vD,this.name=o,this.stack=a}pipe(){return k(this,arguments)}toString(){return this.stack}[ie](){return this.stack}};aO=class aO extends _y{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};sO=class sO extends _y{constructor(e=[]){super("Interrupt","interrupted",e)}};oO=Symbol.for("effect/Micro/MicroFiber"),OD={_A:de,_E:de};cO=class cO{context;interruptible;[oO];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[oO]=OD}getRef(e){return kv(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),Zs;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(Ry)}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===_d)return;let n=iO.interruptChildren&&iO.interruptChildren(this);if(n!==void 0)return this.evaluate(Td(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(Rd).shouldYield(this)){t=!0;let r=n;n=Td(PD,()=>r)}if(n=n[Sy](this),n===_d){let r=this._yielded;if(wd in r)return this._yielded=void 0,r;return _d}}}catch(r){if(!N(n,Sy))return by(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return by(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[vd]&&t[vd](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,_d}children(){return this._children??=new Set}};iO=K("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),lO=Symbol.for("effect/Micro/identifier"),ut=Symbol.for("effect/Micro/args"),Sy=Symbol.for("effect/Micro/evaluate"),ps=Symbol.for("effect/Micro/successCont"),us=Symbol.for("effect/Micro/failureCont"),vd=Symbol.for("effect/Micro/ensureCont"),_d=Symbol.for("effect/Micro/Yield"),CD={_A:de,_E:de,_R:de},kD={...fR,_op:"Micro",[wD]:CD,pipe(){return k(this,arguments)},[Symbol.iterator](){return new Oa(new Nr(this))},toJSON(){return{_id:"Micro",op:this[lO],...ut in this?{args:this[ut]}:void 0}},toString(){return Se(this)},[ie](){return Se(this)}};vy=uO({op:"Success",prop:"value",eval(e){let t=e.getCont(ps);return t?t[ps](this[ut],e):e.yieldWith(this)}}),pO=uO({op:"Failure",prop:"cause",eval(e){let t=e.getCont(us);while(RD(this[ut])&&t&&e.interruptible)t=e.getCont(us);return t?t[us](this[ut],e):e.yieldWith(this)}}),ID=wy({op:"Yield",eval(e){let t=!1;return e.getRef(Rd).scheduleTask(()=>{if(t)return;e.evaluate(LD)},this[ut]??0),e.yieldWith(()=>{t=!0})}}),PD=ID(0),MD=vy(void 0),Ty=wy({op:"WithMicroFiber",eval(e){return this[ut](e)}}),Td=d(2,(e,t)=>{let n=Object.create(ND);return n[ut]=e,n[ps]=t,n}),ND=Ed({op:"OnSuccess",eval(e){return e._stack.push(this),this[ut]}}),dO=vy,Ey=pO,Ry=Ey(ED()),LD=dO(void 0),DD="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);qD=d(2,(e,t)=>Ty((n)=>{let r=n.context;return n.context=t(r),HD(e,()=>(n.context=r,MD))})),fO=d(2,(e,t)=>qD(e,Ec(t)));mO=class mO extends Rc()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};Rd=class Rd extends Rc()("effect/Micro/currentScheduler",{defaultValue:()=>new Oy}){};UD=d(2,(e,t)=>{let n=Object.create($D);return n[ut]=e,n[ps]=t.onSuccess,n[us]=t.onFailure,n}),$D=Ed({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[ut]}}),HD=d(2,(e,t)=>BD((n)=>UD(n(e),{onFailure:(r)=>Td(t(Ey(r)),()=>pO(r)),onSuccess:(r)=>Td(t(dO(r)),()=>vy(r))}))),hO=wy({op:"SetInterruptible",ensure(e){if(e.interruptible=this[ut],e._interrupted&&e.interruptible)return()=>Ry}})});class Od{scheduleDrain;running=!1;tasks=new Cy;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 Od(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new Od(e),n.set(r,o);return o}}}class Cy{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 xO{maxNextTickBeforeTimer;getRunner=Od.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(Vg)?e.getFiberRef(rs):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class rl{tasks=new Cy;deferred=!1;scheduleTask(e,t,n){if(this.deferred)SO.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(Vg)?e.getFiberRef(rs):!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 SO,Cd;var kd=x(()=>{at();SO=K(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new xO(2048));Cd=K(Symbol.for("effect/FiberRef/currentScheduler"),()=>Et(SO))});var Ad;var ky=x(()=>{at();Ad=K(Symbol.for("effect/FiberRef/currentRequestMap"),()=>Et(new Map))});var Ay=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return Ui(dE,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var _O=x(()=>{at()});var Iy=(e)=>e.replace(/[\s="]/g,"_"),wO=(e)=>(t)=>`${Iy(t.label)}=${e-t.startTime}ms`;var vO="effect/MetricLabel",Py,TO,EO=(e,t)=>new TO(e,t),JD=(e)=>N(e,Py);var RO=x(()=>{fe();Le();Re();we();Py=Symbol.for(vO);TO=class TO{key;value;[Py]=Py;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=xe(vO+this.key+this.value)}[q](){return this._hash}[D](e){return JD(e)&&this.key===e.key&&this.value===e.value}pipe(){return k(this,arguments)}}});var My;var OO=x(()=>{_n();Ge();pd();My=Dn((e)=>vc(e.context,lR)?e._tag==="Span"?My(e.parent):F():B(e))});var CO;var kO=x(()=>{at();CO=Kg});var Ny="InterruptSignal",Fy="Stateful",Ly="Resume",Dy="YieldNow",Id=(e)=>({_tag:"InterruptSignal",cause:e}),ds=(e)=>({_tag:"Stateful",onFiber:e}),zi=(e)=>({_tag:"Resume",effect:e}),AO=()=>({_tag:"YieldNow"});var eq="effect/FiberScope",Pd,PO,MO,NO=(e)=>new MO(e.id(),e),ol;var qy=x(()=>{Ga();Pd=Symbol.for(eq);PO=class PO{[Pd]=Pd;fiberId=wn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};MO=class MO{fiberId;parent;[Pd]=Pd;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(ds((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};ol=K(Symbol.for("effect/FiberScope/Global"),()=>new PO)});var rq="effect/Fiber",Uy,$y,oq,iq="effect/Fiber",LO,Md=(e)=>Hp(Hc(e.await),e.inheritAll),lG,zo="effect/FiberCurrent";var DO=x(()=>{Ga();Ge();Re();at();Dr();Uy=Symbol.for(rq),$y={_E:(e)=>e,_A:(e)=>e},oq={[Uy]:$y,pipe(){return k(this,arguments)}},LO=Symbol.for(iq),lG={..._o,commit(){return Md(this)},...oq,id:()=>wn,await:zc,children:he([]),inheritAll:zc,poll:he(F()),interruptAsFork:()=>zc}});var sq="effect/Logger",qO,UO,Nd=(e)=>({[qO]:UO,log:e,pipe(){return k(this,arguments)}}),dG,cq,lq=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(cq)?m:e(m),u=(m,S)=>`${Iy(m)}=${l(S)}`,p=(m,S)=>" "+u(m,S),f=u("timestamp",o.toISOString());f+=p("level",a.label),f+=p("fiber",mp(i));let h=Xm(s);for(let m=0;m<h.length;m++)f+=p("message",Fr(h[m],t));if(!Rh(r))f+=p("cause",Vn(r,{renderErrorCause:!0}));for(let m of c)f+=" "+wO(o.getTime())(m);for(let[m,S]of n)f+=p(m,Fr(S,t));return f},uq=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,$O,Wi,fG,HO,mG,hG;var jO=x(()=>{Ve();W();Be();Re();Wa();Jh();qO=Symbol.for(sq),UO={_Message:(e)=>e,_Output:(e)=>e},dG={[qO]:UO,log:Zs,pipe(){return k(this,arguments)}},cq=/^[^\s"=]*$/,$O=Nd(lq(uq)),Wi={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},fG={None:[],All:[],Trace:[Wi.gray],Debug:[Wi.blue],Info:[Wi.green],Warning:[Wi.yellow],Error:[Wi.red],Fatal:[Wi.bgBrightRed,Wi.black]},HO=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,mG=HO&&process.stdout.isTTY===!0,hG=HO||"Deno"in globalThis});var BO="effect/MetricBoundaries",Hy,VO,dq=(e)=>N(e,Hy),fq=(e)=>{let t=y(e,Qm(ot(Number.POSITIVE_INFINITY)),ah);return new VO(t)},zO=(e)=>y(Zm(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),gc,fq);var WO=x(()=>{Ve();cr();fe();W();Le();Re();we();Hy=Symbol.for(BO);VO=class VO{values;[Hy]=Hy;constructor(e){this.values=e,this._hash=y(xe(BO),te(on(this.values)))}_hash;[q](){return this._hash}[D](e){return dq(e)&&P(this.values,e.values)}pipe(){return k(this,arguments)}}});var hq="effect/MetricKeyType",KO,JO="effect/MetricKeyType/Counter",jy,gq="effect/MetricKeyType/Frequency",yq,xq="effect/MetricKeyType/Gauge",Sq,GO="effect/MetricKeyType/Histogram",By,bq="effect/MetricKeyType/Summary",_q,YO,ZO,XO,QO=(e)=>new ZO(e?.incremental??!1,e?.bigint??!1),eC=(e)=>new XO(e),Vy=(e)=>N(e,jy),tC=(e)=>N(e,yq),nC=(e)=>N(e,Sq),zy=(e)=>N(e,By),rC=(e)=>N(e,_q);var Wy=x(()=>{fe();W();Le();Re();we();KO=Symbol.for(hq),jy=Symbol.for(JO),yq=Symbol.for(gq),Sq=Symbol.for(xq),By=Symbol.for(GO),_q=Symbol.for(bq),YO={_In:(e)=>e,_Out:(e)=>e};ZO=class ZO{incremental;bigint;[KO]=YO;[jy]=jy;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=xe(JO)}_hash;[q](){return this._hash}[D](e){return Vy(e)}pipe(){return k(this,arguments)}};XO=class XO{boundaries;[KO]=YO;[By]=By;constructor(e){this.boundaries=e,this._hash=y(xe(GO),te(I(this.boundaries)))}_hash;[q](){return this._hash}[D](e){return zy(e)&&P(this.boundaries,e.boundaries)}pipe(){return k(this,arguments)}}});var wq="effect/MetricKey",iC,vq,Tq,Fd,Eq=(e)=>N(e,iC),aC=(e,t)=>new Fd(e,QO(t),qr(t?.description)),sC=(e,t,n)=>new Fd(e,eC(t),qr(n)),cC;var lC=x(()=>{Ve();fe();W();Le();Ge();Re();we();Wy();iC=Symbol.for(wq),vq={_Type:(e)=>e},Tq=To(P);Fd=class Fd{name;keyType;description;tags;[iC]=vq;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=y(xe(this.name+this.description),te(I(this.keyType)),te(on(this.tags)))}_hash;[q](){return this._hash}[D](e){return Eq(e)&&this.name===e.name&&P(this.keyType,e.keyType)&&P(this.description,e.description)&&Tq(this.tags,e.tags)}pipe(){return k(this,arguments)}};cC=d(2,(e,t)=>t.length===0?e:new Fd(e.name,e.keyType,e.description,vo(e.tags,t)))});class pC{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 uC,Oq,Ky,dC=()=>{let e=Object.create(Oq);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},Wo,Cq=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[D](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return B(a)}return F()},fs,ms,kq=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[D](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var fC=x(()=>{fe();W();Le();Be();Ge();Re();uC=Symbol.for("effect/MutableHashMap"),Oq={[uC]:uC,[Symbol.iterator](){return new Ky(this)},toString(){return Se(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(me)}},[ie](){return this.toJSON()},pipe(){return k(this,arguments)}};Ky=class Ky{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 pC(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new Ky(this.self)}};Wo=d(2,(e,t)=>{if(ic(t)===!1)return e.referential.has(t)?B(e.referential.get(t)):F();let n=t[q](),r=e.buckets.get(n);if(r===void 0)return F();return Cq(e,r,t)}),fs=d(2,(e,t)=>Ie(Wo(e,t))),ms=d(3,(e,t,n)=>{if(ic(t)===!1)return e.referential.set(t,n),e;let r=t[q](),o=e.buckets.get(r);if(o===void 0)return e.buckets.set(r,[[t,n]]),e.bucketsSize++,e;return kq(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var Iq="effect/MetricState",il,mC="effect/MetricState/Counter",Jy,hC="effect/MetricState/Frequency",Gy,gC="effect/MetricState/Gauge",Yy,yC="effect/MetricState/Histogram",Zy,xC="effect/MetricState/Summary",Xy,al,SC,Pq,bC,_C,wC,vC,TC=(e)=>new SC(e),EC=(e)=>new bC(e),RC=(e)=>new _C(e),OC=(e)=>new wC(e.buckets,e.count,e.min,e.max,e.sum),CC=(e)=>new vC(e.error,e.quantiles,e.count,e.min,e.max,e.sum),Mq=(e)=>N(e,Jy),Nq=(e)=>N(e,Gy),Fq=(e)=>N(e,Yy),Lq=(e)=>N(e,Zy),Dq=(e)=>N(e,Xy);var kC=x(()=>{Ve();fe();W();Le();Re();we();il=Symbol.for(Iq),Jy=Symbol.for(mC),Gy=Symbol.for(hC),Yy=Symbol.for(gC),Zy=Symbol.for(yC),Xy=Symbol.for(xC),al={_A:(e)=>e};SC=class SC{count;[il]=al;[Jy]=Jy;constructor(e){this.count=e}[q](){return y(I(mC),te(I(this.count)),le(this))}[D](e){return Mq(e)&&this.count===e.count}pipe(){return k(this,arguments)}};Pq=To(P);bC=class bC{occurrences;[il]=al;[Gy]=Gy;constructor(e){this.occurrences=e}_hash;[q](){return y(xe(hC),te(on(Pe(this.occurrences.entries()))),le(this))}[D](e){return Nq(e)&&Pq(Pe(this.occurrences.entries()),Pe(e.occurrences.entries()))}pipe(){return k(this,arguments)}};_C=class _C{value;[il]=al;[Yy]=Yy;constructor(e){this.value=e}[q](){return y(I(gC),te(I(this.value)),le(this))}[D](e){return Fq(e)&&this.value===e.value}pipe(){return k(this,arguments)}};wC=class wC{buckets;count;min;max;sum;[il]=al;[Zy]=Zy;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[q](){return y(I(yC),te(I(this.buckets)),te(I(this.count)),te(I(this.min)),te(I(this.max)),te(I(this.sum)),le(this))}[D](e){return Lq(e)&&P(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return k(this,arguments)}};vC=class vC{error;quantiles;count;min;max;sum;[il]=al;[Xy]=Xy;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}[q](){return y(I(xC),te(I(this.error)),te(I(this.quantiles)),te(I(this.count)),te(I(this.min)),te(I(this.max)),te(I(this.sum)),le(this))}[D](e){return Dq(e)&&this.error===e.error&&P(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return k(this,arguments)}}});var Uq="effect/MetricHook",$q,Hq,sl=(e)=>({[$q]:Hq,pipe(){return k(this,arguments)},...e}),AC,PC=(e)=>{let t=e.keyType.bigint?AC:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=AC:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return sl({get:()=>TC(t),update:r,modify:r})},MC=(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 sl({get:()=>EC(t),update:n,modify:n})},NC=(e,t)=>{let n=t;return sl({get:()=>RC(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},FC=(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;y(t,$r(mr),Un((p,f)=>{o[f]=p}));let l=(p)=>{let f=0,h=n;while(f!==h){let m=Math.floor(f+(h-f)/2),S=o[m];if(p<=S)h=m;else f=m;if(h===f+1)if(p<=o[f])h=f;else f=h}if(r[f]=r[f]+1,i=i+1,a=a+p,p<s)s=p;if(p>c)c=p},u=()=>{let p=_i(n),f=0;for(let h=0;h<n;h++){let m=o[h],S=r[h];f=f+S,p[h]=[m,f]}return p};return sl({get:()=>OC({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},LC=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=y(o,$r(mr)),a=_i(r),s=0,c=0,l=0,u=0,p=0,f=(m)=>{let S=[],E=0;while(E!==r-1){let v=a[E];if(v!=null){let[b,g]=v,R=cp(m-b);if(jv(R,Hh)&&Hv(R,n))S.push(g)}E=E+1}return jq(t,i,$r(S,mr))},h=(m,S)=>{if(r>0){s=s+1;let E=s%r;a[E]=[S,m]}u=c===0?m:Math.min(u,m),p=c===0?m:Math.max(p,m),c=c+1,l=l+m};return sl({get:()=>CC({error:t,quantiles:f(Date.now()),count:c,min:u,max:p,sum:l}),update:([m,S])=>h(m,S),modify:([m,S])=>h(m,S)})},jq=(e,t,n)=>{let r=n.length;if(!Oe(t))return Hr();let o=t[0],i=t.slice(1),a=IC(e,r,F(),0,o,n),s=At(a);return i.forEach((c)=>{s.push(IC(e,r,a.value,a.consumed,c,a.rest))}),Un(s,(c)=>[c.quantile,c.value])},IC=(e,t,n,r,o,i)=>{let a=e,s=t,c=n,l=r,u=o,p=i,f=e,h=t,m=n,S=r,E=o,v=i;while(!0){if(!Oe(p))return{quantile:u,value:F(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:B(nh(p)),consumed:l+p.length,rest:[]};let b=rt(p),g=Rw(p,(U)=>U===b),R=u*s,O=a/2*R,C=l+g[0].length,Y=Math.abs(C-R);if(C<R-O){f=a,h=s,m=Ur(p),S=C,E=u,v=g[1],a=f,s=h,c=m,l=S,u=E,p=v;continue}if(C>R+O){let U=De(c)?B(b):c;return{quantile:u,value:U,consumed:l,rest:p}}switch(c._tag){case"None":{f=a,h=s,m=Ur(p),S=C,E=u,v=g[1],a=f,s=h,c=m,l=S,u=E,p=v;continue}case"Some":{let U=Math.abs(R-c.value);if(Y<U){f=a,h=s,m=Ur(p),S=C,E=u,v=g[1],a=f,s=h,c=m,l=S,u=E,p=v;continue}return{quantile:u,value:B(c.value),consumed:l,rest:p}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var DC=x(()=>{Ve();Bh();W();Qc();Ge();Re();kC();$q=Symbol.for(Uq),Hq={_In:(e)=>e,_Out:(e)=>e},AC=BigInt(0)});var Vq="effect/MetricPair",zq,Wq,qC=(e,t)=>({[zq]:Wq,metricKey:e,metricState:t,pipe(){return k(this,arguments)}});var UC=x(()=>{Re();zq=Symbol.for(Vq),Wq={_Type:(e)=>e}});var Jq="effect/MetricRegistry",$C,HC,jC=()=>new HC;var BC=x(()=>{W();fC();Ge();DC();Wy();UC();$C=Symbol.for(Jq);HC=class HC{[$C]=$C;map=dC();snapshot(){let e=[];for(let[t,n]of this.map)e.push(qC(t,n.get()));return e}get(e){let t=y(this.map,Wo(e),Zt);if(t==null){if(Vy(e.keyType))return this.getCounter(e);if(nC(e.keyType))return this.getGauge(e);if(tC(e.keyType))return this.getFrequency(e);if(zy(e.keyType))return this.getHistogram(e);if(rC(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=y(this.map,Wo(e),Zt);if(t==null){let n=PC(e);if(!y(this.map,fs(e)))y(this.map,ms(e,n));t=n}return t}getFrequency(e){let t=y(this.map,Wo(e),Zt);if(t==null){let n=MC(e);if(!y(this.map,fs(e)))y(this.map,ms(e,n));t=n}return t}getGauge(e){let t=y(this.map,Wo(e),Zt);if(t==null){let n=NC(e,e.keyType.bigint?BigInt(0):0);if(!y(this.map,fs(e)))y(this.map,ms(e,n));t=n}return t}getHistogram(e){let t=y(this.map,Wo(e),Zt);if(t==null){let n=FC(e);if(!y(this.map,fs(e)))y(this.map,ms(e,n));t=n}return t}getSummary(e){let t=y(this.map,Wo(e),Zt);if(t==null){let n=LC(e);if(!y(this.map,fs(e)))y(this.map,ms(e,n));t=n}return t}}});var Yq="effect/Metric",Zq,Xq,VC,zC=function(e,t,n,r){let o=Object.assign((i)=>qp(i,(a)=>eU(o,a)),{[Zq]:Xq,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return k(this,arguments)}});return o},cl=(e,t)=>WC(aC(e,t)),WC=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=VC.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=VC.get(cC(e,o)),n.set(o,i),i};return zC(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},KC=(e,t,n)=>WC(sC(e,t,n)),JC,Qq,eU;var GC=x(()=>{Ve();W();Re();at();lC();RO();BC();Zq=Symbol.for(Yq),Xq={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},VC=K(Symbol.for("effect/Metric/globalMetricRegistry"),()=>jC()),JC=d(3,(e,t,n)=>Qq(e,[EO(t,n)])),Qq=d(2,(e,t)=>zC(e.keyType,(n,r)=>e.unsafeUpdate(n,vo(t,r)),(n)=>e.unsafeValue(vo(t,n)),(n,r)=>e.unsafeModify(n,vo(t,r)))),eU=d(2,(e,t)=>Ui(Kc,(n)=>V(()=>e.unsafeUpdate(t,n))))});var nU="effect/Request",rU,oU,WG,YC;var ZC=x(()=>{W();ky();at();Dr();rU=Symbol.for(nU),oU={_E:(e)=>e,_A:(e)=>e},WG={...pc,[rU]:oU},YC=d(2,(e,t)=>Ui(Ad,(n)=>V(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,Yp(r.result,t)}})))});var iU="effect/Supervisor",Ld,Qy,Dd,qd,ex=(e)=>N(e,Ld)&&rc(e,"Zip"),XC,aU=(e)=>new XC(e),Ki;var Ud=x(()=>{W();we();at();Ld=Symbol.for(iU),Qy={_T:(e)=>e};Dd=class Dd{underlying;value0;[Ld]=Qy;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 Dd(this,y(this.value,ze(e)))}zip(e){return new qd(this,e)}};qd=class qd{left;right;_tag="Zip";[Ld]=Qy;constructor(e,t){this.left=e,this.right=t}get value(){return $p(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 Dd(this,y(this.value,ze(e)))}zip(e){return new qd(this,e)}};XC=class XC{effect;[Ld]=Qy;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 Dd(this,y(this.value,ze(e)))}zip(e){return new qd(this,e)}onRun(e,t){return e()}};Ki=K("effect/Supervisor/none",()=>aU(it))});var QC;var ek=x(()=>{vp();QC=Fo});var tk="Empty",nk="AddSupervisor",rk="RemoveSupervisor",ok="AndThen",hs,$d=(e,t)=>({_tag:ok,first:e,second:t}),cU=(e,t)=>lU(t,ot(e)),lU=(e,t)=>{let n=e,r=t;while($n(r)){let o=Hn(r);switch(o._tag){case tk:{r=jn(r);break}case nk:{n=n.zip(o.supervisor),r=jn(r);break}case rk:{n=nx(n,o.supervisor),r=jn(r);break}case ok:{r=It(o.first)(It(o.second)(jn(r)));break}}}return n},nx=(e,t)=>{if(P(e,t))return Ki;else if(ex(e))return nx(e.left,t).zip(nx(e.right,t));else return e},Hd=(e)=>{if(P(e,Ki))return lr();else if(ex(e))return y(Hd(e.left),Wr(Hd(e.right)));else return Ei(e)},uU=(e,t)=>{if(P(e,t))return hs;let n=Hd(e),r=Hd(t),o=y(r,wh(n),Oi(hs,(a,s)=>$d(a,{_tag:nk,supervisor:s}))),i=y(n,wh(r),Oi(hs,(a,s)=>$d(a,{_tag:rk,supervisor:s})));return $d(o,i)},ik;var ak=x(()=>{cr();ek();fe();W();Ci();Ud();hs={_tag:tk},ik=QC({empty:hs,patch:cU,combine:$d,diff:uU})});var bU,sk,_U,wU,vU,ll="Continue",TU="Done",ck="Yield",EU,jd=(e)=>{throw Error(`BUG: FiberRuntime - ${Fr(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},to,no,ul,RU,OU=(e)=>Di(PT(e),(t)=>Ji(NT(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(Br(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return Ho(jU(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),Ad,o)},!1,!1)),CU,Bd,kU,AU=(e)=>Nd((t)=>{let n=TR(t.context,tl);vc(n,ld).unsafe.log(e.log(t))}),IU,PU,MU,pk,dk=(e,t,n)=>Me(()=>{let r=Pe(e),o=Array(r.length);return $o(Ji(r,(a,s)=>J(t(a,s),(c)=>V(()=>o[s]=c)),n,!1),he(o))}),Ji=(e,t,n,r,o)=>Uo((i)=>Ug((a)=>Tt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return it;let u=0,p=!1,f=o?Math.min(c.length,o):c.length,h=new Set,m=[],S=()=>h.forEach((U)=>{U.currentScheduler.scheduleTask(()=>{U.unsafeInterruptAsFork(s.id())},0,U)}),E=[],v=[],b=[],g=()=>{let U=m.filter(({exit:Z})=>Z._tag==="Failure").sort((Z,ce)=>Z.index<ce.index?-1:Z.index===ce.index?0:1).map(({exit:Z})=>Z);if(U.length===0)U.push(En);return U},R=(U,Z=!1)=>{let ce=Up(a(U)),oe=FU(ce,s,s.currentRuntimeFlags,ol);return s.currentScheduler.scheduleTask(()=>{if(Z)oe.unsafeInterruptAsFork(s.id());oe.resume(ce)},0,oe),oe},O=()=>{if(!r)l-=c.length,c=[];p=!0,S()},C=n?qg:qo,Y=R(Do((U)=>{let Z=(oe,Te)=>{if(oe._op==="Blocked")b.push(oe);else if(m.push({index:Te,exit:oe}),oe._op==="Failure"&&!p)O()},ce=()=>{if(c.length>0){let oe=c.pop(),Te=u++,Ut=()=>{let tt=c.pop();return Te=u++,J(Vc(),()=>J(C(i(t(tt,Te))),$t))},$t=(tt)=>{if(c.length>0){if(Z(tt,Te),c.length>0)return Ut()}return he(tt)},Kt=J(C(i(t(oe,Te))),$t),et=R(Kt);if(E.push(et),h.add(et),p)et.currentScheduler.scheduleTask(()=>{et.unsafeInterruptAsFork(s.id())},0,et);et.addObserver((tt)=>{let Ht;if(tt._op==="Failure")Ht=tt;else Ht=tt.effect_instruction_i0;if(v.push(et),h.delete(et),Z(Ht,Te),m.length===l)U(he(Ae(Bi(g(),{parallel:!0}),()=>En)));else if(b.length+m.length===l){let Pn=g(),po=b.map((Mn)=>Mn.effect_instruction_i0).reduce(Rg);U(he(Mp(po,Ji([Ae(Bi(Pn,{parallel:!0}),()=>En),...b.map((Mn)=>Mn.effect_instruction_i1)],(Mn)=>Mn,n,!0,o))))}else ce()})}};for(let oe=0;oe<f;oe++)ce()}));return Qr(ns(Hc(i(Md(Y))),Jp({onFailure:(U)=>{O();let Z=b.length+1,ce=Math.min(typeof o==="number"?o:b.length,b.length),oe=Array.from(b);return Do((Te)=>{let Ut=[],$t=0,Kt=0,et=(Ht,Pn)=>(po)=>{if(Ut[Ht]=po,$t++,$t===Z)Te(Fe(Ce(U)));if(oe.length>0&&Pn)tt()},tt=()=>{R(oe.pop(),!0).addObserver(et(Kt,!0)),Kt++};Y.addObserver(et(Kt,!1)),Kt++;for(let Ht=0;Ht<ce;Ht++)tt()})},onSuccess:()=>Tn(v,(U)=>U.inheritAll)})))}))),rx=(e,t,n,r)=>Me(()=>{let o=Pe(e),i=Array(o.length);return $o(Ji(o,(s,c)=>ze(n(s,c),(l)=>i[c]=l),r,!1,t),he(i))}),ax=(e)=>LU(e,ol),NU=(e,t,n,r=null)=>{let o=fk(e,t,n,r);return o.resume(e),o},FU=(e,t,n,r=null)=>fk(e,t,n,r),fk=(e,t,n,r=null)=>{let o=hp(),i=t.getFiberRefs(),a=my(i,o),s=new Bd(o,a,n),c=Bo(a,Hi),l=s.currentSupervisor;return l.onStart(c,e,B(t),s),s.addObserver((p)=>l.onEnd(p,s)),(r!==null?r:y(t.getFiberRef(Pp),Ae(()=>t.scope()))).add(n,s),s},LU=(e,t)=>Tt((n,r)=>he(NU(e,n,r.runtimeFlags,t))),ox=(e)=>Vi((t)=>Je(Mo(t,pl),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return J(os(n,md),(r)=>sx(e,r))}}})),lk=(e)=>(t)=>Vi((n)=>Je(Mo(n,pl),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return J(os(r,hd(e)),(o)=>sx(t,o))}})),gs=(e,t)=>(n)=>Vi((r)=>Je(Mo(r,pl),{onNone:()=>n(de),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?ox:e._tag==="Sequential"?ix:lk(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(ox));case"Sequential":return i(n(ix));case"ParallelN":return i(n(lk(o.strategy.parallelism)))}}else return n(de)}})),ix=(e)=>Vi((t)=>Je(Mo(t,pl),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return J(os(n,fd),(r)=>sx(e,r))}}})),pl,DU=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},qU,UU=(e=cs)=>{let t=Object.create(qU);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},sx,$U=(e)=>$i(e,{differ:ik,fork:hs}),uk,HU,mk,jU=(e,t,n)=>$c((r)=>mk(J(ax(Lp(e)),(o)=>Do((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"&&is(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&np(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(tE(o))}};o.addObserver((l)=>{c.forEach((u)=>u()),i(l)});let c=t.map((l,u)=>{let p=(f)=>{a[u]=f,s()};return l.listeners.addObserver(p),()=>l.listeners.removeObserver(p)});return s(),V(()=>{c.forEach((l)=>l())})})),Me(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return Di(o,(i)=>YC(i.request,Gg(r)))})));var cx=x(()=>{Ve();cr();_n();sy();SR();Ga();yy();UR();QR();W();Ci();Be();nO();yO();Ge();Re();we();Tg();kd();So();FT();Wa();ny();ky();_O();OO();at();uR();oy();dd();DO();gd();qy();jO();GC();WO();ZC();Dc();Dc();Ud();ak();pd();bU=cl("effect_fiber_started",{incremental:!0}),sk=cl("effect_fiber_active"),_U=cl("effect_fiber_successes",{incremental:!0}),wU=cl("effect_fiber_failures",{incremental:!0}),vU=JC(KC("effect_fiber_lifetimes",zO({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),EU={_E:(e)=>e,_A:(e)=>e},to=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),no=K("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),ul={[Ca]:(e,t,n)=>vt(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>Fe(Fe(n)),[ka]:(e,t,n)=>vt(()=>t.effect_instruction_i2(n)),[lc]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),Zr(e.currentRuntimeFlags)&&e.isInterrupted())return Ce(e.getInterruptedCause());else return Fe(n)},[Aa]:(e,t,n)=>{if(vt(()=>t.effect_instruction_i2(n)),vt(()=>t.effect_instruction_i0()))return e.pushStack(t),vt(()=>t.effect_instruction_i1());else return it},[Ia]:(e,t,n)=>{while(!0){let r=vt(()=>t.effect_instruction_i0.next(n));if(r.done)return Fe(r.value);let o=Mm(r.value);if(!is(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},RU={[Ny]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),Zr(t)?Ce(r.cause):n),[Ly]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[Fy]:(e,t,n,r)=>(r.onFiber(e,xy(t)),n),[Dy]:(e,t,n,r)=>J(Vc(),()=>n)},CU=uc();Bd=class Bd extends ay{[Uy]=$y;[LO]=EU;_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,Sg(n)){let r=this.getFiberRef(Kc);bU.unsafeUpdate(1,r),sk.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return Md(this)}id(){return this._fiberId}resume(e){this.tell(zi(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(XR(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return NO(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(Jc)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return Me(()=>{let t=xE(this._fiberId);return this.tell(ds((n,r)=>{Yp(t,V(()=>e(n,r)))})),Gp(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return Do((e)=>{let t=(n)=>e(he(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(ds((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),V(()=>this.tell(ds((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return Tt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=fy(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(uk),c=y(Fc(o,s),vg(Yr),vg(Rp));return $g(c)})}get poll(){return V(()=>qr(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return V(()=>this.tell(Id(Bn(e))))}unsafeInterruptAsFork(e){this.tell(Id(Bn(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(uk,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=nl(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=ls(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(tl),this.currentTracer=this.currentDefaultServices.unsafeMap.get(el.key),this.currentSupervisor=this.getFiberRef(HU),this.currentScheduler=this.getFiberRef(Cd),this.currentContext=this.getFiberRef(Hi),this.currentSpan=this.currentContext.unsafeMap.get(ud.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=ll,n=globalThis[zo];globalThis[zo]=this;try{while(t===ll)t=this._queue.length===0?TU:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[zo]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===ck)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(rs),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=RU[r._tag](this,e,n,r)}return n}isInterrupted(){return!tp(this.getFiberRef(Jc))}addInterruptedCause(e){let t=this.getFiberRef(Jc);this.setFiberRef(Jc,Pt(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(Id(Bn(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return Bc({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Qr(r.value.await);else return V(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(Sg(this.currentRuntimeFlags)){let t=this.getFiberRef(Kc),n=this.id().startTimeMillis,r=Date.now();switch(vU.unsafeUpdate(r-n,t),sk.unsafeUpdate(-1,t),e._tag){case Yt:{_U.unsafeUpdate(1,t);break}case Gt:{wU.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(mE);if(!za(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(MU)}log(e,t,n){let r=Ie(n)?n.value:this.getFiberRef(zg),o=this.getFiberRef(kU);if(eO(o,r))return;let i=this.getFiberRef(uE),a=this.getFiberRef(lE),s=this.getLoggers(),c=this.getFiberRefs();if(Sc(s)>0){let l=vc(this.getFiberRef(tl),Xc),u=new Date(l.unsafeCurrentTimeMillis());W_(c,()=>{for(let p of s)p.log({fiberId:this.id(),logLevel:r,message:e,cause:t,context:c,spans:i,annotations:a,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case Dy:return ck;case Ny:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Ce(e.cause)),this._asyncInterruptor=null;return ll}case Ly:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),ll;case Fy:return e.onFiber(this,this._exitValue!==null?YR:ZR(this.currentRuntimeFlags,this._asyncBlockingOn)),ll;default:return jd(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=Zr(this.currentRuntimeFlags)&&this.isInterrupted()?Ce(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===to){let o=no.currentOp;if(no.currentOp=null,o._op===Pa)if(CT(this.currentRuntimeFlags))this.tell(AO()),this.tell(zi(En)),t=null;else t=En;else if(o._op===xi)t=null}else{this.currentRuntimeFlags=y(this.currentRuntimeFlags,gg(Rp));let o=this.interruptAllChildren();if(o!==null)t=J(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(zi(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[zo];globalThis[zo]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[zo]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(zi(e))}startFork(e){this.tell(zi(e))}patchRuntimeFlags(e,t){let n=Lc(e,t);return globalThis[zo]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(zi(o))};if(Zr(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(Mt(cn(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!==cc)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==Ca&&e._op!==Aa&&e._op!==Ia)return e;e=this.popStack()}}[J_](e){return V(()=>Tc(this.currentContext,e))}["Left"](e){return yt(e.left)}["None"](e){return yt(new Gc)}["Right"](e){return Fe(e.right)}["Some"](e){return Fe(e.value)}["Micro"](e){return qc((t)=>{let n=t,r=gO(fO(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(Fe(o.value));switch(o.cause._tag){case"Interrupt":return n(Ce(Bn(wn)));case"Fail":return n(yt(o.cause.error));case"Die":return n(Fp(o.cause.defect))}}),qc((o)=>{n=(i)=>{o(it)},r.unsafeInterrupt()})})}[Au](e){let t=vt(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in ul))jd(n);return ul[n._op](this,n,t)}else return no.currentOp=Fe(t),to}[Yt](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in ul))jd(n);return ul[n._op](this,n,t.effect_instruction_i0)}else return no.currentOp=t,to}[Gt](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case cc:case ka:if(!(Zr(this.currentRuntimeFlags)&&this.isInterrupted()))return vt(()=>n.effect_instruction_i1(t));else return Ce(op(t));case"OnStep":if(!(Zr(this.currentRuntimeFlags)&&this.isInterrupted()))return Fe(Ce(t));else return Ce(op(t));case lc:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),Zr(this.currentRuntimeFlags)&&this.isInterrupted())return Ce(Pt(t,this.getInterruptedCause()));else return Ce(t);default:jd(n)}else return no.currentOp=Ce(t),to}[Iu](e){return vt(()=>e.effect_instruction_i0(this,xy(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=DR(o.refs,t),s=Fc(o.flags,n);return Fe(Mp(e.effect_instruction_i0,Tt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(qR(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=Lc(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return Uo((r)=>J(ax(Ag(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return OU(e.effect_instruction_i0)}[bi](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=Lc(n,t);if(Zr(r)&&this.isInterrupted())return Ce(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Fc(r,n);return this.pushStack(new Ig(o,e)),vt(()=>e.effect_instruction_i1(n))}else return En}[Ca](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[cc](e){return this.pushStack(e),e.effect_instruction_i0}[ka](e){return this.pushStack(e),e.effect_instruction_i0}[xi](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),no.currentOp=e,to}[Pa](e){return this._isYielding=!1,no.currentOp=e,to}[Aa](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return En}[Ia](e){return ul[Ia](this,e,void 0)}[Si](e){return vt(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&OT)!==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=J(Vc({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(CU!==t[Lo]._V){let n=this.getFiberRef(hE);if(n._tag==="Some"){let r=t[Lo]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${uc()}, 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`,Kr,n)}}return this[t._op](t)},this),t===to){let n=no.currentOp;if(n._op===Pa||n._op===xi)return to;return no.currentOp=null,n._op===Yt||n._op===Gt?n:Ce(cn(n))}}catch(n){if(t!==to&&!N(t,"_op")||!(t._op in this))t=Fg(`Not a valid effect: ${Fr(t)}`);else if(gE(n))t=Ce(Pt(cn(n),Bn(wn)));else t=Fp(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};kU=K("effect/FiberRef/currentMinimumLogLevel",()=>Et(tO("Info"))),IU=K(Symbol.for("effect/Logger/defaultLogger"),()=>AU($O)),PU=K(Symbol.for("effect/Logger/tracerLogger"),()=>Nd(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=My(Mo(Bo(n,Hi),ud));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=Tc(Bo(n,tl),Xc),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=Xv(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=Vn(t,{renderErrorCause:!0});a.value.event(Fr(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),MU=K(Symbol.for("effect/FiberRef/currentLoggers"),()=>sE(Ei(IU,PU))),pk=d((e)=>km(e[0]),(e,t,n)=>Tt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(fE);if(n?.discard)return Ay(n.concurrency,()=>gs(fd,n?.concurrentFinalizers)((i)=>o?Ji(e,(a,s)=>i(t(a,s)),!0,!1,1):Di(e,(a,s)=>i(t(a,s)))),()=>gs(md,n?.concurrentFinalizers)((i)=>Ji(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>gs(hd(i),n?.concurrentFinalizers)((a)=>Ji(e,(s,c)=>a(t(s,c)),o,!1,i)));return Ay(n?.concurrency,()=>gs(fd,n?.concurrentFinalizers)((i)=>o?rx(e,1,(a,s)=>i(t(a,s)),!0):Tn(e,(a,s)=>i(t(a,s)))),()=>gs(md,n?.concurrentFinalizers)((i)=>dk(e,(a,s)=>i(t(a,s)),o)),(i)=>gs(hd(i),n?.concurrentFinalizers)((a)=>rx(e,i,(s,c)=>a(t(s,c)),o)))})),pl=Xt("effect/Scope"),qU={[Vp]:Vp,[zp]:zp,pipe(){return k(this,arguments)},fork(e){return V(()=>{let t=UU(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),DU(t,(o)=>V(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return Me(()=>{if(this.state._tag==="Closed")return it;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return it;return cy(this.strategy)?y(Tn(t,(n)=>qo(n(e))),J((n)=>y(Bi(n),Ln(Yc),Ae(()=>En)))):ly(this.strategy)?y(dk(t,(n)=>qo(n(e)),!1),J((n)=>y(Bi(n,{parallel:!0}),Ln(Yc),Ae(()=>En)))):y(rx(t,this.strategy.parallelism,(n)=>qo(n(e)),!1),J((n)=>y(Bi(n,{parallel:!0}),Ln(Yc),Ae(()=>En))))})},addFinalizer(e){return Me(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),it})}},sx=d(2,(e,t)=>Zg(e,Ec(Nv(pl,t)))),uk=cE(kT),HU=$U(Ki),mk=d(2,(e,t)=>Uo((n)=>vn(n(e),{onFailure:(r)=>vn(t,{onFailure:(o)=>Mt(Pt(r,o)),onSuccess:()=>Mt(r)}),onSuccess:(r)=>Xr(t,r)})))});var gk,yk;var xk=x(()=>{at();gk=Wg,yk=os});class wk{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return k(this,arguments)}}var ux=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},Sk,WU,bk,KU=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new bk(e);return Error.stackTraceLimit=t,n},lx,Vd,_k,JU=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new _k(e);return Error.stackTraceLimit=t,n},GU=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return Zc(t.left);case"Right":return Fe(t.right);case"Some":return Fe(t.value);case"None":return Zc(new Gc)}},YU,ZU=(e)=>new wk(e.context,e.runtimeFlags,e.fiberRefs),XU,vk,Tk,Ek;var Rk=x(()=>{_n();fe();Ga();yy();Be();Ge();Re();kd();xk();Wa();at();dd();cx();qy();Dc();Ud();Sk=ux((e,t,n)=>{let r=hp(),o=[[Hi,[[r,e.context]]]];if(n?.scheduler)o.push([Cd,[[r,n.scheduler]]]);let i=ER(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new Bd(r,i,e.runtimeFlags),s=t;if(n?.scope)s=J(yk(n.scope,cs),(l)=>$o(Wp(l,$c((u)=>P(u,a.id())?it:Wc(a,u))),ns(t,(u)=>gk(l,u))));let c=a.currentSupervisor;if(c!==Ki)c.onStart(e.context,s,F(),a),a.addObserver((l)=>c.onEnd(l,a));if(ol.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),WU=ux((e,t)=>{let n=YU(e)(t);if(n._tag==="Failure")throw JU(n.effect_instruction_i0);return n.effect_instruction_i0});bk=class bk 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}};lx=Symbol.for("effect/Runtime/FiberFailure"),Vd=Symbol.for("effect/Runtime/FiberFailure/Cause");_k=class _k extends Error{[lx];[Vd];constructor(e){let t=bc(e)[0];super(t?.message||"An error has occurred");if(this[lx]=lx,this[Vd]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[Vd].toJSON()}}toString(){return"(FiberFailure) "+Vn(this[Vd],{renderErrorCause:!0})}[ie](){return this.toString()}};YU=ux((e,t)=>{let n=GU(t);if(n)return n;let r=new rl,o=Sk(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return Jg(Np(KU(o),Zp(o)))});XU=xg(Yr,hg,mg),vk=ZU({context:Po(),runtimeFlags:XU,fiberRefs:RR()}),Tk=Sk(vk),Ek=WU(vk)});var Ok,dl,fl,un,Ck,zd,kk,Gi,Wn,Ak,Ik;var Pk=x(()=>{at();cx();Rk();Ok=es,dl=pk,fl=Me,un=it,Ck=Uc,zd=ze,kk=qi,Gi=Li,Wn=J,Ak=Tk,Ik=Ek});var px=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return px(e,t.from)}},ml=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},dx=(e)=>Array.isArray(e),Nk=(e)=>!Array.isArray(e),Mk=(e)=>`[${sc(e)}]`,Wd=(e)=>dx(e)?e.map(Mk).join(""):Mk(e);var hl=x(()=>{Be()});var Ko=(e,t,n,r)=>{let o=e;if(n&&Oe(n))o+=`
31
+ at path: ${Wd(n)}`;if(t!==void 0)o+=`
32
32
  details: ${t}`;if(r)o+=`
33
- schema (${r._tag}): ${r}`;return o},Fk=(e)=>Ko("Invalid Argument",e),Lk=(e)=>Ko("Unsupported key schema",void 0,void 0,e),Dk=(e)=>Ko("Unsupported literal",`literal value: ${ar(e)}`),mx=(e)=>Ko("Duplicate index signature",`${e} index signature`),qk,Uk,hx=(e)=>Ko("Duplicate property signature transformation",`Duplicate key ${ar(e)}`),gx=(e)=>Ko("Duplicate property signature",`Duplicate key ${ar(e)}`);var yx=x(()=>{Ve();Be();hl();qk=Ko("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),Uk=Ko("Invalid element","A required element cannot follow an optional element. ts(1257)")});var Hk,jk,Bk,Vk,zk,Kk,Wk;var Jk=x(()=>{Hk=Symbol.for("effect/SchemaId/DateFromSelf"),jk=Symbol.for("effect/SchemaId/GreaterThan"),Bk=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),Vk=Symbol.for("effect/SchemaId/Int"),zk=Symbol.for("effect/SchemaId/MinLength"),Kk=Symbol.for("effect/SchemaId/MaxLength"),Wk=Symbol.for("effect/SchemaId/MinItems")});class xs{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 Ae(gr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Gi{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Ae(gr(this),()=>ar(this.literal))}toJSON(){return{_tag:this._tag,literal:go(this.literal)?String(this.literal):this.literal,annotations:He(this.annotations)}}}class Xd{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Ae(gr(this),()=>ar(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:He(this.annotations)}}}class sA{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class cA{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class lA{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class uA{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class pA{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class fA{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class hA{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class yA{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class SA{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class bA{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class wA{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return Wn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class Ss{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:He(this.annotations)}}toString(){return String(this.type)}}class xl{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(Uk)}toString(){return Ae(gr(this),()=>c2(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:He(this.annotations)}}}class bs{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,TA(e))this.parameter=e;else throw Error(qk)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class yr{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(gx(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=Gx(t[i].parameter);if(tf(a)){if(o.string)throw Error(mx("string"));o.string=!0}else if(_A(a)){if(o.symbol)throw Error(mx("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Ae(gr(this),()=>l2(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Vt{types;annotations;static make=(e,t)=>nf(e)?new Vt(e,t):e.length===1?e[0]:ef;static unify=(e,t)=>Vt.make(d2(EA(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Ae(gr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class rf{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=ml(e)}toString(){return gr(this).pipe(Fn(()=>Dn(hw(this.f)(),(e)=>gr(e))),Ae(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=xx.get(e);if(t)return t;return xx.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:He(this.annotations)},xx.set(e,t),t}}class Sl{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return gl(this).pipe(Ae(()=>Je(AA(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>bl(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:He(this.annotations)}}}class Vx{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 Ae(gr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:He(this.annotations)}}}class zx{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class Kx{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(hx(o));t[o]=!0;let i=r.to;if(n[i])throw Error(hx(i));n[i]=!0}}}function On(e,t){let n=!1,r=bi(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 y2(e){return Je(Fx(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${ar(n)}>`).join("")})}var Yk,bx,Zk,_x,Jd,Gd,Qt,Yd,no,wx,vx,Tx,Ex,Ox,Rx,Xk,Cx,kx,Ax,Ix,Px,Mx,Nx,Nt,Fx,Qk,eA,Lx,Dx,gl,qx,tA,nA,rA,oA,iA,Ux,t2,$x=(e)=>xw(t2(e),(t)=>t===!0),Hx,n2,r2=(e)=>Fn(n2(e),()=>gl(e)),yl=(e)=>(t)=>t._tag===e,Zd,aA,Qd,o2,ef,jx,dA,mA,tf,gA,xA,i2,a2,_A,s2,Wo,vA=(e)=>e.map((t)=>t.type),c2=(e)=>{let t=e.elements.map(String).join(", ");return _w(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}>`}})},dt,TA=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return TA(e.from)}return!1},Gk=(e)=>e.map(String).join("; "),l2=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${Gk(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${Gk(e.indexSignatures)} }`;else return"{}"},u2,p2,EA=(e)=>mc(e,(t)=>Bx(t)?EA(t.types):[t]),d2=(e)=>{let t=u2(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[dA];case"UnknownKeyword":return[jx];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=p2[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},OA=(e,t)=>e.map(t),nf=(e)=>e.length>1,Bx,xx,bl,of,_l=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[Gd];let o={...r,...t},i=Ux(e);if(Ie(i))o[Mx]=_l(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},f2="[\\s\\S]*?",m2="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",RA=(e,t)=>{switch(e._tag){case"Literal":return cs(String(e.literal));case"StringKeyword":return f2;case"NumberKeyword":return m2;case"TemplateLiteral":return CA(e,t,!1);case"Union":return e.types.map((n)=>RA(n,t)).join("|")}},h2=(e,t,n,r)=>{if(Bx(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},CA=(e,t,n)=>{let r="";if(e.head!==""){let o=cs(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=RA(o.type,t);if(r+=h2(o.type,i,t,n),o.literal!==""){let a=cs(o.literal);r+=t&&n?`(${a})`:a}}return r},kA=(e)=>new RegExp(`^${CA(e,!1,!0)}$`),Wx=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new bs(i,t,!0));break;case"Literal":if(wt(i.literal)||rn(i.literal))n.push(new dt(i.literal,t,!1,!0));else throw Error(Dk(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new dt(s,t,!1,!0));break}case"UniqueSymbol":n.push(new dt(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(Lk(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},Jx=(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},g2,pt=(e)=>{switch(e._tag){case"Declaration":{let t=On(e.typeParameters,pt);return t===e.typeParameters?e:new xs(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=On(e.elements,(o)=>{let i=pt(o.type);return i===o.type?o:new Wo(i,o.isOptional)}),n=vA(e.rest),r=On(n,pt);return t===e.elements&&r===n?e:new xl(t,r.map((o)=>new Ss(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=On(e.propertySignatures,(r)=>{let o=pt(r.type);return o===r.type?r:new dt(r.name,o,r.isOptional,r.isReadonly)}),n=On(e.indexSignatures,(r)=>{let o=pt(r.type);return o===r.type?r:new bs(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new yr(t,n,e.annotations)}case"Union":{let t=On(e.types,pt);return t===e.types?e:Vt.make(t,e.annotations)}case"Suspend":return new rf(()=>pt(e.f()),e.annotations);case"Refinement":{let t=pt(e.from);return t===e.from?e:new Sl(t,e.filter,e.annotations)}case"Transformation":{let t=g2(e);return pt(t!==void 0?_l(e.to,t):e.to)}}return e},Sx=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return Sx(e.from);case"Suspend":return Sx(e.f())}},hr=(e,t)=>{switch(e._tag){case"Declaration":{let n=On(e.typeParameters,(r)=>hr(r,t));return n===e.typeParameters?e:new xs(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=On(e.elements,(i)=>{let a=hr(i.type,t);return a===i.type?i:new Wo(a,i.isOptional)}),r=vA(e.rest),o=On(r,(i)=>hr(i,t));return n===e.elements&&o===r?e:new xl(n,o.map((i)=>new Ss(i)),e.isReadonly)}case"TypeLiteral":{let n=On(e.propertySignatures,(o)=>{let i=hr(o.type,t);return i===o.type?o:new dt(o.name,i,o.isOptional,o.isReadonly)}),r=On(e.indexSignatures,(o)=>{let i=hr(o.type,t);return i===o.type?o:new bs(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new yr(n,r)}case"Union":{let n=On(e.types,(r)=>hr(r,t));return n===e.types?e:Vt.make(n)}case"Suspend":{let n=void 0,r=r2(e);if(Ie(r)){let o=t?"Bound":"";n={[Hx]:`${r.value}Encoded${o}`}}return new rf(()=>hr(e.f(),t),n)}case"Refinement":{let n=hr(e.from,t);if(t){if(n===e.from)return e;if(Sx(e.from)===void 0&&$x(e))return new Sl(n,e.filter,e.annotations);return n}else return n}case"Transformation":return hr(e.from,t)}return e},af=(e)=>hr(e,!1),He=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},Gx=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return Gx(e.from)}},Wn=(e)=>Ae(gr(e),()=>e._tag),AA=(e)=>Lx(e).pipe(Fn(()=>qx(e)),Fn(()=>Dx(e)),Ln((t)=>t+y2(e))),gr=(e)=>Fn(gl(e),()=>AA(e));var Yx=x(()=>{Ve();z();Be();yx();hl();Qc();Ge();Lu();we();oy();Yk=Symbol.for("effect/annotation/TypeConstructor"),bx=Symbol.for("effect/annotation/Brand"),Zk=Symbol.for("effect/annotation/SchemaId"),_x=Symbol.for("effect/annotation/Message"),Jd=Symbol.for("effect/annotation/MissingMessage"),Gd=Symbol.for("effect/annotation/Identifier"),Qt=Symbol.for("effect/annotation/Title"),Yd=Symbol.for("effect/annotation/AutoTitle"),no=Symbol.for("effect/annotation/Description"),wx=Symbol.for("effect/annotation/Examples"),vx=Symbol.for("effect/annotation/Default"),Tx=Symbol.for("effect/annotation/JSONSchema"),Ex=Symbol.for("effect/annotation/Arbitrary"),Ox=Symbol.for("effect/annotation/Pretty"),Rx=Symbol.for("effect/annotation/Equivalence"),Xk=Symbol.for("effect/annotation/Documentation"),Cx=Symbol.for("effect/annotation/Concurrency"),kx=Symbol.for("effect/annotation/Batching"),Ax=Symbol.for("effect/annotation/ParseIssueTitle"),Ix=Symbol.for("effect/annotation/ParseOptions"),Px=Symbol.for("effect/annotation/DecodingFallback"),Mx=Symbol.for("effect/annotation/Surrogate"),Nx=Symbol.for("effect/annotation/StableFilter"),Nt=d(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?H(e.annotations[t]):F()),Fx=Nt(bx),Qk=Nt(_x),eA=Nt(Jd),Lx=Nt(Qt),Dx=Nt(Yd),gl=Nt(Gd),qx=Nt(no),tA=Nt(Cx),nA=Nt(kx),rA=Nt(Ax),oA=Nt(Ix),iA=Nt(Px),Ux=Nt(Mx),t2=Nt(Nx),Hx=Symbol.for("effect/annotation/JSONIdentifier"),n2=Nt(Hx);Zd=yl("Literal"),aA=new Gi(null);Qd=new sA({[Qt]:"undefined"});o2=new cA({[Qt]:"void"});ef=new lA({[Qt]:"never"});jx=new uA({[Qt]:"unknown"});dA=new pA({[Qt]:"any"});mA=new fA({[Qt]:"string",[no]:"a string"}),tf=yl("StringKeyword");gA=new hA({[Qt]:"number",[no]:"a number"});xA=new yA({[Qt]:"boolean",[no]:"a boolean"});i2=new SA({[Qt]:"bigint",[no]:"a bigint"});a2=new bA({[Qt]:"symbol",[no]:"a symbol"}),_A=yl("SymbolKeyword");s2=new wA({[Qt]:"object",[no]:"an object in the TypeScript meaning, i.e. the `object` type"});Wo=class Wo extends Ss{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:He(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};dt=class dt extends Wo{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:He(this.annotations)}}};u2=Ur(Fu(mr,(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})),p2={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};Bx=yl("Union"),xx=K(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);bl=yl("Refinement"),of={};g2=Jx([wx,vx,Tx,Ex,Ox,Rx])});class ft{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class Qx{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class _s{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class je{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class cf{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class lf{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Rn{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class eS{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function Jn(e){return e.sort(w2).map((t)=>t[1])}function C2(e){return qx(e).pipe(Fn(()=>Lx(e)),Fn(()=>Dx(e)),Fn(()=>gl(e)),Ae(()=>`{ ${e.from} | filter }`))}function k2(e){if(e.message!==void 0)return e.message;return`Expected ${bl(e.ast)?C2(e.ast):String(e.ast)}, actual ${ar(e.actual)}`}var PA,FA,nS=(e)=>new FA({issue:e}),LA,DA,tn,ro,Gn,uf,qA,UA=(e,t)=>{if(t===void 0||rn(t))return e;if(e===void 0)return t;return{...e,...t}},$A=(e,t,n)=>{let r=Ft(e,t);return(o,i)=>r(o,UA(n,i))},x2=(e,t,n)=>{let r=$A(e,t,n);return(o,i)=>Jm(r(o,i),nS)},HA=(e,t)=>$A(e.ast,!0,t),pf=(e,t)=>x2(pt(e.ast),!0,t),S2,b2,Ft=(e,t)=>{let n=t?S2:b2,r=n.get(e);if(r)return r;let o=_2(e,t),i=oA(e),a=Ie(i)?(l,u)=>o(l,UA(u,i.value)):o,s=iA(e),c=t&&Ie(s)?(l,u)=>vl(qA(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},Zx=(e)=>Zt(tA(e)),Xx=(e)=>Zt(nA(e)),_2=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=Ft(e.from,!0);return(r,o)=>{o=o??of;let i=o?.errors==="all",a=ro(qA(n(r,o),(s)=>{let c=new cf(e,r,"From",s);if(i&&$x(e)&&KA(s))return Je(e.filter(r,o,e),{onNone:()=>X(c),onSome:(l)=>X(new je(e,r,[c,new cf(e,r,"Predicate",l)]))});return X(c)}),(s)=>Je(e.filter(s,o,e),{onNone:()=>ne(s),onSome:(c)=>X(new cf(e,r,"Predicate",c))}));return vl(a,e,r,o)}}else{let n=Ft(pt(e),!0),r=Ft(BA(e.from),!1);return(o,i)=>vl(ro(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=v2(e.transformation,t),r=t?Ft(e.from,!0):Ft(e.to,!1),o=t?Ft(e.to,!0):Ft(e.from,!1);return(i,a)=>vl(ro(uf(r(i,a),(s)=>new lf(e,i,t?"Encoded":"Type",s)),(s)=>ro(uf(n(s,a??of,e,i),(c)=>new lf(e,i,"Transformation",c)),(c)=>uf(o(c,a),(l)=>new lf(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)=>vl(n(r,o??of,e),e,r,o)}case"Literal":return en(e,(n)=>n===e.literal);case"UniqueSymbol":return en(e,(n)=>n===e.symbol);case"UndefinedKeyword":return en(e,U_);case"NeverKeyword":return en(e,$_);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return ne;case"StringKeyword":return en(e,wt);case"NumberKeyword":return en(e,rn);case"BooleanKeyword":return en(e,pi);case"BigIntKeyword":return en(e,go);case"SymbolKeyword":return en(e,di);case"ObjectKeyword":return en(e,Bt);case"Enums":return en(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>tf(r.type)))return en(e,(r)=>{if(!wt(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=kA(e);return en(e,(r)=>wt(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>Ft(l.type,t)),r=e.rest.map((l)=>Ft(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=Zx(e),c=Xx(e);return(l,u)=>{if(!th(l))return X(new Rn(e,l));let p=u?.errors==="all",f=[],h=0,m=[],S=l.length;for(let g=S;g<=i-1;g++){let O=new ft(g,l,new _s(o[g-S]));if(p){f.push([h++,O]);continue}else return X(new je(e,l,O,m))}if(e.rest.length===0)for(let g=e.elements.length;g<=S-1;g++){let O=new ft(g,l,new Qx(l[g],`is unexpected, expected: ${a}`));if(p){f.push([h++,O]);continue}else return X(new je(e,l,O,m))}let E=0,w=void 0;for(;E<n.length;E++)if(S<E+1){if(e.elements[E].isOptional)continue}else{let g=n[E],O=g(l[E],u);if(tn(O)){if(ke(O)){let R=new ft(E,l,O.left);if(p){f.push([h++,R]);continue}else return X(new je(e,l,R,Jn(m)))}m.push([h++,O.right])}else{let R=h++,C=E;if(!w)w=[];w.push(({es:G,output:q})=>Kn(Ji(O),(Y)=>{if(ke(Y)){let ce=new ft(C,l,Y.left);if(p)return G.push([R,ce]),un;else return X(new je(e,l,ce,Jn(q)))}return q.push([R,Y.right]),un}))}}if(Re(r)){let[g,...O]=r;for(;E<S-O.length;E++){let R=g(l[E],u);if(tn(R))if(ke(R)){let C=new ft(E,l,R.left);if(p){f.push([h++,C]);continue}else return X(new je(e,l,C,Jn(m)))}else m.push([h++,R.right]);else{let C=h++,G=E;if(!w)w=[];w.push(({es:q,output:Y})=>Kn(Ji(R),(ce)=>{if(ke(ce)){let oe=new ft(G,l,ce.left);if(p)return q.push([C,oe]),un;else return X(new je(e,l,oe,Jn(Y)))}else return Y.push([C,ce.right]),un}))}}for(let R=0;R<O.length;R++){let C=E+R;if(S<C+1)continue;else{let G=O[R](l[C],u);if(tn(G)){if(ke(G)){let q=new ft(C,l,G.left);if(p){f.push([h++,q]);continue}else return X(new je(e,l,q,Jn(m)))}m.push([h++,G.right])}else{let q=h++;if(!w)w=[];w.push(({es:Y,output:ce})=>Kn(Ji(G),(oe)=>{if(ke(oe)){let Te=new ft(C,l,oe.left);if(p)return Y.push([q,Te]),un;else return X(new je(e,l,Te,Jn(ce)))}return ce.push([q,oe.right]),un}))}}}}let b=({es:g,output:O})=>_o(g)?X(new je(e,l,Jn(g),Jn(O))):ne(Jn(O));if(w&&w.length>0){let g=w;return fl(()=>{let O={es:Fa(f),output:Fa(m)};return Kn(dl(g,(R)=>R(O),{concurrency:s,batching:c,discard:!0}),()=>b(O))})}return b({output:m,es:f})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return en(e,H_);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([Ft(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Ft(u.parameter,t),Ft(u.type,t),u.parameter]),a=Vt.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>di(u)?new Xd(u):new Gi(u)))),s=Ft(a,t),c=Zx(e),l=Xx(e);return(u,p)=>{if(!Im(u))return X(new Rn(e,u));let f=p?.errors==="all",h=[],m=0,S=p?.onExcessProperty==="error",E=p?.onExcessProperty==="preserve",w={},b;if(S||E){b=Reflect.ownKeys(u);for(let C of b){let G=s(C,p);if(tn(G)&&ke(G))if(S){let q=new ft(C,u,new Qx(u[C],`is unexpected, expected: ${String(a)}`));if(f){h.push([m++,q]);continue}else return X(new je(e,u,q,w))}else w[C]=u[C]}}let g=void 0,O=p?.exact===!0;for(let C=0;C<n.length;C++){let G=n[C][1],q=G.name,Y=Object.prototype.hasOwnProperty.call(u,q);if(!Y){if(G.isOptional)continue;else if(O){let Te=new ft(q,u,new _s(G));if(f){h.push([m++,Te]);continue}else return X(new je(e,u,Te,w))}}let ce=n[C][0],oe=ce(u[q],p);if(tn(oe)){if(ke(oe)){let Te=new ft(q,u,Y?oe.left:new _s(G));if(f){h.push([m++,Te]);continue}else return X(new je(e,u,Te,w))}w[q]=oe.right}else{let Te=m++,Ut=q;if(!g)g=[];g.push(({es:$t,output:Wt})=>Kn(Ji(oe),(et)=>{if(ke(et)){let tt=new ft(Ut,u,Y?et.left:new _s(G));if(f)return $t.push([Te,tt]),un;else return X(new je(e,u,tt,Wt))}return Wt[Ut]=et.right,un}))}}for(let C=0;C<i.length;C++){let G=i[C],q=G[0],Y=G[1],ce=dx(u,G[2]);for(let oe of ce){let Te=q(oe,p);if(tn(Te)&&kt(Te)){let Ut=Y(u[oe],p);if(tn(Ut)){if(ke(Ut)){let $t=new ft(oe,u,Ut.left);if(f){h.push([m++,$t]);continue}else return X(new je(e,u,$t,w))}else if(!Object.prototype.hasOwnProperty.call(r,oe))w[oe]=Ut.right}else{let $t=m++,Wt=oe;if(!g)g=[];g.push(({es:et,output:tt})=>Kn(Ji(Ut),(Ht)=>{if(ke(Ht)){let Pn=new ft(Wt,u,Ht.left);if(f)return et.push([$t,Pn]),un;else return X(new je(e,u,Pn,tt))}else{if(!Object.prototype.hasOwnProperty.call(r,oe))tt[oe]=Ht.right;return un}}))}}}}let R=({es:C,output:G})=>{if(_o(C))return X(new je(e,u,Jn(C),G));if(p?.propertyOrder==="original"){let q=b||Reflect.ownKeys(u);for(let ce of o)if(q.indexOf(ce)===-1)q.push(ce);let Y={};for(let ce of q)if(Object.prototype.hasOwnProperty.call(G,ce))Y[ce]=G[ce];return ne(Y)}return ne(G)};if(g&&g.length>0){let C=g;return fl(()=>{let G={es:Fa(h),output:Object.assign({},w)};return Kn(dl(C,(q)=>q(G),{concurrency:c,batching:l,discard:!0}),()=>R(G))})}return R({es:h,output:w})}}case"Union":{let n=jA(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],Ft(e.types[l],t));let s=Zx(e)??1,c=Xx(e);return(l,u)=>{let p=[],f=0,h=[];if(o>0)if(nc(l))for(let E=0;E<o;E++){let w=r[E],b=n.keys[w].buckets;if(Object.prototype.hasOwnProperty.call(l,w)){let g=String(l[w]);if(Object.prototype.hasOwnProperty.call(b,g))h=h.concat(b[g]);else{let{candidates:O,literals:R}=n.keys[w],C=Vt.make(R),G=O.length===i?new yr([new dt(w,C,!1,!0)],[]):Vt.make(O);p.push([f++,new je(G,l,new ft(w,l,new Rn(C,l[w])))])}}else{let{candidates:g,literals:O}=n.keys[w],R=new dt(w,Vt.make(O),!1,!0),C=g.length===i?new yr([R],[]):Vt.make(g);p.push([f++,new je(C,l,new ft(w,l,new _s(R)))])}}else{let E=n.candidates.length===i?e:Vt.make(n.candidates);p.push([f++,new Rn(E,l)])}if(n.otherwise.length>0)h=h.concat(n.otherwise);let m=void 0;for(let E=0;E<h.length;E++){let w=h[E],b=a.get(w)(l,u);if(tn(b)&&(!m||m.length===0))if(kt(b))return b;else p.push([f++,b.left]);else{let g=f++;if(!m)m=[];m.push((O)=>fl(()=>{if("finalResult"in O)return un;else return Kn(Ji(b),(R)=>{if(kt(R))O.finalResult=R;else O.es.push([g,R.left]);return un})}))}}let S=(E)=>_o(E)?E.length===1&&E[0][1]._tag==="Type"?X(E[0][1]):X(new je(e,l,Jn(E))):X(new Rn(e,l));if(m&&m.length>0){let E=m;return fl(()=>{let w={es:Fa(p)};return Kn(dl(E,(b)=>b(w),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in w)return w.finalResult;return S(w.es)})})}return S(p)}}case"Suspend":{let n=ml(()=>Ft(e.f(),t));return(r,o)=>n()(r,o)}}},en=(e,t)=>(n)=>t(n)?ne(n):X(new Rn(e,n)),wl=(e,t)=>{switch(e._tag){case"Declaration":{let n=Ux(e);if(Ie(n))return wl(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?af(o.type):pt(o.type);if(Zd(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?af(o.type):pt(o.type);if(Zd(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return wl(e.from,t);case"Suspend":return wl(e.f(),t);case"Transformation":return wl(t?e.from:e.to,t)}return[]},jA=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=wl(a,t);if(s.length>0){o.push(a);for(let c=0;c<s.length;c++){let[l,u]=s[c],p=String(u.literal);n[l]=n[l]||{buckets:{},literals:[],candidates:[]};let f=n[l].buckets;if(Object.prototype.hasOwnProperty.call(f,p)){if(c<s.length-1)continue;f[p].push(a),n[l].literals.push(u),n[l].candidates.push(a)}else{f[p]=[a],n[l].literals.push(u),n[l].candidates.push(a);break}}}else r.push(a)}return{keys:n,otherwise:r,candidates:o}},BA=(e)=>bl(e)?BA(e.from):e,vl=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(tn(e))return e;let o=new rl,i=Ak(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(CR(a))return ne(a.value);let s=a.cause;if(bE(s))return X(s.error);return X(new eS(t,n,_E(s)))}return X(new eS(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},w2=([e],[t])=>e>t?1:e<t?-1:0,v2=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return ne;case"TypeLiteralTransformation":return(n)=>{let r=ne(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=Gn(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?H(l[i]):F());if(delete l[i],Ie(u))l[a]=u.value;return l})}return r}}},zt=(e,t=[])=>({value:e,forest:t}),Tl,T2=(e)=>e.value+VA(`
34
- `,e.forest),VA=(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+=VA(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},E2=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},O2=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},zA=(e)=>("ast"in e)?H(e.ast):F(),tS,R2=(e)=>zA(e).pipe(Dn(Qk),Je({onNone:()=>tS,onSome:(t)=>{let n=t(e);if(wt(n))return ne({message:n,override:!1});if(Rk(n))return zd(n,(r)=>({message:r,override:!1}));if(wt(n.message))return ne({message:n.message,override:n.override});return zd(n.message,(r)=>({message:r,override:n.override}))}})),rS=(e)=>(t)=>t._tag===e,KA,MA,NA,El=(e)=>ro(R2(e),(t)=>{if(t!==void 0)return!t.override&&(KA(e)||MA(e)&&e.kind==="From"||NA(e)&&e.kind!=="Transformation")?NA(e)||MA(e)?El(e.issue):tS:ne(t.message);return tS}),WA=(e)=>zA(e).pipe(Dn(rA),gw((t)=>t(e)),Zt),A2=(e)=>Gn(El(e),(t)=>t??WA(e)??k2(e)),sf=(e)=>WA(e)??String(e.ast),I2=(e)=>e.message??"is forbidden",P2=(e)=>e.message??"is unexpected",M2=(e)=>{let t=eA(e.ast);if(Ie(t)){let n=t.value();return wt(n)?ne(n):n}return ne(e.message??"is missing")},ws=(e)=>{switch(e._tag){case"Type":return Gn(A2(e),zt);case"Forbidden":return ne(zt(sf(e),[zt(I2(e))]));case"Unexpected":return ne(zt(P2(e)));case"Missing":return Gn(M2(e),zt);case"Transformation":return ro(El(e),(t)=>{if(t!==void 0)return ne(zt(t));return Gn(ws(e.issue),(n)=>zt(sf(e),[zt(E2(e.kind),[n])]))});case"Refinement":return ro(El(e),(t)=>{if(t!==void 0)return ne(zt(t));return Gn(ws(e.issue),(n)=>zt(sf(e),[zt(O2(e.kind),[n])]))});case"Pointer":return Gn(ws(e.issue),(t)=>zt(Kd(e.path),[t]));case"Composite":return ro(El(e),(t)=>{if(t!==void 0)return ne(zt(t));let n=sf(e);return fx(e.issues)?Gn(dl(e.issues,ws),(r)=>zt(n,r)):Gn(ws(e.issues),(r)=>zt(n,[r]))})}};var JA=x(()=>{Ve();wE();dO();Pk();an();kR();z();Be();hl();Ge();we();kd();Yx();PA=Symbol.for("effect/Schema/ParseErrorTypeId");FA=class FA extends pO("ParseError"){[PA]=PA;get message(){return this.toString()}toString(){return Tl.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[ie](){return this.toJSON()}};LA=ne,DA=X,tn=Wm,ro=d(2,(e,t)=>tn(e)?fc(e,{onLeft:X,onRight:t}):Kn(e,t)),Gn=d(2,(e,t)=>tn(e)?lw(e,t):zd(e,t)),uf=d(2,(e,t)=>tn(e)?Nu(e,t):kk(e,t)),qA=d(2,(e,t)=>tn(e)?fc(e,{onLeft:t,onRight:ne}):Ck(e,t)),S2=K(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),b2=K(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);Tl={formatIssue:(e)=>Gn(ws(e),T2),formatIssueSync:(e)=>{let t=Tl.formatIssue(e);return tn(t)?pw(t):Ik(t)},formatError:(e)=>Tl.formatIssue(e.issue),formatErrorSync:(e)=>Tl.formatIssueSync(e.issue)},tS=ne(void 0),KA=rS("Composite"),MA=rS("Refinement"),NA=rS("Transformation")});var GA,YA;var ZA=x(()=>{z();we();GA=d((e)=>Bt(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),YA=d((e)=>Bt(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function Ot(e){return class{[Ol]=XA;static ast=e;static annotations(n){return Ot(xr(this.ast,n))}static pipe(){return k(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Ol]=XA}}function L2(e){return nf(e)?Vt.make(OA(e,(t)=>new Gi(t))):new Gi(e[0])}function aI(e,t=L2(e)){return class extends Ot(t){static annotations(r){return aI(this.literals,xr(this.ast,r))}static literals=[...e]}}function T(...e){return Re(e)?aI(e):aS}function iS(e,t){return class extends Ot(t){static annotations(r){return iS(this.typeParameters,xr(this.ast,r))}static typeParameters=[...e]}}function cI(e,t=U2(e)){return class extends Ot(t){static annotations(r){return cI(this.members,xr(this.ast,r))}static members=[...e]}}function be(...e){return nf(e)?cI(e):Re(e)?e[0]:aS}function df(e,t,n=H2(e,t)){return class extends Ot(n){static annotations(o){return df(this.elements,this.rest,xr(this.ast,o))}static elements=[...e];static rest=[...t]}}function lI(...e){return Array.isArray(e[0])?df(e[0],e.slice(1)):df(e,[])}function uI(e,t){return class extends df([],[e],t){static annotations(r){return uI(this.value,xr(this.ast,r))}static value=e}}class dI{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<${oS(this.to.isOptional)}, ${this.to.type}, ${j2(this.from.fromKey)}, ${oS(this.from.isOptional)}, ${this.from.type}>`}}function pS(e,t,n=V2(e,t)){return class extends Ot(n){static annotations(o){return pS(this.fields,this.records,xr(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=z2(e,{...o});return hS(i)?a:pf(this)(a)};static pick(...o){return _(GA(e,...o))}static omit(...o){return _(YA(e,...o))}}}function _(e,...t){return pS(e,t)}function gI(e,t,n){return class extends pS({},[{key:e,value:t}],n){static annotations(o){return gI(e,t,xr(this.ast,o))}static key=e;static value=t}}function yI(e,t){return class extends Ot(t){static annotations(r){return yI(this.from,xr(this.ast,r))}static make=(r,o)=>hS(o)?r:pf(this)(r);static from=e}}function xI(e,t,n){return class extends Ot(n){static annotations(o){return xI(this.from,this.filter,xr(this.ast,o))}static[K2]=e;static from=e;static filter=t;static make=(o,i)=>hS(i)?o:pf(this)(o)}}function Ze(e,t){return(n)=>{function r(i,a,s){return W2(e(i,a,s),s,i)}let o=new Sl(n.ast,r,Yi(t));return xI(n,r,o)}}function hS(e){return pi(e)?e:e?.disableValidation??!1}var Ol,XA,QA,Yi=(e)=>{if(!e)return{};let t={...e};for(let n in QA)if(n in e){let r=QA[n];t[r]=e[n],delete t[n]}return t},xr=(e,t)=>_l(e,Yi(t)),iI=(e,t)=>{let n=HA(e,t);return(r,o)=>Nu(n(r,o),nS)},eI=(e)=>N(e,Ol)&&Bt(e[Ol]),D2=(e,t,n)=>iS(e,new xs(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(Ot)),(...r)=>t.encode(...r.map(Ot)),Yi(n))),q2=(e,t)=>{let n=()=>(o,i,a)=>e(o)?LA(o):DA(new Rn(a,o));return iS([],new xs([],n,n,Yi(t)))},V=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return D2(n,r,o)}let e=arguments[0],t=arguments[1];return q2(e,t)},sI,mt,aS,sS,A,nn,Z,U2=(e)=>Vt.make(e.map((t)=>t.ast)),$2=(e)=>be(e,sI),H2=(e,t)=>new xl(e.map((n)=>eI(n)?new Wo(n.ast,!1):n.ast),t.map((n)=>eI(n)?new Ss(n.ast):n.ast),!0),j=(e)=>uI(e),oS=(e)=>e?'"?:"':'":"',cS,pI,j2=(e)=>{if(e===void 0)return"never";if(wt(e))return JSON.stringify(e);return String(e)},fI=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new cS(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new dI(e.from,new pI(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},mI,hI=(e)=>N(e,mI),lS,uS,v=(e)=>{let t=e.ast===Qd||e.ast===ef?Qd:$2(e).ast;return new uS(new cS(t,!0,!0,{},void 0),e)},B2,V2=(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(hI(u)){let p=u.ast;switch(p._tag){case"PropertySignatureDeclaration":{let{type:f,isOptional:h,annotations:m}=p;i.push(new dt(l,f,h,!0,B2(p))),a.push(new dt(l,pt(f),h,!0,m)),r.push(new dt(l,f,h,!0,m));break}case"PropertySignatureTransformation":{let f=p.from.fromKey??l;i.push(new dt(f,p.from.type,p.from.isOptional,!0,p.from.annotations)),a.push(new dt(l,p.to.type,p.to.isOptional,!0,p.to.annotations)),s.push(new zx(f,l,p.decode,p.encode));break}}}else i.push(new dt(l,u.ast,!1,!0)),a.push(new dt(l,pt(u.ast),!1,!0)),r.push(new dt(l,u.ast,!1,!0))}if(Re(s)){let c=[],l=[];for(let u of t){let{indexSignatures:p,propertySignatures:f}=Wx(u.key.ast,u.value.ast);f.forEach((h)=>{i.push(h),a.push(new dt(h.name,pt(h.type),h.isOptional,h.isReadonly,h.annotations))}),p.forEach((h)=>{c.push(h),l.push(new bs(h.parameter,pt(h.type),h.isReadonly))})}return new Vx(new yr(i,c,{[Yd]:"Struct (Encoded side)"}),new yr(a,l,{[Yd]:"Struct (Type side)"}),new Kx(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=Wx(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new yr(r,o)},z2=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&hI(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},ff=(e)=>gI(e.key,e.value),Rl=(e,t)=>(n)=>{let r=Je(Fx(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=_l(n.ast,Yi({[bx]:r,...t}));return yI(n,o)},K2,tI=(e,t,n)=>{if(pi(e))return e?F():H(new Rn(t,n));if(wt(e))return H(new Rn(t,n,e));if(e!==void 0){if("_tag"in e)return H(e);let r=new Rn(t,n,e.message);return H(Re(e.path)?new ft(e.path,n,r):r)}return F()},W2=(e,t,n)=>{if(Nk(e))return tI(e,t,n);if(Re(e)){let r=qu(e,(o)=>tI(o,t,n));if(Re(r))return H(r.length===1?r[0]:new je(t,n,r))}return F()},J2,dS=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length<=e,{schemaId:J2,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),G2,vs=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length>=e,{schemaId:G2,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),nI,pe=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ze((o)=>(e.lastIndex=0,e.test(o)),{schemaId:nI,[nI]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},Y2,rI,Z2,X2,fS=(e,t)=>(n)=>n.pipe(Ze((r)=>r>e,{schemaId:X2,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),Q2,SI=(e,t)=>(n)=>n.pipe(Ze((r)=>r>=e,{schemaId:Q2,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),e$,mf=(e)=>(t)=>t.pipe(Ze((n)=>Number.isSafeInteger(n),{schemaId:e$,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),mS=(e)=>fS(0,{title:"positive",...e}),hf,t$,Zi=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(Fk(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ze((o)=>o.length>=r,{schemaId:t$,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[Nx]:!0,...t}))},oI,n$;var Rt=x(()=>{Ve();an();ec();yx();Jk();hl();Ge();JA();Oe();we();Yx();ZA();Ol=Symbol.for("effect/Schema");XA={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},QA={typeConstructor:Yk,schemaId:Zk,message:_x,missingMessage:Jd,identifier:Gd,title:Qt,description:no,examples:wx,default:vx,documentation:Xk,jsonSchema:Tx,arbitrary:Ex,pretty:Ox,equivalence:Rx,concurrency:Cx,batching:kx,parseIssueTitle:Ax,parseOptions:Ix,decodingFallback:Px};sI=class sI extends Ot(Qd){};mt=class mt extends Ot(aA){};aS=class aS extends Ot(ef){};sS=class sS extends Ot(jx){};A=class A extends Ot(mA){};nn=class nn extends Ot(gA){};Z=class Z extends Ot(xA){};cS=class cS extends Wo{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=oS(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};pI=class pI extends Wo{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};mI=Symbol.for("effect/PropertySignature");lS=class lS{ast;[Ol];[mI]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return k(this,arguments)}annotations(e){return new lS(fI(this.ast,Yi(e)))}toString(){return String(this.ast)}};uS=class uS extends lS{from;constructor(e,t){super(e);this.from=t}annotations(e){return new uS(fI(this.ast,Yi(e)),this.from)}};B2=Jx([Jd]);K2=Symbol.for("effect/SchemaId/Refine");J2=Kk,G2=zk,nI=Symbol.for("effect/SchemaId/Pattern"),Y2=Symbol.for("effect/SchemaId/UUID"),rI=/^[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;Z2=class Z2 extends A.pipe(pe(rI,{schemaId:Y2,identifier:"UUID",jsonSchema:{format:"uuid",pattern:rI.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};X2=jk,Q2=Bk,e$=Vk;hf=class hf extends nn.pipe(mf({identifier:"Int"})){};t$=Wk,oI=Hk;n$=class n$ extends V(Tu,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:oI,[oI]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>D_}){}});function Cn(e,t){return iI(e,r$)(t)}var r$;var Ts=x(()=>{Rt();r$={onExcessProperty:"error"}});function yS(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(!wI(r)||!_I(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function Yn(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);return wI(n)&&_I(r)?`${n}@openai-curated`:void 0}function _I(e){return bI.includes(e)}function wI(e){return gf.includes(e)}function xS(e,t){let n=t??oo;return{computer_use:e?.computer_use??n.computer_use,frontend:e?.frontend??n.frontend,security:e?.security??n.security}}function Cl(e,t=[]){let n=[],r=new Set;for(let o of vI){if(!e[o])continue;for(let i of Qi[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 gS,o$,i$,a$,bI,gf,Xi,Es,s$,c$,Qi,vI,l$,oo;var SS=x(()=>{Rt();gS=T("computer_use","frontend","security"),o$=T("computer_use","frontend","security"),i$=T("installed","disabled","missing","uncertain"),a$=T("healthy","missing","disabled","uncertain"),bI=Object.freeze(["openai-curated","openai-curated-remote"]),gf=Object.freeze(["build-web-apps","codex-security"]);Xi=Object.freeze({coding:!0,computer_use:!1,frontend:!0,security:!0}),Es=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([])}),s$=Es.frontend,c$={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Xi.frontend,migrationKey:"frontend",semanticSkillIds:Object.freeze(Es.frontend.map(({skillId:e})=>e)),applicability:Es.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Xi.security,migrationKey:"security",semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:Es.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Xi.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:Es.computer_use,ownership:"shared-preserve"}},Qi=Object.freeze(c$),vI=Object.freeze(["computer_use","frontend","security"]),l$=Object.freeze(["writing-instructions","babysit-ci"]),oo=Object.freeze({computer_use:Xi.computer_use,frontend:Xi.frontend,security:Xi.security})});function Sr(e){return _({identifier:T(e),label:A,requiresRootApproval:Z})}function TI(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 EI(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var OI,u$,p$,bS,d$,RI,f$,m$,h$;var CI=x(()=>{Rt();OI=T("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"),u$=_({identifier:OI,label:A,requiresRootApproval:Z});p$=_({localRepositoryEdit:Sr("local.repository.edit"),localRepositoryCheck:Sr("local.repository.check"),localRepositoryLint:Sr("local.repository.lint"),localRepositoryFormat:Sr("local.repository.format"),localRepositoryCommit:Sr("local.repository.commit"),externalRead:Sr("external.read"),specialistDispatch:Sr("specialist.dispatch"),versionControlServerMutation:Sr("vcs.server.mutation"),versionControlServerCiTrigger:Sr("vcs.server.ci-trigger"),unknownEffect:Sr("unknown.effect")}),bS={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(bS);d$=T("never","root"),RI=Object.values(bS);f$=RI.filter((e)=>!e.requiresRootApproval),m$=RI.filter((e)=>e.requiresRootApproval),h$=Object.freeze({noRootApproval:`${EI(TI(f$))} actions do not require Root approval.`,rootApproval:`${EI(TI(m$))} require Root approval.`})});function yf(e){let t=Cn(g$,e);if(ke(t))return ui(Js("sha256 digest",t.left));return Ea(t.right)}var Zn,_S,D7,q7,U7,g$,y$,x$,S$,b$;var xf=x(()=>{an();Rt();Oa();Ts();Zn=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),_S=A.pipe(pe(/^[0-9a-f]{64}$/u)),D7=Zn.pipe(Rl("RunId")),q7=Zn.pipe(Rl("ProjectId")),U7=Zn.pipe(Rl("TrustId")),g$=_S.pipe(Rl("Sha256Digest"));y$=_({run_id:Zn,objective_lineage:Zn,parent_run_id:v(be(Zn,mt))}),x$=_({project_id:Zn,trust_id:Zn,trust_digest:_S}),S$=_({project_id:Zn,project_digest:_S}),b$=A.pipe(pe(/^state-[0-9]+\.[0-9]+$/u))});function wS(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 II(e){return typeof e==="string"&&T$.has(e)}function O$(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!II(t)||typeof n!=="string")return!1;return Al.get(t)?.tasks.some((r)=>r.name===n)===!0}function _f(e,t){return typeof t==="string"&&Al.get(e)?.tasks.some((n)=>n.name===t)===!0}function PI(e){return typeof e==="string"&&E$.has(e)}function OS(e){let t=`${e.role}.${e.task}`;if(!TS.has(t))throw Error("Unknown native specialist agent type.");return t}function RS(e){let t=Al.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.instruction}function CS(e){let t=Al.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function NI(e){let t=Al.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function kS(e){let n=NI(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 Go,kI,kl,ea,_$,bf="Make the smallest complete edit set within the authorized boundary, touch no unrelated paths, avoid speculative refactors or formatting churn, and perform no redundant writes or operations; preserve unrelated work and stop for Root input before expanding scope.",Jo="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",w$,v$,kn,Al,T$,vS,E$,AI,TS,ES,R$,C$,k$,A$,Il,ta,MI,br,I$,wf,FI,Sf,P$,M$,N$,AS,vf,IS,Yo,F$,L$,re;var Pl=x(()=>{Rt();Go=T("low","default","high"),kI=T("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),kl=be(Go,kI);ea=T("standard","fast","fast-all"),_$=T("low","medium","high","xhigh","max"),w$=T("none"),v$=T("read-only","workspace-write"),kn=[{role:"Explorer",tasks:[{name:"lookup",description:"Repository fact lookup specialist.",instruction:`Locate the exact requested repository fact. ${Jo}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:`Trace the complete in-scope execution or reference path. ${Jo}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS, lifecycle, and decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:`Locate the exact requested authoritative external fact. For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or generic web sources. Return a typed Context7 evidence state in the context7 field with supporting version/source evidence; fall back only for an allowed evidence state or when the required version is absent, and prefer authoritative first-party documentation when sources conflict. ${Jo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:`Synthesize the assigned current sources with citations. For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or generic web sources. Return a typed Context7 evidence state in the context7 field with supporting version/source evidence; fall back only for an allowed evidence state or when the required version is absent, and prefer authoritative first-party documentation when sources conflict. ${Jo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS, lifecycle, and 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:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply only deterministic, already-decided edits.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Implement and verify the bounded behavior seam.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Integrate the decided seams and verify them together.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Observe the assigned post-VCS external gate at the supplied exact ref or SHA. ${Jo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`When independent proof is useful, run the smallest relevant local checks for the delegated seam, classify failures, and report evidence without redesigning the solution or replacing code review. ${Jo}`,permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Establish the failure reproducibly, identify the evidence-backed root cause, make the narrow bounded repair, and prove the regression is gone; return material redesigns to Root.",permissions:{network:!1,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, 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:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",tasks:[{name:"plan",description:"Adversarial implementation-plan review specialist.",instruction:`Review the complete plan to a fixed point. ${Jo}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. The acceptance contract covers correctness, safety, compatibility, mergeability, clarity, simplicity, cohesion, idiomaticity, appropriate abstraction, accidental complexity, duplication, unnecessary files or file splitting, speculative abstraction, test quality, and generated-artifact hygiene. Prefer simple cohesive code over clever or over-engineered code.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Review and repair the produced artifact to a fixed point.",permissions:{network:!1,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, 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:!1,filesystem:"read-only",sourceMutation:!1}}];ir(kn);Al=new Map(kn.map((e)=>[e.role,e])),T$=new Set(kn.map((e)=>e.role)),vS=kn.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),E$=new Set(vS),AI=vS.map((e)=>e.replace(":",".")),TS=new Set(AI);ES=V(II),R$=V((e)=>_f("Explorer",e)),C$=V((e)=>_f("Librarian",e)),k$=V((e)=>_f("Worker",e)),A$=V((e)=>_f("Reviewer",e)),Il=V(O$),ta=Object.freeze(vS.filter((e)=>PI(e))),MI=V(PI),br=Object.freeze(AI.filter((e)=>TS.has(e))),I$=V((e)=>typeof e==="string"&&TS.has(e)),wf=Object.freeze(["worker","explorer","reviewer","librarian"]);FI=_({profile:Go,service_tier:v(ea)}),Sf=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","gui_browser","computer_use"]),P$=T(...Sf),M$=T("delegated","root_direct","unavailable"),N$=T(...Sf),AS=T("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),vf=Object.freeze({rule:"Run meaningful proof appropriate to changed behavior plus repository-required checks.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),IS=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"]),fallbackRequiresEvidenceStateOrMissingVersion:!0,authoritativeFirstPartyResolvesConflicts:!0,materialDecisionsRemainRootOwned:!0}),Yo=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnInspectionImplementationAndRepair:!0,rootOwnsLiveVisualAndInteractionAcceptance:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsCannotSubstituteForRootAcceptance:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["specialist_implements","root_renders_opens_and_interacts","root_judges_current_result","root_delegates_discrepancies","specialist_repairs","root_rerenders_and_retests"])}),F$=Object.freeze({interactiveCapabilitiesRemainRootOwned:!0,credentialEntryAndSubmissionRemainUserOwned:!0,useDefaultBrowserWithComputerUse:!0,agentsMustNeverHandleCredentials:!0,authenticationSequence:Object.freeze(["root_navigates_to_authentication","root_hands_control_to_user","user_enters_and_submits_credentials","root_waits_for_completion","root_resumes_authenticated_session"]),missingAuthorizedPathIsCapabilityBlocker:!0}),L$=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),re=Object.freeze({requiresDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:br,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:wf,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","review","ci_release_observation"]),directExecutionExceptions:Sf,rootOwnedAuthority:Sf,requestUserInputGates:Object.freeze(["plan_approval","installation_profile_approval","remote_origin_server_vcs_mutation","public_publication_or_release","ambiguity_or_missing_material_input"]),surgicalMutationRule:bf,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,longestPracticalEventWait:!0,busyPollingForbidden:!0,statusOnlyCoordinationLoopsForbidden:!0,batchIndependentLifecycleActions:!0,releaseLeavesAfterAcceptedOutcome:!0,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,routineSafeReversibleInScopeDecisionsProceedAutonomously:!0,userInstructionsOverrideSkillGuidelinesExceptHardInvariants:!0,authorizedWorkContinuesThroughRequestedTerminalState:!0,testingPolicy:vf,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Dt(e,t){return new We("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function PS(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw Dt(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw Dt(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw Dt(t,"invalid number");return r}case"undefined":throw Dt(t,"undefined is not JSON");case"bigint":throw Dt(t,"bigint is not JSON");case"function":throw Dt(t,"function is not JSON");case"symbol":throw Dt(t,"symbol is not JSON");case"object":break}if(n.has(e))throw Dt(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw Dt(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 Dt(`${t}[${s}]`,"sparse or accessor array item");a.push(PS(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 Dt(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw Dt(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Dt(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw Dt(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 Dt(`${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 Dt(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${PS(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function _r(e){return PS(e,"$",new Set)}function Xn(e){return new TextEncoder().encode(_r(e))}function LI(e,t){if(e.length===0||e.includes("\x00"))throw new We("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 We("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 q$(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function Qn(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new We("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",U$(LI(e,t)));return q$(new Uint8Array(r))}function U$(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var MS=x(()=>{Oa();xf()});function UI(e){try{return _r(e)!==void 0}catch{return!1}}function Ef(e){let t=Cn(KI,e);if(ke(t))return ui(Js("CLI envelope",t.left));return Ea(t.right)}var DI,qI,$I,$$,H$,NS="holycodex-specialist-outcome-2",Ct,Os,Ml,j$,B$,V$,z$,K$,W$,Tf,J$,G$,Y$,Z$,X$,HI,jI,BI,Q$,VI,zI,KI;var FS=x(()=>{an();Rt();MS();SS();Oa();xf();Pl();Ts();DI=T("blocked","completed","failed","partial"),qI=be(T("high","max","xhigh"),mt);$I=V((e)=>UI(e)),$$=V((e)=>Rm(e)&&!Array.isArray(e)&&UI(e)),H$=_({blocked:Z,changed_files:j(A),confidence:nn,context_owner:be(A,mt),material_findings:j(A),needs_more_context:Z,needs_root_decision:Z,needs_verification:Z,relevant_files:j(A),remaining_risk:j(A),reuse_recommended:Z,status:DI,suggested_followup:be(A,mt),suggested_luna_effort:qI,suggested_specialist:be(ES,mt),verification:j(A),verification_passed:Z}),Ct=A.pipe(vs(1)),Os=_({state:AS,evidence:j(Ct).pipe(Zi(1)),library:v(Ct),version:v(Ct)}),Ml={protocol_version:T(NS),route:Il,evidence:j(Ct),context7:v(Os)},j$=_(Ml),B$=_({...Ml,status:T("completed"),summary:Ct}),V$=_({...Ml,status:T("blocked"),reason:Ct,needs_root_decision:Z}),z$=_({...Ml,status:T("partial"),summary:Ct,completed:j(Ct),remaining:j(Ct),needs_root_decision:Z}),K$=_({...Ml,status:T("failed"),error:Ct}),W$=be(B$,V$,z$,K$),Tf={protocol_version:T(NS),capability:gS,route:be(Il,mt),evidence:j(Ct),context7:v(Os),data:$I},J$=_({...Tf,status:T("completed"),summary:Ct}),G$=_({...Tf,status:T("blocked"),reason:Ct,needs_root_decision:Z}),Y$=_({...Tf,status:T("partial"),summary:Ct,completed:j(Ct),remaining:j(Ct),needs_root_decision:Z}),Z$=_({...Tf,status:T("failed"),error:Ct}),X$=be(J$,G$,Y$,Z$),HI=j(A),jI=A.pipe(pe(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),BI=T(Pr),Q$=_({code:Zn,message:A,details:$$}),VI=_({schema_version:BI,ok:T(!0),command:jI,data:$I,warnings:HI}),zI=_({schema_version:BI,ok:T(!1),command:jI,error:Q$,warnings:HI}),KI=be(VI,zI)});function eH(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:JI,effort:n}}function rH(e){let t=nH.get(e);if(t===void 0)throw new We("catalog_invalid","A profile has no route effort policy.",{profile:e});return kn.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new We("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return eH(n.role,r.name,i)}))}function LS(e){return{name:e.name,root:{model:"gpt-6-astra",effort:e.effort},specialistModel:"gpt-5.6-luna",defaultServiceTier:"standard",routes:rH(e.name)}}function oH(e){let t=["low","default","high"];if(e.length!==t.length)throw new We("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 We("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=o==="low"?"low":o==="default"?"medium":"high";if(r.root.model!=="gpt-6-astra"||r.root.effort!==i||r.specialistModel!=="gpt-5.6-luna")throw new We("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==ta.length)throw new We("catalog_invalid","A profile is incomplete.",{profile:r.name});let a=new Set;for(let s of r.routes){if(a.has(s.key)||!tH.has(s.key)||s.model!=="gpt-5.6-luna"||`${s.role}:${s.task}`!==s.key)throw new We("catalog_invalid","A profile contains an invalid route.",{profile:r.name});a.add(s.key)}if(a.size!==ta.length)throw new We("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<ta.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||WI[i.effort]<r)throw new We("catalog_invalid","Profile route effort is not monotonic.",{route:ta[n]??"unknown"});r=WI[i.effort]}}}function wr(e){let t=Cn(Go,e);if(ke(t))return ui(new We("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=YI.get(t.right);if(!n)return ui(new We("invalid_profile","Unknown profile selection.",{profile:t.right}));return Ea(n)}var JI="gpt-5.6-luna",tH,WI,DS,nH,qS,GI,YI,iH;var ZI=x(()=>{an();Oa();Pl();Ts();tH=new Set(ta),WI={low:0,medium:1,high:2,xhigh:3,max:4},DS=[{profile:"low",rationale:"The low profile keeps bounded specialist work economical.",efforts:{"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: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: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(DS);nH=new Map(DS.map((e)=>[e.profile,e]));qS=[LS({name:"low",effort:"low"}),LS({name:"default",effort:"medium"}),LS({name:"high",effort:"high"})];oH(qS);ir(qS);GI=qS,YI=new Map,iH=new Map;for(let e of GI){YI.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);iH.set(e.name,t)}});import{execFile as sH}from"child_process";import{promisify as cH}from"util";var QI="holycodex-intent-1",eP="holycodex-plan-1",tP="holycodex-assignment-1",Of="toon-4",te,Zo,US,nP,Nl,er,Xe,u5,$S,na,HS,jS,lH,XI,uH,pH,BS,rP,oP,dH,p5,fH,mH,hH,gH,yH,xH,SH,d5;var iP=x(()=>{Rt();FS();Pl();Ts();te=A.pipe(Ze((e)=>e.trim().length>0)),Zo=A.pipe(pe(/^[a-z0-9][a-z0-9-]{0,95}$/u)),US=A.pipe(pe(/^[a-f0-9]{64}$/u)),nP=A.pipe(pe(/^[a-f0-9]{40}$/u)),Nl=hf.pipe(SI(1)),er=A.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),Xe=j(te),u5=_({pid:hf.pipe(fS(0)),token:te}),$S=_({role:T("Explorer","Librarian","Worker","Reviewer"),task:te}).pipe(Ze((e)=>kn.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),na=_({kind:T("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:te,result:v(T("passed","failed","observed","unknown"))}),HS=_({root:te,git_common_dir:te,initial_head:te,expected_head:te,expected_changes:Xe,expected_status_digest:US,integrated_commit:v(nP),updated_at:er}),jS=T("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),lH=T("scoping","ready","executing","verifying","reviewing"),XI=_({required:Z,status:T("not_required","missing","passed","failed","accepted","rejected"),evidence:j(na)}),uH=_({schema_version:T(QI),toon_compatibility:T(Of),id:Zo,slug:Zo,title:te,goal:te,acceptance_criteria:Xe,state:jS,revision:Nl,plan_required:Z,active_plan_revision:v(Nl),active_plan_digest:v(US),blockers:Xe,resume_state:v(lH),verification:XI,review:XI,acceptance_met:Z,root_readiness:Z,evidence:j(na),baseline:HS,created_at:er,updated_at:er}),pH=_({schema_version:T(eP),toon_compatibility:T(Of),intent_id:Zo,revision:Nl,predecessor_digest:v(US),approach:te,scope:Xe,exclusions:Xe,assignments:Xe,dependencies:Xe,architecture:Xe,risks:Xe,assumptions:Xe,open_questions:Xe,verification:Xe,recovery:Xe,updated_at:er}),BS=T("completed","blocked","needs_root_input","failed"),rP=T("pending","executing","completed","blocked","needs_root_input","failed"),oP=_({id:Zo,outcome:BS,started_at:er,finished_at:er,summary:te,evidence:j(na),context7:v(Os),blocker:v(te),remaining_risk:Xe}),dH=_({schema_version:T(tP),toon_compatibility:T(Of),intent_id:Zo,id:Zo,objective:te,owner:$S,scope:Xe,constraints:Xe,exclusions:Xe,dependencies:Xe,acceptance_criteria:Xe,status:rP,revision:Nl,invocations:j(oP),active_invocation_id:v(te),active_started_at:v(er),evidence:j(na),blocker:v(te),remaining_risk:Xe,created_at:er,updated_at:er}),p5=_({schema_version:T("holycodex-intent-0"),id:Zo,slug:Zo,title:te,goal:te,acceptance_criteria:Xe,state:jS,revision:Nl,baseline:HS,created_at:er,updated_at:er}),fH=_({title:te,goal:te,acceptanceCriteria:j(te).pipe(Zi(1)),planRequired:v(Z),verificationRequired:v(Z),reviewRequired:v(Z)}),mH=_({approach:te,scope:v(j(te)),exclusions:v(j(te)),assignments:v(j(te)),dependencies:v(j(te)),architecture:v(j(te)),risks:v(j(te)),assumptions:v(j(te)),openQuestions:v(j(te)),verification:v(j(te)),recovery:v(j(te))}),hH=_({id:v(te),objective:te,owner:$S,scope:j(te).pipe(Zi(1)),constraints:v(j(te)),exclusions:v(j(te)),dependencies:v(j(te)),acceptanceCriteria:j(te).pipe(Zi(1))}),gH=_({scope:j(te).pipe(Zi(1))}),yH=_({commit:nP}),xH=_({invocationId:v(te),outcome:BS,startedAt:v(te),summary:te,evidence:v(j(na)),context7:v(Os),blocker:v(te),remainingRisk:v(j(te))}),SH=_({evidence:v(j(na)),verification:v(T("passed","failed")),review:v(T("accepted","rejected")),acceptanceMet:v(Z),rootReadiness:v(Z),clearBlockers:v(Z)}),d5=cH(sH)});var st=x(()=>{L_();Oa();Ts();SS();CI();xf();Pl();FS();ZI();MS();iP()});function ae(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qe(e){try{return _r(e),!0}catch{return!1}}function PH(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 cP(e){return{ok:!1,error:e}}function lP(e){return{ok:!0,value:e}}function pn(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 oa(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return pn(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>oa(n,t+1));if(ae(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=pn(r,96);if(i.length>0)n[i]=oa(o,t+1)}return n}return"[redacted]"}function uP(e){let t=oa(e);return ae(t)?t:{value:t}}function Ue(e,t,n){return new J("invalid_external_data",`Invalid ${e}.`,{field:e,received:oa(t)},n===void 0?void 0:{cause:n})}function Ne(e,t,n){let r=Cn(e,t);if(ke(r))throw Ue(n,t,String(r.left));return r.right}function pP(e,t){try{return Ne(e,t,"value"),!0}catch{return!1}}var KS,ql=1048576,WS=65536,dn,Xo,c4,io,IH,J;var vr=x(()=>{st();an();Rt();KS=Pr;dn=V((e)=>qe(e)),Xo=V((e)=>ae(e)&&qe(e)),c4=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),io=A.pipe(Ze((e)=>e.length>0&&e.length<=4096)),IH=nn.pipe(Ze((e)=>Number.isFinite(e)&&e>=0));J=class J 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=PH(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var JS,Ul,$l,GS,YS,ZS,XS="turn/completed";var Cf=x(()=>{JS=["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"],Ul=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],$l=["item/permissions/requestApproval"],GS=["mcpServer/elicitation/request"],YS=["item/tool/call"],ZS={method:"initialized"}});function Rs(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)=>Rs(n,t));return ae(e)&&Object.values(e).every((n)=>Rs(n,t))}finally{t.delete(e)}}function Tr(e){return ae(e)&&Rs(e)}function QS(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('"')?NH(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!br.includes(c))throw Ue("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 Ue("TOML key path",e);if(t.some((i)=>i==="__proto__"||i==="constructor"||i==="prototype"))throw Ue("TOML key path",e);return t}function NH(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Ue("TOML quoted key",e)}function ge(e,t){if(!Tr(e))throw Ue("TOML document",e);let n=e;for(let r of QS(t)){if(!Tr(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function kf(e){if(Array.isArray(e))return e.map(kf);if(ae(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,kf(n)]));return e}function Af(e){return kf(e)}function ks(e,t,n){if(!Tr(e)||!Rs(n))throw Ue("TOML write",{keyPath:t});let r=QS(t),o={...Af(e)},i=o;for(let a of r.slice(0,-1)){let s=i[a];if(s!==void 0&&!Tr(s))throw Ue("TOML table path",t);let c=s===void 0?{}:{...s};i[a]=c,i=c}return i[r.at(-1)]=kf(n),o}function ao(e,t){if(!Tr(e))throw Ue("TOML document",e);let n=QS(t),r={...Af(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!Tr(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(Tr(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function jl(e){if(typeof e!=="string")return!1;if(fP.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return br.some((t)=>e===`agents."${t}".config_file`)}function If(e){return jl(e)}function Qo(e){return typeof e==="string"&&LH.test(e)}function eb(e){return e==="gpt-6-astra"||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"}function DH(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function tb(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function nb(e){if(!ae(e)||!tb(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return eb(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&Nf(e.value);case"digest":return DH(e.value);default:return!1}}function dP(e,t){switch(ob(e)){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-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";return t.value==="low"||t.value==="medium"||t.value==="high"}}function yP(e){return ae(e)&&e.kind==="absent"?Object.keys(e).length===1:nb(e)}function xP(e){return ae(e)&&tb(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Qo(e.schema)&&Qo(e.installId)&&If(e.keyPath)&&yP(e.originalValue)&&nb(e.lastManagedValue)&&dP(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||dP(e.keyPath,e.originalValue))}function Cs(e){if(!ae(e)||!tb(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Qo(e.schema)||!Qo(e.installId)||!ae(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>If(t)&&xP(n)&&n.keyPath===t)}function Mf(e){if(!Qo(e.schema)||!Qo(e.installId))throw Ue("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Nf(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 rb(e){if(!Nf(e))throw Ue("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function Bl(e,t){let n=rb(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 ob(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="suppress_unstable_features_warning"||e==="features.default_mode_request_user_input"||e==="features.multi_agent"||e==="features.multi_agent_v2"||e==="features.context_management"||e==="features.context_management.experimental_mode")return"boolean";return"enum"}function qH(e,t){let n=ob(e);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&Nf(t);if(n==="digest")return typeof t==="string";return typeof t==="string"&&eb(t)}async function tr(e,t){if(!If(e)||!Rs(t))throw Ue("managed config value",{keyPath:e});let n=ob(e);if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&Nf(t))return{kind:n,value:rb(t)};if(n==="enum"&&typeof t==="string"&&eb(t))return{kind:n,value:t};return{kind:"digest",value:await Qn("holycodex-managed-config-value",[Xn({keyPath:e,value:t})])}}function UH(e){if(e.kind==="enum"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function As(e,t,n,r){if(!Tr(e)||!Cs(t)||!Qo(r.schema)||!Qo(r.installId))throw Ue("managed runtime config",{});let o={...t.managed},i=Af(e),a=[];for(let[c,l]of Object.entries(n)){if(!jl(c)||typeof l!=="string"&&typeof l!=="boolean")throw Ue("managed config key",c);let u=c,p=t.managed[u],f=ge(i,u);if(p&&(p.schema!==r.schema||p.installId!==r.installId)){a.push(u);continue}if(p&&p.owner==="holycodex"){let m=f===void 0?void 0:await tr(u,f);if(m===void 0||JSON.stringify(m)!==JSON.stringify(p.lastManagedValue)){a.push(u);continue}}let h=p?.originalValue??(f===void 0?{kind:"absent"}:await tr(u,f));if(!qH(u,l))throw Ue("managed config value",{keyPath:u});i=ks(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:h,lastManagedValue:await tr(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!Cs(s))throw Ue("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function ei(e,t,n){if(!Tr(e)||!Cs(t))throw Ue("managed runtime config",{});let r=Af(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!If(c))throw Ue("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 p=ge(r,u);if(!(p!==void 0&&JSON.stringify(await tr(u,p))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=ao(r,u),i.push(u),delete o[u];else{let h=UH(l.originalValue);if(h===void 0){s.push(u),a.push(u);continue}r=ks(r,u,h),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function ia(e,t,n){if(!jl(n)||!Cs(t))throw Ue("managed config key",n);let r=t.managed[n],o=ge(e,n),i=o===void 0?void 0:await tr(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 MH,Hl,fP,FH,mP,hP,gP,Pf,LH;var Ff=x(()=>{st();st();Rt();vr();MH=V((e)=>Rs(e)),Hl=V((e)=>Tr(e));fP=["model","model_reasoning_effort","service_tier","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.default_mode_request_user_input","features.multi_agent","features.multi_agent_v2","features.context_management","features.context_management.experimental_mode"],FH=V((e)=>jl(e));mP=V((e)=>nb(e)),hP=V((e)=>yP(e)),gP=V((e)=>xP(e)),Pf=V((e)=>Cs(e)),LH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function HH(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function SP(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)=>HH(e[i]))}function wP(e){if(!ae(e)||!qe(e))return!1;return SP(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||SP(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function Lf(e){return ae(e)&&qe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function vP(e){return ae(e)&&qe(e)&&Lf(e.thread)}function VH(e){return ae(e)&&qe(e)&&typeof e.id==="string"}function ti(e){return ae(e)&&qe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function TP(e){return ae(e)&&qe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||wP(e.usage))}function zH(e){return ae(e)&&qe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>ae(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>ae(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 EP(e){if($l.some((t)=>t===e))return"permissions";if(Ul.some((t)=>t===e))return"approval";if(GS.some((t)=>t===e))return"elicitation";if(YS.some((t)=>t===e))return"dynamic_tool";return"other"}var bP,Vl,_P,zl,$H,ib,Kl,jH,Df,ab,sb,BH,Wl,cb,lb,ub,pb,db,fb,mb,hb,gb,yb,xb,Sb,bb,_b,wb,vb,Tb,Eb,Ob,Rb,Cb,kb,Ab,Ib,Pb,Mb,Nb,Fb,x4,KH,S4;var Lb=x(()=>{Rt();vr();Cf();Ff();bP=A.pipe(pe(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),Vl=be(A.pipe(vs(1)),nn.pipe(Ze((e)=>Number.isSafeInteger(e)))),_P=_({code:nn.pipe(Ze((e)=>Number.isSafeInteger(e))),message:A,data:v(dn)}),zl=be(_({id:Vl,result:dn}),_({id:Vl,error:_P})),$H=_({id:Vl,error:_P}),ib=_({method:bP,params:v(dn)}),Kl=_({id:Vl,method:bP,params:v(dn),trace:v(dn)});jH=V(wP),Df=_({clientInfo:_({name:io,version:io,title:be(io,mt)}),capabilities:be(_({experimentalApi:Z,requestAttestation:Z,mcpServerOpenaiFormElicitation:v(Z),optOutNotificationMethods:v(be(j(A),mt)),extensions:v(Xo)}),mt)}),ab=V((e)=>ae(e)&&qe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),sb=_({method:T("initialized")});BH=V(Lf);Wl=V((e)=>vP(e)||VH(e)),cb=Wl,lb=Wl,ub=V(ti),pb=V((e)=>ae(e)&&qe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),db=V((e)=>vP(e)),fb=V((e)=>{if(!ae(e)||!qe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>Lf(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>Lf(r));return t&&e.threads===void 0||n&&e.data===void 0}),mb=V((e)=>ae(e)&&qe(e));hb=V(ti),gb=V(ti),yb=V(ti),xb=V((e)=>ae(e)&&qe(e));Sb=V((e)=>ti(e)&&(Array.isArray(e.input)&&e.input.every((t)=>qe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),bb=V((e)=>ti(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>qe(t))),_b=V((e)=>ae(e)&&qe(e)&&(e.turn!==void 0&&TP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),wb=V((e)=>ae(e)&&qe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),vb=V((e)=>ti(e)&&typeof e.turnId==="string"&&e.turnId.length>0),Tb=V((e)=>ae(e)&&qe(e)),Eb=V((e)=>ti(e)&&(e.turn!==void 0&&TP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),Ob=V((e)=>ae(e)&&qe(e));Rb=V((e)=>ae(e)&&qe(e)&&Array.isArray(e.data)&&e.data.every((t)=>zH(t))),Cb=Xo,kb=Xo,Ab=_({includeLayers:v(Z),cwd:v(be(A,mt))}),Ib=_({config:Hl,origins:Xo,layers:be(j(Xo),mt)}),Pb=Xo,Mb=Xo,Nb=V((e)=>ae(e)&&qe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&ae(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),Fb=dn,x4=V((e)=>ae(e)&&qe(e)&&typeof e.kind==="string"&&typeof e.method==="string");KH=be(T("stable","experimental","disabled"),Z),S4=ff({key:A,value:KH})});class qf{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??ql,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new J("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new J("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=WH){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new J("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Ne(Df,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",mb,e,Wl)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",hb,t,cb)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",gb,t,db)}async listThreads(e={}){return this.action("thread/list",xb,e,fb)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",yb,t,lb)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",ub,t,pb)}async startTurn(e){return this.action("turn/start",Sb,e,_b)}async steerTurn(e){return this.action("turn/steer",bb,e,wb)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",vb,n,Tb)}async listModels(e={}){return this.action("model/list",Ob,e,Rb)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",Cb,e,kb)}async readConfig(e={}){return this.action("config/read",Ab,e,Ib)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",Pb,e,Mb)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Ne(Df,t,"initialize parameters"));return Ne(dn,r,"initialize result")}let n=Ne(Kl,{id:1,method:e,params:t},"App Server method");if(!JH.has(n.method))throw new J("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 J("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Ne(dn,e,"initialize parameters")),n=Ne(ab,t,"initialize result"),r=Ne(sb,ZS,"initialized notification");return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(t){let n=t instanceof J?t:new J("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(n),n}}async action(e,t,n,r){let o=Ne(t,n,`${e} parameters`),i=Ne(dn,o,`${e} parameters`),a=await this.request(e,i);return Ne(r,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new J("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=Ne(Kl,{id:n,method:e,params:t},`${e} request`);return new Promise((o,i)=>{let a=!1,s,c,l=(p)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(p)};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new J("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let p=()=>l(new J("cancellation",`The ${e} request was cancelled.`,{method:e}));this.signal.addEventListener("abort",p,{once:!0}),c=()=>this.signal?.removeEventListener("abort",p)}let u={method:e,resolve:(p)=>{if(a)return;if(a=!0,s!==void 0)clearTimeout(s);c?.(),o(p)},reject:l,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,u),this.transport.writeLine(JSON.stringify(r)).catch((p)=>{l(p instanceof J?p:new J("transport_failure","The App Server request could not be written.",{},{cause:p}))})})}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 J("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new J("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof J?e:new J("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 J("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let n=this.tryDecode(zl,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(Kl,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(ib,t);if(o!==void 0){this.handleNotification(o);return}throw Ue("JSON-RPC message",t)}tryDecode(e,t){try{return Ne(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new J("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=YH(t.method);t.reject(new J(r,`The App Server rejected ${t.method}: ${pn(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:oa(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Ne(Nb,{...e,params:t,category:EP(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,pn(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,pn(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Ne(Fb,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,pn(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=Ne(zl,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Ne(zl,{id:e,error:{code:t,message:GH(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===XS){let n=Ne(Eb,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:uP({params:oa(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 J("closed","The App Server client is closed.")}}function GH(e){let t=pn(e);return t.length>0?t:"server request failed"}function YH(e){if($l.some((t)=>t===e))return"permission_denied";if(Ul.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var WH,JH;var Db=x(()=>{vr();Cf();Lb();WH={clientInfo:{name:"holycodex",title:null,version:KS},capabilities:null},JH=new Set(JS)});import{isAbsolute as ZH}from"path";function ni(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 qb(e=process.env){return Object.freeze(ni(e))}async function Uf(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 J("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 $f(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new J("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}}function Is(e){return pn(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}class Hf{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!ZH(e.executablePath))throw new J("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??ql,this.maxDiagnosticBytes=e.maxDiagnosticBytes??WS,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new J("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:ni(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new J("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new J("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 J("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 J("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 J("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 J)throw t;throw new J("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new J("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new J("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 J("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 Uf(this.stderrStream,this.maxDiagnosticBytes),t=$f(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=Is(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var jf=x(()=>{vr()});import{lstat as k4,mkdir as A4,readFile as XH,readdir as I4,realpath as QH,stat as ej}from"fs/promises";import{delimiter as tj,isAbsolute as M4,join as N4,relative as F4,resolve as OP}from"path";async function rj(e){let t=[];if(e.executablePath!==void 0)t.push(OP(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(tj).filter((i)=>i.length>0))for(let i of r)t.push(OP(o,i))}for(let n of t)try{let r=await ej(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await QH(n)}catch{if(e.executablePath!==void 0)throw new J("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new J("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function oj(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 J("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await aj(Promise.all([Uf(n.stdout,16384),Uf(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=pn($f(r,"Codex version output"));if(i!==0||a.length===0){let s=Is($f(o,"Codex version diagnostics"));throw new J("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 J)throw r;throw new J("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function ij(e){let t=await XH(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=yf(r);if(!o.ok)throw new J("discovery_failed","The Codex executable digest was invalid.");return o.value}async function Ub(e={}){let t=await rj(e),n=ni(e.environment),r=e.versionRunner?pn(await e.versionRunner(t,n)):await oj(t,n);if(r.length===0)throw new J("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await ij(t)}}async function aj(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new J("timeout",n))},nj)})])}finally{if(r!==void 0)clearTimeout(r)}}var nj=30000,U4;var RP=x(()=>{st();Rt();vr();jf();U4=_({exitCode:nn.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:A.pipe(dS(1048576)),stderr:A.pipe(dS(1048576))})});var sj="packages/codex/generated",cj,lj,$b,B4,V4;var CP=x(()=>{st();Rt();vr();cj=/^codex-cli \d+\.\d+\.\d+$/u,lj=/^codex-app-server-\d+\.\d+\.\d+$/u,$b=A.pipe(pe(/^[a-f0-9]{64}$/u)),B4=_({schema_version:T("holycodex-generated-v2"),artifact_root:T(sj),codex_cli_version:A.pipe(pe(cj)),codex_cli_digest:$b,protocol_epoch:A.pipe(pe(lj)),generator:_({command:lI(T("app-server"),T("generate-ts")),supported_surface:T("codex app-server generators")}),typescript_root:T("typescript"),files:_({count:nn.pipe(mf(),mS()),digest:$b})}),V4=_({path:A.pipe(vs(1)),size:nn.pipe(mf(),mS()),sha256:$b})});var uj;var kP=x(()=>{Rt();Ff();uj=_({owner:T("holycodex"),schema:A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});import{spawn as pj}from"child_process";import{lstat as oi,mkdir as dj,mkdtemp as fj,readFile as mj,readdir as hj,realpath as Hb,rename as gj,rm as yj,stat as Y4}from"fs/promises";import{dirname as IP,isAbsolute as Kb,join as ri,relative as PP,resolve as Vf,sep as MP}from"path";async function FP(e){let t=Yb(e.selectedPluginIds);if(t.length===0)return;if(UP(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new ve("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>Gb(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&Kf(r,t))return r;let o=e.initializeRuntime??(()=>Cj(e)),i,a;try{i=await o()}catch(s){a=ee("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??Jb,c=e.pollIntervalMs??xj,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new ve("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&Kf(u,t))return u;let p=s-(Date.now()-l);if(p<=0)break;await(e.sleep??Aj)(Math.min(c,p))}a=ee("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 ve&&s.code==="cancelled")throw s;a=s instanceof ve?s:ee("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await LP({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 ve)throw s;throw ee("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??ee("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function LP(e){let t=Yb(e.selectedPluginIds);if(t.length===0)throw ee("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(UP(e.timeoutMs,void 0),!Kb(e.codexHome))throw ee("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new ve("cancelled","Official Codex marketplace fallback was cancelled.");let n=ni(e.environment),r=e.gitRunner??jP("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??Jb,i;try{i=await _j(r,o,e.signal)}catch(u){if(u instanceof ve)throw u;throw ee("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=ri(e.codexHome,"plugins"),s=ri(a,Wb[1]);if(await vj(a,e.codexHome),await oi(s).catch((u)=>{if(Zl(u))return;throw ee("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw ee("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await fj(ri(a,".openai-plugins-stage-"));try{if(await Bb(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(aa,l)}catch(m){if(kj(m))throw ee("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",aa,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw ee("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await zf(l);let u=await DP(l,e.codexHome,t);if(u===void 0||!Kf(u,t))throw ee("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await wj(r,l,o,e.signal)!==i)throw ee("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await oi(s).catch((m)=>{if(Zl(m))return;throw ee("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw ee("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await gj(l,s);let h=await Gb(e.codexHome,e.selectedPluginIds);if(h===void 0||!Kf(h,t))throw ee("marketplace_invalid","The published official marketplace failed validation.");return h}catch(u){if(u instanceof ve)throw u;throw ee("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await yj(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function _j(e,t,n){let r=await e.run(["ls-remote",aa,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw ee("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 ee("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function wj(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 ee("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function vj(e,t){await jb(t,e),await dj(e,{recursive:!0}),await jb(t,e)}async function jb(e,t){let n=Vf(e),r=Vf(t);while(!0){if((await oi(r).catch((a)=>{if(Zl(a))return;throw a}))?.isSymbolicLink())throw ee("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=IP(r);if(i===r||i!==n&&!Tj(n,i))throw ee("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function Tj(e,t){let n=PP(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${MP}`)&&!Kb(n)}async function zf(e){let t=await oi(e);if(t.isSymbolicLink())throw ee("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw ee("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await hj(e,{withFileTypes:!0});for(let r of n){let o=ri(e,r.name),i=await oi(o);if(i.isSymbolicLink())throw ee("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await zf(o)}}async function Gb(e,t=[]){return await DP(ri(e,...Wb),e,Yb(t))}async function DP(e,t,n=[]){if(t!==void 0)await jb(t,e);let r=await oi(e).catch((l)=>{if(Zl(l))return;throw ee("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 ee("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await Bb(t,e);else await zf(e);if(t!==void 0)await zf(e);let o=await Hb(e),i=[ri(o,".agents","plugins","marketplace.json"),ri(o,".codex-plugin","marketplace.json"),ri(o,"marketplace.json")],a,s;for(let l of i){let u=await oi(l).catch((p)=>{if(Zl(p))return;throw ee("marketplace_invalid","The official marketplace manifest could not be read safely.",p)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw ee("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await Bb(o,l),a!==void 0)throw ee("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await mj(l))}catch(p){throw ee("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",p)}}if(a===void 0||s===void 0)return;let c;try{c=JSON.parse(s)}catch(l){throw ee("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return qP(c,o,a,n)}function qP(e,t=`${Wb.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!ae(e)||e.name!==Yl)throw ee("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");Ej(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw ee("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!ae(s)||typeof s.name!=="string"){if(r.length>0)continue;throw ee("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 ee("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw ee("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=Oj(s);if(!Rj(l))throw ee("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 ee("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:Yl,source:aa,rootPath:t,manifestPath:n,plugins:i}}function Ej(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:ae(n)&&typeof n.url==="string"?n.url:void 0)!==aa)throw ee("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function Oj(e){let t=e.source;if(typeof t==="string")return t;if(ae(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function Rj(e){if(e===void 0||e.length===0||Kb(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 Yb(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!==Yl&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw ee("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!$P(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function Kf(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 Cj(e){let t=ni(e.environment),n;try{n=new Hf({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new qf(n,{requestTimeoutMs:Math.min(e.timeoutMs??Jb,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 UP(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw ee("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw ee("marketplace_invalid","The official marketplace poll interval is invalid.")}async function Bb(e,t){let n=await Hb(e),r=await Hb(t),o=PP(n,r);if(o===""||o===".."||o.startsWith(`..${MP}`))throw ee("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=Vf(e),a=Vf(t);while(!0){if((await oi(a)).isSymbolicLink())throw ee("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=IP(a);if(c===a)throw ee("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Zl(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function kj(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function Aj(e){await new Promise((t)=>setTimeout(t,e))}function ee(e,t,n){return new ve(e,t,n instanceof Error?{cause:Is(n.message)}:{})}function Er(e,t){let n=Yn(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=yS(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 $P(e){return gf.includes(e)}function HP(e){if(!pP(zb,e))return cP(Ue("live official plugin list",e));return lP(Ne(zb,e,"live official plugin list"))}function Wf(e){let t=e.runner??jP(e.executable,{environment:e.environment??ni(),...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 Bf("list",r);let o;try{o=JSON.parse(r.stdout)}catch{throw new ve("command_failed","Codex returned invalid plugin data.")}let i=HP(o);if(!i.ok)throw new ve("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 ve("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await FP({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=Ne(Gl,r,"plugin marketplace source");if(i===Yl||i===aa)throw new ve("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 Bf("marketplace add",a,i)},add:async(r,o)=>{let i=Ne(Gl,r,"official plugin id"),a=await t.run(["plugin","add",i,"--json"],o===void 0?void 0:{signal:o});if(a.exitCode!==0)throw Bf("add",a,i);let s=await n(),c=Er(s,i),l=Yn(i),u=[...s.installed,...s.available].filter((f)=>f.pluginId===i&&(l===void 0||f.marketplaceName==null)),p=c?.entry??u.find((f)=>f.installed)??u[0];if(!p)throw new ve("readback_mismatch",`Codex did not report ${i} after installation.`,{plugin_id:i});if(!p.installed)throw new ve("plugin_missing",`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!p.enabled)throw new ve("plugin_disabled",`Codex installed ${i} but it is disabled; enable it in Codex and retry.`,{plugin_id:i})},remove:async(r,o)=>{let i=Ne(Gl,r,"official plugin id"),a=i;if(Yn(i)===i){let u=await n(),p=Er(u,i);if(p?.entry.installed)a=p.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 Bf("remove",s,a);let c=await n(),l=[...c.installed,...c.available].find((u)=>u.pluginId===a);if(l?.installed)throw new ve("readback_mismatch",`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:l.pluginId})}}}function Bf(e,t,n){let r=Is(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new ve("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function jP(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>Pj(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 Pj(e,t,n){if(n.signal?.aborted)throw new ve("cancelled","The Codex plugin command was cancelled.");let r=pj(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=AP(r.stdout,n.stdoutLimit),i=AP(r.stderr,n.stderrLimit),a=new Promise((p,f)=>{r.once("error",f),r.once("close",(h)=>p(h??-1))}),s,c,l=new Promise((p,f)=>{c=()=>{try{r.kill()}catch{}f(new ve("cancelled","The Codex plugin command was cancelled."))},n.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((p,f)=>{s=setTimeout(()=>{try{r.kill()}catch{}f(new ve("timeout","The Codex plugin command timed out."))},n.timeoutMs)});try{let[p,f,h]=await Promise.race([Promise.all([o,i,a]),l,u]);return{stdout:p,stderr:f,exitCode:h}}catch(p){try{r.kill()}catch{}if(p instanceof ve)throw p;throw new ve("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function AP(e,t){if(e===null)return Promise.reject(new ve("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 ve("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new ve("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 Yl="openai-curated",aa="https://github.com/openai/plugins.git",Wb,Jb=30000,xj=100,NP,Sj,Jl,Gl,bj,Ij,Vb,zb,ve;var Zb=x(()=>{st();Rt();Db();vr();jf();Wb=["plugins","openai-plugins"],NP=A.pipe(pe(/^[a-z][a-z0-9._-]{1,63}$/u)),Sj=A.pipe(pe(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),Jl=j(A),Gl=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),bj=_({name:NP,version:Sj,description:io,author:v(dn),license:v(io),homepage:v(io),repository:v(io),keywords:v(Jl),skills:v(Jl),commands:v(Jl),hooks:v(Jl),assets:v(Jl),official:v(Z)});Ij=_({id:NP,selected:T(!0)}),Vb=_({pluginId:Gl,installed:Z,enabled:Z,name:v(be(A,mt)),marketplaceName:v(be(A,mt)),version:v(be(A,mt))},ff({key:A,value:sS})),zb=_({installed:j(Vb),available:j(Vb)});ve=class ve extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});var Xl=x(()=>{vr();vr();Cf();Lb();Db();jf();RP();CP();kP();Ff();Zb();Zb()});function fn(e){if(!Ps(e))throw Error("The value is not JSON serializable.");return _r(e),e}function Ps(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)=>Ps(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>Ps(n,t))}finally{t.delete(e)}}var Ql=x(()=>{st()});function St(e,t){let n=Cn(e,t);return kt(n)?n.right:void 0}function WP(e){return St(Gf,e)!==void 0}var Gf,H8,Yf,eu,Mj,Ms,Nj,Fj,VP,Xb,tu,Zf,Ns,Xf,Lj,Dj,qj,Uj,$j,Hj,Jf,jj,BP,Bj,Qb,Fs,Vj,zP,zj,KP,Kj,Wj,Kt;var Ls=x(()=>{Xl();st();an();Rt();Ql();Gf=V((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&Ps(e)),H8=V(Ps),Yf=A.pipe(pe(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)),eu=A.pipe(pe(/^[0-9a-f]{64}$/u)),Mj=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Ms=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),Nj=A.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),Fj=_({path:A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:eu}),VP=_({computer_use:Z,frontend:Z,security:Z,coding:T(!0)}),Xb=_({computer_use:v(Z),frontend:v(Z),security:v(Z)}),tu=_({profile:v(Go),tier:v(ea),optional:v(Xb),officialPlugins:v(j(Ms))}),Zf=tu,Ns=_({selected:Z,status:T("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:j(Ms),reason:v(A)}),Xf=_({computer_use:Ns,frontend:Ns,security:Ns}),Lj=_({...VP.fields,work:Z}),Dj=_({...Xb.fields,work:v(Z)}),qj=_({...Xf.fields,work:Ns}),Uj=be(_({status:T("not_applicable")}),_({status:T("missing")}),_({status:T("healthy"),path:A,installed:Z})),$j=_({manager:T("bun","npm","pnpm"),launcher:T("bunx","npx","pnpm dlx"),version:Yf,executable:A,ownership:T("user","holycodex"),identity:v(eu)}),Hj=_({git_bash:Uj,context7:$j}),Jf=_({presence:T("absent","present"),digest:eu,safe_value:v(be(_({kind:T("boolean"),value:Z}),_({kind:T("marketplace"),source_type:T("git"),source:T("https://github.com/davidbasilefilho/holycodex.git")})))}),jj=_({plugin_id:T("holycodex@holycodex"),before:_({preference:Jf,marketplace:Jf}),after:_({preference:Jf,marketplace:Jf})}),BP=_({presence:T("absent","present"),digest:eu,safe_value:v(_({kind:T("boolean"),value:Z}))}),Bj=_({plugin_id:Ms,before:BP,after:BP}),Qb={owner:T("holycodex"),schema_epoch:T(yn),install_id:Mj,version:Yf,digest:eu,profile:Go,tier:ea,optional_selections:VP,explicit_optional_selections:Xb,official_plugins:v(j(Ms)),capability_state:v(Xf),managed_artifacts:j(Fj),installed_at:Nj,status:v(T("active")),step:v(T("active")),managed_config:v(Pf),plugin_snapshot:v(j(_({plugin_id:Ms,status:T("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:v(jj),provider_config:v(j(Bj)),owned_plugins:v(j(Ms)),tooling:v(Hj)},Fs=_(Qb),Vj=(({profile:e,...t})=>t)(Qb),zP={...Qb,optional_selections:Lj,explicit_optional_selections:Dj,capability_state:v(qj)},zj=(({profile:e,...t})=>t)(zP),KP=be(_({...zP,profile:kl}),_({...zj,plan:kl}),_({...Vj,plan:kl})),Kj=T("preparing","conflicted"),Wj=T("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),Kt=_({...Fs.fields,status:Kj,step:Wj})});import{lstat as Jj,mkdir as Gj}from"fs/promises";import{homedir as Yj}from"os";import{dirname as Zj,join as sa,posix as JP,resolve as Xj,sep as GP,win32 as YP}from"path";function ii(e={},t=process.env){let n=Yj(),r=e.paths?.codexHome??t.CODEX_HOME??sa(n,".codex"),o=t_(r,"CODEX_HOME"),i=sa(o,Qj);return{codexHome:o,stateRoot:i,activeRecord:sa(i,e1),preparingRecord:sa(i,t1),conflictedRecord:sa(i,n1),roleRoot:sa(i,"agents"),configFile:sa(o,"config.toml")}}function t_(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||o1(e))throw new An("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?YP:JP,o=e_(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new An("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":GP).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new An("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new An("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function o1(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function nu(e){t_(e,"owned path"),await Or(e),await Gj(e,{recursive:!0}),await Or(e)}async function Or(e){let n=Xj(e);while(!0){try{if((await Jj(n)).isSymbolicLink())throw new An("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof An)throw o;if(!bt(o,"ENOENT"))throw o}let r=Zj(n);if(r===n)break;n=r}}async function ca(e){await Or(e)}function so(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?YP:JP,o=r.resolve(e_(e,n)),i=r.resolve(e_(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":GP}`)&&a!==".."&&!r.isAbsolute(a)}function e_(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function bt(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var Qj="holycodex",e1="active.json",t1="preparing.json",n1="conflicted.json",r1,An;var la=x(()=>{st();r1=yn;An=class An extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as ZP,open as i1,readFile as XP,rename as a1,unlink as s1,writeFile as c1}from"fs/promises";import{dirname as l1}from"path";async function QP(e){let t;try{t=await i1(e,"r"),await t.sync()}catch(n){if(!eM(n))throw n}finally{await t?.close().catch(()=>{return})}}async function p1(e){await QP(e).catch((t)=>{if(!eM(t))throw t})}async function pa(e,t){await co(e,`${_r(t)}
36
- `)}async function co(e,t){let n=l1(e);await nu(n),await Or(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await c1(r,t,{encoding:"utf8",mode:384}),await QP(r),await a1(r,e),await p1(n)}catch(o){throw await s1(r).catch(()=>{return}),o}}async function d1(e,t){let n=await ZP(e);if(!n.isFile()||n.isSymbolicLink())throw new ua("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await XP(e,"utf8"))}catch(i){throw new ua("state_corrupt","A persisted file is not valid JSON.",i)}let o=St(t,r);if(o===void 0)throw new ua("state_corrupt","A persisted file failed schema validation.");return o}async function qt(e){try{let t=await ZP(e);if(!t.isFile()||t.isSymbolicLink())throw new ua("state_corrupt","A persisted file is not a regular file.");return await XP(e,"utf8")}catch(t){if(bt(t,"ENOENT"))return;throw t}}async function mn(e,t){try{return await d1(e,t)}catch(n){if(bt(n,"ENOENT"))return;throw n}}function eM(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return u1.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var u1,ua;var Ds=x(()=>{st();la();Ls();u1=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);ua=class ua extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as f1}from"fs/promises";import{dirname as m1,resolve as h1}from"path";import{fileURLToPath as g1}from"url";async function tM(e=ru){let t=JSON.parse(await f1(e,"utf8")),n=St(x1,t);if(n===void 0)throw new ou("manifest_invalid","The public package manifest is invalid.");return n}async function Qf(e=ru){return(await tM(e)).version}async function qs(e=ru){return(await Qf(e)).split("-",1)[0]??""}async function n_(e,t,n=ru){let r=await tM(n),o=await qs(n),i=S1(e,o);if(!t)await pa(n,{...r,version:i});return{previous:o,next:i}}function S1(e,t){if(e!=="patch"&&e!=="minor"){if(St(Yf,e)===void 0)throw new ou("version_invalid","The version target is invalid.");return e}let n=t.split("."),r=Number(n[1]),o=Number(n[2]);return e==="minor"?`0.${r+1}.0`:`0.${r}.${o+1}`}var y1,x1,ru,ou;var iu=x(()=>{Rt();Ls();Ds();y1=A.pipe(pe(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*\.[1-9]\d*)?$/u)),x1=V((e)=>WP(e)&&e.name==="holycodex"&&St(y1,e.version)!==void 0),ru=h1(m1(g1(import.meta.url)),"../package.json");ou=class ou extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{lstat as em,readFile as tm,rm as Us}from"fs/promises";import{join as Qe,relative as nM}from"path";async function nm(e,t,n=[],r="standard",o){let i=Qe(e,"holycodex","agents"),a=ai(t,r).map((l)=>({path:Qe(i,`${l.name}.toml`),contents:au(l,o===void 0?{}:{windowsGitBashExecutable:o})})),s=new Map(n.map((l)=>[Qe(e,l.path),l])),c=[];for(let l of a){let u=await da(l.path),p=s.get(l.path);if(u!==void 0&&p===void 0&&u!==l.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${l.path}`);if(u!==void 0&&p!==void 0&&await Rr(u)!==p.digest&&u!==l.contents)c.push({path:l.path,action:"replace"})}for(let l of n){let u=Qe(e,l.path);if(a.some((f)=>f.path===u)||!oM(e,u,l.path))continue;let p=await da(u);if(p!==void 0&&await Rr(p)!==l.digest)c.push({path:u,action:"remove"})}return c}async function rM(e,t){let n=Qe(e,"agents"),r=Qe(e,"holycodex","agents"),o=[];for(let i of t){let a=Qe(e,i.path);if(!so(e,a)||!so(n,a)&&!so(r,a)&&a!==Qe(e,"config.toml"))continue;let s=await da(a);if(s!==void 0&&await Rr(s)!==i.digest)o.push({path:a,action:"remove"})}return o}function ai(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:OS(o),rolePolicy:kn.find((i)=>i.role===r.role),description:CS(o),taskInstruction:RS(o),permissions:kS(o),model:"gpt-5.6-luna",effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function r_(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 o_(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e,n=t.computerUse??!1;if(!re.requiresDelegation||!re.assignmentStartAndDispatchPrecedeDelegableExecution||!re.trivialWorkRequiresDelegation||!re.preparatoryAndExploratoryWorkRequiresDelegation||re.genericDirectWorkFallback||re.directExecutionExceptions!==re.rootOwnedAuthority||!re.codeReviewRequiredForImplementation||!re.codeReviewRequiredBeforeVcs||!re.externalVerificationMustBeTerminal||!re.concreteSpecialistDispatchRequired||!re.roleFamiliesAreLabelsOnly||!re.missingConcreteRouteIsBlocker||!re.normalSpawnRequiresExplicitForkTurns||re.normalSpawnForkTurns!=="none"||!re.normalSpawnUsesConcreteRegisteredAgentType||!re.assignmentContextIsTaskSpecificOnly||!re.configuredRouteModelAndEffortPreserved||re.normalProgressMessages||re.normalHeartbeatMessages||re.normalIntermediateEvidence||!re.userUpdatesUsefulOrImportantOnly||!re.routinePerToolOrSubagentNarrationForbidden||!re.routineStatusOnlyChatterForbidden||!re.fixedCadenceUserUpdatesForbidden||!re.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!re.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!re.materialUserUpdateKinds.includes("release_milestones")||!re.outOfBoundaryRequiresNewAssignment||!re.longestPracticalEventWait||!re.busyPollingForbidden||!re.statusOnlyCoordinationLoopsForbidden||!re.batchIndependentLifecycleActions||!re.releaseLeavesAfterAcceptedOutcome||re.registeredSpecialistAgentTypes!==br||re.forbiddenGenericAgentTypes!==wf)throw Error("The Root orchestration policy is incomplete.");let r=[`You are the HolyCodex Root/session orchestrator running gpt-6-astra. Root directly owns only ${re.rootOwnedAuthority.map((o)=>_1[o]).join("; ")}. These actions remain subject to their approval and capability boundaries.`,`Delegate every delegable action with a bounded Assignment and dispatch spawn_agent using the exact concrete registered Role.task agent_type selected from this canonical HolyCodex inventory: ${re.registeredSpecialistAgentTypes.join(", ")}. The role families Explorer, Librarian, Worker, and Reviewer are labels only and are never dispatch targets. Generic built-in agent_type values ${re.forbiddenGenericAgentTypes.join(", ")} are forbidden for HolyCodex specialist Assignments. If no matching concrete registered route is available, stop with needs_root_input; never substitute a generic agent. This includes ${re.delegableActions.map((o)=>w1[o]).join("; ")}. Starting the Assignment and dispatching its specialist must precede every such inspection or execution, including trivial, preparatory, and exploratory work. There is no generic Root direct-work fallback. Root may inspect returned evidence for integration acceptance. Root-only execution does not grant Root authority to perform specialist work.`,`For every normal specialist spawn, pass the exact concrete Role.task agent_type and explicitly set fork_turns: "${re.normalSpawnForkTurns}"; never omit fork_turns or use "all" or its default. Preserve the selected route's configured model and reasoning effort. Each Assignment must be self-contained and carry only task-specific semantic context for its bounded objective, scope, constraints, exclusions, dependencies, acceptance criteria, and relevant evidence.`,"Use holycodex-agent semantic operations for Intent, optional Plan, and Assignment state. Never edit TOON state or create standalone handoff, Decision, or blocker files.","Explicit user instructions override skill guidelines on conflict except genuine HolyCodex hard safety, authority, capability, and lifecycle invariants. Infer routine safe, reversible, in-scope choices and carry authorized read-only, reversible, preparatory, and independent work through implementation, inspection, repair, meaningful proof, required CI, and every requested terminal state. Ask only for a material unresolved choice, a genuine approval boundary such as installation profile approval or remote/public external mutation, user-owned credential entry, or a blocker that can change the outcome; persist needs_root_input when applicable. Out-of-boundary work returns to Root for a new bounded Assignment.","Dispatch independent non-overlapping Assignments concurrently, keep dependent phases ordered, and serialize writes to one mutable seam. Use writing-instructions for GPT-6 model-facing contracts, add only the missing semantic delta for the receiver's effective context, and keep each meaning with one authoritative owner.","Make each phase a coherent dependency, decision, or integration boundary. Resolve choices needed by the current phase, persist Plan and Assignment evidence, and advance after acceptance; do not ask later-phase questions prematurely.","Give the user only useful or important information. Do not output after every tool use or subagent update, emit routine status-only chatter or heartbeat messages, or follow a fixed update cadence. Material updates include significant findings or decisions, consequential blockers or input needs, and release milestones. Preserve native Astra Default questions, including asking while independent work proceeds; this rule adds no question protocol.","Use the longest practical event wait and never busy-poll or run status-only coordination loops. Batch independent lifecycle actions and stop or release specialist leaves once their accepted terminal outcomes are recorded.",`${vf.rule} Do not add tests for low-impact reversible changes when they merely mirror implementation details. Once relevant proof passes, broaden or repeat it only after another source change, a failure, or an unresolved material concern. Mandatory repository gates and Reviewer.code remain required. Inspect specialist evidence before integration; Worker.validation supplies independent local proof without replacing implementation proof or Reviewer.code. Reviewer.code fixed-point review is mandatory after implementation or a major codebase change and before completion or VCS.`,`For current technical documentation, Librarian.lookup and Librarian.research resolve the library identity and use Context7 before model memory or generic web, query narrowly, and return one typed evidence state (${IS.evidenceStates.join(" | ")}) in the context7 field with version/source evidence. Fallback is allowed only for one of those states or an absent required version; authoritative first-party documentation resolves conflicts. Context7 supplies facts while Root owns material product, architecture, dependency, compatibility, and implementation decisions.`,"After integration, Root performs approved VCS actions and dispatches Worker.operations with the exact ref or SHA for terminal CI or release evidence. Pending is never success. Discover the actual topology; repair failures through bounded Assignments and repeat integration, fixed-point review, VCS, and terminal observation until the applicable gate is green."];if(t.frontend??!0)r.push(v1());if(t.security??!0)r.push("Security is selected. Use threat-model for material trust-boundary changes, security-diff-scan before VCS for security-sensitive diffs, and full security-scan for explicit audits, substantial new exposed surfaces, or broader systemic concern. Validate supported findings before blocking. A validated vulnerability introduced or worsened by the change blocks VCS until repaired or explicitly risk-accepted; report unrelated pre-existing findings without expanding scope. Security-driven edits invalidate Reviewer.code, and security-sensitive Reviewer.code edits invalidate the applicable security review; repeat both gates until green together.");if(n)r.push("Computer Use is selected and is directly executable by Root/session only; it must not be delegated.","For interactive authentication, use Computer Use with the user's default browser unless the builtin browser is that default. Navigate to authentication, hand control to the user, wait while the user personally enters and submits every credential, then resume from the authenticated session. Never ask for credentials in chat or type, paste, retrieve, infer, expose, store, or submit them. If no authorized Computer Use/default-browser path exists, report the capability blocker.");else r.push("Computer Use is unavailable for this installation and cannot be delegated. GUI and browser execution remain Root/session-only.");if(t.windowsGitBashExecutable!==void 0)r.push(a_(t.windowsGitBashExecutable));return r.join(`
37
- `)}function v1(){if(!Yo.repositoryAndUserRequirementsPrecedePluginDefaults||!Yo.specialistsOwnInspectionImplementationAndRepair||!Yo.rootOwnsLiveVisualAndInteractionAcceptance||!Yo.sourceChangesInvalidateRenderEvidence||!Yo.specialistReportsCannotSubstituteForRootAcceptance||Yo.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`Frontend is selected. For a user-visible frontend task, ${Qi.frontend.applicability.map(({skillId:n,appliesWhen:r})=>`${r} uses ${n}`).join("; ")}. Repository stack, existing design system, and explicit user requirements govern over generic plugin defaults. Specialists inspect, implement, and repair; Root renders, opens, and interacts with the current result, judges it against the accepted outcome, delegates concrete discrepancies, and repeats repair and live acceptance to a fixed point. Every source change invalidates earlier render evidence. Build results, specialist reports, and Reviewer.artifact cannot replace Root's acceptance of the current UI. Apply proportional responsive, accessibility, and core-interaction checks; logic-only nonvisual changes do not require visual ceremony.`}async function i_(e,t,n=[],r="standard",o,i,a=[]){let s=Qe(e,"holycodex","agents"),c=[],l=[],u=ai(t,r).map((S)=>({path:Qe(s,`${S.name}.toml`),contents:au(S,o===void 0?{}:{windowsGitBashExecutable:o})})),p=new Map(n.map((S)=>[Qe(e,S.path),S])),f=new Map,h=new Set;for(let S of u){let E=await da(S.path);f.set(S.path,E);let w=p.get(S.path);if(E!==void 0&&w===void 0&&E!==S.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${S.path}`);if(E!==void 0&&w!==void 0){if(await Rr(E)!==w.digest&&E!==S.contents){let g={path:S.path,action:"replace",key:void 0},R=a.some((C)=>C.path===g.path&&C.action===g.action&&C.key===g.key)?"accept":await i?.(g);if(R==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${S.path}`);if(R==="accept")h.add(S.path)}}}let m=[];try{for(let b of u){let g=f.get(b.path),O=p.get(b.path);if(g!==void 0&&O!==void 0){if(await Rr(g)!==O.digest&&g!==b.contents&&!h.has(b.path)){c.push(b.path),m.push({path:nM(e,b.path).replaceAll("\\","/"),digest:O.digest});continue}}if(g===void 0||g!==b.contents)await co(b.path,b.contents),l.push({path:b.path,previous:g,installedDigest:await Rr(b.contents)});m.push({path:nM(e,b.path).replaceAll("\\","/"),digest:await Rr(b.contents)})}let S=Qe(e,"agents","root.toml"),E=await da(S),w=await iM(S);if(w==="preserved")c.push(S);if(w==="removed"&&E!==void 0)l.push({path:S,previous:E,installedDigest:void 0});for(let b of n){let g=Qe(e,b.path);if(!u.some((O)=>O.path===g)){if(!oM(e,g,b.path)){c.push(g);continue}if(a.some((C)=>C.path===g&&C.action==="remove")){let C=await da(g);if(C!==void 0)await Us(g,{force:!1}),l.push({path:g,previous:C,installedDigest:void 0});continue}let R=await O1(g,b.digest);if(R.status==="preserved")c.push(g);else if(R.previous!==void 0)l.push({path:g,previous:R.previous,installedDigest:void 0})}}for(let b of n){let g=Qe(e,b.path);if(c.includes(g)&&!m.some((O)=>Qe(e,O.path)===g))m.push(b)}return{managed_artifacts:m,preserved:c,rollback:l}}catch(S){throw await rm(l).catch(()=>{return}),S}}async function rm(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await da(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await Rr(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await Us(r.path,{force:!1}).catch((a)=>{if(!bt(a,"ENOENT"))throw a}),t.push(r.path);else await co(r.path,r.previous)}return{removed:t,preserved:n}}async function om(e,t,n=new Set){let r=[],o=[],i=Qe(e,"agents"),a=Qe(e,"holycodex","agents");for(let l of t){let u=Qe(e,l.path);if(!so(e,u)||!so(i,u)&&!so(a,u)&&u!==Qe(e,"config.toml")){o.push(u);continue}try{await Or(u);let p=await em(u);if(p.isSymbolicLink()||!p.isFile()){o.push(u);continue}let f=await tm(u);if(await Rr(f)!==l.digest){if(n.has(u)){await Us(u,{force:!1}),r.push(u);continue}o.push(u);continue}await Us(u,{force:!1}),r.push(u)}catch(p){if(!bt(p,"ENOENT"))o.push(u)}}let s=Qe(e,"agents","root.toml"),c=await iM(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);return{removed:r,preserved:o}}function au(e,t={}){let n=[b1,e.taskInstruction,...e.permissions.sourceMutation?[`Surgical mutation rule: ${bf}`]:[],...t.windowsGitBashExecutable===void 0?[]:[a_(t.windowsGitBashExecutable)]].join(`
33
+ schema (${r._tag}): ${r}`;return o},Fk=(e)=>Ko("Invalid Argument",e),Lk=(e)=>Ko("Unsupported key schema",void 0,void 0,e),Dk=(e)=>Ko("Unsupported literal",`literal value: ${ar(e)}`),fx=(e)=>Ko("Duplicate index signature",`${e} index signature`),qk,Uk,mx=(e)=>Ko("Duplicate property signature transformation",`Duplicate key ${ar(e)}`),hx=(e)=>Ko("Duplicate property signature",`Duplicate key ${ar(e)}`);var gx=x(()=>{Ve();Be();hl();qk=Ko("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),Uk=Ko("Invalid element","A required element cannot follow an optional element. ts(1257)")});var Hk,jk,Bk,Vk,zk,Wk,Kk;var Jk=x(()=>{Hk=Symbol.for("effect/SchemaId/DateFromSelf"),jk=Symbol.for("effect/SchemaId/GreaterThan"),Bk=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),Vk=Symbol.for("effect/SchemaId/Int"),zk=Symbol.for("effect/SchemaId/MinLength"),Wk=Symbol.for("effect/SchemaId/MaxLength"),Kk=Symbol.for("effect/SchemaId/MinItems")});class ys{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 Ae(gr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Yi{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Ae(gr(this),()=>ar(this.literal))}toJSON(){return{_tag:this._tag,literal:yo(this.literal)?String(this.literal):this.literal,annotations:He(this.annotations)}}}class Xd{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Ae(gr(this),()=>ar(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:He(this.annotations)}}}class sA{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class cA{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class lA{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class uA{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class pA{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class fA{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class hA{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class yA{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class SA{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class bA{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class wA{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return Kn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class xs{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:He(this.annotations)}}toString(){return String(this.type)}}class xl{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(Uk)}toString(){return Ae(gr(this),()=>l2(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:He(this.annotations)}}}class Ss{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,TA(e))this.parameter=e;else throw Error(qk)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class yr{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(hx(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=Jx(t[i].parameter);if(tf(a)){if(o.string)throw Error(fx("string"));o.string=!0}else if(_A(a)){if(o.symbol)throw Error(fx("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Ae(gr(this),()=>u2(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Vt{types;annotations;static make=(e,t)=>nf(e)?new Vt(e,t):e.length===1?e[0]:ef;static unify=(e,t)=>Vt.make(f2(EA(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Ae(gr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class rf{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=ml(e)}toString(){return gr(this).pipe(Fn(()=>Dn(hw(this.f)(),(e)=>gr(e))),Ae(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=yx.get(e);if(t)return t;return yx.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:He(this.annotations)},yx.set(e,t),t}}class Sl{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return gl(this).pipe(Ae(()=>Je(AA(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>bl(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:He(this.annotations)}}}class Bx{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 Ae(gr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:He(this.annotations)}}}class Vx{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class zx{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(mx(o));t[o]=!0;let i=r.to;if(n[i])throw Error(mx(i));n[i]=!0}}}function Rn(e,t){let n=!1,r=_i(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 x2(e){return Je(Nx(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${ar(n)}>`).join("")})}var Yk,Sx,Zk,bx,Jd,Gd,Qt,Yd,ro,_x,wx,vx,Tx,Ex,Rx,Xk,Ox,Cx,kx,Ax,Ix,Px,Mx,Nt,Nx,Qk,eA,Fx,Lx,gl,Dx,tA,nA,rA,oA,iA,qx,n2,Ux=(e)=>xw(n2(e),(t)=>t===!0),$x,r2,o2=(e)=>Fn(r2(e),()=>gl(e)),yl=(e)=>(t)=>t._tag===e,Zd,aA,Qd,i2,ef,Hx,dA,mA,tf,gA,xA,a2,s2,_A,c2,Jo,vA=(e)=>e.map((t)=>t.type),l2=(e)=>{let t=e.elements.map(String).join(", ");return _w(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}>`}})},dt,TA=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return TA(e.from)}return!1},Gk=(e)=>e.map(String).join("; "),u2=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${Gk(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${Gk(e.indexSignatures)} }`;else return"{}"},p2,d2,EA=(e)=>mc(e,(t)=>jx(t)?EA(t.types):[t]),f2=(e)=>{let t=p2(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[dA];case"UnknownKeyword":return[Hx];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=d2[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},RA=(e,t)=>e.map(t),nf=(e)=>e.length>1,jx,yx,bl,of,_l=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[Gd];let o={...r,...t},i=qx(e);if(Ie(i))o[Px]=_l(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},m2="[\\s\\S]*?",h2="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",OA=(e,t)=>{switch(e._tag){case"Literal":return ss(String(e.literal));case"StringKeyword":return m2;case"NumberKeyword":return h2;case"TemplateLiteral":return CA(e,t,!1);case"Union":return e.types.map((n)=>OA(n,t)).join("|")}},g2=(e,t,n,r)=>{if(jx(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},CA=(e,t,n)=>{let r="";if(e.head!==""){let o=ss(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=OA(o.type,t);if(r+=g2(o.type,i,t,n),o.literal!==""){let a=ss(o.literal);r+=t&&n?`(${a})`:a}}return r},kA=(e)=>new RegExp(`^${CA(e,!1,!0)}$`),Wx=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new Ss(i,t,!0));break;case"Literal":if(wt(i.literal)||rn(i.literal))n.push(new dt(i.literal,t,!1,!0));else throw Error(Dk(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new dt(s,t,!1,!0));break}case"UniqueSymbol":n.push(new dt(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(Lk(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},Kx=(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},y2,pt=(e)=>{switch(e._tag){case"Declaration":{let t=Rn(e.typeParameters,pt);return t===e.typeParameters?e:new ys(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Rn(e.elements,(o)=>{let i=pt(o.type);return i===o.type?o:new Jo(i,o.isOptional)}),n=vA(e.rest),r=Rn(n,pt);return t===e.elements&&r===n?e:new xl(t,r.map((o)=>new xs(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Rn(e.propertySignatures,(r)=>{let o=pt(r.type);return o===r.type?r:new dt(r.name,o,r.isOptional,r.isReadonly)}),n=Rn(e.indexSignatures,(r)=>{let o=pt(r.type);return o===r.type?r:new Ss(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new yr(t,n,e.annotations)}case"Union":{let t=Rn(e.types,pt);return t===e.types?e:Vt.make(t,e.annotations)}case"Suspend":return new rf(()=>pt(e.f()),e.annotations);case"Refinement":{let t=pt(e.from);return t===e.from?e:new Sl(t,e.filter,e.annotations)}case"Transformation":{let t=y2(e);return pt(t!==void 0?_l(e.to,t):e.to)}}return e},xx=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return xx(e.from);case"Suspend":return xx(e.f())}},hr=(e,t)=>{switch(e._tag){case"Declaration":{let n=Rn(e.typeParameters,(r)=>hr(r,t));return n===e.typeParameters?e:new ys(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=Rn(e.elements,(i)=>{let a=hr(i.type,t);return a===i.type?i:new Jo(a,i.isOptional)}),r=vA(e.rest),o=Rn(r,(i)=>hr(i,t));return n===e.elements&&o===r?e:new xl(n,o.map((i)=>new xs(i)),e.isReadonly)}case"TypeLiteral":{let n=Rn(e.propertySignatures,(o)=>{let i=hr(o.type,t);return i===o.type?o:new dt(o.name,i,o.isOptional,o.isReadonly)}),r=Rn(e.indexSignatures,(o)=>{let i=hr(o.type,t);return i===o.type?o:new Ss(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new yr(n,r)}case"Union":{let n=Rn(e.types,(r)=>hr(r,t));return n===e.types?e:Vt.make(n)}case"Suspend":{let n=void 0,r=o2(e);if(Ie(r)){let o=t?"Bound":"";n={[$x]:`${r.value}Encoded${o}`}}return new rf(()=>hr(e.f(),t),n)}case"Refinement":{let n=hr(e.from,t);if(t){if(n===e.from)return e;if(xx(e.from)===void 0&&Ux(e))return new Sl(n,e.filter,e.annotations);return n}else return n}case"Transformation":return hr(e.from,t)}return e},af=(e)=>hr(e,!1),He=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},Jx=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return Jx(e.from)}},Kn=(e)=>Ae(gr(e),()=>e._tag),AA=(e)=>Fx(e).pipe(Fn(()=>Dx(e)),Fn(()=>Lx(e)),Ln((t)=>t+x2(e))),gr=(e)=>Fn(gl(e),()=>AA(e));var Gx=x(()=>{Ve();W();Be();gx();hl();Qc();Ge();Lu();we();ry();Yk=Symbol.for("effect/annotation/TypeConstructor"),Sx=Symbol.for("effect/annotation/Brand"),Zk=Symbol.for("effect/annotation/SchemaId"),bx=Symbol.for("effect/annotation/Message"),Jd=Symbol.for("effect/annotation/MissingMessage"),Gd=Symbol.for("effect/annotation/Identifier"),Qt=Symbol.for("effect/annotation/Title"),Yd=Symbol.for("effect/annotation/AutoTitle"),ro=Symbol.for("effect/annotation/Description"),_x=Symbol.for("effect/annotation/Examples"),wx=Symbol.for("effect/annotation/Default"),vx=Symbol.for("effect/annotation/JSONSchema"),Tx=Symbol.for("effect/annotation/Arbitrary"),Ex=Symbol.for("effect/annotation/Pretty"),Rx=Symbol.for("effect/annotation/Equivalence"),Xk=Symbol.for("effect/annotation/Documentation"),Ox=Symbol.for("effect/annotation/Concurrency"),Cx=Symbol.for("effect/annotation/Batching"),kx=Symbol.for("effect/annotation/ParseIssueTitle"),Ax=Symbol.for("effect/annotation/ParseOptions"),Ix=Symbol.for("effect/annotation/DecodingFallback"),Px=Symbol.for("effect/annotation/Surrogate"),Mx=Symbol.for("effect/annotation/StableFilter"),Nt=d(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?B(e.annotations[t]):F()),Nx=Nt(Sx),Qk=Nt(bx),eA=Nt(Jd),Fx=Nt(Qt),Lx=Nt(Yd),gl=Nt(Gd),Dx=Nt(ro),tA=Nt(Ox),nA=Nt(Cx),rA=Nt(kx),oA=Nt(Ax),iA=Nt(Ix),qx=Nt(Px),n2=Nt(Mx),$x=Symbol.for("effect/annotation/JSONIdentifier"),r2=Nt($x);Zd=yl("Literal"),aA=new Yi(null);Qd=new sA({[Qt]:"undefined"});i2=new cA({[Qt]:"void"});ef=new lA({[Qt]:"never"});Hx=new uA({[Qt]:"unknown"});dA=new pA({[Qt]:"any"});mA=new fA({[Qt]:"string",[ro]:"a string"}),tf=yl("StringKeyword");gA=new hA({[Qt]:"number",[ro]:"a number"});xA=new yA({[Qt]:"boolean",[ro]:"a boolean"});a2=new SA({[Qt]:"bigint",[ro]:"a bigint"});s2=new bA({[Qt]:"symbol",[ro]:"a symbol"}),_A=yl("SymbolKeyword");c2=new wA({[Qt]:"object",[ro]:"an object in the TypeScript meaning, i.e. the `object` type"});Jo=class Jo extends xs{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:He(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};dt=class dt extends Jo{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:He(this.annotations)}}};p2=$r(Fu(mr,(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})),d2={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};jx=yl("Union"),yx=K(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);bl=yl("Refinement"),of={};y2=Kx([_x,wx,vx,Tx,Ex,Rx])});class ft{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class Xx{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class bs{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class je{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class cf{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class lf{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class On{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class Qx{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function Jn(e){return e.sort(v2).map((t)=>t[1])}function k2(e){return Dx(e).pipe(Fn(()=>Fx(e)),Fn(()=>Lx(e)),Fn(()=>gl(e)),Ae(()=>`{ ${e.from} | filter }`))}function A2(e){if(e.message!==void 0)return e.message;return`Expected ${bl(e.ast)?k2(e.ast):String(e.ast)}, actual ${ar(e.actual)}`}var PA,FA,tS=(e)=>new FA({issue:e}),LA,DA,tn,oo,Gn,uf,qA,UA=(e,t)=>{if(t===void 0||rn(t))return e;if(e===void 0)return t;return{...e,...t}},$A=(e,t,n)=>{let r=Ft(e,t);return(o,i)=>r(o,UA(n,i))},S2=(e,t,n)=>{let r=$A(e,t,n);return(o,i)=>Km(r(o,i),tS)},HA=(e,t)=>$A(e.ast,!0,t),pf=(e,t)=>S2(pt(e.ast),!0,t),b2,_2,Ft=(e,t)=>{let n=t?b2:_2,r=n.get(e);if(r)return r;let o=w2(e,t),i=oA(e),a=Ie(i)?(l,u)=>o(l,UA(u,i.value)):o,s=iA(e),c=t&&Ie(s)?(l,u)=>vl(qA(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},Yx=(e)=>Zt(tA(e)),Zx=(e)=>Zt(nA(e)),w2=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=Ft(e.from,!0);return(r,o)=>{o=o??of;let i=o?.errors==="all",a=oo(qA(n(r,o),(s)=>{let c=new cf(e,r,"From",s);if(i&&Ux(e)&&WA(s))return Je(e.filter(r,o,e),{onNone:()=>Q(c),onSome:(l)=>Q(new je(e,r,[c,new cf(e,r,"Predicate",l)]))});return Q(c)}),(s)=>Je(e.filter(s,o,e),{onNone:()=>re(s),onSome:(c)=>Q(new cf(e,r,"Predicate",c))}));return vl(a,e,r,o)}}else{let n=Ft(pt(e),!0),r=Ft(BA(e.from),!1);return(o,i)=>vl(oo(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=T2(e.transformation,t),r=t?Ft(e.from,!0):Ft(e.to,!1),o=t?Ft(e.to,!0):Ft(e.from,!1);return(i,a)=>vl(oo(uf(r(i,a),(s)=>new lf(e,i,t?"Encoded":"Type",s)),(s)=>oo(uf(n(s,a??of,e,i),(c)=>new lf(e,i,"Transformation",c)),(c)=>uf(o(c,a),(l)=>new lf(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)=>vl(n(r,o??of,e),e,r,o)}case"Literal":return en(e,(n)=>n===e.literal);case"UniqueSymbol":return en(e,(n)=>n===e.symbol);case"UndefinedKeyword":return en(e,U_);case"NeverKeyword":return en(e,$_);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return re;case"StringKeyword":return en(e,wt);case"NumberKeyword":return en(e,rn);case"BooleanKeyword":return en(e,di);case"BigIntKeyword":return en(e,yo);case"SymbolKeyword":return en(e,fi);case"ObjectKeyword":return en(e,Bt);case"Enums":return en(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>tf(r.type)))return en(e,(r)=>{if(!wt(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=kA(e);return en(e,(r)=>wt(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>Ft(l.type,t)),r=e.rest.map((l)=>Ft(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=Yx(e),c=Zx(e);return(l,u)=>{if(!eh(l))return Q(new On(e,l));let p=u?.errors==="all",f=[],h=0,m=[],S=l.length;for(let g=S;g<=i-1;g++){let R=new ft(g,l,new bs(o[g-S]));if(p){f.push([h++,R]);continue}else return Q(new je(e,l,R,m))}if(e.rest.length===0)for(let g=e.elements.length;g<=S-1;g++){let R=new ft(g,l,new Xx(l[g],`is unexpected, expected: ${a}`));if(p){f.push([h++,R]);continue}else return Q(new je(e,l,R,m))}let E=0,v=void 0;for(;E<n.length;E++)if(S<E+1){if(e.elements[E].isOptional)continue}else{let g=n[E],R=g(l[E],u);if(tn(R)){if(ke(R)){let O=new ft(E,l,R.left);if(p){f.push([h++,O]);continue}else return Q(new je(e,l,O,Jn(m)))}m.push([h++,R.right])}else{let O=h++,C=E;if(!v)v=[];v.push(({es:Y,output:U})=>Wn(Gi(R),(Z)=>{if(ke(Z)){let ce=new ft(C,l,Z.left);if(p)return Y.push([O,ce]),un;else return Q(new je(e,l,ce,Jn(U)))}return U.push([O,Z.right]),un}))}}if(Oe(r)){let[g,...R]=r;for(;E<S-R.length;E++){let O=g(l[E],u);if(tn(O))if(ke(O)){let C=new ft(E,l,O.left);if(p){f.push([h++,C]);continue}else return Q(new je(e,l,C,Jn(m)))}else m.push([h++,O.right]);else{let C=h++,Y=E;if(!v)v=[];v.push(({es:U,output:Z})=>Wn(Gi(O),(ce)=>{if(ke(ce)){let oe=new ft(Y,l,ce.left);if(p)return U.push([C,oe]),un;else return Q(new je(e,l,oe,Jn(Z)))}else return Z.push([C,ce.right]),un}))}}for(let O=0;O<R.length;O++){let C=E+O;if(S<C+1)continue;else{let Y=R[O](l[C],u);if(tn(Y)){if(ke(Y)){let U=new ft(C,l,Y.left);if(p){f.push([h++,U]);continue}else return Q(new je(e,l,U,Jn(m)))}m.push([h++,Y.right])}else{let U=h++;if(!v)v=[];v.push(({es:Z,output:ce})=>Wn(Gi(Y),(oe)=>{if(ke(oe)){let Te=new ft(C,l,oe.left);if(p)return Z.push([U,Te]),un;else return Q(new je(e,l,Te,Jn(ce)))}return ce.push([U,oe.right]),un}))}}}}let b=({es:g,output:R})=>wo(g)?Q(new je(e,l,Jn(g),Jn(R))):re(Jn(R));if(v&&v.length>0){let g=v;return fl(()=>{let R={es:Na(f),output:Na(m)};return Wn(dl(g,(O)=>O(R),{concurrency:s,batching:c,discard:!0}),()=>b(R))})}return b({output:m,es:f})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return en(e,H_);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([Ft(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Ft(u.parameter,t),Ft(u.type,t),u.parameter]),a=Vt.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>fi(u)?new Xd(u):new Yi(u)))),s=Ft(a,t),c=Yx(e),l=Zx(e);return(u,p)=>{if(!Am(u))return Q(new On(e,u));let f=p?.errors==="all",h=[],m=0,S=p?.onExcessProperty==="error",E=p?.onExcessProperty==="preserve",v={},b;if(S||E){b=Reflect.ownKeys(u);for(let C of b){let Y=s(C,p);if(tn(Y)&&ke(Y))if(S){let U=new ft(C,u,new Xx(u[C],`is unexpected, expected: ${String(a)}`));if(f){h.push([m++,U]);continue}else return Q(new je(e,u,U,v))}else v[C]=u[C]}}let g=void 0,R=p?.exact===!0;for(let C=0;C<n.length;C++){let Y=n[C][1],U=Y.name,Z=Object.prototype.hasOwnProperty.call(u,U);if(!Z){if(Y.isOptional)continue;else if(R){let Te=new ft(U,u,new bs(Y));if(f){h.push([m++,Te]);continue}else return Q(new je(e,u,Te,v))}}let ce=n[C][0],oe=ce(u[U],p);if(tn(oe)){if(ke(oe)){let Te=new ft(U,u,Z?oe.left:new bs(Y));if(f){h.push([m++,Te]);continue}else return Q(new je(e,u,Te,v))}v[U]=oe.right}else{let Te=m++,Ut=U;if(!g)g=[];g.push(({es:$t,output:Kt})=>Wn(Gi(oe),(et)=>{if(ke(et)){let tt=new ft(Ut,u,Z?et.left:new bs(Y));if(f)return $t.push([Te,tt]),un;else return Q(new je(e,u,tt,Kt))}return Kt[Ut]=et.right,un}))}}for(let C=0;C<i.length;C++){let Y=i[C],U=Y[0],Z=Y[1],ce=px(u,Y[2]);for(let oe of ce){let Te=U(oe,p);if(tn(Te)&&kt(Te)){let Ut=Z(u[oe],p);if(tn(Ut)){if(ke(Ut)){let $t=new ft(oe,u,Ut.left);if(f){h.push([m++,$t]);continue}else return Q(new je(e,u,$t,v))}else if(!Object.prototype.hasOwnProperty.call(r,oe))v[oe]=Ut.right}else{let $t=m++,Kt=oe;if(!g)g=[];g.push(({es:et,output:tt})=>Wn(Gi(Ut),(Ht)=>{if(ke(Ht)){let Pn=new ft(Kt,u,Ht.left);if(f)return et.push([$t,Pn]),un;else return Q(new je(e,u,Pn,tt))}else{if(!Object.prototype.hasOwnProperty.call(r,oe))tt[oe]=Ht.right;return un}}))}}}}let O=({es:C,output:Y})=>{if(wo(C))return Q(new je(e,u,Jn(C),Y));if(p?.propertyOrder==="original"){let U=b||Reflect.ownKeys(u);for(let ce of o)if(U.indexOf(ce)===-1)U.push(ce);let Z={};for(let ce of U)if(Object.prototype.hasOwnProperty.call(Y,ce))Z[ce]=Y[ce];return re(Z)}return re(Y)};if(g&&g.length>0){let C=g;return fl(()=>{let Y={es:Na(h),output:Object.assign({},v)};return Wn(dl(C,(U)=>U(Y),{concurrency:c,batching:l,discard:!0}),()=>O(Y))})}return O({es:h,output:v})}}case"Union":{let n=jA(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],Ft(e.types[l],t));let s=Yx(e)??1,c=Zx(e);return(l,u)=>{let p=[],f=0,h=[];if(o>0)if(nc(l))for(let E=0;E<o;E++){let v=r[E],b=n.keys[v].buckets;if(Object.prototype.hasOwnProperty.call(l,v)){let g=String(l[v]);if(Object.prototype.hasOwnProperty.call(b,g))h=h.concat(b[g]);else{let{candidates:R,literals:O}=n.keys[v],C=Vt.make(O),Y=R.length===i?new yr([new dt(v,C,!1,!0)],[]):Vt.make(R);p.push([f++,new je(Y,l,new ft(v,l,new On(C,l[v])))])}}else{let{candidates:g,literals:R}=n.keys[v],O=new dt(v,Vt.make(R),!1,!0),C=g.length===i?new yr([O],[]):Vt.make(g);p.push([f++,new je(C,l,new ft(v,l,new bs(O)))])}}else{let E=n.candidates.length===i?e:Vt.make(n.candidates);p.push([f++,new On(E,l)])}if(n.otherwise.length>0)h=h.concat(n.otherwise);let m=void 0;for(let E=0;E<h.length;E++){let v=h[E],b=a.get(v)(l,u);if(tn(b)&&(!m||m.length===0))if(kt(b))return b;else p.push([f++,b.left]);else{let g=f++;if(!m)m=[];m.push((R)=>fl(()=>{if("finalResult"in R)return un;else return Wn(Gi(b),(O)=>{if(kt(O))R.finalResult=O;else R.es.push([g,O.left]);return un})}))}}let S=(E)=>wo(E)?E.length===1&&E[0][1]._tag==="Type"?Q(E[0][1]):Q(new je(e,l,Jn(E))):Q(new On(e,l));if(m&&m.length>0){let E=m;return fl(()=>{let v={es:Na(p)};return Wn(dl(E,(b)=>b(v),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in v)return v.finalResult;return S(v.es)})})}return S(p)}}case"Suspend":{let n=ml(()=>Ft(e.f(),t));return(r,o)=>n()(r,o)}}},en=(e,t)=>(n)=>t(n)?re(n):Q(new On(e,n)),wl=(e,t)=>{switch(e._tag){case"Declaration":{let n=qx(e);if(Ie(n))return wl(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?af(o.type):pt(o.type);if(Zd(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?af(o.type):pt(o.type);if(Zd(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return wl(e.from,t);case"Suspend":return wl(e.f(),t);case"Transformation":return wl(t?e.from:e.to,t)}return[]},jA=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=wl(a,t);if(s.length>0){o.push(a);for(let c=0;c<s.length;c++){let[l,u]=s[c],p=String(u.literal);n[l]=n[l]||{buckets:{},literals:[],candidates:[]};let f=n[l].buckets;if(Object.prototype.hasOwnProperty.call(f,p)){if(c<s.length-1)continue;f[p].push(a),n[l].literals.push(u),n[l].candidates.push(a)}else{f[p]=[a],n[l].literals.push(u),n[l].candidates.push(a);break}}}else r.push(a)}return{keys:n,otherwise:r,candidates:o}},BA=(e)=>bl(e)?BA(e.from):e,vl=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(tn(e))return e;let o=new rl,i=Ak(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(CO(a))return re(a.value);let s=a.cause;if(bE(s))return Q(s.error);return Q(new Qx(t,n,_E(s)))}return Q(new Qx(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},v2=([e],[t])=>e>t?1:e<t?-1:0,T2=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return re;case"TypeLiteralTransformation":return(n)=>{let r=re(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=Gn(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?B(l[i]):F());if(delete l[i],Ie(u))l[a]=u.value;return l})}return r}}},zt=(e,t=[])=>({value:e,forest:t}),Tl,E2=(e)=>e.value+VA(`
34
+ `,e.forest),VA=(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+=VA(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},R2=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},O2=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},zA=(e)=>("ast"in e)?B(e.ast):F(),eS,C2=(e)=>zA(e).pipe(Dn(Qk),Je({onNone:()=>eS,onSome:(t)=>{let n=t(e);if(wt(n))return re({message:n,override:!1});if(Ok(n))return zd(n,(r)=>({message:r,override:!1}));if(wt(n.message))return re({message:n.message,override:n.override});return zd(n.message,(r)=>({message:r,override:n.override}))}})),nS=(e)=>(t)=>t._tag===e,WA,MA,NA,El=(e)=>oo(C2(e),(t)=>{if(t!==void 0)return!t.override&&(WA(e)||MA(e)&&e.kind==="From"||NA(e)&&e.kind!=="Transformation")?NA(e)||MA(e)?El(e.issue):eS:re(t.message);return eS}),KA=(e)=>zA(e).pipe(Dn(rA),gw((t)=>t(e)),Zt),I2=(e)=>Gn(El(e),(t)=>t??KA(e)??A2(e)),sf=(e)=>KA(e)??String(e.ast),P2=(e)=>e.message??"is forbidden",M2=(e)=>e.message??"is unexpected",N2=(e)=>{let t=eA(e.ast);if(Ie(t)){let n=t.value();return wt(n)?re(n):n}return re(e.message??"is missing")},_s=(e)=>{switch(e._tag){case"Type":return Gn(I2(e),zt);case"Forbidden":return re(zt(sf(e),[zt(P2(e))]));case"Unexpected":return re(zt(M2(e)));case"Missing":return Gn(N2(e),zt);case"Transformation":return oo(El(e),(t)=>{if(t!==void 0)return re(zt(t));return Gn(_s(e.issue),(n)=>zt(sf(e),[zt(R2(e.kind),[n])]))});case"Refinement":return oo(El(e),(t)=>{if(t!==void 0)return re(zt(t));return Gn(_s(e.issue),(n)=>zt(sf(e),[zt(O2(e.kind),[n])]))});case"Pointer":return Gn(_s(e.issue),(t)=>zt(Wd(e.path),[t]));case"Composite":return oo(El(e),(t)=>{if(t!==void 0)return re(zt(t));let n=sf(e);return dx(e.issues)?Gn(dl(e.issues,_s),(r)=>zt(n,r)):Gn(_s(e.issues),(r)=>zt(n,[r]))})}};var JA=x(()=>{Ve();wE();dR();Pk();an();kO();W();Be();hl();Ge();we();kd();Gx();PA=Symbol.for("effect/Schema/ParseErrorTypeId");FA=class FA extends pR("ParseError"){[PA]=PA;get message(){return this.toString()}toString(){return Tl.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[ie](){return this.toJSON()}};LA=re,DA=Q,tn=Wm,oo=d(2,(e,t)=>tn(e)?fc(e,{onLeft:Q,onRight:t}):Wn(e,t)),Gn=d(2,(e,t)=>tn(e)?lw(e,t):zd(e,t)),uf=d(2,(e,t)=>tn(e)?Nu(e,t):kk(e,t)),qA=d(2,(e,t)=>tn(e)?fc(e,{onLeft:t,onRight:re}):Ck(e,t)),b2=K(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),_2=K(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);Tl={formatIssue:(e)=>Gn(_s(e),E2),formatIssueSync:(e)=>{let t=Tl.formatIssue(e);return tn(t)?pw(t):Ik(t)},formatError:(e)=>Tl.formatIssue(e.issue),formatErrorSync:(e)=>Tl.formatIssueSync(e.issue)},eS=re(void 0),WA=nS("Composite"),MA=nS("Refinement"),NA=nS("Transformation")});var GA,YA;var ZA=x(()=>{W();we();GA=d((e)=>Bt(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),YA=d((e)=>Bt(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function Rt(e){return class{[Rl]=XA;static ast=e;static annotations(n){return Rt(xr(this.ast,n))}static pipe(){return k(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Rl]=XA}}function D2(e){return nf(e)?Vt.make(RA(e,(t)=>new Yi(t))):new Yi(e[0])}function aI(e,t=D2(e)){return class extends Rt(t){static annotations(r){return aI(this.literals,xr(this.ast,r))}static literals=[...e]}}function T(...e){return Oe(e)?aI(e):iS}function oS(e,t){return class extends Rt(t){static annotations(r){return oS(this.typeParameters,xr(this.ast,r))}static typeParameters=[...e]}}function cI(e,t=$2(e)){return class extends Rt(t){static annotations(r){return cI(this.members,xr(this.ast,r))}static members=[...e]}}function be(...e){return nf(e)?cI(e):Oe(e)?e[0]:iS}function df(e,t,n=j2(e,t)){return class extends Rt(n){static annotations(o){return df(this.elements,this.rest,xr(this.ast,o))}static elements=[...e];static rest=[...t]}}function lI(...e){return Array.isArray(e[0])?df(e[0],e.slice(1)):df(e,[])}function uI(e,t){return class extends df([],[e],t){static annotations(r){return uI(this.value,xr(this.ast,r))}static value=e}}class dI{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<${rS(this.to.isOptional)}, ${this.to.type}, ${B2(this.from.fromKey)}, ${rS(this.from.isOptional)}, ${this.from.type}>`}}function uS(e,t,n=z2(e,t)){return class extends Rt(n){static annotations(o){return uS(this.fields,this.records,xr(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=W2(e,{...o});return mS(i)?a:pf(this)(a)};static pick(...o){return _(GA(e,...o))}static omit(...o){return _(YA(e,...o))}}}function _(e,...t){return uS(e,t)}function gI(e,t,n){return class extends uS({},[{key:e,value:t}],n){static annotations(o){return gI(e,t,xr(this.ast,o))}static key=e;static value=t}}function yI(e,t){return class extends Rt(t){static annotations(r){return yI(this.from,xr(this.ast,r))}static make=(r,o)=>mS(o)?r:pf(this)(r);static from=e}}function xI(e,t,n){return class extends Rt(n){static annotations(o){return xI(this.from,this.filter,xr(this.ast,o))}static[K2]=e;static from=e;static filter=t;static make=(o,i)=>mS(i)?o:pf(this)(o)}}function Ze(e,t){return(n)=>{function r(i,a,s){return J2(e(i,a,s),s,i)}let o=new Sl(n.ast,r,Zi(t));return xI(n,r,o)}}function mS(e){return di(e)?e:e?.disableValidation??!1}var Rl,XA,QA,Zi=(e)=>{if(!e)return{};let t={...e};for(let n in QA)if(n in e){let r=QA[n];t[r]=e[n],delete t[n]}return t},xr=(e,t)=>_l(e,Zi(t)),iI=(e,t)=>{let n=HA(e,t);return(r,o)=>Nu(n(r,o),tS)},eI=(e)=>N(e,Rl)&&Bt(e[Rl]),q2=(e,t,n)=>oS(e,new ys(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(Rt)),(...r)=>t.encode(...r.map(Rt)),Zi(n))),U2=(e,t)=>{let n=()=>(o,i,a)=>e(o)?LA(o):DA(new On(a,o));return oS([],new ys([],n,n,Zi(t)))},z=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return q2(n,r,o)}let e=arguments[0],t=arguments[1];return U2(e,t)},sI,mt,iS,aS,A,nn,X,$2=(e)=>Vt.make(e.map((t)=>t.ast)),H2=(e)=>be(e,sI),j2=(e,t)=>new xl(e.map((n)=>eI(n)?new Jo(n.ast,!1):n.ast),t.map((n)=>eI(n)?new xs(n.ast):n.ast),!0),H=(e)=>uI(e),rS=(e)=>e?'"?:"':'":"',sS,pI,B2=(e)=>{if(e===void 0)return"never";if(wt(e))return JSON.stringify(e);return String(e)},fI=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new sS(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new dI(e.from,new pI(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},mI,hI=(e)=>N(e,mI),cS,lS,w=(e)=>{let t=e.ast===Qd||e.ast===ef?Qd:H2(e).ast;return new lS(new sS(t,!0,!0,{},void 0),e)},V2,z2=(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(hI(u)){let p=u.ast;switch(p._tag){case"PropertySignatureDeclaration":{let{type:f,isOptional:h,annotations:m}=p;i.push(new dt(l,f,h,!0,V2(p))),a.push(new dt(l,pt(f),h,!0,m)),r.push(new dt(l,f,h,!0,m));break}case"PropertySignatureTransformation":{let f=p.from.fromKey??l;i.push(new dt(f,p.from.type,p.from.isOptional,!0,p.from.annotations)),a.push(new dt(l,p.to.type,p.to.isOptional,!0,p.to.annotations)),s.push(new Vx(f,l,p.decode,p.encode));break}}}else i.push(new dt(l,u.ast,!1,!0)),a.push(new dt(l,pt(u.ast),!1,!0)),r.push(new dt(l,u.ast,!1,!0))}if(Oe(s)){let c=[],l=[];for(let u of t){let{indexSignatures:p,propertySignatures:f}=Wx(u.key.ast,u.value.ast);f.forEach((h)=>{i.push(h),a.push(new dt(h.name,pt(h.type),h.isOptional,h.isReadonly,h.annotations))}),p.forEach((h)=>{c.push(h),l.push(new Ss(h.parameter,pt(h.type),h.isReadonly))})}return new Bx(new yr(i,c,{[Yd]:"Struct (Encoded side)"}),new yr(a,l,{[Yd]:"Struct (Type side)"}),new zx(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=Wx(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new yr(r,o)},W2=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&hI(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},ff=(e)=>gI(e.key,e.value),Ol=(e,t)=>(n)=>{let r=Je(Nx(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=_l(n.ast,Zi({[Sx]:r,...t}));return yI(n,o)},K2,tI=(e,t,n)=>{if(di(e))return e?F():B(new On(t,n));if(wt(e))return B(new On(t,n,e));if(e!==void 0){if("_tag"in e)return B(e);let r=new On(t,n,e.message);return B(Oe(e.path)?new ft(e.path,n,r):r)}return F()},J2=(e,t,n)=>{if(Nk(e))return tI(e,t,n);if(Oe(e)){let r=qu(e,(o)=>tI(o,t,n));if(Oe(r))return B(r.length===1?r[0]:new je(t,n,r))}return F()},G2,pS=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length<=e,{schemaId:G2,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),Y2,ws=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length>=e,{schemaId:Y2,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),nI,pe=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ze((o)=>(e.lastIndex=0,e.test(o)),{schemaId:nI,[nI]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},Z2,rI,X2,Q2,dS=(e,t)=>(n)=>n.pipe(Ze((r)=>r>e,{schemaId:Q2,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),e$,SI=(e,t)=>(n)=>n.pipe(Ze((r)=>r>=e,{schemaId:e$,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),t$,mf=(e)=>(t)=>t.pipe(Ze((n)=>Number.isSafeInteger(n),{schemaId:t$,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),fS=(e)=>dS(0,{title:"positive",...e}),hf,n$,Sr=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(Fk(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ze((o)=>o.length>=r,{schemaId:n$,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[Mx]:!0,...t}))},oI,r$;var Ot=x(()=>{Ve();an();ec();gx();Jk();hl();Ge();JA();Re();we();Gx();ZA();Rl=Symbol.for("effect/Schema");XA={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},QA={typeConstructor:Yk,schemaId:Zk,message:bx,missingMessage:Jd,identifier:Gd,title:Qt,description:ro,examples:_x,default:wx,documentation:Xk,jsonSchema:vx,arbitrary:Tx,pretty:Ex,equivalence:Rx,concurrency:Ox,batching:Cx,parseIssueTitle:kx,parseOptions:Ax,decodingFallback:Ix};sI=class sI extends Rt(Qd){};mt=class mt extends Rt(aA){};iS=class iS extends Rt(ef){};aS=class aS extends Rt(Hx){};A=class A extends Rt(mA){};nn=class nn extends Rt(gA){};X=class X extends Rt(xA){};sS=class sS extends Jo{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=rS(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};pI=class pI extends Jo{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};mI=Symbol.for("effect/PropertySignature");cS=class cS{ast;[Rl];[mI]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return k(this,arguments)}annotations(e){return new cS(fI(this.ast,Zi(e)))}toString(){return String(this.ast)}};lS=class lS extends cS{from;constructor(e,t){super(e);this.from=t}annotations(e){return new lS(fI(this.ast,Zi(e)),this.from)}};V2=Kx([Jd]);K2=Symbol.for("effect/SchemaId/Refine");G2=Wk,Y2=zk,nI=Symbol.for("effect/SchemaId/Pattern"),Z2=Symbol.for("effect/SchemaId/UUID"),rI=/^[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;X2=class X2 extends A.pipe(pe(rI,{schemaId:Z2,identifier:"UUID",jsonSchema:{format:"uuid",pattern:rI.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};Q2=jk,e$=Bk,t$=Vk;hf=class hf extends nn.pipe(mf({identifier:"Int"})){};n$=Kk,oI=Hk;r$=class r$ extends z(Tu,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:oI,[oI]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>D_}){}});function Cn(e,t){return iI(e,o$)(t)}var o$;var vs=x(()=>{Ot();o$={onExcessProperty:"error"}});function gS(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(!wI(r)||!_I(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function Yn(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);return wI(n)&&_I(r)?`${n}@openai-curated`:void 0}function _I(e){return bI.includes(e)}function wI(e){return gf.includes(e)}function yS(e,t){let n=t??io;return{computer_use:e?.computer_use??n.computer_use,frontend:e?.frontend??n.frontend,security:e?.security??n.security}}function Cl(e,t=[]){let n=[],r=new Set;for(let o of vI){if(!e[o])continue;for(let i of Qi[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 hS,i$,a$,s$,bI,gf,Xi,Ts,c$,l$,Qi,vI,u$,io;var xS=x(()=>{Ot();hS=T("computer_use","frontend","security"),i$=T("computer_use","frontend","security"),a$=T("installed","disabled","missing","uncertain"),s$=T("healthy","missing","disabled","uncertain"),bI=Object.freeze(["openai-curated","openai-curated-remote"]),gf=Object.freeze(["build-web-apps","codex-security"]);Xi=Object.freeze({coding:!0,computer_use:!1,frontend:!0,security:!0}),Ts=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([])}),c$=Ts.frontend,l$={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Xi.frontend,migrationKey:"frontend",semanticSkillIds:Object.freeze(Ts.frontend.map(({skillId:e})=>e)),applicability:Ts.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Xi.security,migrationKey:"security",semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:Ts.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Xi.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:Ts.computer_use,ownership:"shared-preserve"}},Qi=Object.freeze(l$),vI=Object.freeze(["computer_use","frontend","security"]),u$=Object.freeze(["writing-instructions","babysit-ci"]),io=Object.freeze({computer_use:Xi.computer_use,frontend:Xi.frontend,security:Xi.security})});function br(e){return _({identifier:T(e),label:A,requiresRootApproval:X})}function TI(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 EI(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var RI,p$,d$,SS,f$,OI,m$,h$,g$;var CI=x(()=>{Ot();RI=T("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"),p$=_({identifier:RI,label:A,requiresRootApproval:X});d$=_({localRepositoryEdit:br("local.repository.edit"),localRepositoryCheck:br("local.repository.check"),localRepositoryLint:br("local.repository.lint"),localRepositoryFormat:br("local.repository.format"),localRepositoryCommit:br("local.repository.commit"),externalRead:br("external.read"),specialistDispatch:br("specialist.dispatch"),versionControlServerMutation:br("vcs.server.mutation"),versionControlServerCiTrigger:br("vcs.server.ci-trigger"),unknownEffect:br("unknown.effect")}),SS={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(SS);f$=T("never","root"),OI=Object.values(SS);m$=OI.filter((e)=>!e.requiresRootApproval),h$=OI.filter((e)=>e.requiresRootApproval),g$=Object.freeze({noRootApproval:`${EI(TI(m$))} actions do not require Root approval.`,rootApproval:`${EI(TI(h$))} require Root approval.`})});function yf(e){let t=Cn(y$,e);if(ke(t))return pi(Js("sha256 digest",t.left));return Ta(t.right)}var Zn,bS,H7,j7,B7,y$,x$,S$,b$,_$;var xf=x(()=>{an();Ot();Ea();vs();Zn=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),bS=A.pipe(pe(/^[0-9a-f]{64}$/u)),H7=Zn.pipe(Ol("RunId")),j7=Zn.pipe(Ol("ProjectId")),B7=Zn.pipe(Ol("TrustId")),y$=bS.pipe(Ol("Sha256Digest"));x$=_({run_id:Zn,objective_lineage:Zn,parent_run_id:w(be(Zn,mt))}),S$=_({project_id:Zn,trust_id:Zn,trust_digest:bS}),b$=_({project_id:Zn,project_digest:bS}),_$=A.pipe(pe(/^state-[0-9]+\.[0-9]+$/u))});function _S(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 II(e){return typeof e==="string"&&E$.has(e)}function O$(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!II(t)||typeof n!=="string")return!1;return Al.get(t)?.tasks.some((r)=>r.name===n)===!0}function _f(e,t){return typeof t==="string"&&Al.get(e)?.tasks.some((n)=>n.name===t)===!0}function PI(e){return typeof e==="string"&&R$.has(e)}function ES(e){let t=`${e.role}.${e.task}`;if(!vS.has(t))throw Error("Unknown native specialist agent type.");return t}function RS(e){let t=Al.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.instruction}function OS(e){let t=Al.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function NI(e){let t=Al.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function CS(e){let n=NI(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 Yo,kI,kl,ea,w$,bf="Make the smallest complete edit set within the authorized boundary, touch no unrelated paths, avoid speculative refactors or formatting churn, and perform no redundant writes or operations; preserve unrelated work and stop for Root input before expanding scope.",Go="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",v$,T$,kn,Al,E$,wS,R$,AI,vS,TS,C$,k$,A$,I$,Il,ta,MI,_r,P$,wf,FI,Sf,M$,N$,F$,kS,vf,AS,Zo,L$,D$,L;var Pl=x(()=>{Ot();Yo=T("low","default","high"),kI=T("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),kl=be(Yo,kI);ea=T("standard","fast","fast-all"),w$=T("low","medium","high","xhigh","max"),v$=T("none"),T$=T("read-only","workspace-write"),kn=[{role:"Explorer",tasks:[{name:"lookup",description:"Repository fact lookup specialist.",instruction:`Locate the exact requested repository fact. ${Go}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:`Trace the complete in-scope execution or reference path. ${Go}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS, lifecycle, and decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:`Locate the exact requested authoritative external fact. For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or generic web sources. Return a typed Context7 evidence state in the context7 field with supporting version/source evidence; fall back only for an allowed evidence state or when the required version is absent, and prefer authoritative first-party documentation when sources conflict. ${Go}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:`Synthesize the assigned current sources with citations. For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or generic web sources. Return a typed Context7 evidence state in the context7 field with supporting version/source evidence; fall back only for an allowed evidence state or when the required version is absent, and prefer authoritative first-party documentation when sources conflict. ${Go}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS, lifecycle, and 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:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply only deterministic, already-decided edits.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Implement and verify the bounded behavior seam.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Integrate the decided seams and verify them together.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Observe the assigned post-VCS external gate at the supplied exact ref or SHA. ${Go}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`When independent proof is useful, run the smallest relevant local checks for the delegated seam, classify failures, and report evidence without redesigning the solution or replacing code review. ${Go}`,permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Establish the failure reproducibly, identify the evidence-backed root cause, make the narrow bounded repair, and prove the regression is gone; return material redesigns to Root.",permissions:{network:!1,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, 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:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",tasks:[{name:"plan",description:"Adversarial implementation-plan review specialist.",instruction:`Review the complete plan to a fixed point. ${Go}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. The acceptance contract covers correctness, safety, compatibility, mergeability, clarity, simplicity, cohesion, idiomaticity, appropriate abstraction, accidental complexity, duplication, unnecessary files or file splitting, speculative abstraction, test quality, and generated-artifact hygiene. Prefer simple cohesive code over clever or over-engineered code.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Review and repair the produced artifact to a fixed point.",permissions:{network:!1,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, 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:!1,filesystem:"read-only",sourceMutation:!1}}];ir(kn);Al=new Map(kn.map((e)=>[e.role,e])),E$=new Set(kn.map((e)=>e.role)),wS=kn.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),R$=new Set(wS),AI=wS.map((e)=>e.replace(":",".")),vS=new Set(AI);TS=z(II),C$=z((e)=>_f("Explorer",e)),k$=z((e)=>_f("Librarian",e)),A$=z((e)=>_f("Worker",e)),I$=z((e)=>_f("Reviewer",e)),Il=z(O$),ta=Object.freeze(wS.filter((e)=>PI(e))),MI=z(PI),_r=Object.freeze(AI.filter((e)=>vS.has(e))),P$=z((e)=>typeof e==="string"&&vS.has(e)),wf=Object.freeze(["worker","explorer","reviewer","librarian"]);FI=_({profile:Yo,service_tier:w(ea)}),Sf=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","gui_browser","computer_use"]),M$=T(...Sf),N$=T("delegated","root_direct","unavailable"),F$=T(...Sf),kS=T("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),vf=Object.freeze({rule:"Run meaningful proof appropriate to changed behavior plus repository-required checks.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),AS=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"]),fallbackRequiresEvidenceStateOrMissingVersion:!0,authoritativeFirstPartyResolvesConflicts:!0,materialDecisionsRemainRootOwned:!0}),Zo=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnInspectionImplementationAndRepair:!0,rootOwnsLiveVisualAndInteractionAcceptance:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsCannotSubstituteForRootAcceptance:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["specialist_implements","root_renders_opens_and_interacts","root_judges_current_result","root_delegates_discrepancies","specialist_repairs","root_rerenders_and_retests"])}),L$=Object.freeze({interactiveCapabilitiesRemainRootOwned:!0,credentialEntryAndSubmissionRemainUserOwned:!0,useDefaultBrowserWithComputerUse:!0,agentsMustNeverHandleCredentials:!0,authenticationSequence:Object.freeze(["root_navigates_to_authentication","root_hands_control_to_user","user_enters_and_submits_credentials","root_waits_for_completion","root_resumes_authenticated_session"]),missingAuthorizedPathIsCapabilityBlocker:!0}),D$=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),L=Object.freeze({requiresDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:_r,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:wf,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","review","ci_release_observation"]),directExecutionExceptions:Sf,rootOwnedAuthority:Sf,requestUserInputGates:Object.freeze(["plan_approval","installation_profile_approval","remote_origin_server_vcs_mutation","public_publication_or_release","ambiguity_or_missing_material_input"]),surgicalMutationRule:bf,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:3600000,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:vf,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Dt(e,t){return new Ke("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function IS(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw Dt(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw Dt(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw Dt(t,"invalid number");return r}case"undefined":throw Dt(t,"undefined is not JSON");case"bigint":throw Dt(t,"bigint is not JSON");case"function":throw Dt(t,"function is not JSON");case"symbol":throw Dt(t,"symbol is not JSON");case"object":break}if(n.has(e))throw Dt(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw Dt(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 Dt(`${t}[${s}]`,"sparse or accessor array item");a.push(IS(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 Dt(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw Dt(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Dt(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw Dt(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 Dt(`${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 Dt(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${IS(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function wr(e){return IS(e,"$",new Set)}function Xn(e){return new TextEncoder().encode(wr(e))}function LI(e,t){if(e.length===0||e.includes("\x00"))throw new Ke("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 Ke("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 U$(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function Qn(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new Ke("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",$$(LI(e,t)));return U$(new Uint8Array(r))}function $$(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var PS=x(()=>{Ea();xf()});function UI(e){try{return wr(e)!==void 0}catch{return!1}}function Ef(e){let t=Cn(WI,e);if(ke(t))return pi(Js("CLI envelope",t.left));return Ta(t.right)}var DI,qI,$I,H$,j$,MS="holycodex-specialist-outcome-2",Ct,Es,Ml,B$,V$,z$,W$,K$,J$,Tf,G$,Y$,Z$,X$,Q$,HI,jI,BI,eH,VI,zI,WI;var NS=x(()=>{an();Ot();PS();xS();Ea();xf();Pl();vs();DI=T("blocked","completed","failed","partial"),qI=be(T("high","max","xhigh"),mt);$I=z((e)=>UI(e)),H$=z((e)=>Rm(e)&&!Array.isArray(e)&&UI(e)),j$=_({blocked:X,changed_files:H(A),confidence:nn,context_owner:be(A,mt),material_findings:H(A),needs_more_context:X,needs_root_decision:X,needs_verification:X,relevant_files:H(A),remaining_risk:H(A),reuse_recommended:X,status:DI,suggested_followup:be(A,mt),suggested_luna_effort:qI,suggested_specialist:be(TS,mt),verification:H(A),verification_passed:X}),Ct=A.pipe(ws(1)),Es=_({state:kS,evidence:H(Ct).pipe(Sr(1)),library:w(Ct),version:w(Ct)}),Ml={protocol_version:T(MS),route:Il,evidence:H(Ct),context7:w(Es)},B$=_(Ml),V$=_({...Ml,status:T("completed"),summary:Ct}),z$=_({...Ml,status:T("blocked"),reason:Ct,needs_root_decision:X}),W$=_({...Ml,status:T("partial"),summary:Ct,completed:H(Ct),remaining:H(Ct),needs_root_decision:X}),K$=_({...Ml,status:T("failed"),error:Ct}),J$=be(V$,z$,W$,K$),Tf={protocol_version:T(MS),capability:hS,route:be(Il,mt),evidence:H(Ct),context7:w(Es),data:$I},G$=_({...Tf,status:T("completed"),summary:Ct}),Y$=_({...Tf,status:T("blocked"),reason:Ct,needs_root_decision:X}),Z$=_({...Tf,status:T("partial"),summary:Ct,completed:H(Ct),remaining:H(Ct),needs_root_decision:X}),X$=_({...Tf,status:T("failed"),error:Ct}),Q$=be(G$,Y$,Z$,X$),HI=H(A),jI=A.pipe(pe(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),BI=T(Mr),eH=_({code:Zn,message:A,details:H$}),VI=_({schema_version:BI,ok:T(!0),command:jI,data:$I,warnings:HI}),zI=_({schema_version:BI,ok:T(!1),command:jI,error:eH,warnings:HI}),WI=be(VI,zI)});function tH(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:JI,effort:n}}function oH(e){let t=rH.get(e);if(t===void 0)throw new Ke("catalog_invalid","A profile has no route effort policy.",{profile:e});return kn.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new Ke("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return tH(n.role,r.name,i)}))}function FS(e){return{name:e.name,root:{model:"gpt-6-astra",effort:e.effort},specialistModel:"gpt-5.6-luna",defaultServiceTier:"standard",routes:oH(e.name)}}function iH(e){let t=["low","default","high"];if(e.length!==t.length)throw new Ke("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 Ke("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=o==="low"?"low":o==="default"?"medium":"high";if(r.root.model!=="gpt-6-astra"||r.root.effort!==i||r.specialistModel!=="gpt-5.6-luna")throw new Ke("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==ta.length)throw new Ke("catalog_invalid","A profile is incomplete.",{profile:r.name});let a=new Set;for(let s of r.routes){if(a.has(s.key)||!nH.has(s.key)||s.model!=="gpt-5.6-luna"||`${s.role}:${s.task}`!==s.key)throw new Ke("catalog_invalid","A profile contains an invalid route.",{profile:r.name});a.add(s.key)}if(a.size!==ta.length)throw new Ke("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<ta.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||KI[i.effort]<r)throw new Ke("catalog_invalid","Profile route effort is not monotonic.",{route:ta[n]??"unknown"});r=KI[i.effort]}}}function vr(e){let t=Cn(Yo,e);if(ke(t))return pi(new Ke("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=YI.get(t.right);if(!n)return pi(new Ke("invalid_profile","Unknown profile selection.",{profile:t.right}));return Ta(n)}var JI="gpt-5.6-luna",nH,KI,LS,rH,DS,GI,YI,aH;var ZI=x(()=>{an();Ea();Pl();vs();nH=new Set(ta),KI={low:0,medium:1,high:2,xhigh:3,max:4},LS=[{profile:"low",rationale:"The low profile keeps bounded specialist work economical.",efforts:{"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: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: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(LS);rH=new Map(LS.map((e)=>[e.profile,e]));DS=[FS({name:"low",effort:"low"}),FS({name:"default",effort:"medium"}),FS({name:"high",effort:"high"})];iH(DS);ir(DS);GI=DS,YI=new Map,aH=new Map;for(let e of GI){YI.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);aH.set(e.name,t)}});import{execFile as cH}from"child_process";import{promisify as lH}from"util";var QI="holycodex-intent-1",eP="holycodex-plan-1",tP="holycodex-assignment-1",Rf="toon-4",ee,Xo,qS,nP,Nl,er,Xe,m5,US,na,$S,HS,uH,XI,pH,dH,jS,rP,oP,fH,mH="holycodex-work-state-transaction-1",h5,g5,hH,gH,yH,xH,SH,bH,_H,wH,y5;var iP=x(()=>{Ot();NS();Pl();vs();ee=A.pipe(Ze((e)=>e.trim().length>0)),Xo=A.pipe(pe(/^[a-z0-9][a-z0-9-]{0,95}$/u)),qS=A.pipe(pe(/^[a-f0-9]{64}$/u)),nP=A.pipe(pe(/^[a-f0-9]{40}$/u)),Nl=hf.pipe(SI(1)),er=A.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),Xe=H(ee),m5=_({pid:hf.pipe(dS(0)),token:ee}),US=_({role:T("Explorer","Librarian","Worker","Reviewer"),task:ee}).pipe(Ze((e)=>kn.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),na=_({kind:T("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:ee,result:w(T("passed","failed","observed","unknown"))}),$S=_({root:ee,git_common_dir:ee,initial_head:ee,expected_head:ee,expected_changes:Xe,expected_status_digest:qS,integrated_commit:w(nP),updated_at:er}),HS=T("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),uH=T("scoping","ready","executing","verifying","reviewing"),XI=_({required:X,status:T("not_required","missing","passed","failed","accepted","rejected"),evidence:H(na)}),pH=_({schema_version:T(QI),toon_compatibility:T(Rf),id:Xo,slug:Xo,title:ee,goal:ee,acceptance_criteria:Xe,state:HS,revision:Nl,plan_required:X,active_plan_revision:w(Nl),active_plan_digest:w(qS),blockers:Xe,resume_state:w(uH),verification:XI,review:XI,acceptance_met:X,root_readiness:X,evidence:H(na),baseline:$S,created_at:er,updated_at:er}),dH=_({schema_version:T(eP),toon_compatibility:T(Rf),intent_id:Xo,revision:Nl,predecessor_digest:w(qS),approach:ee,scope:Xe,exclusions:Xe,assignments:Xe,dependencies:Xe,architecture:Xe,risks:Xe,assumptions:Xe,open_questions:Xe,verification:Xe,recovery:Xe,updated_at:er}),jS=T("completed","blocked","needs_root_input","failed"),rP=T("pending","executing","completed","blocked","needs_root_input","failed"),oP=_({id:Xo,outcome:jS,started_at:er,finished_at:er,summary:ee,evidence:H(na),context7:w(Es),blocker:w(ee),remaining_risk:Xe}),fH=_({schema_version:T(tP),toon_compatibility:T(Rf),intent_id:Xo,id:Xo,objective:ee,owner:US,scope:Xe,constraints:Xe,exclusions:Xe,dependencies:Xe,acceptance_criteria:Xe,status:rP,revision:Nl,invocations:H(oP),active_invocation_id:w(ee),active_started_at:w(er),evidence:H(na),blocker:w(ee),remaining_risk:Xe,created_at:er,updated_at:er}),h5=_({schema_version:T(mH),state:T("prepared","committed"),files:H(_({path:ee,previous:A,next:A})).pipe(Sr(1))}),g5=_({schema_version:T("holycodex-intent-0"),id:Xo,slug:Xo,title:ee,goal:ee,acceptance_criteria:Xe,state:HS,revision:Nl,baseline:$S,created_at:er,updated_at:er}),hH=_({title:ee,goal:ee,acceptanceCriteria:H(ee).pipe(Sr(1)),planRequired:w(X),verificationRequired:w(X),reviewRequired:w(X)}),gH=_({approach:ee,scope:w(H(ee)),exclusions:w(H(ee)),assignments:w(H(ee)),dependencies:w(H(ee)),architecture:w(H(ee)),risks:w(H(ee)),assumptions:w(H(ee)),openQuestions:w(H(ee)),verification:w(H(ee)),recovery:w(H(ee))}),yH=_({id:w(ee),objective:ee,owner:US,scope:H(ee).pipe(Sr(1)),constraints:w(H(ee)),exclusions:w(H(ee)),dependencies:w(H(ee)),acceptanceCriteria:H(ee).pipe(Sr(1))}),xH=_({scope:H(ee).pipe(Sr(1))}),SH=_({scope:w(H(ee).pipe(Sr(1)))}),bH=_({commit:nP}),_H=_({invocationId:w(ee),outcome:jS,startedAt:w(ee),summary:ee,scope:w(H(ee).pipe(Sr(1))),evidence:w(H(na)),context7:w(Es),blocker:w(ee),remainingRisk:w(H(ee))}),wH=_({evidence:w(H(na)),verification:w(T("passed","failed")),review:w(T("accepted","rejected")),acceptanceMet:w(X),rootReadiness:w(X),clearBlockers:w(X)}),y5=lH(cH)});var st=x(()=>{L_();Ea();vs();xS();CI();xf();Pl();NS();ZI();PS();iP()});function ae(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qe(e){try{return wr(e),!0}catch{return!1}}function FH(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 cP(e){return{ok:!1,error:e}}function lP(e){return{ok:!0,value:e}}function pn(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 ra(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return pn(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>ra(n,t+1));if(ae(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=pn(r,96);if(i.length>0)n[i]=ra(o,t+1)}return n}return"[redacted]"}function uP(e){let t=ra(e);return ae(t)?t:{value:t}}function Ue(e,t,n){return new G("invalid_external_data",`Invalid ${e}.`,{field:e,received:ra(t)},n===void 0?void 0:{cause:n})}function Ne(e,t,n){let r=Cn(e,t);if(ke(r))throw Ue(n,t,String(r.left));return r.right}function pP(e,t){try{return Ne(e,t,"value"),!0}catch{return!1}}var zS,ql=1048576,WS=65536,dn,Qo,f4,ao,NH,G;var Tr=x(()=>{st();an();Ot();zS=Mr;dn=z((e)=>qe(e)),Qo=z((e)=>ae(e)&&qe(e)),f4=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),ao=A.pipe(Ze((e)=>e.length>0&&e.length<=4096)),NH=nn.pipe(Ze((e)=>Number.isFinite(e)&&e>=0));G=class G 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=FH(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var KS,Ul,$l,JS,GS,YS,ZS="turn/completed";var Cf=x(()=>{KS=["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"],Ul=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],$l=["item/permissions/requestApproval"],JS=["mcpServer/elicitation/request"],GS=["item/tool/call"],YS={method:"initialized"}});function Os(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)=>Os(n,t));return ae(e)&&Object.values(e).every((n)=>Os(n,t))}finally{t.delete(e)}}function Er(e){return ae(e)&&Os(e)}function XS(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('"')?DH(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!_r.includes(c))throw Ue("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 Ue("TOML key path",e);if(t.some((i)=>i==="__proto__"||i==="constructor"||i==="prototype"))throw Ue("TOML key path",e);return t}function DH(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Ue("TOML quoted key",e)}function ge(e,t){if(!Er(e))throw Ue("TOML document",e);let n=e;for(let r of XS(t)){if(!Er(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function kf(e){if(Array.isArray(e))return e.map(kf);if(ae(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,kf(n)]));return e}function Af(e){return kf(e)}function ks(e,t,n){if(!Er(e)||!Os(n))throw Ue("TOML write",{keyPath:t});let r=XS(t),o={...Af(e)},i=o;for(let a of r.slice(0,-1)){let s=i[a];if(s!==void 0&&!Er(s))throw Ue("TOML table path",t);let c=s===void 0?{}:{...s};i[a]=c,i=c}return i[r.at(-1)]=kf(n),o}function so(e,t){if(!Er(e))throw Ue("TOML document",e);let n=XS(t),r={...Af(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!Er(c))return r;let l={...c};o.push({table:i,key:s}),i[s]=l,i=l}let a=n.at(-1);if(!Object.prototype.hasOwnProperty.call(i,a))return r;delete i[a];for(let s=o.length-1;s>=0;s-=1){let c=o[s],l=c.table[c.key];if(Er(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function jl(e){if(typeof e!=="string")return!1;if(fP.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return _r.some((t)=>e===`agents."${t}".config_file`)}function If(e){return jl(e)}function ei(e){return typeof e==="string"&&UH.test(e)}function QS(e){return e==="gpt-6-astra"||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"}function $H(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function eb(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function tb(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function nb(e){if(!ae(e)||!tb(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return QS(e.value);case"number":return eb(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&Nf(e.value);case"digest":return $H(e.value);default:return!1}}function dP(e,t){switch(ob(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-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";return t.value==="low"||t.value==="medium"||t.value==="high"}}function yP(e){return ae(e)&&e.kind==="absent"?Object.keys(e).length===1:nb(e)}function xP(e){return ae(e)&&tb(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&ei(e.schema)&&ei(e.installId)&&If(e.keyPath)&&yP(e.originalValue)&&nb(e.lastManagedValue)&&dP(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||dP(e.keyPath,e.originalValue))}function Cs(e){if(!ae(e)||!tb(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!ei(e.schema)||!ei(e.installId)||!ae(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>If(t)&&xP(n)&&n.keyPath===t)}function Mf(e){if(!ei(e.schema)||!ei(e.installId))throw Ue("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Nf(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 rb(e){if(!Nf(e))throw Ue("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function Bl(e,t){let n=rb(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 ob(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="features.default_mode_request_user_input"||e==="features.multi_agent"||e==="features.multi_agent_v2"||e==="features.context_management"||e==="features.context_management.experimental_mode")return"boolean";return"enum"}function HH(e,t){let n=ob(e);if(n==="number")return eb(t);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&Nf(t);if(n==="digest")return typeof t==="string";return typeof t==="string"&&QS(t)}async function tr(e,t){if(!If(e)||!Os(t))throw Ue("managed config value",{keyPath:e});let n=ob(e);if(n==="number"&&eb(t))return{kind:n,value:t};if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&Nf(t))return{kind:n,value:rb(t)};if(n==="enum"&&typeof t==="string"&&QS(t))return{kind:n,value:t};return{kind:"digest",value:await Qn("holycodex-managed-config-value",[Xn({keyPath:e,value:t})])}}function jH(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function As(e,t,n,r){if(!Er(e)||!Cs(t)||!ei(r.schema)||!ei(r.installId))throw Ue("managed runtime config",{});let o={...t.managed},i=Af(e),a=[];for(let[c,l]of Object.entries(n)){if(!jl(c)||typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Ue("managed config key",c);let u=c,p=t.managed[u],f=ge(i,u);if(p&&(p.schema!==r.schema||p.installId!==r.installId)){a.push(u);continue}if(p&&p.owner==="holycodex"){let m=f===void 0?void 0:await tr(u,f);if(m===void 0||JSON.stringify(m)!==JSON.stringify(p.lastManagedValue)){a.push(u);continue}}let h=p?.originalValue??(f===void 0?{kind:"absent"}:await tr(u,f));if(!HH(u,l))throw Ue("managed config value",{keyPath:u});i=ks(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:h,lastManagedValue:await tr(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!Cs(s))throw Ue("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function ti(e,t,n){if(!Er(e)||!Cs(t))throw Ue("managed runtime config",{});let r=Af(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!If(c))throw Ue("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 p=ge(r,u);if(!(p!==void 0&&JSON.stringify(await tr(u,p))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=so(r,u),i.push(u),delete o[u];else{let h=jH(l.originalValue);if(h===void 0){s.push(u),a.push(u);continue}r=ks(r,u,h),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function oa(e,t,n){if(!jl(n)||!Cs(t))throw Ue("managed config key",n);let r=t.managed[n],o=ge(e,n),i=o===void 0?void 0:await tr(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 LH,Hl,fP,qH,mP,hP,gP,Pf,UH;var Ff=x(()=>{st();st();Ot();Tr();LH=z((e)=>Os(e)),Hl=z((e)=>Er(e));fP=["model","model_auto_compact_token_limit","model_reasoning_effort","service_tier","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.default_mode_request_user_input","features.multi_agent","features.multi_agent_v2","features.context_management","features.context_management.experimental_mode"],qH=z((e)=>jl(e));mP=z((e)=>nb(e)),hP=z((e)=>yP(e)),gP=z((e)=>xP(e)),Pf=z((e)=>Cs(e)),UH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function VH(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function SP(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)=>VH(e[i]))}function wP(e){if(!ae(e)||!qe(e))return!1;return SP(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||SP(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function Lf(e){return ae(e)&&qe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function vP(e){return ae(e)&&qe(e)&&Lf(e.thread)}function KH(e){return ae(e)&&qe(e)&&typeof e.id==="string"}function ni(e){return ae(e)&&qe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function TP(e){return ae(e)&&qe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||wP(e.usage))}function JH(e){return ae(e)&&qe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>ae(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>ae(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 EP(e){if($l.some((t)=>t===e))return"permissions";if(Ul.some((t)=>t===e))return"approval";if(JS.some((t)=>t===e))return"elicitation";if(GS.some((t)=>t===e))return"dynamic_tool";return"other"}var bP,Vl,_P,zl,BH,ib,Wl,zH,Df,ab,sb,WH,Kl,cb,lb,ub,pb,db,fb,mb,hb,gb,yb,xb,Sb,bb,_b,wb,vb,Tb,Eb,Rb,Ob,Cb,kb,Ab,Ib,Pb,Mb,Nb,Fb,v4,GH,T4;var Lb=x(()=>{Ot();Tr();Cf();Ff();bP=A.pipe(pe(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),Vl=be(A.pipe(ws(1)),nn.pipe(Ze((e)=>Number.isSafeInteger(e)))),_P=_({code:nn.pipe(Ze((e)=>Number.isSafeInteger(e))),message:A,data:w(dn)}),zl=be(_({id:Vl,result:dn}),_({id:Vl,error:_P})),BH=_({id:Vl,error:_P}),ib=_({method:bP,params:w(dn)}),Wl=_({id:Vl,method:bP,params:w(dn),trace:w(dn)});zH=z(wP),Df=_({clientInfo:_({name:ao,version:ao,title:be(ao,mt)}),capabilities:be(_({experimentalApi:X,requestAttestation:X,mcpServerOpenaiFormElicitation:w(X),optOutNotificationMethods:w(be(H(A),mt)),extensions:w(Qo)}),mt)}),ab=z((e)=>ae(e)&&qe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),sb=_({method:T("initialized")});WH=z(Lf);Kl=z((e)=>vP(e)||KH(e)),cb=Kl,lb=Kl,ub=z(ni),pb=z((e)=>ae(e)&&qe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),db=z((e)=>vP(e)),fb=z((e)=>{if(!ae(e)||!qe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>Lf(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>Lf(r));return t&&e.threads===void 0||n&&e.data===void 0}),mb=z((e)=>ae(e)&&qe(e));hb=z(ni),gb=z(ni),yb=z(ni),xb=z((e)=>ae(e)&&qe(e));Sb=z((e)=>ni(e)&&(Array.isArray(e.input)&&e.input.every((t)=>qe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),bb=z((e)=>ni(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>qe(t))),_b=z((e)=>ae(e)&&qe(e)&&(e.turn!==void 0&&TP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),wb=z((e)=>ae(e)&&qe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),vb=z((e)=>ni(e)&&typeof e.turnId==="string"&&e.turnId.length>0),Tb=z((e)=>ae(e)&&qe(e)),Eb=z((e)=>ni(e)&&(e.turn!==void 0&&TP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),Rb=z((e)=>ae(e)&&qe(e));Ob=z((e)=>ae(e)&&qe(e)&&Array.isArray(e.data)&&e.data.every((t)=>JH(t))),Cb=Qo,kb=Qo,Ab=_({includeLayers:w(X),cwd:w(be(A,mt))}),Ib=_({config:Hl,origins:Qo,layers:be(H(Qo),mt)}),Pb=Qo,Mb=Qo,Nb=z((e)=>ae(e)&&qe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&ae(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),Fb=dn,v4=z((e)=>ae(e)&&qe(e)&&typeof e.kind==="string"&&typeof e.method==="string");GH=be(T("stable","experimental","disabled"),X),T4=ff({key:A,value:GH})});class qf{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??ql,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new G("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new G("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=YH){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new G("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Ne(Df,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",mb,e,Kl)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",hb,t,cb)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",gb,t,db)}async listThreads(e={}){return this.action("thread/list",xb,e,fb)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",yb,t,lb)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",ub,t,pb)}async startTurn(e){return this.action("turn/start",Sb,e,_b)}async steerTurn(e){return this.action("turn/steer",bb,e,wb)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",vb,n,Tb)}async listModels(e={}){return this.action("model/list",Rb,e,Ob)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",Cb,e,kb)}async readConfig(e={}){return this.action("config/read",Ab,e,Ib)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",Pb,e,Mb)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Ne(Df,t,"initialize parameters"));return Ne(dn,r,"initialize result")}let n=Ne(Wl,{id:1,method:e,params:t},"App Server method");if(!ZH.has(n.method))throw new G("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 G("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Ne(dn,e,"initialize parameters")),n=Ne(ab,t,"initialize result"),r=Ne(sb,YS,"initialized notification");return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(t){let n=t instanceof G?t:new G("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(n),n}}async action(e,t,n,r){let o=Ne(t,n,`${e} parameters`),i=Ne(dn,o,`${e} parameters`),a=await this.request(e,i);return Ne(r,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new G("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=Ne(Wl,{id:n,method:e,params:t},`${e} request`);return new Promise((o,i)=>{let a=!1,s,c,l=(p)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(p)};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new G("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let p=()=>l(new G("cancellation",`The ${e} request was cancelled.`,{method:e}));this.signal.addEventListener("abort",p,{once:!0}),c=()=>this.signal?.removeEventListener("abort",p)}let u={method:e,resolve:(p)=>{if(a)return;if(a=!0,s!==void 0)clearTimeout(s);c?.(),o(p)},reject:l,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,u),this.transport.writeLine(JSON.stringify(r)).catch((p)=>{l(p instanceof G?p:new G("transport_failure","The App Server request could not be written.",{},{cause:p}))})})}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 G("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new G("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof G?e:new G("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 G("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let n=this.tryDecode(zl,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(Wl,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(ib,t);if(o!==void 0){this.handleNotification(o);return}throw Ue("JSON-RPC message",t)}tryDecode(e,t){try{return Ne(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new G("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=QH(t.method);t.reject(new G(r,`The App Server rejected ${t.method}: ${pn(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:ra(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Ne(Nb,{...e,params:t,category:EP(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,pn(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,pn(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Ne(Fb,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,pn(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=Ne(zl,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Ne(zl,{id:e,error:{code:t,message:XH(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===ZS){let n=Ne(Eb,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:uP({params:ra(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 G("closed","The App Server client is closed.")}}function XH(e){let t=pn(e);return t.length>0?t:"server request failed"}function QH(e){if($l.some((t)=>t===e))return"permission_denied";if(Ul.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var YH,ZH;var Db=x(()=>{Tr();Cf();Lb();YH={clientInfo:{name:"holycodex",title:null,version:zS},capabilities:null},ZH=new Set(KS)});import{isAbsolute as ej}from"path";function ri(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 qb(e=process.env){return Object.freeze(ri(e))}async function Uf(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 G("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 $f(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new G("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}}function Is(e){return pn(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}class Hf{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!ej(e.executablePath))throw new G("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??ql,this.maxDiagnosticBytes=e.maxDiagnosticBytes??WS,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new G("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:ri(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new G("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new G("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 G("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 G("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 G("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 G)throw t;throw new G("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new G("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new G("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 G("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 Uf(this.stderrStream,this.maxDiagnosticBytes),t=$f(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=Is(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var jf=x(()=>{Tr()});import{lstat as N4,mkdir as F4,readFile as tj,readdir as L4,realpath as nj,stat as rj}from"fs/promises";import{delimiter as oj,isAbsolute as q4,join as U4,relative as $4,resolve as RP}from"path";async function aj(e){let t=[];if(e.executablePath!==void 0)t.push(RP(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(oj).filter((i)=>i.length>0))for(let i of r)t.push(RP(o,i))}for(let n of t)try{let r=await rj(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await nj(n)}catch{if(e.executablePath!==void 0)throw new G("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new G("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function sj(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 G("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await lj(Promise.all([Uf(n.stdout,16384),Uf(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=pn($f(r,"Codex version output"));if(i!==0||a.length===0){let s=Is($f(o,"Codex version diagnostics"));throw new G("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 G)throw r;throw new G("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function cj(e){let t=await tj(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=yf(r);if(!o.ok)throw new G("discovery_failed","The Codex executable digest was invalid.");return o.value}async function Ub(e={}){let t=await aj(e),n=ri(e.environment),r=e.versionRunner?pn(await e.versionRunner(t,n)):await sj(t,n);if(r.length===0)throw new G("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await cj(t)}}async function lj(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new G("timeout",n))},ij)})])}finally{if(r!==void 0)clearTimeout(r)}}var ij=30000,V4;var OP=x(()=>{st();Ot();Tr();jf();V4=_({exitCode:nn.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:A.pipe(pS(1048576)),stderr:A.pipe(pS(1048576))})});var uj="packages/codex/generated",pj,dj,$b,J4,G4;var CP=x(()=>{st();Ot();Tr();pj=/^codex-cli \d+\.\d+\.\d+$/u,dj=/^codex-app-server-\d+\.\d+\.\d+$/u,$b=A.pipe(pe(/^[a-f0-9]{64}$/u)),J4=_({schema_version:T("holycodex-generated-v2"),artifact_root:T(uj),codex_cli_version:A.pipe(pe(pj)),codex_cli_digest:$b,protocol_epoch:A.pipe(pe(dj)),generator:_({command:lI(T("app-server"),T("generate-ts")),supported_surface:T("codex app-server generators")}),typescript_root:T("typescript"),files:_({count:nn.pipe(mf(),fS()),digest:$b})}),G4=_({path:A.pipe(ws(1)),size:nn.pipe(mf(),fS()),sha256:$b})});var fj;var kP=x(()=>{Ot();Ff();fj=_({owner:T("holycodex"),schema:A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});import{spawn as mj}from"child_process";import{lstat as ii,mkdir as hj,mkdtemp as gj,readFile as yj,readdir as xj,realpath as Hb,rename as Sj,rm as bj,stat as t8}from"fs/promises";import{dirname as IP,isAbsolute as Wb,join as oi,relative as PP,resolve as Vf,sep as MP}from"path";async function FP(e){let t=Yb(e.selectedPluginIds);if(t.length===0)return;if(UP(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new ve("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>Gb(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&Wf(r,t))return r;let o=e.initializeRuntime??(()=>Ij(e)),i,a;try{i=await o()}catch(s){a=ne("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??Jb,c=e.pollIntervalMs??_j,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new ve("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&Wf(u,t))return u;let p=s-(Date.now()-l);if(p<=0)break;await(e.sleep??Mj)(Math.min(c,p))}a=ne("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 ve&&s.code==="cancelled")throw s;a=s instanceof ve?s:ne("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await LP({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 ve)throw s;throw ne("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??ne("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function LP(e){let t=Yb(e.selectedPluginIds);if(t.length===0)throw ne("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(UP(e.timeoutMs,void 0),!Wb(e.codexHome))throw ne("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new ve("cancelled","Official Codex marketplace fallback was cancelled.");let n=ri(e.environment),r=e.gitRunner??jP("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??Jb,i;try{i=await Tj(r,o,e.signal)}catch(u){if(u instanceof ve)throw u;throw ne("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=oi(e.codexHome,"plugins"),s=oi(a,Kb[1]);if(await Rj(a,e.codexHome),await ii(s).catch((u)=>{if(Zl(u))return;throw ne("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw ne("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await gj(oi(a,".openai-plugins-stage-"));try{if(await Bb(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(ia,l)}catch(m){if(Pj(m))throw ne("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",ia,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw ne("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await zf(l);let u=await DP(l,e.codexHome,t);if(u===void 0||!Wf(u,t))throw ne("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await Ej(r,l,o,e.signal)!==i)throw ne("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await ii(s).catch((m)=>{if(Zl(m))return;throw ne("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw ne("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await Sj(l,s);let h=await Gb(e.codexHome,e.selectedPluginIds);if(h===void 0||!Wf(h,t))throw ne("marketplace_invalid","The published official marketplace failed validation.");return h}catch(u){if(u instanceof ve)throw u;throw ne("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await bj(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function Tj(e,t,n){let r=await e.run(["ls-remote",ia,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw ne("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 ne("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function Ej(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 ne("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function Rj(e,t){await jb(t,e),await hj(e,{recursive:!0}),await jb(t,e)}async function jb(e,t){let n=Vf(e),r=Vf(t);while(!0){if((await ii(r).catch((a)=>{if(Zl(a))return;throw a}))?.isSymbolicLink())throw ne("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=IP(r);if(i===r||i!==n&&!Oj(n,i))throw ne("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function Oj(e,t){let n=PP(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${MP}`)&&!Wb(n)}async function zf(e){let t=await ii(e);if(t.isSymbolicLink())throw ne("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw ne("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await xj(e,{withFileTypes:!0});for(let r of n){let o=oi(e,r.name),i=await ii(o);if(i.isSymbolicLink())throw ne("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await zf(o)}}async function Gb(e,t=[]){return await DP(oi(e,...Kb),e,Yb(t))}async function DP(e,t,n=[]){if(t!==void 0)await jb(t,e);let r=await ii(e).catch((l)=>{if(Zl(l))return;throw ne("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 ne("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await Bb(t,e);else await zf(e);if(t!==void 0)await zf(e);let o=await Hb(e),i=[oi(o,".agents","plugins","marketplace.json"),oi(o,".codex-plugin","marketplace.json"),oi(o,"marketplace.json")],a,s;for(let l of i){let u=await ii(l).catch((p)=>{if(Zl(p))return;throw ne("marketplace_invalid","The official marketplace manifest could not be read safely.",p)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw ne("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await Bb(o,l),a!==void 0)throw ne("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await yj(l))}catch(p){throw ne("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",p)}}if(a===void 0||s===void 0)return;let c;try{c=JSON.parse(s)}catch(l){throw ne("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return qP(c,o,a,n)}function qP(e,t=`${Kb.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!ae(e)||e.name!==Yl)throw ne("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");Cj(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw ne("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!ae(s)||typeof s.name!=="string"){if(r.length>0)continue;throw ne("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 ne("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw ne("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=kj(s);if(!Aj(l))throw ne("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 ne("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:Yl,source:ia,rootPath:t,manifestPath:n,plugins:i}}function Cj(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:ae(n)&&typeof n.url==="string"?n.url:void 0)!==ia)throw ne("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function kj(e){let t=e.source;if(typeof t==="string")return t;if(ae(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function Aj(e){if(e===void 0||e.length===0||Wb(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 Yb(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!==Yl&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw ne("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!$P(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function Wf(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 Ij(e){let t=ri(e.environment),n;try{n=new Hf({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new qf(n,{requestTimeoutMs:Math.min(e.timeoutMs??Jb,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 UP(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw ne("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw ne("marketplace_invalid","The official marketplace poll interval is invalid.")}async function Bb(e,t){let n=await Hb(e),r=await Hb(t),o=PP(n,r);if(o===""||o===".."||o.startsWith(`..${MP}`))throw ne("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=Vf(e),a=Vf(t);while(!0){if((await ii(a)).isSymbolicLink())throw ne("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=IP(a);if(c===a)throw ne("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Zl(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Pj(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function Mj(e){await new Promise((t)=>setTimeout(t,e))}function ne(e,t,n){return new ve(e,t,n instanceof Error?{cause:Is(n.message)}:{})}function Rr(e,t){let n=Yn(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=gS(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 $P(e){return gf.includes(e)}function HP(e){if(!pP(zb,e))return cP(Ue("live official plugin list",e));return lP(Ne(zb,e,"live official plugin list"))}function Kf(e){let t=e.runner??jP(e.executable,{environment:e.environment??ri(),...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 Bf("list",r);let o;try{o=JSON.parse(r.stdout)}catch{throw new ve("command_failed","Codex returned invalid plugin data.")}let i=HP(o);if(!i.ok)throw new ve("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 ve("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await FP({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=Ne(Gl,r,"plugin marketplace source");if(i===Yl||i===ia)throw new ve("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 Bf("marketplace add",a,i)},add:async(r,o)=>{let i=Ne(Gl,r,"official plugin id"),a=await t.run(["plugin","add",i,"--json"],o===void 0?void 0:{signal:o});if(a.exitCode!==0)throw Bf("add",a,i);let s=await n(),c=Rr(s,i),l=Yn(i),u=[...s.installed,...s.available].filter((f)=>f.pluginId===i&&(l===void 0||f.marketplaceName==null)),p=c?.entry??u.find((f)=>f.installed)??u[0];if(!p)throw new ve("readback_mismatch",`Codex did not report ${i} after installation.`,{plugin_id:i});if(!p.installed)throw new ve("plugin_missing",`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!p.enabled)throw new ve("plugin_disabled",`Codex installed ${i} but it is disabled; enable it in Codex and retry.`,{plugin_id:i})},remove:async(r,o)=>{let i=Ne(Gl,r,"official plugin id"),a=i;if(Yn(i)===i){let u=await n(),p=Rr(u,i);if(p?.entry.installed)a=p.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 Bf("remove",s,a);let c=await n(),l=[...c.installed,...c.available].find((u)=>u.pluginId===a);if(l?.installed)throw new ve("readback_mismatch",`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:l.pluginId})}}}function Bf(e,t,n){let r=Is(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new ve("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function jP(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>Fj(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 Fj(e,t,n){if(n.signal?.aborted)throw new ve("cancelled","The Codex plugin command was cancelled.");let r=mj(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=AP(r.stdout,n.stdoutLimit),i=AP(r.stderr,n.stderrLimit),a=new Promise((p,f)=>{r.once("error",f),r.once("close",(h)=>p(h??-1))}),s,c,l=new Promise((p,f)=>{c=()=>{try{r.kill()}catch{}f(new ve("cancelled","The Codex plugin command was cancelled."))},n.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((p,f)=>{s=setTimeout(()=>{try{r.kill()}catch{}f(new ve("timeout","The Codex plugin command timed out."))},n.timeoutMs)});try{let[p,f,h]=await Promise.race([Promise.all([o,i,a]),l,u]);return{stdout:p,stderr:f,exitCode:h}}catch(p){try{r.kill()}catch{}if(p instanceof ve)throw p;throw new ve("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function AP(e,t){if(e===null)return Promise.reject(new ve("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 ve("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new ve("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 Yl="openai-curated",ia="https://github.com/openai/plugins.git",Kb,Jb=30000,_j=100,NP,wj,Jl,Gl,vj,Nj,Vb,zb,ve;var Zb=x(()=>{st();Ot();Db();Tr();jf();Kb=["plugins","openai-plugins"],NP=A.pipe(pe(/^[a-z][a-z0-9._-]{1,63}$/u)),wj=A.pipe(pe(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),Jl=H(A),Gl=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),vj=_({name:NP,version:wj,description:ao,author:w(dn),license:w(ao),homepage:w(ao),repository:w(ao),keywords:w(Jl),skills:w(Jl),commands:w(Jl),hooks:w(Jl),assets:w(Jl),official:w(X)});Nj=_({id:NP,selected:T(!0)}),Vb=_({pluginId:Gl,installed:X,enabled:X,name:w(be(A,mt)),marketplaceName:w(be(A,mt)),version:w(be(A,mt))},ff({key:A,value:aS})),zb=_({installed:H(Vb),available:H(Vb)});ve=class ve extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});var Xl=x(()=>{Tr();Tr();Cf();Lb();Db();jf();OP();CP();kP();Ff();Zb();Zb()});function fn(e){if(!Ps(e))throw Error("The value is not JSON serializable.");return wr(e),e}function Ps(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)=>Ps(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>Ps(n,t))}finally{t.delete(e)}}var Ql=x(()=>{st()});function St(e,t){let n=Cn(e,t);return kt(n)?n.right:void 0}function JP(e){return St(Gf,e)!==void 0}var Gf,W8,VP,eu,Lj,Ms,Dj,qj,zP,Xb,tu,Yf,Ns,Zf,Uj,$j,Hj,jj,Bj,Vj,Jf,zj,BP,Wj,Qb,Fs,Kj,WP,Jj,KP,Gj,Yj,Wt;var Ls=x(()=>{Xl();st();an();Ot();Ql();Gf=z((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&Ps(e)),W8=z(Ps),VP=A.pipe(pe(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)),eu=A.pipe(pe(/^[0-9a-f]{64}$/u)),Lj=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Ms=A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),Dj=A.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),qj=_({path:A.pipe(pe(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:eu}),zP=_({computer_use:X,frontend:X,security:X,coding:T(!0)}),Xb=_({computer_use:w(X),frontend:w(X),security:w(X)}),tu=_({profile:w(Yo),tier:w(ea),optional:w(Xb),officialPlugins:w(H(Ms))}),Yf=tu,Ns=_({selected:X,status:T("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:H(Ms),reason:w(A)}),Zf=_({computer_use:Ns,frontend:Ns,security:Ns}),Uj=_({...zP.fields,work:X}),$j=_({...Xb.fields,work:w(X)}),Hj=_({...Zf.fields,work:Ns}),jj=be(_({status:T("not_applicable")}),_({status:T("missing")}),_({status:T("healthy"),path:A,installed:X})),Bj=_({manager:T("bun","npm","pnpm"),launcher:T("bunx","npx","pnpm dlx"),version:VP,executable:A,ownership:T("user","holycodex"),identity:w(eu)}),Vj=_({git_bash:jj,context7:Bj}),Jf=_({presence:T("absent","present"),digest:eu,safe_value:w(be(_({kind:T("boolean"),value:X}),_({kind:T("marketplace"),source_type:T("git"),source:T("https://github.com/davidbasilefilho/holycodex.git")})))}),zj=_({plugin_id:T("holycodex@holycodex"),before:_({preference:Jf,marketplace:Jf}),after:_({preference:Jf,marketplace:Jf})}),BP=_({presence:T("absent","present"),digest:eu,safe_value:w(_({kind:T("boolean"),value:X}))}),Wj=_({plugin_id:Ms,before:BP,after:BP}),Qb={owner:T("holycodex"),schema_epoch:T(yn),install_id:Lj,version:VP,digest:eu,profile:Yo,tier:ea,optional_selections:zP,explicit_optional_selections:Xb,official_plugins:w(H(Ms)),capability_state:w(Zf),managed_artifacts:H(qj),installed_at:Dj,status:w(T("active")),step:w(T("active")),managed_config:w(Pf),plugin_snapshot:w(H(_({plugin_id:Ms,status:T("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:w(zj),provider_config:w(H(Wj)),owned_plugins:w(H(Ms)),tooling:w(Vj)},Fs=_(Qb),Kj=(({profile:e,...t})=>t)(Qb),WP={...Qb,optional_selections:Uj,explicit_optional_selections:$j,capability_state:w(Hj)},Jj=(({profile:e,...t})=>t)(WP),KP=be(_({...WP,profile:kl}),_({...Jj,plan:kl}),_({...Kj,plan:kl})),Gj=T("preparing","conflicted"),Yj=T("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),Wt=_({...Fs.fields,status:Gj,step:Yj})});import{lstat as Zj,mkdir as Xj}from"fs/promises";import{homedir as Qj}from"os";import{dirname as e1,join as aa,posix as GP,resolve as t1,sep as YP,win32 as ZP}from"path";function ai(e={},t=process.env){let n=Qj(),r=e.paths?.codexHome??t.CODEX_HOME??aa(n,".codex"),o=t_(r,"CODEX_HOME"),i=aa(o,n1);return{codexHome:o,stateRoot:i,activeRecord:aa(i,r1),preparingRecord:aa(i,o1),conflictedRecord:aa(i,i1),roleRoot:aa(i,"agents"),configFile:aa(o,"config.toml")}}function t_(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||s1(e))throw new An("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?ZP:GP,o=e_(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new An("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":YP).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new An("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new An("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function s1(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function nu(e){t_(e,"owned path"),await Or(e),await Xj(e,{recursive:!0}),await Or(e)}async function Or(e){let n=t1(e);while(!0){try{if((await Zj(n)).isSymbolicLink())throw new An("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof An)throw o;if(!bt(o,"ENOENT"))throw o}let r=e1(n);if(r===n)break;n=r}}async function sa(e){await Or(e)}function co(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?ZP:GP,o=r.resolve(e_(e,n)),i=r.resolve(e_(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":YP}`)&&a!==".."&&!r.isAbsolute(a)}function e_(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function bt(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var n1="holycodex",r1="active.json",o1="preparing.json",i1="conflicted.json",a1,An;var ca=x(()=>{st();a1=yn;An=class An extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as XP,open as c1,readFile as QP,rename as l1,unlink as u1,writeFile as p1}from"fs/promises";import{dirname as d1}from"path";async function eM(e){let t;try{t=await c1(e,"r"),await t.sync()}catch(n){if(!tM(n))throw n}finally{await t?.close().catch(()=>{return})}}async function m1(e){await eM(e).catch((t)=>{if(!tM(t))throw t})}async function ua(e,t){await lo(e,`${wr(t)}
36
+ `)}async function lo(e,t){let n=d1(e);await nu(n),await Or(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await p1(r,t,{encoding:"utf8",mode:384}),await eM(r),await l1(r,e),await m1(n)}catch(o){throw await u1(r).catch(()=>{return}),o}}async function h1(e,t){let n=await XP(e);if(!n.isFile()||n.isSymbolicLink())throw new la("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await QP(e,"utf8"))}catch(i){throw new la("state_corrupt","A persisted file is not valid JSON.",i)}let o=St(t,r);if(o===void 0)throw new la("state_corrupt","A persisted file failed schema validation.");return o}async function qt(e){try{let t=await XP(e);if(!t.isFile()||t.isSymbolicLink())throw new la("state_corrupt","A persisted file is not a regular file.");return await QP(e,"utf8")}catch(t){if(bt(t,"ENOENT"))return;throw t}}async function mn(e,t){try{return await h1(e,t)}catch(n){if(bt(n,"ENOENT"))return;throw n}}function tM(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return f1.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var f1,la;var Ds=x(()=>{st();ca();Ls();f1=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);la=class la extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as g1}from"fs/promises";import{dirname as y1,resolve as x1}from"path";import{fileURLToPath as S1}from"url";async function nM(e=ru){let t=JSON.parse(await g1(e,"utf8")),n=St(w1,t);if(n===void 0)throw new ou("manifest_invalid","The public package manifest is invalid.");return n}async function Xf(e=ru){return(await nM(e)).version}async function qs(e=ru){return(await Xf(e)).split("-",1)[0]??""}async function n_(e,t,n=ru){let r=await nM(n),o=await qs(n),i=v1(e,o);if(!t)await ua(n,{...r,version:i});return{previous:o,next:i}}function v1(e,t){if(e!=="patch"&&e!=="minor"){if(St(b1,e)===void 0)throw new ou("version_invalid","The version target is invalid.");return e}let n=(t.split("-",1)[0]??"").split("."),r=Number(n[1]),o=Number(n[2]);return e==="minor"?`0.${r+1}.0`:`0.${r}.${o+1}`}var b1,_1,w1,ru,ou;var iu=x(()=>{Ot();Ls();Ds();b1=A.pipe(pe(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u)),_1=A.pipe(pe(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*)|-dev\.[1-9]\d*\.[1-9]\d*)?$/u)),w1=z((e)=>JP(e)&&e.name==="holycodex"&&St(_1,e.version)!==void 0),ru=x1(y1(S1(import.meta.url)),"../package.json");ou=class ou extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{lstat as Qf,readFile as em,rm as Us}from"fs/promises";import{join as Qe,relative as rM}from"path";async function tm(e,t,n=[],r="standard",o){let i=Qe(e,"holycodex","agents"),a=si(t,r).map((l)=>({path:Qe(i,`${l.name}.toml`),contents:au(l,o===void 0?{}:{windowsGitBashExecutable:o})})),s=new Map(n.map((l)=>[Qe(e,l.path),l])),c=[];for(let l of a){let u=await pa(l.path),p=s.get(l.path);if(u!==void 0&&p===void 0&&u!==l.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${l.path}`);if(u!==void 0&&p!==void 0&&await Cr(u)!==p.digest&&u!==l.contents)c.push({path:l.path,action:"replace"})}for(let l of n){let u=Qe(e,l.path);if(a.some((f)=>f.path===u)||!iM(e,u,l.path))continue;let p=await pa(u);if(p!==void 0&&await Cr(p)!==l.digest)c.push({path:u,action:"remove"})}return c}async function oM(e,t){let n=Qe(e,"agents"),r=Qe(e,"holycodex","agents"),o=[];for(let i of t){let a=Qe(e,i.path);if(!co(e,a)||!co(n,a)&&!co(r,a)&&a!==Qe(e,"config.toml"))continue;let s=await pa(a);if(s!==void 0&&await Cr(s)!==i.digest)o.push({path:a,action:"remove"})}return o}function si(e,t="standard"){let n=vr(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:ES(o),rolePolicy:kn.find((i)=>i.role===r.role),description:OS(o),taskInstruction:RS(o),permissions:CS(o),model:"gpt-5.6-luna",effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function r_(e,t="standard"){let n=vr(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 o_(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e,n=t.computerUse??!1;if(!L.requiresDelegation||!L.assignmentStartAndDispatchPrecedeDelegableExecution||!L.trivialWorkRequiresDelegation||!L.preparatoryAndExploratoryWorkRequiresDelegation||L.genericDirectWorkFallback||L.directExecutionExceptions!==L.rootOwnedAuthority||!L.codeReviewRequiredForImplementation||!L.codeReviewRequiredBeforeVcs||!L.externalVerificationMustBeTerminal||!L.concreteSpecialistDispatchRequired||!L.roleFamiliesAreLabelsOnly||!L.missingConcreteRouteIsBlocker||!L.normalSpawnRequiresExplicitForkTurns||L.normalSpawnForkTurns!=="none"||!L.normalSpawnUsesConcreteRegisteredAgentType||!L.assignmentContextIsTaskSpecificOnly||!L.configuredRouteModelAndEffortPreserved||L.normalProgressMessages||L.normalHeartbeatMessages||L.normalIntermediateEvidence||!L.userUpdatesUsefulOrImportantOnly||!L.routinePerToolOrSubagentNarrationForbidden||!L.routineStatusOnlyChatterForbidden||!L.fixedCadenceUserUpdatesForbidden||!L.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!L.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!L.materialUserUpdateKinds.includes("release_milestones")||!L.outOfBoundaryRequiresNewAssignment||!L.longestPracticalEventWait||!L.busyPollingForbidden||!L.statusOnlyCoordinationLoopsForbidden||!L.batchIndependentLifecycleActions||!L.releaseLeavesAfterAcceptedOutcome||L.routineWaitTool!=="collaboration.wait_agent"||!Number.isSafeInteger(L.routineWaitMaximumTimeoutMs)||L.routineWaitMaximumTimeoutMs<=0||!L.routineWaitUsesMaximumRuntimeTimeout||!L.earlySpecialistCompletionWakesWait||!L.collectiveMailboxIncludesRelevantAgents||!L.idleTimeoutRepeatsMaximumWait||!L.shortRoutineWaitsForbidden||!L.evidenceFirstConciseStructuredReports||L.specialistReportFields.length===0||L.rootLargeReadsOnlyFor.length===0||!L.stableFactsReused||!L.duplicatePolicyForbidden||!L.stableBoundedComponentScopesAreCanonical||!L.lifecycleWorkerOwnsDeterministicApi||L.registeredSpecialistAgentTypes!==_r||L.forbiddenGenericAgentTypes!==wf)throw Error("The Root orchestration policy is incomplete.");let r=[`You are the HolyCodex Root/session orchestrator running gpt-6-astra. Root directly owns only ${L.rootOwnedAuthority.map((o)=>E1[o]).join("; ")}. These actions remain subject to their approval and capability boundaries.`,`Delegate every delegable action with a bounded Assignment and dispatch spawn_agent using the exact concrete registered Role.task agent_type selected from this canonical HolyCodex inventory: ${L.registeredSpecialistAgentTypes.join(", ")}. The role families Explorer, Librarian, Worker, and Reviewer are labels only and are never dispatch targets. Generic built-in agent_type values ${L.forbiddenGenericAgentTypes.join(", ")} are forbidden for HolyCodex specialist Assignments. If no matching concrete registered route is available, stop with needs_root_input; never substitute a generic agent. This includes ${L.delegableActions.map((o)=>R1[o]).join("; ")}. Starting the Assignment and dispatching its specialist must precede every such inspection or execution, including trivial, preparatory, and exploratory work. There is no generic Root direct-work fallback. Root may inspect returned evidence for integration acceptance. Root-only execution does not grant Root authority to perform specialist work.`,`For every normal specialist spawn, pass the exact concrete Role.task agent_type and explicitly set fork_turns: "${L.normalSpawnForkTurns}"; never omit fork_turns or use "all" or its default. Preserve the selected route's configured model and reasoning effort. Each Assignment must be self-contained and carry only task-specific semantic context for its bounded objective, scope, constraints, exclusions, dependencies, acceptance criteria, and relevant evidence.`,"Use holycodex-agent semantic operations for Intent, optional Plan, and Assignment state. Never edit TOON state or create standalone handoff, Decision, or blocker files.","Explicit user instructions override skill guidelines on conflict except genuine HolyCodex hard safety, authority, capability, and lifecycle invariants. Infer routine safe, reversible, in-scope choices and carry authorized read-only, reversible, preparatory, and independent work through implementation, inspection, repair, meaningful proof, required CI, and every requested terminal state. Ask only for a material unresolved choice, a genuine approval boundary such as installation profile approval or remote/public external mutation, user-owned credential entry, or a blocker that can change the outcome; persist needs_root_input when applicable. Out-of-boundary work returns to Root for a new bounded Assignment.","Dispatch independent non-overlapping Assignments concurrently, keep dependent phases ordered, and serialize writes to one mutable seam. Use writing-instructions for GPT-6 model-facing contracts, add only the missing semantic delta for the receiver's effective context, and keep each meaning with one authoritative owner.","Make each phase a coherent dependency, decision, or integration boundary. Resolve choices needed by the current phase, persist Plan and Assignment evidence, and advance after acceptance; do not ask later-phase questions prematurely.","Give the user only useful or important information. Do not output after every tool use or subagent update, emit routine status-only chatter or heartbeat messages, or follow a fixed update cadence. Material updates include significant findings or decisions, consequential blockers or input needs, and release milestones. Preserve native Astra Default questions, including asking while independent work proceeds; this rule adds no question protocol.",`Use the longest practical event wait for every routine Root wait: call ${L.routineWaitTool} with timeout_ms=${L.routineWaitMaximumTimeoutMs} (the active V1 runtime maximum). Early specialist completion wakes the wait; the collective mailbox already includes all relevant agents. If the maximum wait expires while idle, call the same maximum wait again. Never use short waits, list or status polling, or message loops on idle timeout; never busy-poll or run status-only coordination loops. Batch independent lifecycle actions and stop or release specialist leaves once their accepted terminal outcomes are recorded.`,`Keep specialist and Reviewer reports concise, structured, and evidence-first: lead with ${L.specialistReportFields.join(", ")}. Root reads large transcripts or artifacts only for ${L.rootLargeReadsOnlyFor.join(", ")}; reuse stable facts, keep each meaning with one authoritative owner, and do not duplicate policy. Stable bounded component scopes are canonical guidance; the lifecycle worker owns deterministic Intent, Plan, and Assignment API decisions, while Root owns material decisions, integration, and completion.`,`${vf.rule} Do not add tests for low-impact reversible changes when they merely mirror implementation details. Once relevant proof passes, broaden or repeat it only after another source change, a failure, or an unresolved material concern. Mandatory repository gates and Reviewer.code remain required. Inspect specialist evidence before integration; Worker.validation supplies independent local proof without replacing implementation proof or Reviewer.code. Reviewer.code fixed-point review is mandatory after implementation or a major codebase change and before completion or VCS.`,`For current technical documentation, Librarian.lookup and Librarian.research resolve the library identity and use Context7 before model memory or generic web, query narrowly, and return one typed evidence state (${AS.evidenceStates.join(" | ")}) in the context7 field with version/source evidence. Fallback is allowed only for one of those states or an absent required version; authoritative first-party documentation resolves conflicts. Context7 supplies facts while Root owns material product, architecture, dependency, compatibility, and implementation decisions.`,"After integration, Root performs approved VCS actions and dispatches Worker.operations with the exact ref or SHA for terminal CI or release evidence. Pending is never success. Discover the actual topology; repair failures through bounded Assignments and repeat integration, fixed-point review, VCS, and terminal observation until the applicable gate is green."];if(t.frontend??!0)r.push(O1());if(t.security??!0)r.push("Security is selected. Use threat-model for material trust-boundary changes, security-diff-scan before VCS for security-sensitive diffs, and full security-scan for explicit audits, substantial new exposed surfaces, or broader systemic concern. Validate supported findings before blocking. A validated vulnerability introduced or worsened by the change blocks VCS until repaired or explicitly risk-accepted; report unrelated pre-existing findings without expanding scope. Security-driven edits invalidate Reviewer.code, and security-sensitive Reviewer.code edits invalidate the applicable security review; repeat both gates until green together.");if(n)r.push("Computer Use is selected and is directly executable by Root/session only; it must not be delegated.","For interactive authentication, use Computer Use with the user's default browser unless the builtin browser is that default. Navigate to authentication, hand control to the user, wait while the user personally enters and submits every credential, then resume from the authenticated session. Never ask for credentials in chat or type, paste, retrieve, infer, expose, store, or submit them. If no authorized Computer Use/default-browser path exists, report the capability blocker.");else r.push("Computer Use is unavailable for this installation and cannot be delegated. GUI and browser execution remain Root/session-only.");if(t.windowsGitBashExecutable!==void 0)r.push(a_(t.windowsGitBashExecutable));return r.join(`
37
+ `)}function O1(){if(!Zo.repositoryAndUserRequirementsPrecedePluginDefaults||!Zo.specialistsOwnInspectionImplementationAndRepair||!Zo.rootOwnsLiveVisualAndInteractionAcceptance||!Zo.sourceChangesInvalidateRenderEvidence||!Zo.specialistReportsCannotSubstituteForRootAcceptance||Zo.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`Frontend is selected. For a user-visible frontend task, ${Qi.frontend.applicability.map(({skillId:n,appliesWhen:r})=>`${r} uses ${n}`).join("; ")}. Repository stack, existing design system, and explicit user requirements govern over generic plugin defaults. Specialists inspect, implement, and repair; Root renders, opens, and interacts with the current result, judges it against the accepted outcome, delegates concrete discrepancies, and repeats repair and live acceptance to a fixed point. Every source change invalidates earlier render evidence. Build results, specialist reports, and Reviewer.artifact cannot replace Root's acceptance of the current UI. Apply proportional responsive, accessibility, and core-interaction checks; logic-only nonvisual changes do not require visual ceremony.`}async function i_(e,t,n=[],r="standard",o,i,a=[]){let s=Qe(e,"holycodex","agents"),c=[],l=[],u=si(t,r).map((S)=>({path:Qe(s,`${S.name}.toml`),contents:au(S,o===void 0?{}:{windowsGitBashExecutable:o})})),p=new Map(n.map((S)=>[Qe(e,S.path),S])),f=new Map,h=new Set;for(let S of u){let E=await pa(S.path);f.set(S.path,E);let v=p.get(S.path);if(E!==void 0&&v===void 0&&E!==S.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${S.path}`);if(E!==void 0&&v!==void 0){if(await Cr(E)!==v.digest&&E!==S.contents){let g={path:S.path,action:"replace",key:void 0},O=a.some((C)=>C.path===g.path&&C.action===g.action&&C.key===g.key)?"accept":await i?.(g);if(O==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${S.path}`);if(O==="accept")h.add(S.path)}}}let m=[];try{for(let b of u){let g=f.get(b.path),R=p.get(b.path);if(g!==void 0&&R!==void 0){if(await Cr(g)!==R.digest&&g!==b.contents&&!h.has(b.path)){c.push(b.path),m.push({path:rM(e,b.path).replaceAll("\\","/"),digest:R.digest});continue}}if(g===void 0||g!==b.contents)await lo(b.path,b.contents),l.push({path:b.path,previous:g,installedDigest:await Cr(b.contents)});m.push({path:rM(e,b.path).replaceAll("\\","/"),digest:await Cr(b.contents)})}let S=Qe(e,"agents","root.toml"),E=await pa(S),v=await aM(S);if(v==="preserved")c.push(S);if(v==="removed"&&E!==void 0)l.push({path:S,previous:E,installedDigest:void 0});for(let b of n){let g=Qe(e,b.path);if(!u.some((R)=>R.path===g)){if(!iM(e,g,b.path)){c.push(g);continue}if(a.some((C)=>C.path===g&&C.action==="remove")){let C=await pa(g);if(C!==void 0)await Us(g,{force:!1}),l.push({path:g,previous:C,installedDigest:void 0});continue}let O=await A1(g,b.digest);if(O.status==="preserved")c.push(g);else if(O.previous!==void 0)l.push({path:g,previous:O.previous,installedDigest:void 0})}}for(let b of n){let g=Qe(e,b.path);if(c.includes(g)&&!m.some((R)=>Qe(e,R.path)===g))m.push(b)}return{managed_artifacts:m,preserved:c,rollback:l}}catch(S){throw await nm(l).catch(()=>{return}),S}}async function nm(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await pa(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await Cr(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await Us(r.path,{force:!1}).catch((a)=>{if(!bt(a,"ENOENT"))throw a}),t.push(r.path);else await lo(r.path,r.previous)}return{removed:t,preserved:n}}async function rm(e,t,n=new Set){let r=[],o=[],i=Qe(e,"agents"),a=Qe(e,"holycodex","agents");for(let l of t){let u=Qe(e,l.path);if(!co(e,u)||!co(i,u)&&!co(a,u)&&u!==Qe(e,"config.toml")){o.push(u);continue}try{await Or(u);let p=await Qf(u);if(p.isSymbolicLink()||!p.isFile()){o.push(u);continue}let f=await em(u);if(await Cr(f)!==l.digest){if(n.has(u)){await Us(u,{force:!1}),r.push(u);continue}o.push(u);continue}await Us(u,{force:!1}),r.push(u)}catch(p){if(!bt(p,"ENOENT"))o.push(u)}}let s=Qe(e,"agents","root.toml"),c=await aM(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);return{removed:r,preserved:o}}function au(e,t={}){let n=[T1,e.taskInstruction,...e.permissions.sourceMutation?[`Surgical mutation rule: ${bf}`]:[],...t.windowsGitBashExecutable===void 0?[]:[a_(t.windowsGitBashExecutable)]].join(`
38
38
  `),r=su(e);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(r)}`,'approval_policy = "never"',`web_search = ${JSON.stringify(e.permissions.network?"live":"disabled")}`,`developer_instructions = ${JSON.stringify(n)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","context_management = true","multi_agent_v2 = false","multi_agent = false","computer_use = false","browser_use = false","in_app_browser = false",""].join(`
39
- `)}function a_(e){if(e.trim().length===0)throw Error("Git Bash executable is required.");return`On Windows, execute every shell action through the verified Git-for-Windows Bash executable at ${JSON.stringify(e)}. Resolve C:\\Program Files\\Git\\bin\\bash.exe first and use bash on PATH only if that path is unavailable and the resolved executable has been verified as Git for Windows. PowerShell, pwsh, powershell.exe, cmd.exe, WSL Bash, Cygwin, and unrelated MSYS shells are unauthorized. This shell directive does not change authority; specialists still cannot perform Git/VCS.`}function su(e){return e.permissions.filesystem==="workspace-write"?"workspace-write":"read-only"}function T1(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 $s(e){return E1.has(e)}function oM(e,t,n){if(n==="agents/root.toml")return!0;if(kn.some((r)=>n===`holycodex/agents/${r.role.toLowerCase()}.toml`))return!0;if(!so(Qe(e,"agents"),t))return!1;return br.some((r)=>{let[o,i]=r.split("."),a=`${o[0].toUpperCase()}${o.slice(1)}.${i}.toml`;return n===`agents/${a}`})}async function iM(e){try{await Or(e);let t=await em(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await tm(e,"utf8");if(!$s(n))return"preserved";return await Us(e,{force:!1}),"removed"}catch(t){if(bt(t,"ENOENT"))return"absent";throw t}}async function da(e){try{await Or(e);let t=await em(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await tm(e))}catch(t){if(bt(t,"ENOENT"))return;throw t}}async function O1(e,t){try{await Or(e);let n=await em(e);if(n.isSymbolicLink()||!n.isFile())return{status:"preserved"};let r=new TextDecoder("utf-8",{fatal:!0}).decode(await tm(e));if(await Rr(r)===t)return await Us(e,{force:!1}),{status:"removed",previous:r};return{status:"preserved"}}catch(n){if(bt(n,"ENOENT"))return{status:"removed"};throw n}}async function Rr(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("")}var b1,_1,w1,E1;var im=x(()=>{st();la();Ds();b1=["You are a HolyCodex GPT-6-family specialist executing one active bounded Assignment. Follow its exact boundary, exclusions, acceptance criteria, and evidence requirements. Preserve unrelated work. Do not delegate, message peers, mutate global Intent lifecycle, make material decisions, perform external effects, or perform Git/VCS. Repository source mutation is governed only by the concrete task contract; workspace writes for caches, generated test state, and proof outputs do not grant source-mutation authority. Continue through implementation, repair, and proportional proof until the Assignment is completed or exactly blocked.","Do not emit normal progress, heartbeat, or intermediate evidence messages. Communicate only the terminal outcome, or surface the material Root-owned decision required to proceed.","Do not expand beyond the Assignment boundary; report out-of-boundary work to Root for a new bounded Assignment.",`Return one compact structured outcome (${re.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with changed paths, checks, observable evidence, blockers, Root decisions needed, and remaining risk.`].join(" "),_1={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",external_effects:"external effects",gui_browser:"GUI and browser execution",computer_use:"Computer Use when selected"},w1={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",review:"review",ci_release_observation:"CI or release observation"};E1=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)=>T1(e,t,n))))});class si{adapter;observedIdentities={};constructor(e){if("run"in e){let t=Wf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await Ub({environment:e}),n=Wf({executable:t.path,environment:qb(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new si(n)}async list(){try{return await this.adapter.list()}catch(e){throw cu("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw cu("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw cu("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw cu("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw cu("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(e.map((i)=>{let a=Er(t,i),s=Yn(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 p=l===void 0?"missing":l.installed&&l.enabled?"installed":l.installed?"disabled":"missing";return[i,p]}));return this.observedIdentities=Object.freeze(n),o}getObservedIdentities(){return this.observedIdentities}}function cu(e,t,n){if(t instanceof Cr)return t;let o=(t instanceof ve?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 Cr(i,a,t,n===void 0?{}:{plugin_id:n})}var Cr;var lu=x(()=>{Xl();st();Cr=class Cr 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 sM(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=C1(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=s_(o.slice(1,-1).trim()),R1(t,n);continue}let i=pM(o);if(i<1)throw Error("TOML assignment is invalid.");let a=s_(o.slice(0,i).trim()),s=am(o.slice(i+1).trim());uM(t,[...n,...a],s)}return t}function cM(e){let t=[];return lM(e,[],t),t.join(`
41
- `)}function lM(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(l_(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(aM).join(".")}]`)}for(let[i,a]of r)n.push(`${aM(i)} = ${dM(a)}`);for(let[i,a]of o)lM(a,[...t,i],n)}function am(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?[]:c_(t,",").map(am)}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 c_(t,",")){let o=pM(r);if(o<1)throw Error("TOML inline table entry is invalid.");uM(n,s_(r.slice(0,o).trim()),am(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 s_(e){let t=c_(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("'")?am(n):n)}function uM(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(l_(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 R1(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(l_(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function c_(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 pM(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 C1(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 l_(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function aM(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function dM(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(dM).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{execFile as k1}from"child_process";import{access as A1,readFile as I1,realpath as P1}from"fs/promises";import{posix as M1,win32 as N1}from"path";import{promisify as F1}from"util";function ha(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:hM,run:async(t,n)=>{try{let r=await L1(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 u_(e){let t=lo(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(uu(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(uu(t,"bunx")||uu(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(uu(t,"npx")||t.endsWith("/npx-cli.js")||uu(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function ga(e,t){if(e.platform!=="win32")return{status:"not_applicable"};let n=await fM(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 _t("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 fM(e);if(o===void 0)throw new _t("git_bash_unavailable",`Git for Windows was installed, but ${ma} could not be verified. Repair Git for Windows and retry.`);return{status:"healthy",path:o,installed:!0}}async function Hs(e,t,n){let r=u_(e.environment);if(r===void 0)throw new _t("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await sm(e,r),i=await V1(e,r);if(i===void 0)throw new _t("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);if(t&&o?.version!==i){let l=gM(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new _t("context7_install_failed",`${r.family} could not install ${fa}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new _t("context7_unavailable",`${fa} is not owned by the ${r.family} global installation.`);let a=await sm(e,r);if(a===void 0)throw new _t("context7_verification_failed",`${fa} could not be verified in the ${r.family} global installation.`);if(a.version!==i)throw new _t("context7_outdated",`The ${r.family} global ctx7 is ${a.version}; ${i} is required.`,{installed:a.version,latest:i});let s=D1(n,r,o);return{manager:r.family,launcher:r.launcher,version:a.version,executable:a.executable,ownership:s,identity:a.identity}}function D1(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(!yM(r)||r!==n.identity)return"user";return"holycodex"}async function p_(e,t){if(t?.ownership!=="holycodex")return!1;let n=u_(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await sm(e,n)}catch(a){if(a instanceof _t&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!SM(r.executable,t.executable,e.platform)||!yM(t.identity)||r.identity!==t.identity)return!1;let o=q1(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new _t("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await sm(e,n)!==void 0)throw new _t("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof _t&&a.code==="context7_remove_failed")throw a;throw new _t("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function gM(e){switch(e){case"bun":return{executable:"bun",args:["add","--global",fa]};case"npm":return{executable:"npm",args:["install","--global",fa]};case"pnpm":return{executable:"pnpm",args:["add","--global",fa]}}}function q1(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 fM(e){if(await mM(e.run,ma,e.platform))return ma;for(let t of(e.environment.PATH??"").split(";")){if(t.length===0)continue;let n=hn(e.platform).join(t,"bash.exe");if(await mM(e.run,n,e.platform))return n}return}async function mM(e,t,n){let r=z1(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 sm(e,t){let n=e.files??hM,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"?hn(e.platform).join(o,"node_modules","ctx7"):t.family==="pnpm"?await B1(e,t):hn(e.platform).join(hn(e.platform).dirname(o),"install","global","node_modules","ctx7");if(i===void 0)return;let a;try{a=JSON.parse(await n.readText(hn(e.platform).join(i,"package.json")))}catch{return}if(typeof a.version!=="string")return;let s=typeof a.bin==="string"?a.bin:K1(a.bin)&&typeof a.bin.ctx7==="string"?a.bin.ctx7:void 0;if(s===void 0)return;let c=hn(e.platform).resolve(i,s),l,u;try{if(await n.access(c),l=await n.realpath(i),u=await n.realpath(c),!lo(u).startsWith(`${lo(l)}/`))return}catch{return}let p=H1(o,t.family,e.platform),f;try{await n.access(p),f=await n.realpath(p)}catch{return}let h=await $1(e.environment,e.platform,n);if(h!==void 0&&!SM(await j1(n,h),f,e.platform))throw new _t("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:h,expected:p});if(h===void 0)return;let m=await e.run(p,["--version"]);if(m.exitCode!==0||xM(m.stdout)!==a.version)return;return{version:a.version,executable:p,identity:await U1(t,l,u,f,a)}}async function U1(e,t,n,r,o){return await Qn("context7-installation",[Xn({manager:e.family,package_root:lo(t),package_executable:lo(n),shim:lo(r),package:o})])}function yM(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function $1(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=hn(t).join(i,a);try{return await n.access(s),s}catch{}}}return}function H1(e,t,n){if(n==="win32")return hn(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?hn(n).join(e,"bin","ctx7"):hn(n).join(e,"ctx7")}async function j1(e,t){try{return await e.realpath(t)}catch{return t}}function xM(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}async function B1(e,t){let n=await e.run(t.executable,["root","--global"]),r=n.stdout.trim();return n.exitCode===0&&r.length>0?hn(e.platform).join(r,"ctx7"):void 0}async function V1(e,t){let n=await e.run(t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return xM(n.stdout)}function z1(e,t){let n=hn(t),r=n.dirname(e),o=lo(r).endsWith("/usr/bin")?n.resolve(r,"..",".."):n.resolve(r,"..");return n.resolve(o,"cmd","git.exe")}function uu(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function SM(e,t,n){let r=hn(n);return lo(r.resolve(e))===lo(r.resolve(t))}function hn(e){return e==="win32"?N1:M1}function lo(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function K1(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var ma="C:\\Program Files\\Git\\bin\\bash.exe",fa="ctx7@latest",L1,hM,_t;var cm=x(()=>{st();L1=F1(k1),hM={access:A1,readText:(e)=>I1(e,"utf8"),realpath:P1};_t=class _t extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as f_,rmdir as bM}from"fs/promises";async function m_(e={},t=process.env){let n=ii(e,t),r={};try{await ca(n.codexHome),await ca(n.stateRoot),r.paths=xa({state_root:n.stateRoot})}catch(u){r.paths=ct(["path_symlink"],{error:gn(u)})}let[o,i,a]=await Promise.all([Sa(n).catch((u)=>{r.configuration=ct(["state_corrupt"],{error:gn(u)});return}),mn(n.preparingRecord,Kt).catch((u)=>{r.transaction=ct(["state_corrupt"],{path:n.preparingRecord,error:gn(u)});return}),mn(n.conflictedRecord,Kt).catch((u)=>{r.transaction=ct(["state_corrupt"],{path:n.conflictedRecord,error:gn(u)});return})]);if(i!==void 0&&r.transaction?.status!=="failed")r.transaction=ct(["incomplete_install_state"]);if(a!==void 0&&r.transaction?.status!=="failed")r.transaction=ct(["conflicted_state"]);if(!r.configuration)if(!o)r.configuration=ct(["configuration_missing"]);else if(await Bs(o))r.configuration=xa({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=ct(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await G1(n,o),r.native_roles=await Y1(n,o.profile,o.tier,o.tooling?.git_bash.status==="healthy"?o.tooling.git_bash.path:void 0);let u=Object.entries(o.capability_state??{}).find(([,p])=>p.selected&&p.status!=="healthy");if(u)r.capabilities=ct(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status})}let s=e.runtime??ha(t);try{let u=await ga(s,!1);r.git_bash=u.status==="missing"?ct(["git_bash_missing"]):xa(u.status==="healthy"?{path:u.path}:{})}catch(u){r.git_bash=ct(["git_bash_unavailable"],{error:gn(u)})}try{let u=await Hs(s,!1,o?.tooling?.context7);r.context7=xa({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7=ct(["context7_unavailable"],{error:gn(u)})}try{let u=await qt(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&$s(u)){let p=r.native_roles;r.native_roles={status:"failed",reasons:[...p?.reasons??[],"stale_legacy_root"],details:{...p?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(u){r.native_roles=ct(["native_role_invalid"],{error:gn(u)})}let c=e.officialPluginManager??await si.discover({...t,CODEX_HOME:n.codexHome}).catch(()=>{return});if(o&&c?.status){let u=[...new Set([In,...Cl({computer_use:o.optional_selections.computer_use,frontend:o.optional_selections.frontend,security:o.optional_selections.security},o.official_plugins),...o.owned_plugins??[]])];try{let p=await c.status(u),f=Object.entries(p).filter(([,m])=>m!=="installed").map(([m])=>m),h=c.getObservedIdentities?.()??{};r.native_plugins=f.length===0?xa({status:p,observed_identities:h}):ct(["native_plugin_disagreement"],{missing:f,status:p,observed_identities:h})}catch(p){r.native_plugins=ct(["native_plugin_status_failed"],{error:gn(p)})}}else r.native_plugins={status:"unsupported",reasons:["native_plugin_manager_unavailable"],details:{}};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 h_(e={},t=process.env){let n=ii(e,t);await ca(n.codexHome),await ca(n.stateRoot);let r=await Sa(n);if(r!==void 0&&!await Bs(r))throw new M("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([mn(n.preparingRecord,Kt),mn(n.conflictedRecord,Kt)]),a=wM(r,o,i);if(a===void 0)return[];let s=nr(await qt(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await ei(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 pu(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 du(s,a.provider_config,new Set(g_(a)));for(let u of l.preserved)c.push({path:n.configFile,key:`plugins."${u}"`,action:"remove"})}return c.push(...await rM(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[ya(l),l])).values()]}async function fu(e={},t=process.env){let n=ii(e,t);await ca(n.codexHome),await ca(n.stateRoot);let r=await Sa(n);if(r&&!await Bs(r))throw new M("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([mn(n.preparingRecord,Kt),mn(n.conflictedRecord,Kt)]),a=wM(r,o,i);d_(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(g_(a)),c=[],l=[],u=[];if(a===void 0)return d_(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let p=await h_(e,t),f=await J1(e,p),h=await qt(n.configFile),m=nr(h),S=a?.managed_config;if(S){let g=await ei(m,S,{schema:S.schema,installId:S.installId});if(g.preservedKeys.length>0||g.unresolvedKeys.length>0){let R=[...g.preservedKeys,...g.unresolvedKeys].map((C)=>({path:n.configFile,key:C,action:"remove"}));for(let C of R)if(f.has(ya(C)))m=ao(m,C.key)}}if(a?.plugin_config){let g=await pu(m,a.plugin_config);if(g.preserved.length>0){let O=g.preserved.map((R)=>({path:n.configFile,key:R==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let R of g.preserved){let C=O.find((G)=>G.key===(R==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(C===void 0||!f.has(ya(C)))continue;m=ao(m,R==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let g=await du(m,a.provider_config,s);if(g.preserved.length>0){let O=g.preserved.map((R)=>({path:n.configFile,key:`plugins."${R}"`,action:"remove"}));for(let R of g.preserved){let C=O.find((G)=>G.key===`plugins."${R}"`);if(C===void 0||!f.has(ya(C)))continue;m=ao(m,`plugins."${R}"`)}}}let E;try{E=e.officialPluginManager??await si.discover({...t,CODEX_HOME:n.codexHome})}catch(g){throw new M("capability_denied","Native Codex plugin removal is unavailable.",g,{recovery:"Install or expose Codex, then retry."})}if(E===void 0||!E.remove||!E.list)throw new M("capability_denied","Native Codex plugin removal and readback are unavailable.");let w=await om(n.codexHome,a?.managed_artifacts??[],new Set(p.filter((g)=>g.key===void 0&&f.has(ya(g))).map((g)=>g.path)));if(c.push(...w.removed),l.push(...w.preserved),w.preserved.length>0)u.push("managed_artifact_changed");for(let g of s)try{let O=await E.list(),R=Z1(O,g);if(R?.entry.installed!==!0)continue;let C=R.entry.pluginId;await E.remove(C);let G=await E.list();if(Er(G,g)?.entry?.installed===!0||[...G.installed,...G.available].some((ce)=>ce.pluginId===g&&ce.installed))throw new M("capability_denied",`Codex still reports ${g} after removal.`);c.push(g)}catch(O){throw u.push("native_plugin_remove_failed"),await ci(n,a??lm()),new M("capability_denied",`Codex native plugin removal did not converge for ${g}: ${gn(O)}`,O)}try{if(await p_(e.runtime??ha(t),a.tooling?.context7))c.push("ctx7")}catch(g){throw u.push("context7_remove_failed"),await ci(n,a),new M("capability_denied",`Context7 removal did not converge: ${gn(g)}`,g)}let b;try{let g=m,O=S;if(O){let R=await ei(g,O,{schema:O.schema,installId:O.installId}),C=[...R.preservedKeys,...R.unresolvedKeys];if(C.filter((q)=>!f.has(ya({path:n.configFile,key:q,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await ci(n,a??lm()),{removed:c,preserved:l,reasons:u};if(g=R.document,C.length>0){let q=new Set(C);O={...R.state,managed:Object.fromEntries(Object.entries(R.state.managed).filter(([Y])=>!q.has(Y)))}}else O=R.state}if(a?.plugin_config){let R=await pu(g,a.plugin_config,{allowBeforeState:!0});if(R.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await ci(n,a),{removed:c,preserved:l,reasons:u};g=R.document}if(a?.provider_config){let R=await du(g,a.provider_config,s,{allowBeforeState:!0});if(R.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await ci(n,a),{removed:c,preserved:l,reasons:u};g=R.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)b=O===void 0?{document:g}:{document:g,state:O};if(b!==void 0)if(Object.keys(b.document).length===0&&h===void 0)await f_(n.configFile,{force:!1});else await co(n.configFile,x_(b.document))}catch(g){if(g instanceof M)throw await ci(n,a??lm()),g;return l.push(n.configFile),u.push("managed_config_write_failed"),await ci(n,a??lm()),{removed:c,preserved:l,reasons:u}}if(r)try{await f_(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(g){if(!bt(g,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await ci(n,a??r),{removed:c,preserved:l,reasons:u}}if(l.length===0)for(let[g,O]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0]]){if(!O)continue;try{await X1(g),c.push(g)}catch{l.push(g),u.push("state_remove_failed")}}if(l.length===0)try{await bM(n.roleRoot),c.push(n.roleRoot)}catch(g){if(!bt(g,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await bM(n.stateRoot),c.push(n.stateRoot)}catch(g){if(bt(g,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return d_(e,{stage:"removal",status:"completed",message:"HolyCodex removal complete"}),{removed:c,preserved:l,reasons:u}}async function um(e={},t=process.env,n={}){let r=ii(e,t),[o,i,a]=await Promise.all([Sa(r),mn(r.preparingRecord,Kt),mn(r.conflictedRecord,Kt)]);if(o!==void 0&&!await Bs(o))throw new M("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});let s=_M(o,i,a),c=s??o;if(c===void 0)throw new M("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l;try{l=await qs()}catch(S){throw new M("upgrade_failed","The running HolyCodex version is unavailable.",S)}let u=W1(l,c.version);if(u<0)throw new M("upgrade_downgrade",`The running HolyCodex version ${l} is older than the installed version ${c.version}.`,void 0,{installed_version:c.version,running_version:l});let p=c.managed_config?.managed["features.context_management.experimental_mode"]!==void 0,f=[];if(n.dryRun===!0){let S=nr(await qt(r.configFile));if(c.managed_config!==void 0){for(let w of Object.keys(c.managed_config.managed))if((await ia(S,c.managed_config,w)).status!=="unchanged")f.push({path:r.configFile,key:w,action:"replace"})}if(c.plugin_config!==void 0){let w=await pu(S,c.plugin_config);for(let b of w.preserved){let g=b==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";f.push({path:r.configFile,key:g,action:"replace"})}}if(c.provider_config!==void 0){let w=await du(S,c.provider_config,new Set(g_(c)));for(let b of w.preserved)f.push({path:r.configFile,key:`plugins."${b}"`,action:"replace"})}let E=await nm(r.codexHome,c.profile,c.managed_artifacts,c.tier,c.tooling?.git_bash.status==="healthy"?c.tooling.git_bash.path:void 0);for(let w of E)f.push(w)}let h=c.tooling===void 0;try{let S=e.runtime??ha(t),E=await ga(S,!1),w=await Hs(S,!1,c.tooling?.context7);h||=E.status==="missing"||w.manager!==c.tooling?.context7.manager||w.version!==c.tooling?.context7.version||w.executable!==c.tooling?.context7.executable}catch{h=!0}let m=[...u>0?["version"]:[],...p?["context-management configuration migration"]:[],...u>0||p?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...h?["shared tooling reconciliation"]:[],...f.map((S)=>`conflict: ${S.path}${S.key===void 0?"":` (${S.key})`} -> ${S.action}`)];if(m.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:l,changes:[],record:o,preserved:[],warnings:[],conflicts:f};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:l,changes:m,record:o,preserved:[],warnings:[],conflicts:f};try{let S=await js({profile:c.profile,tier:c.tier,optional:c.explicit_optional_selections,officialPlugins:c.official_plugins},e,t);return{status:"upgraded",from_version:c.version,to_version:l,changes:m,record:S.record,preserved:S.preserved,warnings:S.warnings}}catch(S){if(S instanceof M)throw S;throw new M("upgrade_failed",`HolyCodex upgrade failed: ${gn(S)}`,S)}}function W1(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let o=0;o<3;o+=1){if((n[o]??0)<(r[o]??0))return-1;if((n[o]??0)>(r[o]??0))return 1}return 0}async function J1(e,t){let n=new Set;for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(ya(r));continue}if(o==="decline")continue;throw new M("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 ya(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function G1(e,t){if(!t.managed_config)return ct(["incomplete_install_state"]);try{let n=nr(await qt(e.configFile)),r=dm(t.profile,t.tier,{computerUse:t.optional_selections.computer_use,frontend:t.optional_selections.frontend,security:t.optional_selections.security,...t.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:t.tooling.git_bash.path}:{}}),o=[];for(let[i,a]of Object.entries(r))if((await ia(n,t.managed_config,i)).status!=="unchanged"||ge(n,i)!==a)o.push(i);return o.length===0?xa({managed_keys:Object.keys(r).length}):ct(["changed_holycodex_config"],{keys:o})}catch(n){return ct(["config_unreadable"],{error:gn(n)})}}async function Y1(e,t,n,r){try{let o=nr(await qt(e.configFile)),i=[];for(let s of ai(t,n)){let c=ge(o,`agents."${s.name}".config_file`),l=`${e.roleRoot}/${s.name}.toml`.replaceAll("\\","/");if(typeof c!=="string"||Bl(e.configFile,c).replaceAll("\\","/")!==l){i.push(`${s.name}:registration`);continue}let u=await qt(`${e.roleRoot}/${s.name}.toml`);if(u===void 0){i.push(`${s.name}:missing`);continue}if(u!==au(s,r===void 0?{}:{windowsGitBashExecutable:r})){i.push(`${s.name}:changed`);continue}let p=nr(u);if(p.name!==s.name||typeof p.description!=="string"||typeof p.developer_instructions!=="string"||p.model!=="gpt-5.6-luna"||p.model_reasoning_summary!=="none"||p.model_verbosity!=="low"||p.tool_output_token_limit!==void 0||p.service_tier!==(n==="standard"?"default":"fast")||p.sandbox_mode!==su(s)||p.approval_policy!=="never"||p.web_search!==(s.permissions.network?"live":"disabled")||ge(p,"agents.enabled")!==!1||ge(p,"features.multi_agent_v2")!==!1||ge(p,"features.multi_agent")!==!1||ge(p,"features.context_management")!==!0||ge(p,"features.computer_use")!==!1||ge(p,"features.browser_use")!==!1||ge(p,"features.in_app_browser")!==!1)i.push(`${s.name}:malformed`)}let a=await qt(`${e.codexHome}/agents/root.toml`);if(a!==void 0&&$s(a))i.push("root:stale");return i.length===0?xa({role_root:e.roleRoot,agent_types:ai(t,n).map((s)=>s.name)}):ct(["native_role_disagreement"],{roles:i})}catch(o){return ct(["native_role_invalid"],{error:gn(o)})}}async function ci(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(St(Kt,n)!==void 0)await pa(e.conflictedRecord,fn(n))}function _M(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||y_(r,e)))}function wM(e,t,n){return _M(e,t,n)??e}function lm(){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:{computer_use:!1,frontend:!1,security:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function g_(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"?[In]:[],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 Z1(e,t){let n=Er(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 xa(e){return{status:"healthy",reasons:[],details:e}}function ct(e,t={}){return{status:"failed",reasons:e,details:t}}async function X1(e){await f_(e,{force:!1}).catch((t)=>{if(!bt(t,"ENOENT"))throw t})}function gn(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function d_(e,t){try{e.onProgress?.(t)}catch{}}var pm=x(()=>{Xl();st();mu();Ql();iu();im();lu();la();Ls();Ds();cm()});import{rm as AM}from"fs/promises";import{join as Q1}from"path";function kr(e){let t=St(Zf,e);if(t===void 0)throw new M("install_failed","The installation options are invalid.");return t}function y_(e,t){return e.install_id===t.install_id&&e.digest===t.digest}async function js(e={},t={},n=process.env){if(St(tu,e)===void 0)throw new M("install_failed","The installation options are invalid.");let r=ii(t,n);rr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let o=await Sa(r);if(o!==void 0&&!await Bs(o))throw new M("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:r.activeRecord});let i=await mn(r.preparingRecord,Kt),s=[await mn(r.conflictedRecord,Kt),i].find((U)=>U!==void 0&&(o===void 0||y_(U,o)));if(s!==void 0){await Promise.resolve().then(() => pm());let ue=await fu(t,n);if(ue.preserved.length>0||ue.reasons.length>0)throw new M("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:ue.preserved.join(","),reasons:ue.reasons.join(",")});return await js({profile:e.profile??s.profile,tier:e.tier??s.tier,optional:{computer_use:e.optional?.computer_use??s.optional_selections.computer_use,frontend:e.optional?.frontend??s.optional_selections.frontend,security:e.optional?.security??s.optional_selections.security},officialPlugins:e.officialPlugins??CM(s)},t,n)}let c=mB(e.profile,o?.profile),l=hB(e.tier,o?.tier),u=gB(e.optional,o?.optional_selections),p=pB(o?.explicit_optional_selections,e.optional),f=e.officialPlugins??CM(o),h=t.runtime??ha(n),m=await ga(h,!1),S=m,E,w=[...new Set(Cl(MM(u),f).map((U)=>Yn(U)??U))],b;try{b=t.officialPluginManager??await si.discover({...n,CODEX_HOME:r.codexHome})}catch(U){throw new M("capability_denied","Native Codex plugin installation is unavailable.",U,{recovery:"Install or expose Codex, then retry."})}if(!b.addMarketplace||!b.add||!b.list)throw new M("install_failed","Native Codex plugin installation and verification are unavailable.");let g;try{g=await b.list()}catch(U){throw new M("capability_denied","Native Codex plugin state could not be read safely.",U)}let O=w.filter((U)=>{if(Yn(U)!==U)return!1;let ue=yu(g,U);return!(ue?.installed&&ue.enabled)});rr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let R=o?.install_id??crypto.randomUUID().replaceAll("-",""),C=await qs(),G=o!==void 0&&o.version!==C&&o.owned_plugins?.includes(In)===!0?new Set([In]):new Set,q=(t.now?.()??new Date).toISOString(),Y=await qt(r.configFile),ce=nr(Y),oe=await TM(ce),Te=o?.plugin_config?.before??oe;if(o?.plugin_config!==void 0){let U=["preference","marketplace"].filter((ue)=>{let _e=oe[ue].digest;return _e!==o.plugin_config?.after[ue].digest&&_e!==o.plugin_config?.before[ue].digest});await fm(t,U.map((ue)=>({path:r.configFile,key:ue==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"replace"})))}let Ut=[...new Set([...w,...(o?.provider_config??[]).map((U)=>U.plugin_id),...o?.owned_plugins??[]])].filter((U)=>U!==In),$t=await EM(ce,Ut);if(o?.provider_config!==void 0){let U=new Set(o.owned_plugins??[]),ue=$t.filter((_e)=>{if(!U.has(_e.plugin_id))return!1;let Ir=o.provider_config?.find((fo)=>fo.plugin_id===_e.plugin_id);return Ir!==void 0&&_e.before.digest!==Ir.after.digest&&_e.before.digest!==Ir.before.digest});await fm(t,ue.map((_e)=>({path:r.configFile,key:`plugins."${_e.plugin_id}"`,action:"replace"})))}let Wt=$t.map((U)=>{let ue=o?.provider_config?.find((_e)=>_e.plugin_id===U.plugin_id);return ue===void 0?U:{plugin_id:U.plugin_id,before:ue.before,after:ue.before}}),et=o?.managed_config??Mf({schema:yn,installId:R}),tt=await OM(ce,et,o),Ht=await RM(tt.document,tt.state),{document:Pn,state:uo}=Ht;aB(Pn,uo);let Mn=dm(c,l,{computerUse:u.computer_use,frontend:u.frontend,security:u.security,...h.platform==="win32"?{windowsGitBashExecutable:m.status==="healthy"?m.path:ma}:{}}),po;try{po=await As(Pn,uo,Mn,{schema:yn,installId:R})}catch(U){if(U instanceof M)throw U;throw new M("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",U,{recovery:"Converge the conflicting Codex setting, then retry."})}if(po.driftedKeys.length>0){await fm(t,po.driftedKeys.map((_e)=>({path:r.configFile,key:_e,action:"replace"})));let U=Pn,ue={...uo.managed};for(let _e of po.driftedKeys){let Ir=ue[_e],fo=Mn[_e];if(Ir===void 0||fo===void 0)throw new M("state_corrupt","The managed conflict cannot be verified.",void 0,{path:r.configFile,key:_e});let mo=ge(U,_e);if(mo===void 0)U=ks(U,_e,fo),mo=fo;ue[_e]={...Ir,lastManagedValue:await tr(_e,mo)}}if(po=await As(U,{...uo,managed:ue},Mn,{schema:yn,installId:R}),po.driftedKeys.length>0)throw new M("state_corrupt","The accepted managed conflicts did not converge.")}let xm;try{xm=await nm(r.codexHome,c,o?.managed_artifacts,l,h.platform==="win32"?m.status==="healthy"?m.path:ma:void 0)}catch(U){throw new M("install_failed",__(U),U)}let eN=await fm(t,xm,!0),k_={owner:"holycodex",schema_epoch:yn,install_id:R,version:C,digest:o?.digest??"0".repeat(64),profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:w,capability_state:w_(u),managed_artifacts:o?.managed_artifacts??[],installed_at:q,status:"preparing",step:"validated",managed_config:po.state,plugin_snapshot:[],plugin_config:{plugin_id:In,before:Te,after:Te},provider_config:Wt,owned_plugins:[...new Set(o?.owned_plugins??[])],...o?.tooling===void 0?{}:{tooling:o.tooling}};await nu(r.stateRoot),await Vs(r.preparingRecord,k_);try{S=await ga(h,!0),E=await Hs(h,!0,o?.tooling?.context7)}catch(U){if(U instanceof _t)throw new M("capability_denied",U.message,U,U.details);throw U}let Sm={git_bash:S,context7:E};if(b.ensureOfficialMarketplace!==void 0&&O.length>0)try{await b.ensureOfficialMarketplace(O)}catch(U){throw new M("capability_denied",`The selected official Codex provider marketplace is unavailable: ${__(U)}`,U,{recovery:"Check Codex network and marketplace policy, then retry."})}let bu;try{bu=await sB({list:()=>b.list()},[...new Set([In,...w,...o?.owned_plugins??[]])])}catch(U){throw new M("capability_denied","Native Codex plugin state could not be read safely.",U)}let bm={...k_,plugin_snapshot:bu,tooling:Sm};await Vs(r.preparingRecord,bm);let Ar,A_=!1,I_=new Set,Ta=new Set(o?.owned_plugins??[]),_m=new Set,jt=bm,P_=!1,M_=!1,wm=Y,Ws=po.state;try{rr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await nu(r.roleRoot),Ar=await i_(r.codexHome,c,o?.managed_artifacts,l,S.status==="healthy"?S.path:void 0,xm.length===0?t.resolveConflict:void 0,eN),jt={...bm,step:"roles_prepared",managed_artifacts:Ar.managed_artifacts},await Vs(r.preparingRecord,jt),rr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),rr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),P_=!0,await b.addMarketplace(eB),await fB({list:()=>b.list(),add:(Nn)=>b.add(Nn)},[In,...w],G,(Nn,Om)=>{if(Om==="new")I_.add(Nn),Ta.add(Nn),jt={...jt,owned_plugins:[...Ta]};else _m.add(Nn),Ta.add(Nn),jt={...jt,owned_plugins:[...Ta]}}),jt={...jt,step:"plugins_installed"},await Vs(r.preparingRecord,jt),rr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let ue=await qt(r.configFile);wm=ue;let _e=nr(ue),Ir=await OM(_e,et,o),fo=await RM(Ir.document,Ir.state),{document:mo,state:N_}=fo,vm=await TM(mo),Tm=(await EM(mo,Ut)).map((Nn)=>({plugin_id:Nn.plugin_id,before:Wt.find((Om)=>Om.plugin_id===Nn.plugin_id)?.before??Nn.before,after:Nn.before}));await iB(mo,Pn,N_,Mn);let _u=await As(mo,N_,Mn,{schema:yn,installId:R});if(_u.driftedKeys.length>0)throw new M("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:_u.driftedKeys.join(",")});M_=!0,rr(t,{stage:"config",status:"started",message:"Configuring Root"}),Ws=_u.state,jt={...jt,managed_config:Ws,plugin_config:{plugin_id:In,before:Te,after:vm},provider_config:Tm},await co(r.configFile,x_(_u.document)),A_=!0,jt={...jt,step:"config_published"},await Vs(r.preparingRecord,jt),rr(t,{stage:"config",status:"completed",message:"Root configuration published"}),rr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await lB(r,c,l,{computerUse:u.computer_use,frontend:u.frontend,security:u.security,...S.status==="healthy"?{windowsGitBashExecutable:S.path}:{}},Ws,Ar.preserved),rr(t,{stage:"verification",status:"completed",message:"Installation verified"});let F_=w_(u),tN=await mm({owner:"holycodex",install_id:R,version:C,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:w,capability_state:F_,managed_artifacts:Ar.managed_artifacts,managed_config:Ws,plugin_config:{plugin_id:In,before:Te,after:vm},provider_config:Tm,plugin_snapshot:bu,owned_plugins:[...Ta],tooling:Sm}),Em={owner:"holycodex",schema_epoch:yn,install_id:R,version:C,digest:tN,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:w,capability_state:F_,managed_artifacts:Ar.managed_artifacts,installed_at:q,status:"active",step:"active",managed_config:Ws,plugin_snapshot:bu,plugin_config:{plugin_id:In,before:Te,after:vm},provider_config:Tm,owned_plugins:[...Ta],tooling:Sm};if(St(Fs,Em)===void 0)throw new M("state_corrupt","The HolyCodex configuration is invalid.");return await pa(r.activeRecord,fn(Em)),await S_(r.preparingRecord),await S_(r.conflictedRecord),rr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Em,optional_plugins:w,preserved:Ar.preserved,warnings:Ar.preserved.length===0?[]:["modified managed files were preserved"]}}catch(U){let ue=[];if(A_)try{await cB(r.configFile,wm)}catch{ue.push("config")}if(P_&&!M_){if(await qt(r.configFile).catch(()=>{return})!==wm)ue.push("config")}if(Ar!==void 0)try{if((await rm(Ar.rollback)).preserved.length>0)ue.push("roles")}catch{ue.push("roles")}if(_m.size>0)ue.push(...[..._m].map((_e)=>`plugin:${_e}`));for(let _e of I_)try{await b.remove?.(_e)}catch{ue.push(`plugin:${_e}`)}if(ue.length>0)await Vs(r.conflictedRecord,{...jt,step:"conflicted",status:"conflicted"}).catch(()=>{return});else await S_(r.preparingRecord).catch(()=>{return});if(U instanceof An)throw U;if(U instanceof M)throw U;throw new M(U instanceof Cr||U instanceof gu?"capability_denied":"install_failed",__(U),U,ue.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function Sa(e){let t=await mn(e.activeRecord,Gf);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:St(Fs,t);if(o!==void 0)return o;let i=St(KP,t);if(i===void 0)throw new M("state_corrupt","The HolyCodex configuration is invalid.");if(!await LM(i))throw new M("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 M("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=wS(a)}catch(Y){throw new M("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,Y,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([Y])=>Y!=="plan")):i,l={computer_use:i.optional_selections.computer_use,frontend:i.optional_selections.frontend,security:i.optional_selections.security,coding:!0},u={...i.explicit_optional_selections.computer_use===void 0?{}:{computer_use:i.explicit_optional_selections.computer_use},...i.explicit_optional_selections.frontend===void 0?{}:{frontend:i.explicit_optional_selections.frontend},...i.explicit_optional_selections.security===void 0?{}:{security:i.explicit_optional_selections.security}},p=i.capability_state===void 0?void 0:w_(l),f=(i.official_plugins??[]).filter((Y)=>!hu(Y)),h=i.owned_plugins?.filter((Y)=>!hu(Y)),m=i.provider_config?.filter((Y)=>!hu(Y.plugin_id)),S=i.plugin_snapshot?.filter((Y)=>!hu(Y.plugin_id)),{optional_selections:E,explicit_optional_selections:w,capability_state:b,official_plugins:g,owned_plugins:O,provider_config:R,plugin_snapshot:C,...G}=c;return{...G,profile:s,optional_selections:l,explicit_optional_selections:u,official_plugins:f,...p===void 0?{}:{capability_state:p},...h===void 0?{}:{owned_plugins:h},...m===void 0?{}:{provider_config:m},...S===void 0?{}:{plugin_snapshot:S},digest:await mm({owner:i.owner,install_id:i.install_id,version:i.version,profile:s,tier:i.tier,optional_selections:l,explicit_optional_selections:u,official_plugins:f,capability_state:p??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},...m===void 0?{}:{provider_config:m},...S===void 0?{}:{plugin_snapshot:S},...h===void 0?{}:{owned_plugins:h},...i.tooling===void 0?{}:{tooling:i.tooling}})}}function MM(e){return{computer_use:e.computer_use,frontend:e.frontend,security:e.security}}function nr(e){if(e===void 0||e.trim().length===0)return{};try{let t=globalThis.Bun,n=t?.TOML?.parse?t.TOML.parse(e):sM(e),r=St(Hl,n);if(r===void 0)throw Error("TOML document contains unsupported values.");return r}catch(t){throw new M("state_corrupt","The Codex config.toml is not valid TOML.",t)}}function x_(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):cM(e)).trimEnd()}
42
- `}catch(t){throw new M("install_failed","The merged Codex configuration is not writable.",t)}}async function TM(e){return{preference:await xu(e,"plugins",IM),marketplace:await xu(e,"marketplaces",PM)}}async function EM(e,t){return await Promise.all(t.map(async(n)=>{let r=await xu(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 pu(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",IM],["marketplace","marketplaces",PM]]){let u=t.before[s],p=t.after[s],f=await xu(e,c,l);if(n.allowBeforeState===!0&&f.digest===u.digest)continue;if(f.digest!==p.digest){a.push(s);continue}if(u.presence==="absent"){if(f.presence==="present")r=FM(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=NM(r,c,l,oB(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function du(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,p=await xu(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&p.digest===l.digest)continue;if(p.digest!==u.digest){s.push(c.plugin_id);continue}if(l.presence==="absent"){if(p.presence==="present")o=FM(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=NM(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 xu(e,t,n){let r=nB(e,t,n),o=await Qn("holycodex-plugin-config",[Xn(fn({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=rB(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function nB(e,t,n){let r=e[t];if(!zs(r))return;return r[n]}function rB(e,t){if(!zs(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!==vM)return;return{kind:"marketplace",source_type:"git",source:vM}}function oB(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function NM(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!zs(i))throw new M("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function FM(e,t,n){let r=e[t];if(!zs(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 zs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function dm(e,t,n=!1){let r=r_(e,t),o={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,model_verbosity:"low",developer_instructions:o_(n),suppress_unstable_features_warning:!0,"features.default_mode_request_user_input":!0,"features.multi_agent":!0,"features.multi_agent_v2":!1,"features.context_management":!0};for(let i of br)o[`agents."${i}".config_file`]=`holycodex/agents/${i}.toml`;return o}async function iB(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await ia(e,n,a)).status==="drifted")o.push(a);continue}let c=ge(t,a),l=ge(e,a);if(c!==l)o.push(a)}if(o.length>0)throw new M("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function OM(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 ei(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new M("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((h)=>h.startsWith(`agents/${c[0]?.toUpperCase()}${c.slice(1)}.`)||h===`holycodex/agents/${c}.toml`))continue;let u=`agents.${c}.config_file`,p=ge(i,u);if(typeof p!=="string")continue;let f=p.replaceAll("\\","/").replace(/^\.\//u,"");if(f===`agents/${c}.toml`||f===`holycodex/agents/${c}.toml`)i=ao(i,u)}return{document:i,state:a}}async function RM(e,t){let o=t.managed["features.context_management.experimental_mode"];if(o===void 0)return{document:e,state:t};let i=ge(e,"features.context_management.experimental_mode"),a=ge(e,"features.context_management"),s=zs(a)?void 0:a;if(zs(a)&&Object.keys(a).some((p)=>p!=="experimental_mode"))throw new M("state_corrupt","The legacy context-management table contains unrelated settings and cannot be migrated without changing user configuration.",void 0,{key:"features.context_management",recovery:"Move unrelated settings, then retry the upgrade."});if(i!==void 0){let p=await tr("features.context_management.experimental_mode",i);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new M("state_corrupt","The legacy context-management setting changed and cannot be migrated safely.",void 0,{key:"features.context_management.experimental_mode"});if(s!==void 0&&JSON.stringify(s)!==JSON.stringify(i))throw new M("state_corrupt","Both legacy and canonical context-management settings are present with different values.",void 0,{keys:"features.context_management.experimental_mode,features.context_management"})}if(i===void 0&&s!==void 0){let p=await tr("features.context_management",s);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new M("state_corrupt","The canonical context-management setting changed and cannot be migrated safely.",void 0,{key:"features.context_management"})}if(i===void 0&&s===void 0)throw new M("state_corrupt","The owned legacy context-management setting is missing and cannot be migrated safely.",void 0,{key:"features.context_management.experimental_mode"});let c=e;if(i!==void 0){if(c=ao(c,"features.context_management.experimental_mode"),s===void 0)c=ks(c,"features.context_management",i)}let l=ge(c,"features.context_management");if(l===void 0)throw new M("state_corrupt","The canonical context-management setting is missing.");let u={...t.managed};return u["features.context_management"]={...o,keyPath:"features.context_management",lastManagedValue:await tr("features.context_management",l)},delete u["features.context_management.experimental_mode"],{document:c,state:{...t,managed:u}}}function aB(e,t){if(ge(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new M("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function sB(e,t){let n=await e.list();return t.map((r)=>{let o=yu(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function Vs(e,t){if(St(Kt,t)===void 0)throw new M("state_corrupt","The HolyCodex transaction state is invalid.");await pa(e,fn(t))}async function S_(e){await AM(e,{force:!1}).catch((t)=>{if(!bt(t,"ENOENT"))throw t})}async function cB(e,t){if(t===void 0){await AM(e,{force:!1}).catch((n)=>{if(!bt(n,"ENOENT"))throw n});return}await co(e,t)}async function lB(e,t,n,r,o,i=[]){let a=await qt(e.configFile),s=nr(a),c=dm(t,n,r);for(let[p,f]of Object.entries(c)){let h=ge(s,p);if(p==="developer_instructions"){if(typeof h!=="string"||h!==f||await uB(p,h)!==o.managed[p]?.lastManagedValue.value)throw new M("install_failed","The effective Root instructions did not converge.")}else if(h!==f)throw new M("install_failed",`The effective Codex setting ${p} did not converge.`)}let l=ai(t,n);for(let p of l){let f=`agents."${p.name}".config_file`,h=ge(s,f);if(typeof h!=="string")throw new M("install_failed",`The ${p.name} registration is missing.`);let m=Q1(e.roleRoot,`${p.name}.toml`),S=m.replaceAll("\\","/");if(Bl(e.configFile,h).replaceAll("\\","/")!==S)throw new M("install_failed",`The ${p.name} registration is stale.`);let w=await qt(m);if(w===void 0)throw new M("install_failed",`The ${p.name} role file is missing.`);if(i.includes(m))continue;let b=nr(w);if(b.name!==p.name||typeof b.description!=="string"||typeof b.model!=="string"||typeof b.model_reasoning_effort!=="string"||typeof b.service_tier!=="string"||typeof b.developer_instructions!=="string"||b.sandbox_mode!==su(p)||b.approval_policy!=="never"||b.web_search!==(p.permissions.network?"live":"disabled")||b.tool_output_token_limit!==void 0||ge(b,"agents.enabled")!==!1||ge(b,"features.multi_agent_v2")!==!1||ge(b,"features.multi_agent")!==!1||ge(b,"features.context_management")!==!0||ge(b,"features.computer_use")!==!1||ge(b,"features.browser_use")!==!1||ge(b,"features.in_app_browser")!==!1)throw new M("install_failed",`The ${p.name} role file is malformed.`)}let u=await qt(`${e.codexHome}/agents/root.toml`);if(u!==void 0&&$s(u))throw new M("install_failed","A stale HolyCodex Root role remains installed.")}async function uB(e,t){return await Qn("holycodex-managed-config-value",[Xn({keyPath:e,value:t})])}function pB(e,t){let n={};for(let r of["computer_use","frontend","security"]){let o=t?.[r]??e?.[r];if(o!==void 0)n[r]=o}return n}function dB(e){return["computer_use","frontend","security"].find((t)=>Qi[t].pluginIds.includes(e))}function CM(e){return(e?.official_plugins??[]).filter((t)=>{if(hu(t))return!1;let n=dB(t);return n===void 0||e?.optional_selections[n]!==!0})}function hu(e){let t=e.slice(0,e.lastIndexOf("@"));return tB.has(t)}async function fB(e,t,n=new Set,r){for(let o of t){let i=n.has(o),a;try{a=yu(await e.list(),o)}catch(l){throw b_("list",l,o)}if(a?.installed&&!a.enabled)throw new gu("uncertain",`${o} is disabled`);let s=i||!(a?.installed&&a.enabled);if(s)try{await e.add(o)}catch(l){try{let u=yu(await e.list(),o);if(i||!kM(a,u))r?.(o,"uncertain")}catch{r?.(o,"uncertain")}throw b_("add",l,o)}let c;try{c=yu(await e.list(),o)}catch(l){if(s)r?.(o,"uncertain");throw b_("list",l,o)}if(!c?.installed){if(s&&(i||!kM(a,c)))r?.(o,"uncertain");throw new gu("missing",`${o} is not installed after add`)}if(s&&c.enabled)r?.(o,i?"uncertain":"new");if(!c.enabled){if(s)r?.(o,i?"uncertain":"new");throw new gu("uncertain",`${o} is disabled after add`)}}}function kM(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function b_(e,t,n){if(t instanceof Cr)return t;return new Cr(e==="list"?"list_failed":"add_failed",e==="list"?`Codex could not read the status of ${n}.`:`Codex could not add ${n}.`,t,{plugin_id:n})}function yu(e,t){let n=Er(e,t);if(n!==void 0)return n.entry;let r=Yn(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function mB(e,t){let n=e??t??"default";if(!wr(n).ok)throw new M("install_failed","Unknown profile.");return n}function hB(e,t){let n=e??t??"standard";if(St(ea,n)===void 0)throw new M("install_failed","The tier is not supported.");return n}function gB(e,t){let n=t?MM(t):oo,r=xS(e,n);return{computer_use:r.computer_use,frontend:r.frontend,security:r.security,coding:!0}}function w_(e,t=new Map){return Object.fromEntries(["computer_use","frontend","security"].map((r)=>{let o=e[r],i={selected:o,status:o?t.get(r)??"healthy":"disabled",plugin_ids:[...Qi[r].pluginIds]};return[r,i]}))}async function mm(e){let{profile:t,plan:n,...r}=e,o=n===void 0?{...r,profile:t}:{...r,plan:n};return await Qn("install-record",[Xn(fn(o))])}async function Bs(e){return await LM(e)}async function LM(e){return await mm({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 __(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}async function fm(e,t,n=!1){let r=[];for(let o of t){let i=await e.resolveConflict?.(o);if(i==="accept"){r.push(o);continue}if(i==="decline"&&n)continue;throw new M("confirmation_required",i==="cancel"?"Conflict resolution was cancelled.":"HolyCodex-owned changes require confirmation before replacement.",void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},action:o.action,resolution:i??"unavailable"})}return r}function rr(e,t){try{e.onProgress?.(t)}catch{}}var eB="davidbasilefilho/holycodex",In="holycodex@holycodex",vM="https://github.com/davidbasilefilho/holycodex.git",IM="holycodex@holycodex",PM="holycodex",tB,gu,M;var mu=x(()=>{Xl();st();Ql();iu();im();lu();la();Ls();Ds();cm();Ls();tB=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]);gu=class gu extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};M=class M 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 JB}from"readline/promises";st();st();st();var VS=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:"frontend",kind:"boolean",usage:"--frontend / --no-frontend",description:"Frontend plugins via build-web-apps (default: true)."},{name:"security",kind:"boolean",usage:"--security / --no-security",description:"Security plugins (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."}]),aP=new Set(["codex-home","profile","tier","add-plugin"]),bH=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","frontend","no-frontend","security","no-security"]);class Ke extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Rf(e){if(e.length===0)throw new Ke("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 Rf(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="upgrade"&&t!=="version")throw new Ke("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 Ke("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 Ke("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!aP.has(u)&&!bH.has(u))throw new Ke("invalid_argument","Unknown option.",{option:`--${c}`});if(aP.has(u)){let p=l??e[o+1];if(p===void 0||p.length===0||p.startsWith("-"))throw new Ke("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(l===void 0)o+=1;if(u==="add-plugin"){let f=r[u];r[u]=Array.isArray(f)?[...f,p]:[p]}else{if(r[u]!==void 0)throw new Ke("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=p}continue}if(l!==void 0&&l!=="true"&&l!=="false")throw new Ke("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new Ke("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return _H(t,n,r),{command:t,positionals:n,options:r}}function _H(e,t,n){let r=vH(e);for(let s of Object.keys(n))if(!r.has(s))throw new Ke("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 Ke("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!wr(i).ok){let s=wH[i];if(s!==void 0)throw new Ke("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 Ke("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new Ke("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 Ke("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["frontend","no-frontend"],["security","no-security"]])if(n[s]!==void 0&&n[c]!==void 0)throw new Ke("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove","upgrade"].includes(e)&&n.yes===!1)throw new Ke("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","frontend","no-frontend","security","no-security","computer-use","no-computer-use","add-plugin"].includes(s)))throw new Ke("invalid_argument",`Installation options are not valid for ${e}.`)}var wH={"plus-low":"low",plus:"default","plus-high":"high"};function vH(e){switch(e){case"install":return new Set([...VS.map((t)=>t.name),"no-frontend","no-security","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"upgrade":return new Set(["yes","json","verbose","dry-run","codex-home"]);case"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var TH=`HolyCodex
39
+ `)}function a_(e){if(e.trim().length===0)throw Error("Git Bash executable is required.");return`On Windows, execute every shell action through the verified Git-for-Windows Bash executable at ${JSON.stringify(e)}. Resolve C:\\Program Files\\Git\\bin\\bash.exe first and use bash on PATH only if that path is unavailable and the resolved executable has been verified as Git for Windows. PowerShell, pwsh, powershell.exe, cmd.exe, WSL Bash, Cygwin, and unrelated MSYS shells are unauthorized. This shell directive does not change authority; specialists still cannot perform Git/VCS.`}function su(e){return e.permissions.filesystem==="workspace-write"?"workspace-write":"read-only"}function C1(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 $s(e){return k1.has(e)}function iM(e,t,n){if(n==="agents/root.toml")return!0;if(kn.some((r)=>n===`holycodex/agents/${r.role.toLowerCase()}.toml`))return!0;if(!co(Qe(e,"agents"),t))return!1;return _r.some((r)=>{let[o,i]=r.split("."),a=`${o[0].toUpperCase()}${o.slice(1)}.${i}.toml`;return n===`agents/${a}`})}async function aM(e){try{await Or(e);let t=await Qf(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await em(e,"utf8");if(!$s(n))return"preserved";return await Us(e,{force:!1}),"removed"}catch(t){if(bt(t,"ENOENT"))return"absent";throw t}}async function pa(e){try{await Or(e);let t=await Qf(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await em(e))}catch(t){if(bt(t,"ENOENT"))return;throw t}}async function A1(e,t){try{await Or(e);let n=await Qf(e);if(n.isSymbolicLink()||!n.isFile())return{status:"preserved"};let r=new TextDecoder("utf-8",{fatal:!0}).decode(await em(e));if(await Cr(r)===t)return await Us(e,{force:!1}),{status:"removed",previous:r};return{status:"preserved"}}catch(n){if(bt(n,"ENOENT"))return{status:"removed"};throw n}}async function Cr(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("")}var T1,E1,R1,k1;var om=x(()=>{st();ca();Ds();T1=["You are a HolyCodex GPT-6-family specialist executing one active bounded Assignment. Follow its exact boundary, exclusions, acceptance criteria, and evidence requirements. Preserve unrelated work. Do not delegate, message peers, mutate global Intent lifecycle, make material decisions, perform external effects, or perform Git/VCS. Repository source mutation is governed only by the concrete task contract; workspace writes for caches, generated test state, and proof outputs do not grant source-mutation authority. Continue through implementation, repair, and proportional proof until the Assignment is completed or exactly blocked.","Do not emit normal progress, heartbeat, or intermediate evidence messages. Communicate only the terminal outcome, or surface the material Root-owned decision required to proceed.","Do not expand beyond the Assignment boundary; report out-of-boundary work to Root for a new bounded Assignment.",`Return one compact, evidence-first structured outcome (${L.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${L.specialistReportFields.join(", ")}.`].join(" "),E1={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",external_effects:"external effects",gui_browser:"GUI and browser execution",computer_use:"Computer Use when selected"},R1={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",review:"review",ci_release_observation:"CI or release observation"};k1=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)=>C1(e,t,n))))});class ci{adapter;observedIdentities={};constructor(e){if("run"in e){let t=Kf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await Ub({environment:e}),n=Kf({executable:t.path,environment:qb(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new ci(n)}async list(){try{return await this.adapter.list()}catch(e){throw cu("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw cu("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw cu("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw cu("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw cu("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(e.map((i)=>{let a=Rr(t,i),s=Yn(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 p=l===void 0?"missing":l.installed&&l.enabled?"installed":l.installed?"disabled":"missing";return[i,p]}));return this.observedIdentities=Object.freeze(n),o}getObservedIdentities(){return this.observedIdentities}}function cu(e,t,n){if(t instanceof kr)return t;let o=(t instanceof ve?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 kr(i,a,t,n===void 0?{}:{plugin_id:n})}var kr;var lu=x(()=>{Xl();st();kr=class kr 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 cM(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=P1(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=s_(o.slice(1,-1).trim()),I1(t,n);continue}let i=dM(o);if(i<1)throw Error("TOML assignment is invalid.");let a=s_(o.slice(0,i).trim()),s=im(o.slice(i+1).trim());pM(t,[...n,...a],s)}return t}function lM(e){let t=[];return uM(e,[],t),t.join(`
41
+ `)}function uM(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(l_(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(sM).join(".")}]`)}for(let[i,a]of r)n.push(`${sM(i)} = ${fM(a)}`);for(let[i,a]of o)uM(a,[...t,i],n)}function im(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?[]:c_(t,",").map(im)}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 c_(t,",")){let o=dM(r);if(o<1)throw Error("TOML inline table entry is invalid.");pM(n,s_(r.slice(0,o).trim()),im(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 s_(e){let t=c_(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("'")?im(n):n)}function pM(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(l_(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 I1(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(l_(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function c_(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 dM(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 P1(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 l_(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function sM(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function fM(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(fM).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{execFile as M1}from"child_process";import{access as N1,readFile as F1,realpath as L1}from"fs/promises";import{posix as D1,win32 as q1}from"path";import{promisify as U1}from"util";function ma(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:gM,run:async(t,n)=>{try{let r=await $1(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 u_(e){let t=uo(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(uu(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(uu(t,"bunx")||uu(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(uu(t,"npx")||t.endsWith("/npx-cli.js")||uu(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function ha(e,t){if(e.platform!=="win32")return{status:"not_applicable"};let n=await mM(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 _t("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 mM(e);if(o===void 0)throw new _t("git_bash_unavailable",`Git for Windows was installed, but ${fa} could not be verified. Repair Git for Windows and retry.`);return{status:"healthy",path:o,installed:!0}}async function Hs(e,t,n){let r=u_(e.environment);if(r===void 0)throw new _t("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await am(e,r),i=await J1(e,r);if(i===void 0)throw new _t("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);if(t&&o?.version!==i){let l=yM(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new _t("context7_install_failed",`${r.family} could not install ${da}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new _t("context7_unavailable",`${da} is not owned by the ${r.family} global installation.`);let a=await am(e,r);if(a===void 0)throw new _t("context7_verification_failed",`${da} could not be verified in the ${r.family} global installation.`);if(a.version!==i)throw new _t("context7_outdated",`The ${r.family} global ctx7 is ${a.version}; ${i} is required.`,{installed:a.version,latest:i});let s=H1(n,r,o);return{manager:r.family,launcher:r.launcher,version:a.version,executable:a.executable,ownership:s,identity:a.identity}}function H1(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(!xM(r)||r!==n.identity)return"user";return"holycodex"}async function p_(e,t){if(t?.ownership!=="holycodex")return!1;let n=u_(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await am(e,n)}catch(a){if(a instanceof _t&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!bM(r.executable,t.executable,e.platform)||!xM(t.identity)||r.identity!==t.identity)return!1;let o=j1(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new _t("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await am(e,n)!==void 0)throw new _t("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof _t&&a.code==="context7_remove_failed")throw a;throw new _t("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function yM(e){switch(e){case"bun":return{executable:"bun",args:["add","--global",da]};case"npm":return{executable:"npm",args:["install","--global",da]};case"pnpm":return{executable:"pnpm",args:["add","--global",da]}}}function j1(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 mM(e){if(await hM(e.run,fa,e.platform))return fa;for(let t of(e.environment.PATH??"").split(";")){if(t.length===0)continue;let n=hn(e.platform).join(t,"bash.exe");if(await hM(e.run,n,e.platform))return n}return}async function hM(e,t,n){let r=G1(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 am(e,t){let n=e.files??gM,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"?hn(e.platform).join(o,"node_modules","ctx7"):t.family==="pnpm"?await K1(e,t):hn(e.platform).join(hn(e.platform).dirname(o),"install","global","node_modules","ctx7");if(i===void 0)return;let a;try{a=JSON.parse(await n.readText(hn(e.platform).join(i,"package.json")))}catch{return}if(typeof a.version!=="string")return;let s=typeof a.bin==="string"?a.bin:Y1(a.bin)&&typeof a.bin.ctx7==="string"?a.bin.ctx7:void 0;if(s===void 0)return;let c=hn(e.platform).resolve(i,s),l,u;try{if(await n.access(c),l=await n.realpath(i),u=await n.realpath(c),!uo(u).startsWith(`${uo(l)}/`))return}catch{return}let p=z1(o,t.family,e.platform),f;try{await n.access(p),f=await n.realpath(p)}catch{return}let h=await V1(e.environment,e.platform,n);if(h!==void 0&&!bM(await W1(n,h),f,e.platform))throw new _t("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:h,expected:p});if(h===void 0)return;let m=await e.run(p,["--version"]);if(m.exitCode!==0||SM(m.stdout)!==a.version)return;return{version:a.version,executable:p,identity:await B1(t,l,u,f,a)}}async function B1(e,t,n,r,o){return await Qn("context7-installation",[Xn({manager:e.family,package_root:uo(t),package_executable:uo(n),shim:uo(r),package:o})])}function xM(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function V1(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=hn(t).join(i,a);try{return await n.access(s),s}catch{}}}return}function z1(e,t,n){if(n==="win32")return hn(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?hn(n).join(e,"bin","ctx7"):hn(n).join(e,"ctx7")}async function W1(e,t){try{return await e.realpath(t)}catch{return t}}function SM(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}async function K1(e,t){let n=await e.run(t.executable,["root","--global"]),r=n.stdout.trim();return n.exitCode===0&&r.length>0?hn(e.platform).join(r,"ctx7"):void 0}async function J1(e,t){let n=await e.run(t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return SM(n.stdout)}function G1(e,t){let n=hn(t),r=n.dirname(e),o=uo(r).endsWith("/usr/bin")?n.resolve(r,"..",".."):n.resolve(r,"..");return n.resolve(o,"cmd","git.exe")}function uu(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function bM(e,t,n){let r=hn(n);return uo(r.resolve(e))===uo(r.resolve(t))}function hn(e){return e==="win32"?q1:D1}function uo(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function Y1(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var fa="C:\\Program Files\\Git\\bin\\bash.exe",da="ctx7@latest",$1,gM,_t;var sm=x(()=>{st();$1=U1(M1),gM={access:N1,readText:(e)=>F1(e,"utf8"),realpath:L1};_t=class _t extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as f_,rmdir as _M}from"fs/promises";async function m_(e={},t=process.env){let n=ai(e,t),r={};try{await sa(n.codexHome),await sa(n.stateRoot),r.paths=ya({state_root:n.stateRoot})}catch(u){r.paths=ct(["path_symlink"],{error:gn(u)})}let[o,i,a]=await Promise.all([xa(n).catch((u)=>{r.configuration=ct(["state_corrupt"],{error:gn(u)});return}),mn(n.preparingRecord,Wt).catch((u)=>{r.transaction=ct(["state_corrupt"],{path:n.preparingRecord,error:gn(u)});return}),mn(n.conflictedRecord,Wt).catch((u)=>{r.transaction=ct(["state_corrupt"],{path:n.conflictedRecord,error:gn(u)});return})]);if(i!==void 0&&r.transaction?.status!=="failed")r.transaction=ct(["incomplete_install_state"]);if(a!==void 0&&r.transaction?.status!=="failed")r.transaction=ct(["conflicted_state"]);if(!r.configuration)if(!o)r.configuration=ct(["configuration_missing"]);else if(await Bs(o))r.configuration=ya({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=ct(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await Q1(n,o),r.native_roles=await eB(n,o.profile,o.tier,o.tooling?.git_bash.status==="healthy"?o.tooling.git_bash.path:void 0);let u=Object.entries(o.capability_state??{}).find(([,p])=>p.selected&&p.status!=="healthy");if(u)r.capabilities=ct(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status})}let s=e.runtime??ma(t);try{let u=await ha(s,!1);r.git_bash=u.status==="missing"?ct(["git_bash_missing"]):ya(u.status==="healthy"?{path:u.path}:{})}catch(u){r.git_bash=ct(["git_bash_unavailable"],{error:gn(u)})}try{let u=await Hs(s,!1,o?.tooling?.context7);r.context7=ya({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7=ct(["context7_unavailable"],{error:gn(u)})}try{let u=await qt(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&$s(u)){let p=r.native_roles;r.native_roles={status:"failed",reasons:[...p?.reasons??[],"stale_legacy_root"],details:{...p?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(u){r.native_roles=ct(["native_role_invalid"],{error:gn(u)})}let c=e.officialPluginManager??await ci.discover({...t,CODEX_HOME:n.codexHome}).catch(()=>{return});if(o&&c?.status){let u=[...new Set([In,...Cl({computer_use:o.optional_selections.computer_use,frontend:o.optional_selections.frontend,security:o.optional_selections.security},o.official_plugins),...o.owned_plugins??[]])];try{let p=await c.status(u),f=Object.entries(p).filter(([,m])=>m!=="installed").map(([m])=>m),h=c.getObservedIdentities?.()??{};r.native_plugins=f.length===0?ya({status:p,observed_identities:h}):ct(["native_plugin_disagreement"],{missing:f,status:p,observed_identities:h})}catch(p){r.native_plugins=ct(["native_plugin_status_failed"],{error:gn(p)})}}else r.native_plugins={status:"unsupported",reasons:["native_plugin_manager_unavailable"],details:{}};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 h_(e={},t=process.env){let n=ai(e,t);await sa(n.codexHome),await sa(n.stateRoot);let r=await xa(n);if(r!==void 0&&!await Bs(r))throw new M("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([mn(n.preparingRecord,Wt),mn(n.conflictedRecord,Wt)]),a=vM(r,o,i);if(a===void 0)return[];let s=nr(await qt(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await ti(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 pu(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 du(s,a.provider_config,new Set(g_(a)));for(let u of l.preserved)c.push({path:n.configFile,key:`plugins."${u}"`,action:"remove"})}return c.push(...await oM(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[ga(l),l])).values()]}async function fu(e={},t=process.env){let n=ai(e,t);await sa(n.codexHome),await sa(n.stateRoot);let r=await xa(n);if(r&&!await Bs(r))throw new M("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([mn(n.preparingRecord,Wt),mn(n.conflictedRecord,Wt)]),a=vM(r,o,i);d_(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(g_(a)),c=[],l=[],u=[];if(a===void 0)return d_(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let p=await h_(e,t),f=await X1(e,p),h=await qt(n.configFile),m=nr(h),S=a?.managed_config;if(S){let g=await ti(m,S,{schema:S.schema,installId:S.installId});if(g.preservedKeys.length>0||g.unresolvedKeys.length>0){let O=[...g.preservedKeys,...g.unresolvedKeys].map((C)=>({path:n.configFile,key:C,action:"remove"}));for(let C of O)if(f.has(ga(C)))m=so(m,C.key)}}if(a?.plugin_config){let g=await pu(m,a.plugin_config);if(g.preserved.length>0){let R=g.preserved.map((O)=>({path:n.configFile,key:O==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let O of g.preserved){let C=R.find((Y)=>Y.key===(O==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(C===void 0||!f.has(ga(C)))continue;m=so(m,O==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let g=await du(m,a.provider_config,s);if(g.preserved.length>0){let R=g.preserved.map((O)=>({path:n.configFile,key:`plugins."${O}"`,action:"remove"}));for(let O of g.preserved){let C=R.find((Y)=>Y.key===`plugins."${O}"`);if(C===void 0||!f.has(ga(C)))continue;m=so(m,`plugins."${O}"`)}}}let E;try{E=e.officialPluginManager??await ci.discover({...t,CODEX_HOME:n.codexHome})}catch(g){throw new M("capability_denied","Native Codex plugin removal is unavailable.",g,{recovery:"Install or expose Codex, then retry."})}if(E===void 0||!E.remove||!E.list)throw new M("capability_denied","Native Codex plugin removal and readback are unavailable.");let v=await rm(n.codexHome,a?.managed_artifacts??[],new Set(p.filter((g)=>g.key===void 0&&f.has(ga(g))).map((g)=>g.path)));if(c.push(...v.removed),l.push(...v.preserved),v.preserved.length>0)u.push("managed_artifact_changed");for(let g of s)try{let R=await E.list(),O=tB(R,g);if(O?.entry.installed!==!0)continue;let C=O.entry.pluginId;await E.remove(C);let Y=await E.list();if(Rr(Y,g)?.entry?.installed===!0||[...Y.installed,...Y.available].some((ce)=>ce.pluginId===g&&ce.installed))throw new M("capability_denied",`Codex still reports ${g} after removal.`);c.push(g)}catch(R){throw u.push("native_plugin_remove_failed"),await li(n,a??cm()),new M("capability_denied",`Codex native plugin removal did not converge for ${g}: ${gn(R)}`,R)}try{if(await p_(e.runtime??ma(t),a.tooling?.context7))c.push("ctx7")}catch(g){throw u.push("context7_remove_failed"),await li(n,a),new M("capability_denied",`Context7 removal did not converge: ${gn(g)}`,g)}let b;try{let g=m,R=S;if(R){let O=await ti(g,R,{schema:R.schema,installId:R.installId}),C=[...O.preservedKeys,...O.unresolvedKeys];if(C.filter((U)=>!f.has(ga({path:n.configFile,key:U,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await li(n,a??cm()),{removed:c,preserved:l,reasons:u};if(g=O.document,C.length>0){let U=new Set(C);R={...O.state,managed:Object.fromEntries(Object.entries(O.state.managed).filter(([Z])=>!U.has(Z)))}}else R=O.state}if(a?.plugin_config){let O=await pu(g,a.plugin_config,{allowBeforeState:!0});if(O.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await li(n,a),{removed:c,preserved:l,reasons:u};g=O.document}if(a?.provider_config){let O=await du(g,a.provider_config,s,{allowBeforeState:!0});if(O.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await li(n,a),{removed:c,preserved:l,reasons:u};g=O.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)b=R===void 0?{document:g}:{document:g,state:R};if(b!==void 0)if(Object.keys(b.document).length===0&&h===void 0)await f_(n.configFile,{force:!1});else await lo(n.configFile,x_(b.document))}catch(g){if(g instanceof M)throw await li(n,a??cm()),g;return l.push(n.configFile),u.push("managed_config_write_failed"),await li(n,a??cm()),{removed:c,preserved:l,reasons:u}}if(r)try{await f_(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(g){if(!bt(g,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await li(n,a??r),{removed:c,preserved:l,reasons:u}}if(l.length===0)for(let[g,R]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0]]){if(!R)continue;try{await nB(g),c.push(g)}catch{l.push(g),u.push("state_remove_failed")}}if(l.length===0)try{await _M(n.roleRoot),c.push(n.roleRoot)}catch(g){if(!bt(g,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await _M(n.stateRoot),c.push(n.stateRoot)}catch(g){if(bt(g,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return d_(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 lm(e={},t=process.env,n={}){let r=ai(e,t),[o,i,a]=await Promise.all([xa(r),mn(r.preparingRecord,Wt),mn(r.conflictedRecord,Wt)]);if(o!==void 0&&!await Bs(o))throw new M("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});let s=wM(o,i,a),c=s??o;if(c===void 0)throw new M("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l;try{l=await qs()}catch(S){throw new M("upgrade_failed","The running HolyCodex version is unavailable.",S)}let u=Z1(l,c.version);if(u<0)throw new M("upgrade_downgrade",`The running HolyCodex version ${l} is older than the installed version ${c.version}.`,void 0,{installed_version:c.version,running_version:l});let p=c.managed_config?.managed["features.context_management.experimental_mode"]!==void 0,f=[];if(n.dryRun===!0){let S=nr(await qt(r.configFile));if(c.managed_config!==void 0){for(let v of Object.keys(c.managed_config.managed))if((await oa(S,c.managed_config,v)).status!=="unchanged")f.push({path:r.configFile,key:v,action:"replace"})}if(c.plugin_config!==void 0){let v=await pu(S,c.plugin_config);for(let b of v.preserved){let g=b==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";f.push({path:r.configFile,key:g,action:"replace"})}}if(c.provider_config!==void 0){let v=await du(S,c.provider_config,new Set(g_(c)));for(let b of v.preserved)f.push({path:r.configFile,key:`plugins."${b}"`,action:"replace"})}let E=await tm(r.codexHome,c.profile,c.managed_artifacts,c.tier,c.tooling?.git_bash.status==="healthy"?c.tooling.git_bash.path:void 0);for(let v of E)f.push(v)}let h=c.tooling===void 0;try{let S=e.runtime??ma(t),E=await ha(S,!1),v=await Hs(S,!1,c.tooling?.context7);h||=E.status==="missing"||v.manager!==c.tooling?.context7.manager||v.version!==c.tooling?.context7.version||v.executable!==c.tooling?.context7.executable}catch{h=!0}let m=[...u>0?["version"]:[],...p?["context-management configuration migration"]:[],...u>0||p?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...h?["shared tooling reconciliation"]:[],...f.map((S)=>`conflict: ${S.path}${S.key===void 0?"":` (${S.key})`} -> ${S.action}`)];if(m.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:l,changes:[],record:o,preserved:[],warnings:[],conflicts:f};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:l,changes:m,record:o,preserved:[],warnings:[],conflicts:f};try{let S=await js({profile:c.profile,tier:c.tier,optional:c.explicit_optional_selections,officialPlugins:c.official_plugins},e,t);return{status:"upgraded",from_version:c.version,to_version:l,changes:m,record:S.record,preserved:S.preserved,warnings:S.warnings}}catch(S){if(S instanceof M)throw S;throw new M("upgrade_failed",`HolyCodex upgrade failed: ${gn(S)}`,S)}}function Z1(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let o=0;o<3;o+=1){if((n[o]??0)<(r[o]??0))return-1;if((n[o]??0)>(r[o]??0))return 1}return 0}async function X1(e,t){let n=new Set;for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(ga(r));continue}if(o==="decline")continue;throw new M("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 ga(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function Q1(e,t){if(!t.managed_config)return ct(["incomplete_install_state"]);try{let n=nr(await qt(e.configFile)),r=pm(t.profile,t.tier,{computerUse:t.optional_selections.computer_use,frontend:t.optional_selections.frontend,security:t.optional_selections.security,...t.tooling?.git_bash.status==="healthy"?{windowsGitBashExecutable:t.tooling.git_bash.path}:{}}),o=[];for(let[i,a]of Object.entries(r))if((await oa(n,t.managed_config,i)).status!=="unchanged"||ge(n,i)!==a)o.push(i);return o.length===0?ya({managed_keys:Object.keys(r).length}):ct(["changed_holycodex_config"],{keys:o})}catch(n){return ct(["config_unreadable"],{error:gn(n)})}}async function eB(e,t,n,r){try{let o=nr(await qt(e.configFile)),i=[];for(let s of si(t,n)){let c=ge(o,`agents."${s.name}".config_file`),l=`${e.roleRoot}/${s.name}.toml`.replaceAll("\\","/");if(typeof c!=="string"||Bl(e.configFile,c).replaceAll("\\","/")!==l){i.push(`${s.name}:registration`);continue}let u=await qt(`${e.roleRoot}/${s.name}.toml`);if(u===void 0){i.push(`${s.name}:missing`);continue}if(u!==au(s,r===void 0?{}:{windowsGitBashExecutable:r})){i.push(`${s.name}:changed`);continue}let p=nr(u);if(p.name!==s.name||typeof p.description!=="string"||typeof p.developer_instructions!=="string"||p.model!=="gpt-5.6-luna"||p.model_reasoning_summary!=="none"||p.model_verbosity!=="low"||p.tool_output_token_limit!==void 0||p.service_tier!==(n==="standard"?"default":"fast")||p.sandbox_mode!==su(s)||p.approval_policy!=="never"||p.web_search!==(s.permissions.network?"live":"disabled")||ge(p,"agents.enabled")!==!1||ge(p,"features.multi_agent_v2")!==!1||ge(p,"features.multi_agent")!==!1||ge(p,"features.context_management")!==!0||ge(p,"features.computer_use")!==!1||ge(p,"features.browser_use")!==!1||ge(p,"features.in_app_browser")!==!1)i.push(`${s.name}:malformed`)}let a=await qt(`${e.codexHome}/agents/root.toml`);if(a!==void 0&&$s(a))i.push("root:stale");return i.length===0?ya({role_root:e.roleRoot,agent_types:si(t,n).map((s)=>s.name)}):ct(["native_role_disagreement"],{roles:i})}catch(o){return ct(["native_role_invalid"],{error:gn(o)})}}async function li(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(St(Wt,n)!==void 0)await ua(e.conflictedRecord,fn(n))}function wM(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||y_(r,e)))}function vM(e,t,n){return wM(e,t,n)??e}function cm(){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:{computer_use:!1,frontend:!1,security:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function g_(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"?[In]:[],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 tB(e,t){let n=Rr(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 ya(e){return{status:"healthy",reasons:[],details:e}}function ct(e,t={}){return{status:"failed",reasons:e,details:t}}async function nB(e){await f_(e,{force:!1}).catch((t)=>{if(!bt(t,"ENOENT"))throw t})}function gn(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function d_(e,t){try{e.onProgress?.(t)}catch{}}var um=x(()=>{Xl();st();mu();Ql();iu();om();lu();ca();Ls();Ds();sm()});import{rm as IM}from"fs/promises";import{join as rB}from"path";function Ar(e){let t=St(Yf,e);if(t===void 0)throw new M("install_failed","The installation options are invalid.");return t}function y_(e,t){return e.install_id===t.install_id&&e.digest===t.digest}async function js(e={},t={},n=process.env){if(St(tu,e)===void 0)throw new M("install_failed","The installation options are invalid.");let r=ai(t,n);rr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let o=await xa(r);if(o!==void 0&&!await Bs(o))throw new M("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:r.activeRecord});let i=await mn(r.preparingRecord,Wt),s=[await mn(r.conflictedRecord,Wt),i].find((j)=>j!==void 0&&(o===void 0||y_(j,o)));if(s!==void 0){await Promise.resolve().then(() => um());let ue=await fu(t,n);if(ue.preserved.length>0||ue.reasons.length>0)throw new M("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:ue.preserved.join(","),reasons:ue.reasons.join(",")});return await js({profile:e.profile??s.profile,tier:e.tier??s.tier,optional:{computer_use:e.optional?.computer_use??s.optional_selections.computer_use,frontend:e.optional?.frontend??s.optional_selections.frontend,security:e.optional?.security??s.optional_selections.security},officialPlugins:e.officialPlugins??kM(s)},t,n)}let c=xB(e.profile,o?.profile),l=SB(e.tier,o?.tier),u=bB(e.optional,o?.optional_selections),p=hB(o?.explicit_optional_selections,e.optional),f=e.officialPlugins??kM(o),h=t.runtime??ma(n),m=await ha(h,!1),S=m,E,v=[...new Set(Cl(NM(u),f).map((j)=>Yn(j)??j))],b;try{b=t.officialPluginManager??await ci.discover({...n,CODEX_HOME:r.codexHome})}catch(j){throw new M("capability_denied","Native Codex plugin installation is unavailable.",j,{recovery:"Install or expose Codex, then retry."})}if(!b.addMarketplace||!b.add||!b.list)throw new M("install_failed","Native Codex plugin installation and verification are unavailable.");let g;try{g=await b.list()}catch(j){throw new M("capability_denied","Native Codex plugin state could not be read safely.",j)}let R=v.filter((j)=>{if(Yn(j)!==j)return!1;let ue=yu(g,j);return!(ue?.installed&&ue.enabled)});rr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let O=o?.install_id??crypto.randomUUID().replaceAll("-",""),C=await qs(),Y=o!==void 0&&o.version!==C&&o.owned_plugins?.includes(In)===!0?new Set([In]):new Set,U=(t.now?.()??new Date).toISOString(),Z=await qt(r.configFile),ce=nr(Z),oe=await EM(ce),Te=o?.plugin_config?.before??oe;if(o?.plugin_config!==void 0){let j=["preference","marketplace"].filter((ue)=>{let _e=oe[ue].digest;return _e!==o.plugin_config?.after[ue].digest&&_e!==o.plugin_config?.before[ue].digest});await dm(t,j.map((ue)=>({path:r.configFile,key:ue==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"replace"})))}let Ut=[...new Set([...v,...(o?.provider_config??[]).map((j)=>j.plugin_id),...o?.owned_plugins??[]])].filter((j)=>j!==In),$t=await RM(ce,Ut);if(o?.provider_config!==void 0){let j=new Set(o.owned_plugins??[]),ue=$t.filter((_e)=>{if(!j.has(_e.plugin_id))return!1;let Pr=o.provider_config?.find((mo)=>mo.plugin_id===_e.plugin_id);return Pr!==void 0&&_e.before.digest!==Pr.after.digest&&_e.before.digest!==Pr.before.digest});await dm(t,ue.map((_e)=>({path:r.configFile,key:`plugins."${_e.plugin_id}"`,action:"replace"})))}let Kt=$t.map((j)=>{let ue=o?.provider_config?.find((_e)=>_e.plugin_id===j.plugin_id);return ue===void 0?j:{plugin_id:j.plugin_id,before:ue.before,after:ue.before}}),et=o?.managed_config??Mf({schema:yn,installId:O}),tt=await OM(ce,et,o),Ht=await CM(tt.document,tt.state),{document:Pn,state:po}=Ht;uB(Pn,po);let Mn=pm(c,l,{computerUse:u.computer_use,frontend:u.frontend,security:u.security,...h.platform==="win32"?{windowsGitBashExecutable:m.status==="healthy"?m.path:fa}:{}}),fo;try{fo=await As(Pn,po,Mn,{schema:yn,installId:O})}catch(j){if(j instanceof M)throw j;throw new M("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",j,{recovery:"Converge the conflicting Codex setting, then retry."})}if(fo.driftedKeys.length>0){await dm(t,fo.driftedKeys.map((_e)=>({path:r.configFile,key:_e,action:"replace"})));let j=Pn,ue={...po.managed};for(let _e of fo.driftedKeys){let Pr=ue[_e],mo=Mn[_e];if(Pr===void 0||mo===void 0)throw new M("state_corrupt","The managed conflict cannot be verified.",void 0,{path:r.configFile,key:_e});let ho=ge(j,_e);if(ho===void 0)j=ks(j,_e,mo),ho=mo;ue[_e]={...Pr,lastManagedValue:await tr(_e,ho)}}if(fo=await As(j,{...po,managed:ue},Mn,{schema:yn,installId:O}),fo.driftedKeys.length>0)throw new M("state_corrupt","The accepted managed conflicts did not converge.")}let ym;try{ym=await tm(r.codexHome,c,o?.managed_artifacts,l,h.platform==="win32"?m.status==="healthy"?m.path:fa:void 0)}catch(j){throw new M("install_failed",__(j),j)}let tN=await dm(t,ym,!0),k_={owner:"holycodex",schema_epoch:yn,install_id:O,version:C,digest:o?.digest??"0".repeat(64),profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:v,capability_state:w_(u),managed_artifacts:o?.managed_artifacts??[],installed_at:U,status:"preparing",step:"validated",managed_config:fo.state,plugin_snapshot:[],plugin_config:{plugin_id:In,before:Te,after:Te},provider_config:Kt,owned_plugins:[...new Set(o?.owned_plugins??[])],...o?.tooling===void 0?{}:{tooling:o.tooling}};await nu(r.stateRoot),await Vs(r.preparingRecord,k_);try{S=await ha(h,!0),E=await Hs(h,!0,o?.tooling?.context7)}catch(j){if(j instanceof _t)throw new M("capability_denied",j.message,j,j.details);throw j}let xm={git_bash:S,context7:E};if(b.ensureOfficialMarketplace!==void 0&&R.length>0)try{await b.ensureOfficialMarketplace(R)}catch(j){throw new M("capability_denied",`The selected official Codex provider marketplace is unavailable: ${__(j)}`,j,{recovery:"Check Codex network and marketplace policy, then retry."})}let bu;try{bu=await pB({list:()=>b.list()},[...new Set([In,...v,...o?.owned_plugins??[]])])}catch(j){throw new M("capability_denied","Native Codex plugin state could not be read safely.",j)}let Sm={...k_,plugin_snapshot:bu,tooling:xm};await Vs(r.preparingRecord,Sm);let Ir,A_=!1,I_=new Set,va=new Set(o?.owned_plugins??[]),bm=new Set,jt=Sm,P_=!1,M_=!1,_m=Z,Ks=fo.state;try{rr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await nu(r.roleRoot),Ir=await i_(r.codexHome,c,o?.managed_artifacts,l,S.status==="healthy"?S.path:void 0,ym.length===0?t.resolveConflict:void 0,tN),jt={...Sm,step:"roles_prepared",managed_artifacts:Ir.managed_artifacts},await Vs(r.preparingRecord,jt),rr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),rr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),P_=!0,await b.addMarketplace(oB),await yB({list:()=>b.list(),add:(Nn)=>b.add(Nn)},[In,...v],Y,(Nn,Em)=>{if(Em==="new")I_.add(Nn),va.add(Nn),jt={...jt,owned_plugins:[...va]};else bm.add(Nn),va.add(Nn),jt={...jt,owned_plugins:[...va]}}),jt={...jt,step:"plugins_installed"},await Vs(r.preparingRecord,jt),rr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let ue=await qt(r.configFile);_m=ue;let _e=nr(ue),Pr=await OM(_e,et,o),mo=await CM(Pr.document,Pr.state),{document:ho,state:N_}=mo,wm=await EM(ho),vm=(await RM(ho,Ut)).map((Nn)=>({plugin_id:Nn.plugin_id,before:Kt.find((Em)=>Em.plugin_id===Nn.plugin_id)?.before??Nn.before,after:Nn.before}));await lB(ho,Pn,N_,Mn);let _u=await As(ho,N_,Mn,{schema:yn,installId:O});if(_u.driftedKeys.length>0)throw new M("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:_u.driftedKeys.join(",")});M_=!0,rr(t,{stage:"config",status:"started",message:"Configuring Root"}),Ks=_u.state,jt={...jt,managed_config:Ks,plugin_config:{plugin_id:In,before:Te,after:wm},provider_config:vm},await lo(r.configFile,x_(_u.document)),A_=!0,jt={...jt,step:"config_published"},await Vs(r.preparingRecord,jt),rr(t,{stage:"config",status:"completed",message:"Root configuration published"}),rr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await fB(r,c,l,{computerUse:u.computer_use,frontend:u.frontend,security:u.security,...S.status==="healthy"?{windowsGitBashExecutable:S.path}:{}},Ks,Ir.preserved),rr(t,{stage:"verification",status:"completed",message:"Installation verified"});let F_=w_(u),nN=await fm({owner:"holycodex",install_id:O,version:C,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:v,capability_state:F_,managed_artifacts:Ir.managed_artifacts,managed_config:Ks,plugin_config:{plugin_id:In,before:Te,after:wm},provider_config:vm,plugin_snapshot:bu,owned_plugins:[...va],tooling:xm}),Tm={owner:"holycodex",schema_epoch:yn,install_id:O,version:C,digest:nN,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:v,capability_state:F_,managed_artifacts:Ir.managed_artifacts,installed_at:U,status:"active",step:"active",managed_config:Ks,plugin_snapshot:bu,plugin_config:{plugin_id:In,before:Te,after:wm},provider_config:vm,owned_plugins:[...va],tooling:xm};if(St(Fs,Tm)===void 0)throw new M("state_corrupt","The HolyCodex configuration is invalid.");return await ua(r.activeRecord,fn(Tm)),await S_(r.preparingRecord),await S_(r.conflictedRecord),rr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Tm,optional_plugins:v,preserved:Ir.preserved,warnings:Ir.preserved.length===0?[]:["modified managed files were preserved"]}}catch(j){let ue=[];if(A_)try{await dB(r.configFile,_m)}catch{ue.push("config")}if(P_&&!M_){if(await qt(r.configFile).catch(()=>{return})!==_m)ue.push("config")}if(Ir!==void 0)try{if((await nm(Ir.rollback)).preserved.length>0)ue.push("roles")}catch{ue.push("roles")}if(bm.size>0)ue.push(...[...bm].map((_e)=>`plugin:${_e}`));for(let _e of I_)try{await b.remove?.(_e)}catch{ue.push(`plugin:${_e}`)}if(ue.length>0)await Vs(r.conflictedRecord,{...jt,step:"conflicted",status:"conflicted"}).catch(()=>{return});else await S_(r.preparingRecord).catch(()=>{return});if(j instanceof An)throw j;if(j instanceof M)throw j;throw new M(j instanceof kr||j instanceof gu?"capability_denied":"install_failed",__(j),j,ue.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function xa(e){let t=await mn(e.activeRecord,Gf);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:St(Fs,t);if(o!==void 0)return o;let i=St(KP,t);if(i===void 0)throw new M("state_corrupt","The HolyCodex configuration is invalid.");if(!await DM(i))throw new M("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 M("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=_S(a)}catch(Z){throw new M("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,Z,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([Z])=>Z!=="plan")):i,l={computer_use:i.optional_selections.computer_use,frontend:i.optional_selections.frontend,security:i.optional_selections.security,coding:!0},u={...i.explicit_optional_selections.computer_use===void 0?{}:{computer_use:i.explicit_optional_selections.computer_use},...i.explicit_optional_selections.frontend===void 0?{}:{frontend:i.explicit_optional_selections.frontend},...i.explicit_optional_selections.security===void 0?{}:{security:i.explicit_optional_selections.security}},p=i.capability_state===void 0?void 0:w_(l),f=(i.official_plugins??[]).filter((Z)=>!hu(Z)),h=i.owned_plugins?.filter((Z)=>!hu(Z)),m=i.provider_config?.filter((Z)=>!hu(Z.plugin_id)),S=i.plugin_snapshot?.filter((Z)=>!hu(Z.plugin_id)),{optional_selections:E,explicit_optional_selections:v,capability_state:b,official_plugins:g,owned_plugins:R,provider_config:O,plugin_snapshot:C,...Y}=c;return{...Y,profile:s,optional_selections:l,explicit_optional_selections:u,official_plugins:f,...p===void 0?{}:{capability_state:p},...h===void 0?{}:{owned_plugins:h},...m===void 0?{}:{provider_config:m},...S===void 0?{}:{plugin_snapshot:S},digest:await fm({owner:i.owner,install_id:i.install_id,version:i.version,profile:s,tier:i.tier,optional_selections:l,explicit_optional_selections:u,official_plugins:f,capability_state:p??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},...m===void 0?{}:{provider_config:m},...S===void 0?{}:{plugin_snapshot:S},...h===void 0?{}:{owned_plugins:h},...i.tooling===void 0?{}:{tooling:i.tooling}})}}function NM(e){return{computer_use:e.computer_use,frontend:e.frontend,security:e.security}}function nr(e){if(e===void 0||e.trim().length===0)return{};try{let t=globalThis.Bun,n=t?.TOML?.parse?t.TOML.parse(e):cM(e),r=St(Hl,n);if(r===void 0)throw Error("TOML document contains unsupported values.");return r}catch(t){throw new M("state_corrupt","The Codex config.toml is not valid TOML.",t)}}function x_(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):lM(e)).trimEnd()}
42
+ `}catch(t){throw new M("install_failed","The merged Codex configuration is not writable.",t)}}async function EM(e){return{preference:await xu(e,"plugins",PM),marketplace:await xu(e,"marketplaces",MM)}}async function RM(e,t){return await Promise.all(t.map(async(n)=>{let r=await xu(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 pu(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",PM],["marketplace","marketplaces",MM]]){let u=t.before[s],p=t.after[s],f=await xu(e,c,l);if(n.allowBeforeState===!0&&f.digest===u.digest)continue;if(f.digest!==p.digest){a.push(s);continue}if(u.presence==="absent"){if(f.presence==="present")r=LM(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=FM(r,c,l,cB(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function du(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,p=await xu(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&p.digest===l.digest)continue;if(p.digest!==u.digest){s.push(c.plugin_id);continue}if(l.presence==="absent"){if(p.presence==="present")o=LM(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=FM(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 xu(e,t,n){let r=aB(e,t,n),o=await Qn("holycodex-plugin-config",[Xn(fn({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=sB(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function aB(e,t,n){let r=e[t];if(!zs(r))return;return r[n]}function sB(e,t){if(!zs(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!==TM)return;return{kind:"marketplace",source_type:"git",source:TM}}function cB(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function FM(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!zs(i))throw new M("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function LM(e,t,n){let r=e[t];if(!zs(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 zs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function pm(e,t,n=!1){let r=r_(e,t),o={model:r.model,model_auto_compact_token_limit:64000,model_reasoning_effort:r.effort,service_tier:r.serviceTier,model_verbosity:"low",developer_instructions:o_(n),suppress_unstable_features_warning:!0,"features.default_mode_request_user_input":!0,"features.multi_agent":!0,"features.multi_agent_v2":!1,"features.context_management":!0};for(let i of _r)o[`agents."${i}".config_file`]=`holycodex/agents/${i}.toml`;return o}async function lB(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await oa(e,n,a)).status==="drifted")o.push(a);continue}let c=ge(t,a),l=ge(e,a);if(c!==l)o.push(a)}if(o.length>0)throw new M("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function OM(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 ti(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new M("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((h)=>h.startsWith(`agents/${c[0]?.toUpperCase()}${c.slice(1)}.`)||h===`holycodex/agents/${c}.toml`))continue;let u=`agents.${c}.config_file`,p=ge(i,u);if(typeof p!=="string")continue;let f=p.replaceAll("\\","/").replace(/^\.\//u,"");if(f===`agents/${c}.toml`||f===`holycodex/agents/${c}.toml`)i=so(i,u)}return{document:i,state:a}}async function CM(e,t){let o=t.managed["features.context_management.experimental_mode"];if(o===void 0)return{document:e,state:t};let i=ge(e,"features.context_management.experimental_mode"),a=ge(e,"features.context_management"),s=zs(a)?void 0:a;if(zs(a)&&Object.keys(a).some((p)=>p!=="experimental_mode"))throw new M("state_corrupt","The legacy context-management table contains unrelated settings and cannot be migrated without changing user configuration.",void 0,{key:"features.context_management",recovery:"Move unrelated settings, then retry the upgrade."});if(i!==void 0){let p=await tr("features.context_management.experimental_mode",i);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new M("state_corrupt","The legacy context-management setting changed and cannot be migrated safely.",void 0,{key:"features.context_management.experimental_mode"});if(s!==void 0&&JSON.stringify(s)!==JSON.stringify(i))throw new M("state_corrupt","Both legacy and canonical context-management settings are present with different values.",void 0,{keys:"features.context_management.experimental_mode,features.context_management"})}if(i===void 0&&s!==void 0){let p=await tr("features.context_management",s);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new M("state_corrupt","The canonical context-management setting changed and cannot be migrated safely.",void 0,{key:"features.context_management"})}if(i===void 0&&s===void 0)throw new M("state_corrupt","The owned legacy context-management setting is missing and cannot be migrated safely.",void 0,{key:"features.context_management.experimental_mode"});let c=e;if(i!==void 0){if(c=so(c,"features.context_management.experimental_mode"),s===void 0)c=ks(c,"features.context_management",i)}let l=ge(c,"features.context_management");if(l===void 0)throw new M("state_corrupt","The canonical context-management setting is missing.");let u={...t.managed};return u["features.context_management"]={...o,keyPath:"features.context_management",lastManagedValue:await tr("features.context_management",l)},delete u["features.context_management.experimental_mode"],{document:c,state:{...t,managed:u}}}function uB(e,t){if(ge(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new M("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function pB(e,t){let n=await e.list();return t.map((r)=>{let o=yu(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function Vs(e,t){if(St(Wt,t)===void 0)throw new M("state_corrupt","The HolyCodex transaction state is invalid.");await ua(e,fn(t))}async function S_(e){await IM(e,{force:!1}).catch((t)=>{if(!bt(t,"ENOENT"))throw t})}async function dB(e,t){if(t===void 0){await IM(e,{force:!1}).catch((n)=>{if(!bt(n,"ENOENT"))throw n});return}await lo(e,t)}async function fB(e,t,n,r,o,i=[]){let a=await qt(e.configFile),s=nr(a),c=pm(t,n,r);for(let[p,f]of Object.entries(c)){let h=ge(s,p);if(p==="developer_instructions"){if(typeof h!=="string"||h!==f||await mB(p,h)!==o.managed[p]?.lastManagedValue.value)throw new M("install_failed","The effective Root instructions did not converge.")}else if(h!==f)throw new M("install_failed",`The effective Codex setting ${p} did not converge.`)}let l=si(t,n);for(let p of l){let f=`agents."${p.name}".config_file`,h=ge(s,f);if(typeof h!=="string")throw new M("install_failed",`The ${p.name} registration is missing.`);let m=rB(e.roleRoot,`${p.name}.toml`),S=m.replaceAll("\\","/");if(Bl(e.configFile,h).replaceAll("\\","/")!==S)throw new M("install_failed",`The ${p.name} registration is stale.`);let v=await qt(m);if(v===void 0)throw new M("install_failed",`The ${p.name} role file is missing.`);if(i.includes(m))continue;let b=nr(v);if(b.name!==p.name||typeof b.description!=="string"||typeof b.model!=="string"||typeof b.model_reasoning_effort!=="string"||typeof b.service_tier!=="string"||typeof b.developer_instructions!=="string"||b.sandbox_mode!==su(p)||b.approval_policy!=="never"||b.web_search!==(p.permissions.network?"live":"disabled")||b.tool_output_token_limit!==void 0||ge(b,"agents.enabled")!==!1||ge(b,"features.multi_agent_v2")!==!1||ge(b,"features.multi_agent")!==!1||ge(b,"features.context_management")!==!0||ge(b,"features.computer_use")!==!1||ge(b,"features.browser_use")!==!1||ge(b,"features.in_app_browser")!==!1)throw new M("install_failed",`The ${p.name} role file is malformed.`)}let u=await qt(`${e.codexHome}/agents/root.toml`);if(u!==void 0&&$s(u))throw new M("install_failed","A stale HolyCodex Root role remains installed.")}async function mB(e,t){return await Qn("holycodex-managed-config-value",[Xn({keyPath:e,value:t})])}function hB(e,t){let n={};for(let r of["computer_use","frontend","security"]){let o=t?.[r]??e?.[r];if(o!==void 0)n[r]=o}return n}function gB(e){return["computer_use","frontend","security"].find((t)=>Qi[t].pluginIds.includes(e))}function kM(e){return(e?.official_plugins??[]).filter((t)=>{if(hu(t))return!1;let n=gB(t);return n===void 0||e?.optional_selections[n]!==!0})}function hu(e){let t=e.slice(0,e.lastIndexOf("@"));return iB.has(t)}async function yB(e,t,n=new Set,r){for(let o of t){let i=n.has(o),a;try{a=yu(await e.list(),o)}catch(l){throw b_("list",l,o)}if(a?.installed&&!a.enabled)throw new gu("uncertain",`${o} is disabled`);let s=i||!(a?.installed&&a.enabled);if(s)try{await e.add(o)}catch(l){try{let u=yu(await e.list(),o);if(i||!AM(a,u))r?.(o,"uncertain")}catch{r?.(o,"uncertain")}throw b_("add",l,o)}let c;try{c=yu(await e.list(),o)}catch(l){if(s)r?.(o,"uncertain");throw b_("list",l,o)}if(!c?.installed){if(s&&(i||!AM(a,c)))r?.(o,"uncertain");throw new gu("missing",`${o} is not installed after add`)}if(s&&c.enabled)r?.(o,i?"uncertain":"new");if(!c.enabled){if(s)r?.(o,i?"uncertain":"new");throw new gu("uncertain",`${o} is disabled after add`)}}}function AM(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function b_(e,t,n){if(t instanceof kr)return t;return new kr(e==="list"?"list_failed":"add_failed",e==="list"?`Codex could not read the status of ${n}.`:`Codex could not add ${n}.`,t,{plugin_id:n})}function yu(e,t){let n=Rr(e,t);if(n!==void 0)return n.entry;let r=Yn(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function xB(e,t){let n=e??t??"default";if(!vr(n).ok)throw new M("install_failed","Unknown profile.");return n}function SB(e,t){let n=e??t??"standard";if(St(ea,n)===void 0)throw new M("install_failed","The tier is not supported.");return n}function bB(e,t){let n=t?NM(t):io,r=yS(e,n);return{computer_use:r.computer_use,frontend:r.frontend,security:r.security,coding:!0}}function w_(e,t=new Map){return Object.fromEntries(["computer_use","frontend","security"].map((r)=>{let o=e[r],i={selected:o,status:o?t.get(r)??"healthy":"disabled",plugin_ids:[...Qi[r].pluginIds]};return[r,i]}))}async function fm(e){let{profile:t,plan:n,...r}=e,o=n===void 0?{...r,profile:t}:{...r,plan:n};return await Qn("install-record",[Xn(fn(o))])}async function Bs(e){return await DM(e)}async function DM(e){return await fm({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 __(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}async function dm(e,t,n=!1){let r=[];for(let o of t){let i=await e.resolveConflict?.(o);if(i==="accept"){r.push(o);continue}if(i==="decline"&&n)continue;throw new M("confirmation_required",i==="cancel"?"Conflict resolution was cancelled.":"HolyCodex-owned changes require confirmation before replacement.",void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},action:o.action,resolution:i??"unavailable"})}return r}function rr(e,t){try{e.onProgress?.(t)}catch{}}var oB="davidbasilefilho/holycodex",In="holycodex@holycodex",TM="https://github.com/davidbasilefilho/holycodex.git",PM="holycodex@holycodex",MM="holycodex",iB,gu,M;var mu=x(()=>{Xl();st();Ql();iu();om();lu();ca();Ls();Ds();sm();Ls();iB=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]);gu=class gu extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};M=class M 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 XB}from"readline/promises";st();st();st();var BS=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:"frontend",kind:"boolean",usage:"--frontend / --no-frontend",description:"Frontend plugins via build-web-apps (default: true)."},{name:"security",kind:"boolean",usage:"--security / --no-security",description:"Security plugins (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."}]),aP=new Set(["codex-home","profile","tier","add-plugin"]),vH=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","frontend","no-frontend","security","no-security"]);class We extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Of(e){if(e.length===0)throw new We("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 Of(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="upgrade"&&t!=="version")throw new We("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 We("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 We("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!aP.has(u)&&!vH.has(u))throw new We("invalid_argument","Unknown option.",{option:`--${c}`});if(aP.has(u)){let p=l??e[o+1];if(p===void 0||p.length===0||p.startsWith("-"))throw new We("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(l===void 0)o+=1;if(u==="add-plugin"){let f=r[u];r[u]=Array.isArray(f)?[...f,p]:[p]}else{if(r[u]!==void 0)throw new We("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=p}continue}if(l!==void 0&&l!=="true"&&l!=="false")throw new We("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new We("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return TH(t,n,r),{command:t,positionals:n,options:r}}function TH(e,t,n){let r=RH(e);for(let s of Object.keys(n))if(!r.has(s))throw new We("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 We("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!vr(i).ok){let s=EH[i];if(s!==void 0)throw new We("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 We("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new We("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 We("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["frontend","no-frontend"],["security","no-security"]])if(n[s]!==void 0&&n[c]!==void 0)throw new We("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove","upgrade"].includes(e)&&n.yes===!1)throw new We("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","frontend","no-frontend","security","no-security","computer-use","no-computer-use","add-plugin"].includes(s)))throw new We("invalid_argument",`Installation options are not valid for ${e}.`)}var EH={"plus-low":"low",plus:"default","plus-high":"high"};function RH(e){switch(e){case"install":return new Set([...BS.map((t)=>t.name),"no-frontend","no-security","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"upgrade":return new Set(["yes","json","verbose","dry-run","codex-home"]);case"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var OH=`HolyCodex
43
43
 
44
44
  Usage:
45
45
  holycodex install [options]
46
46
  holycodex remove [options]
47
47
  holycodex upgrade [options]
48
48
  holycodex doctor [options]
49
- holycodex version [<0.x.y|patch|minor>] [options]
49
+ holycodex version [<0.x.y[-n]|patch|minor>] [options]
50
50
 
51
51
  Options:
52
52
  --help, -h Show this help.
@@ -54,7 +54,7 @@ Options:
54
54
  --json Emit one validated JSON envelope.
55
55
 
56
56
  Use --json for scripts. Install and remove use native Codex plugin management.
57
- `,EH=`Install HolyCodex through Codex native plugin management.
57
+ `,CH=`Install HolyCodex through Codex native plugin management.
58
58
 
59
59
  Usage:
60
60
  holycodex install [options]
@@ -71,7 +71,7 @@ Tier is independent service handling (CLI values are lowercase only):
71
71
  fast-all Fast service handling for Root and leaves.
72
72
 
73
73
  Options:
74
- ${VS.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
74
+ ${BS.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
75
75
  `)}
76
76
  --no-frontend / --no-security / --no-computer-use
77
77
  Disable the corresponding plugin.
@@ -83,18 +83,18 @@ On an interactive TTY, install opens one wizard and final review with Install,
83
83
  Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
84
84
  Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
85
85
  remains repeatable on the command line.
86
- `,OH=`Remove HolyCodex-owned state through Codex native plugin management.
86
+ `,kH=`Remove HolyCodex-owned state through Codex native plugin management.
87
87
 
88
88
  Usage:
89
89
  holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
90
90
 
91
91
  Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
92
92
  configuration are preserved; changed owned files are preserved for review.
93
- `,RH=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
93
+ `,AH=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
94
94
 
95
95
  Usage:
96
96
  holycodex doctor [--json] [--codex-home <absolute-path>]
97
- `,CH=`Migrate an existing HolyCodex installation in place.
97
+ `,IH=`Migrate an existing HolyCodex installation in place.
98
98
 
99
99
  Usage:
100
100
  holycodex upgrade [--dry-run] [--yes] [--json] [--codex-home <absolute-path>]
@@ -102,37 +102,37 @@ Usage:
102
102
  Upgrade preserves your selected profile, service tier, capabilities, additional
103
103
  plugins, and unrelated Codex configuration while applying the running version.
104
104
  Use --dry-run to preview changes. It does not download or install a new binary.
105
- `,kH=`Read or update the canonical public package version.
105
+ `,PH=`Read or update the canonical public package version.
106
106
 
107
107
  Usage:
108
- holycodex version [<0.x.y|patch|minor>] [--dry-run] [--json]
108
+ holycodex version [<0.x.y[-n]|patch|minor>] [--dry-run] [--json]
109
109
  holycodex --version
110
110
  holycodex -v
111
- `;function Fl(e){switch(e){case"install":return EH;case"remove":return OH;case"doctor":return RH;case"upgrade":return CH;case"version":return kH;default:return TH}}function zS(e,t={}){let n=ra({...t,stream:"stdout"});return Fl(e).split(`
111
+ `;function Fl(e){switch(e){case"install":return CH;case"remove":return kH;case"doctor":return AH;case"upgrade":return IH;case"version":return PH;default:return OH}}function VS(e,t={}){let n=Rs({...t,stream:"stdout"});return Fl(e).split(`
112
112
  `).map((r)=>{if(r==="HolyCodex")return ht(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return ht(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>ht(o,"option",n)).replace(/<[^>]+>/gu,(o)=>ht(o,"argument",n))}).join(`
113
- `)}function Ll(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function Dl(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 ra(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}function ht(e,t,n){if(!n)return e;return`\x1B[${{heading:"1",option:"36",argument:"2",focus:"1;36",enabled:"32",disabled:"2",success:"32",warning:"33",error:"31",hint:"2"}[t]}m${e}\x1B[0m`}st();mu();var yB=["low","default","high"],xB=["standard","fast","fast-all"],ba=["frontend","security","computer_use"];async function v_(e={},t={}){let n=kr(e),r=await import("@opentui/core"),o=T_(n),i=await r.createCliRenderer({...t,exitOnCtrlC:!0,clearOnShutdown:!0}),a=ra({stdoutIsTTY:!0,env:process.env,stream:"stdout"}),s=new r.TextRenderable(i,{content:HM(o,0,a)});return i.root.add(s),await new Promise((c,l)=>{let u=0,p=!1,f=0,h=!1,m=(b)=>{if(h)return;h=!0,i.keyInput.off("keypress",w),i.destroy(),c(b)},S=(b)=>{if(h)return;h=!0,i.keyInput.off("keypress",w),i.destroy(),l(b)},E=()=>{s.content=p?KM(o,f,a):HM(o,u,a),i.requestRender()},w=(b)=>{try{let g=b.name.toLowerCase();if(b.ctrl===!0&&g==="c"){m({action:"cancel"});return}if(p){if(g==="escape"){p=!1,E();return}if(g==="up"||g==="k")f=(f+2)%3;else if(g==="down"||g==="j")f=(f+1)%3;else if(g==="return"||g==="enter"||g==="linefeed"){if(f===0)m({action:"install",request:VM(o)});else if(f===1)p=!1,u=0;else m({action:"cancel"});return}E();return}let O=BM(o,u,b);if(u=O.cursor,O.action==="cancel"){m({action:"cancel"});return}if(O.action==="review")p=!0,f=0;E()}catch(g){S(g)}};i.keyInput.on("keypress",w);try{i.start()}catch(b){S(b)}})}function BM(e,t,n){let r=n.name.toLowerCase(),o=ba.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=zM(e.pluginInput),{cursor:t,action:"review"};if(t===o){if(r==="backspace")UM(e,-1);else if(r==="delete")UM(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")qM(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!TB(n.name))qM(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)bB(e,t-2);else if(r==="left")DM(e,t,-1);else if(r==="right")DM(e,t,1);return{cursor:t,action:"render"}}function VM(e){let t=e.plugins.length>0?{profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]}:{profile:e.profile,tier:e.tier,optional:{...e.optional}};return kr(t)}function SB(e,t="install",n={}){let r=T_(kr(e));return KM(r,t==="install"?0:t==="change"?1:2,ra({...n,stream:"stdout"}))}function T_(e){let t={...oo,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{computer_use:t.computer_use??oo.computer_use,frontend:t.frontend??oo.frontend,security:t.security??oo.security},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function DM(e,t,n){if(t===0)e.profile=$M(yB,e.profile,n);else if(t===1)e.tier=$M(xB,e.tier,n)}function bB(e,t){let n=ba[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function qM(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function UM(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 $M(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function zM(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return kr({officialPlugins:t}),t}function HM(e,t,n){let r=t<2?t===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":t<ba.length+2?wB(ba[t-2]):"Optional plugin IDs separated by spaces. Enter continues to review.";return`${[ht("HolyCodex \xB7 install","heading",n),ht("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint",n),"",ht("PROFILE","heading",n),jM("Profile",e.profile,t===0,n),jM("Service tier",e.tier,t===1,n),"",ht("OPTIONAL CAPABILITIES","heading",n),...ba.map((i,a)=>_B(i,e.optional[i],t===a+2,n)),"",ht("ADDITIONAL PLUGINS","heading",n),...WM(`${t===ba.length+2?"\u276F":" "} ${e.pluginInput||"(none)"}`),"",ht(r,"hint",n)].join(`
113
+ `)}function Ll(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function Dl(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 Rs(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}function ht(e,t,n){if(!n)return e;return`\x1B[${{heading:"1",option:"36",argument:"2",focus:"1;36",enabled:"32",disabled:"2",success:"32",warning:"33",error:"31",hint:"2"}[t]}m${e}\x1B[0m`}st();mu();var _B=["low","default","high"],wB=["standard","fast","fast-all"],Sa=["frontend","security","computer_use"];async function v_(e={},t={}){let n=Ar(e),r=await import("@opentui/core"),o=T_(n),i=await r.createCliRenderer({...t,exitOnCtrlC:!0,clearOnShutdown:!0}),a=!1,s=new r.TextRenderable(i,{content:jM(o,0,!1)});return i.root.add(s),await new Promise((c,l)=>{let u=0,p=!1,f=0,h=!1,m=(b)=>{if(h)return;h=!0,i.keyInput.off("keypress",v),i.destroy(),c(b)},S=(b)=>{if(h)return;h=!0,i.keyInput.off("keypress",v),i.destroy(),l(b)},E=()=>{s.content=p?KM(o,f,!1):jM(o,u,!1),i.requestRender()},v=(b)=>{try{let g=b.name.toLowerCase();if(b.ctrl===!0&&g==="c"){m({action:"cancel"});return}if(p){if(g==="escape"){p=!1,E();return}if(g==="up"||g==="k")f=(f+2)%3;else if(g==="down"||g==="j")f=(f+1)%3;else if(g==="return"||g==="enter"||g==="linefeed"){if(f===0)m({action:"install",request:zM(o)});else if(f===1)p=!1,u=0;else m({action:"cancel"});return}E();return}let R=VM(o,u,b);if(u=R.cursor,R.action==="cancel"){m({action:"cancel"});return}if(R.action==="review")p=!0,f=0;E()}catch(g){S(g)}};i.keyInput.on("keypress",v);try{i.start()}catch(b){S(b)}})}function VM(e,t,n){let r=n.name.toLowerCase(),o=Sa.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=WM(e.pluginInput),{cursor:t,action:"review"};if(t===o){if(r==="backspace")$M(e,-1);else if(r==="delete")$M(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")UM(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!CB(n.name))UM(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)TB(e,t-2);else if(r==="left")qM(e,t,-1);else if(r==="right")qM(e,t,1);return{cursor:t,action:"render"}}function zM(e){let t=e.plugins.length>0?{profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]}:{profile:e.profile,tier:e.tier,optional:{...e.optional}};return Ar(t)}function vB(e,t="install",n={}){let r=T_(Ar(e));return KM(r,t==="install"?0:t==="change"?1:2,Rs({...n,stream:"stdout"}))}function T_(e){let t={...io,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{computer_use:t.computer_use??io.computer_use,frontend:t.frontend??io.frontend,security:t.security??io.security},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function qM(e,t,n){if(t===0)e.profile=HM(_B,e.profile,n);else if(t===1)e.tier=HM(wB,e.tier,n)}function TB(e,t){let n=Sa[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function UM(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function $M(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 HM(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function WM(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return Ar({officialPlugins:t}),t}function jM(e,t,n){let r=t<2?t===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":t<Sa.length+2?RB(Sa[t-2]):"Optional plugin IDs separated by spaces. Enter continues to review.";return`${[ht("HolyCodex \xB7 install","heading",n),ht("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint",n),"",ht("PROFILE","heading",n),BM("Profile",e.profile,t===0,n),BM("Service tier",e.tier,t===1,n),"",ht("OPTIONAL CAPABILITIES","heading",n),...Sa.map((i,a)=>EB(i,e.optional[i],t===a+2,n)),"",ht("ADDITIONAL PLUGINS","heading",n),...JM(`${t===Sa.length+2?"\u276F":" "} ${e.pluginInput||"(none)"}`),"",ht(r,"hint",n)].join(`
114
114
  `)}
115
- `}function jM(e,t,n,r){let o=`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`;return ht(o,n?"focus":"argument",r)}function _B(e,t,n,r){let o=t?"[x] enabled":"[ ] disabled",i=`${n?"\u276F":" "} ${JM(e).padEnd(14)} ${o}`;return ht(i,n?"focus":t?"enabled":"disabled",r)}function KM(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[ht("HolyCodex \xB7 review","heading",n),ht("Review configuration","heading",n),ht("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",ht("CAPABILITIES","heading",n),...ba.map((i)=>` ${JM(i)}: ${ht(vB(e.optional[i]),e.optional[i]?"enabled":"disabled",n)}`),...WM(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((i,a)=>ht(`${a===t?"\u203A":" "} ${i}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
115
+ `}function BM(e,t,n,r){let o=`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`;return ht(o,n?"focus":"argument",r)}function EB(e,t,n,r){let o=t?"[x] enabled":"[ ] disabled",i=`${n?"\u276F":" "} ${GM(e).padEnd(14)} ${o}`;return ht(i,n?"focus":t?"enabled":"disabled",r)}function KM(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[ht("HolyCodex \xB7 review","heading",n),ht("Review configuration","heading",n),ht("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",ht("CAPABILITIES","heading",n),...Sa.map((i)=>` ${GM(i)}: ${ht(OB(e.optional[i]),e.optional[i]?"enabled":"disabled",n)}`),...JM(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((i,a)=>ht(`${a===t?"\u203A":" "} ${i}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
116
116
  `)}
117
- `}function wB(e){switch(e){case"frontend":return"Frontend tools for building and testing web experiences.";case"security":return"Security review and vulnerability analysis tools.";case"computer_use":return"Computer Use tools for interactive GUI and browser tasks."}}function WM(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 JM(e){return e==="computer_use"?"Computer Use":`${e[0].toUpperCase()}${e.slice(1)}`}function vB(e){return e?"enabled":"disabled"}function TB(e){let t=e.codePointAt(0)??0;return t<=31||t===127}mu();Ql();pm();iu();lu();la();Ds();async function O_(e,t={}){if(Ll(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:Dl(e);return{envelope:GM(r===void 0?"help":`${r} help`,{help:Fl(r)}),exitCode:0}}let n;try{n=Rf(e);let r=await YM(n,t);return{envelope:GM(n.command,r),exitCode:LB(n.command,r)}}catch(r){return FB(n?.command??qB(e),r)}}async function YM(e,t){switch(e.command){case"install":return fn(await EB(e,t));case"doctor":return fn(await m_(Ks(e,t),t.env));case"remove":return fn(await CB(e,t));case"upgrade":return fn(await kB(e,t));case"version":return fn(await AB(e,t));case"help":return{help:Fl(e.positionals[0])};default:throw new va("invalid_argument","Unknown command.")}}async function EB(e,t){let n=RB(e),r=await OB(e,t,n);if("cancelled"in r)return r;return await js(r,Ks(e,t),t.env)}async function OB(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await(t.io?.installWizard??v_)(n);if(i.action==="cancel")return{cancelled:!0};return kr(i.request)}let o=await R_(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new va("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return kr(n)}function RB(e){let t=PB(e),n=MB(e),r=IB(e),o=NB(e,"add-plugin");return kr({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o.length===0?{}:{officialPlugins:o}})}async function CB(e,t){let n=await R_(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let o=(await h_(Ks(e,t),t.env))[0];if(o!==void 0)throw new M("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 va("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.")}return await fu(Ks(e,t),t.env)}async function kB(e,t){let n=e.options["dry-run"]===!0;if(!n){let r=await R_(e,t,"Upgrade the existing HolyCodex installation in place?");if(r==="cancelled")return{cancelled:!0,status:"cancelled",changes:[]};if(r==="unavailable"){let i=(await um(Ks(e,t),t.env,{dryRun:!0})).conflicts?.[0];if(i!==void 0)throw new M("confirmation_required","Modified HolyCodex-owned state requires confirmation before upgrade.",void 0,{path:i.path,...i.key===void 0?{}:{key:i.key},action:i.action});throw new va("non_tty_confirmation_required","Upgrade requires --yes in non-interactive mode.")}}return await um(Ks(e,t),t.env,{dryRun:n})}async function AB(e,t){let n=e.positionals[0];if(!n)return{version:await Qf()};return await n_(n,e.options["dry-run"]===!0)}async function R_(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 ZM(t,n)}async function ZM(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 IB(e){let t={};for(let n of["computer_use","frontend","security"]){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 PB(e){let t=e.options.profile;if(typeof t!=="string")return;let n=wr(t);return n.ok?n.value.name:void 0}function MB(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function NB(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Ks(e,t){let n=t.installer??{},r=e.options.json===!0,o=(s)=>{n.onProgress?.(s),t.onProgress?.(s),UB(t,r,s.message)},i=n.resolveConflict??(e.options.yes===!0?async()=>"accept":async(s)=>{let c=s.key===void 0?s.path:`${s.path} (${s.key})`,l=await ZM(t,`${s.action==="remove"?"Remove":"Replace"} modified HolyCodex-owned state at ${c}?`);return l==="confirmed"?"accept":l==="cancelled"?"decline":"cancel"}),a=e.options["codex-home"];if(typeof a!=="string")return{...n,onProgress:o,resolveConflict:i,...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:a},onProgress:o,resolveConflict:i,...t.now?{now:t.now}:{}}}function GM(e,t){let n=Ef({schema_version:Pr,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new va("internal_error","The success envelope failed validation.");return n.value}function FB(e,t){let n=DB(t),r=Ef({schema_version:Pr,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:Pr,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 LB(e,t){return e==="doctor"&&or(t)&&t.healthy===!1?4:0}function DB(e){if(e instanceof Ke)return{code:e.code,message:_a(e.message),details:e.details,exitCode:1};if(e instanceof va)return{code:e.code,message:_a(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof An)return{code:"trust_boundary_failed",message:_a(e.message),details:{},exitCode:4};if(e instanceof M){let t=e.code==="confirmation_required"?1:e.code==="capability_denied"?2:e.code==="state_corrupt"?4:3;return{code:e.code,message:_a(e.message),details:e.details,exitCode:t}}if(e instanceof Cr){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:_a(e.message),details:e.details,exitCode:t?4:n?2:3}}if(e instanceof ua)return{code:e.code,message:_a(e.message),details:{},exitCode:4};if(e instanceof ou)return{code:e.code,message:_a(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 qB(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function _a(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 or(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function UB(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${XM(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
118
- `)}function hm(e,t={}){let n=ra(t);if(e.envelope.ok){if(e.envelope.command==="version")return $B(e.envelope.data);if(e.envelope.command==="install")return HB(e.envelope.data,n);if(e.envelope.command==="remove")return jB(e.envelope.data,n);if(e.envelope.command==="upgrade")return BB(e.envelope.data,n);if(e.envelope.command==="doctor")return VB(e.envelope.data,n);return`${se("\u2714","green",n)} ${se(e.envelope.command,"heading",n)}
119
- ${zB(e.envelope.data,n)}`}let r=e.envelope.error,o=WB(r.code,e.envelope.command);return[`${se("\u2716","red",n)} ${se(e.envelope.command,"heading",n)}`,` ${se(r.code,"red",n)}: ${r.message}`,...KB(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
120
- `)}function XM(e,t={}){return`${se("\u2022","cyan",ra({...t,stream:"stderr"}))} ${e}`}function $B(e){if(or(e)&&typeof e.version==="string")return`holycodex ${e.version}
117
+ `}function RB(e){switch(e){case"frontend":return"Frontend tools for building and testing web experiences.";case"security":return"Security review and vulnerability analysis tools.";case"computer_use":return"Computer Use tools for interactive GUI and browser tasks."}}function JM(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 GM(e){return e==="computer_use"?"Computer Use":`${e[0].toUpperCase()}${e.slice(1)}`}function OB(e){return e?"enabled":"disabled"}function CB(e){let t=e.codePointAt(0)??0;return t<=31||t===127}mu();Ql();um();iu();lu();ca();Ds();async function R_(e,t={}){if(e.length===0||Ll(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:Dl(e);return{envelope:YM(r===void 0?"help":`${r} help`,{help:Fl(r)}),exitCode:0}}let n;try{n=Of(e);let r=await ZM(n,t);return{envelope:YM(n.command,r),exitCode:$B(n.command,r)}}catch(r){return UB(n?.command??jB(e),r)}}async function ZM(e,t){switch(e.command){case"install":return fn(await kB(e,t));case"doctor":return fn(await m_(Ws(e,t),t.env));case"remove":return fn(await PB(e,t));case"upgrade":return fn(await MB(e,t));case"version":return fn(await NB(e,t));case"help":return{help:Fl(e.positionals[0])};default:throw new wa("invalid_argument","Unknown command.")}}async function kB(e,t){let n=IB(e),r=await AB(e,t,n);if("cancelled"in r)return r;return await js(r,Ws(e,t),t.env)}async function AB(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await(t.io?.installWizard??v_)(n);if(i.action==="cancel")return{cancelled:!0};return Ar(i.request)}let o=await O_(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new wa("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return Ar(n)}function IB(e){let t=LB(e),n=DB(e),r=FB(e),o=qB(e,"add-plugin");return Ar({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o.length===0?{}:{officialPlugins:o}})}async function PB(e,t){let n=await O_(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let o=(await h_(Ws(e,t),t.env))[0];if(o!==void 0)throw new M("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 wa("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.")}return await fu(Ws(e,t),t.env)}async function MB(e,t){let n=e.options["dry-run"]===!0;if(!n){let r=await O_(e,t,"Upgrade the existing HolyCodex installation in place?");if(r==="cancelled")return{cancelled:!0,status:"cancelled",changes:[]};if(r==="unavailable"){let i=(await lm(Ws(e,t),t.env,{dryRun:!0})).conflicts?.[0];if(i!==void 0)throw new M("confirmation_required","Modified HolyCodex-owned state requires confirmation before upgrade.",void 0,{path:i.path,...i.key===void 0?{}:{key:i.key},action:i.action});throw new wa("non_tty_confirmation_required","Upgrade requires --yes in non-interactive mode.")}}return await lm(Ws(e,t),t.env,{dryRun:n})}async function NB(e,t){let n=e.positionals[0];if(!n)return{version:await Xf()};return await n_(n,e.options["dry-run"]===!0)}async function O_(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 XM(t,n)}async function XM(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 FB(e){let t={};for(let n of["computer_use","frontend","security"]){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 LB(e){let t=e.options.profile;if(typeof t!=="string")return;let n=vr(t);return n.ok?n.value.name:void 0}function DB(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function qB(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Ws(e,t){let n=t.installer??{},r=e.options.json===!0,o=(s)=>{n.onProgress?.(s),t.onProgress?.(s),BB(t,r,s.message)},i=n.resolveConflict??(e.options.yes===!0?async()=>"accept":async(s)=>{let c=s.key===void 0?s.path:`${s.path} (${s.key})`,l=await XM(t,`${s.action==="remove"?"Remove":"Replace"} modified HolyCodex-owned state at ${c}?`);return l==="confirmed"?"accept":l==="cancelled"?"decline":"cancel"}),a=e.options["codex-home"];if(typeof a!=="string")return{...n,onProgress:o,resolveConflict:i,...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:a},onProgress:o,resolveConflict:i,...t.now?{now:t.now}:{}}}function YM(e,t){let n=Ef({schema_version:Mr,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new wa("internal_error","The success envelope failed validation.");return n.value}function UB(e,t){let n=HB(t),r=Ef({schema_version:Mr,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:Mr,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 $B(e,t){return e==="doctor"&&or(t)&&t.healthy===!1?4:0}function HB(e){if(e instanceof We)return{code:e.code,message:ba(e.message),details:e.details,exitCode:1};if(e instanceof wa)return{code:e.code,message:ba(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof An)return{code:"trust_boundary_failed",message:ba(e.message),details:{},exitCode:4};if(e instanceof M){let t=e.code==="confirmation_required"?1:e.code==="capability_denied"?2:e.code==="state_corrupt"?4:3;return{code:e.code,message:ba(e.message),details:e.details,exitCode:t}}if(e instanceof kr){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:ba(e.message),details:e.details,exitCode:t?4:n?2:3}}if(e instanceof la)return{code:e.code,message:ba(e.message),details:{},exitCode:4};if(e instanceof ou)return{code:e.code,message:ba(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 jB(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function ba(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 or(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function BB(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${QM(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
118
+ `)}function mm(e,t={}){let n=Rs(t);if(e.envelope.ok){if(e.envelope.command==="version")return VB(e.envelope.data);if(e.envelope.command==="install")return zB(e.envelope.data,n);if(e.envelope.command==="remove")return WB(e.envelope.data,n);if(e.envelope.command==="upgrade")return KB(e.envelope.data,n);if(e.envelope.command==="doctor")return JB(e.envelope.data,n);return`${se("\u2714","green",n)} ${se(e.envelope.command,"heading",n)}
119
+ ${GB(e.envelope.data,n)}`}let r=e.envelope.error,o=ZB(r.code,e.envelope.command);return[`${se("\u2716","red",n)} ${se(e.envelope.command,"heading",n)}`,` ${se(r.code,"red",n)}: ${r.message}`,...YB(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
120
+ `)}function QM(e,t={}){return`${se("\u2022","cyan",Rs({...t,stream:"stderr"}))} ${e}`}function VB(e){if(or(e)&&typeof e.version==="string")return`holycodex ${e.version}
121
121
  `;if(or(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
122
122
  `}return`holycodex version completed
123
- `}function HB(e,t){if(gm(e,"cancelled")===!0)return`${se("\u21A9","cyan",t)} ${se("install","heading",t)} cancelled
124
- `;let n=Su(e,"record"),r=li(n,"version")??"unknown",o=li(n,"profile")??"unknown",i=li(n,"tier")??"unknown",a=Su(n,"optional_selections"),s=Su(n,"capability_state"),c=["frontend","security","computer_use"].filter((m)=>a?.[m]===!0).map((m)=>{let S=li(Su(s,m),"status");return S===void 0||S==="healthy"?m:`${m} (${S})`}),l=wa(e,"preserved"),u=wa(e,"warnings"),p=c.length===0?"none":c.join(", "),f=l.length===0?"none":`${l.length} managed item${l.length===1?"":"s"} (review before retrying)`;return`${[`${se("\u2714","green",t)} ${se("install","heading",t)}`,` ${se("version","option",t)}: ${r}`,` ${se("profile","option",t)}: ${o}`,` ${se("tier","option",t)}: ${i}`,` ${se("capabilities","option",t)}: ${p}`,` ${se("preserved","option",t)}: ${f}`,...u.map((m)=>` ${se("warning","red",t)}: ${ym(m)}`)].join(`
123
+ `}function zB(e,t){if(hm(e,"cancelled")===!0)return`${se("\u21A9","cyan",t)} ${se("install","heading",t)} cancelled
124
+ `;let n=Su(e,"record"),r=ui(n,"version")??"unknown",o=ui(n,"profile")??"unknown",i=ui(n,"tier")??"unknown",a=Su(n,"optional_selections"),s=Su(n,"capability_state"),c=["frontend","security","computer_use"].filter((m)=>a?.[m]===!0).map((m)=>{let S=ui(Su(s,m),"status");return S===void 0||S==="healthy"?m:`${m} (${S})`}),l=_a(e,"preserved"),u=_a(e,"warnings"),p=c.length===0?"none":c.join(", "),f=l.length===0?"none":`${l.length} managed item${l.length===1?"":"s"} (review before retrying)`;return`${[`${se("\u2714","green",t)} ${se("install","heading",t)}`,` ${se("version","option",t)}: ${r}`,` ${se("profile","option",t)}: ${o}`,` ${se("tier","option",t)}: ${i}`,` ${se("capabilities","option",t)}: ${p}`,` ${se("preserved","option",t)}: ${f}`,...u.map((m)=>` ${se("warning","red",t)}: ${gm(m)}`)].join(`
125
125
  `)}
126
- `}function jB(e,t){if(gm(e,"cancelled")===!0)return`${se("\u21A9","cyan",t)} ${se("remove","heading",t)} cancelled
127
- `;let n=wa(e,"removed"),r=wa(e,"preserved"),o=wa(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`;return`${[`${se("\u2714","green",t)} ${se("remove","heading",t)}`,` ${se("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${se("preserved","option",t)}: ${i}`,...o.map((s)=>` ${se("reason","option",t)}: ${ym(s)}`)].join(`
126
+ `}function WB(e,t){if(hm(e,"cancelled")===!0)return`${se("\u21A9","cyan",t)} ${se("remove","heading",t)} cancelled
127
+ `;let n=_a(e,"removed"),r=_a(e,"preserved"),o=_a(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`;return`${[`${se("\u2714","green",t)} ${se("remove","heading",t)}`,` ${se("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${se("preserved","option",t)}: ${i}`,...o.map((s)=>` ${se("reason","option",t)}: ${gm(s)}`)].join(`
128
128
  `)}
129
- `}function BB(e,t){if(gm(e,"cancelled")===!0)return`${se("\u21A9","cyan",t)} ${se("upgrade","heading",t)} cancelled
130
- `;let n=li(or(e)?e:void 0,"status")??"completed",r=li(or(e)?e:void 0,"from_version"),o=li(or(e)?e:void 0,"to_version"),i=wa(e,"changes"),a=r!==void 0&&o!==void 0?` (${r} \u2192 ${o})`:"";return`${[`${se("\u2714","green",t)} ${se("upgrade","heading",t)}${a}`,` ${se("status","option",t)}: ${n}`,` ${se("changes","option",t)}: ${i.length===0?"none":i.map(ym).join(", ")}`].join(`
129
+ `}function KB(e,t){if(hm(e,"cancelled")===!0)return`${se("\u21A9","cyan",t)} ${se("upgrade","heading",t)} cancelled
130
+ `;let n=ui(or(e)?e:void 0,"status")??"completed",r=ui(or(e)?e:void 0,"from_version"),o=ui(or(e)?e:void 0,"to_version"),i=_a(e,"changes"),a=r!==void 0&&o!==void 0?` (${r} \u2192 ${o})`:"";return`${[`${se("\u2714","green",t)} ${se("upgrade","heading",t)}${a}`,` ${se("status","option",t)}: ${n}`,` ${se("changes","option",t)}: ${i.length===0?"none":i.map(gm).join(", ")}`].join(`
131
131
  `)}
132
- `}function VB(e,t){let n=gm(e,"healthy")===!0,r=Su(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=or(l)?l:void 0,p=li(u,"status");if(p===void 0||p==="healthy")return[];let f=wa(u,"reasons");return[` ${se(c,"option",t)}: ${f.length===0?p:f.map(ym).join(", ")}`]});return`${[`${n?se("\u2714","green",t):se("\u2716","red",t)} ${se("doctor","heading",t)}`,` ${se("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${se("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${se("issues","option",t)}:`,...i]].join(`
132
+ `}function JB(e,t){let n=hm(e,"healthy")===!0,r=Su(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=or(l)?l:void 0,p=ui(u,"status");if(p===void 0||p==="healthy")return[];let f=_a(u,"reasons");return[` ${se(c,"option",t)}: ${f.length===0?p:f.map(gm).join(", ")}`]});return`${[`${n?se("\u2714","green",t):se("\u2716","red",t)} ${se("doctor","heading",t)}`,` ${se("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${se("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${se("issues","option",t)}:`,...i]].join(`
133
133
  `)}
134
- `}function Su(e,t){if(!or(e))return;return or(e[t])?e[t]:void 0}function gm(e,t){return or(e)?e[t]:void 0}function li(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function wa(e,t){if(!or(e)||!Array.isArray(e[t]))return[];return e[t]}function ym(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function zB(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${se(E_(e),"dim",t)}
134
+ `}function Su(e,t){if(!or(e))return;return or(e[t])?e[t]:void 0}function hm(e,t){return or(e)?e[t]:void 0}function ui(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function _a(e,t){if(!or(e)||!Array.isArray(e[t]))return[];return e[t]}function gm(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function GB(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${se(E_(e),"dim",t)}
135
135
  `;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([o])=>o.length));return`${n.map(([o,i])=>` ${se(o.padEnd(r),"option",t)}: ${E_(i)}`).join(`
136
136
  `)}
137
- `}function KB(e,t){return Object.entries(e).map(([n,r])=>` ${se(n,"option",t)}: ${se(E_(r),"dim",t)}`)}function E_(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function WB(e,t){if(e==="invalid_argument"||e==="unknown_command")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 se(e,t,n){if(!n)return e;return`\x1B[${{red:"31",green:"32",cyan:"36",dim:"2",heading:"1",option:"36"}[t]}m${e}\x1B[0m`}class va extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function C_(e=Bun.argv.slice(2),t=GB()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??YB(),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 O_(e,n);if((Ll(e)||e[0]==="help")&&!QM(e))n.io?.writeStdout?.(zS(Dl(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(QM(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
138
- `);else if(r.envelope.ok)n.io?.writeStdout?.(hm(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(hm(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function GB(){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=JB({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 QM(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*YB(){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}mu();pm();iu();la();lu();cm();im();var x9="holycodex";if(import.meta.main)process.exitCode=await C_();export{Ke as ArgumentError,fa as CONTEXT7_SPEC,Ns as CapabilityInstallStateSchema,Xf as CapabilityStateRecordSchema,si as CodexOfficialPluginManager,Zf as InstallOptionsSchema,Fs as InstallRecordSchema,tu as InstallRequestSchema,M as InstallerError,Cr as OfficialPluginManagerError,An as PathBoundaryError,r1 as STATE_SCHEMA,_t as ToolingError,ma as WINDOWS_GIT_BASH,BM as applyWizardConfigurationKey,t_ as assertRootText,gM as context7InstallCommand,ha as createInstallerRuntime,u_ as detectContext7Manager,m_ as doctorHolyCodex,Hs as ensureContext7,ga as ensureGitBash,YM as executeCommand,Ll as helpRequested,Fl as helpText,Dl as helpTopic,js as installHolyCodex,i_ as installNativeAgents,mm as installRecordDigest,x9 as packageName,Rf as parseArgv,zM as parsePluginInput,so as pathWithin,ai as projectNativeAgents,r_ as projectRootAgent,ru as publicManifestPath,Sa as readActiveInstallRecord,qs as readCanonicalBaseVersion,Qf as readCanonicalVersion,fu as removeHolyCodex,om as removeManagedNativeAgents,p_ as removeOwnedContext7,zS as renderHelp,hm as renderHuman,SB as renderInstallWizardReview,au as renderNativeAgent,XM as renderProgress,ii as resolveInstallerPaths,rm as rollbackNativeAgentInstall,o_ as rootDeveloperInstructions,C_ as runBinary,O_ as runCli,v_ as runOpenTuiInstallWizard,T_ as stateFromRequest,VM as toInstallOptions,n_ as updateCanonicalVersion,um as upgradeHolyCodex,kr as validateInstallOptions,a_ as windowsGitBashShellDirective};
137
+ `}function YB(e,t){return Object.entries(e).map(([n,r])=>` ${se(n,"option",t)}: ${se(E_(r),"dim",t)}`)}function E_(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function ZB(e,t){if(e==="invalid_argument"||e==="unknown_command")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 se(e,t,n){if(!n)return e;return`\x1B[${{red:"31",green:"32",cyan:"36",dim:"2",heading:"1",option:"36"}[t]}m${e}\x1B[0m`}class wa extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function C_(e=Bun.argv.slice(2),t=QB()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??eV(),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 R_(e,n);if((e.length===0||Ll(e)||e[0]==="help")&&!eN(e))n.io?.writeStdout?.(VS(Dl(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(eN(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
138
+ `);else if(r.envelope.ok)n.io?.writeStdout?.(mm(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(mm(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function QB(){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=XB({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 eN(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*eV(){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}mu();um();iu();ca();lu();sm();om();var vZ="holycodex";if(import.meta.main)process.exitCode=await C_();export{We as ArgumentError,da as CONTEXT7_SPEC,Ns as CapabilityInstallStateSchema,Zf as CapabilityStateRecordSchema,ci as CodexOfficialPluginManager,Yf as InstallOptionsSchema,Fs as InstallRecordSchema,tu as InstallRequestSchema,M as InstallerError,kr as OfficialPluginManagerError,An as PathBoundaryError,a1 as STATE_SCHEMA,_t as ToolingError,fa as WINDOWS_GIT_BASH,VM as applyWizardConfigurationKey,t_ as assertRootText,yM as context7InstallCommand,ma as createInstallerRuntime,u_ as detectContext7Manager,m_ as doctorHolyCodex,Hs as ensureContext7,ha as ensureGitBash,ZM as executeCommand,Ll as helpRequested,Fl as helpText,Dl as helpTopic,js as installHolyCodex,i_ as installNativeAgents,fm as installRecordDigest,vZ as packageName,Of as parseArgv,WM as parsePluginInput,co as pathWithin,si as projectNativeAgents,r_ as projectRootAgent,ru as publicManifestPath,xa as readActiveInstallRecord,qs as readCanonicalBaseVersion,Xf as readCanonicalVersion,fu as removeHolyCodex,rm as removeManagedNativeAgents,p_ as removeOwnedContext7,VS as renderHelp,mm as renderHuman,vB as renderInstallWizardReview,au as renderNativeAgent,QM as renderProgress,ai as resolveInstallerPaths,nm as rollbackNativeAgentInstall,o_ as rootDeveloperInstructions,C_ as runBinary,R_ as runCli,v_ as runOpenTuiInstallWizard,T_ as stateFromRequest,zM as toInstallOptions,n_ as updateCanonicalVersion,lm as upgradeHolyCodex,Ar as validateInstallOptions,a_ as windowsGitBashShellDirective};