holycodex 0.16.4-dev.77.1 → 0.16.4

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.
Files changed (37) hide show
  1. package/README.md +0 -5
  2. package/dist/agent.js +38 -52
  3. package/dist/assets/plugin/plugin.json +1 -1
  4. package/dist/assets/plugin/skills/code-review/SKILL.md +24 -5
  5. package/dist/assets/plugin/skills/code-review/agents/openai.yaml +1 -1
  6. package/dist/assets/plugin/skills/commit/SKILL.md +12 -6
  7. package/dist/assets/plugin/skills/commit/agents/openai.yaml +1 -1
  8. package/dist/assets/plugin/skills/compress/SKILL.md +15 -4
  9. package/dist/assets/plugin/skills/compress/agents/openai.yaml +1 -1
  10. package/dist/assets/plugin/skills/context7-cli/SKILL.md +10 -4
  11. package/dist/assets/plugin/skills/context7-cli/agents/openai.yaml +1 -1
  12. package/dist/assets/plugin/skills/debugging/SKILL.md +23 -4
  13. package/dist/assets/plugin/skills/debugging/agents/openai.yaml +1 -1
  14. package/dist/assets/plugin/skills/handoff/SKILL.md +13 -4
  15. package/dist/assets/plugin/skills/handoff/agents/openai.yaml +1 -1
  16. package/dist/assets/plugin/skills/operations/SKILL.md +27 -7
  17. package/dist/assets/plugin/skills/operations/agents/openai.yaml +1 -1
  18. package/dist/assets/plugin/skills/plan/SKILL.md +21 -6
  19. package/dist/assets/plugin/skills/plan/agents/openai.yaml +1 -1
  20. package/dist/assets/plugin/skills/plan-review/SKILL.md +19 -5
  21. package/dist/assets/plugin/skills/plan-review/agents/openai.yaml +1 -1
  22. package/dist/assets/plugin/skills/programming/SKILL.md +18 -4
  23. package/dist/assets/plugin/skills/programming/agents/openai.yaml +1 -1
  24. package/dist/assets/plugin/skills/refactor/SKILL.md +18 -4
  25. package/dist/assets/plugin/skills/refactor/agents/openai.yaml +1 -1
  26. package/dist/assets/plugin/skills/rules/SKILL.md +15 -4
  27. package/dist/assets/plugin/skills/rules/agents/openai.yaml +1 -1
  28. package/dist/assets/plugin/skills/stop-slop/SKILL.md +42 -5
  29. package/dist/assets/plugin/skills/stop-slop/agents/openai.yaml +1 -1
  30. package/dist/assets/plugin/skills/testing-quality.md +26 -10
  31. package/dist/assets/plugin/skills/writing-for-agents/SKILL-MECHANICS.md +16 -6
  32. package/dist/assets/plugin/skills/writing-for-agents/SKILL.md +55 -29
  33. package/dist/assets/plugin/skills/writing-for-agents/agents/openai.yaml +1 -1
  34. package/dist/index.js +53 -69
  35. package/package.json +3 -3
  36. package/dist/assets/plugin/skills/grill-me/SKILL.md +0 -21
  37. package/dist/assets/plugin/skills/grill-me/agents/openai.yaml +0 -6
package/dist/index.js CHANGED
@@ -1,50 +1,49 @@
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 Yn(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&&Vf(r.value))Yn(r.value,t)}Object.freeze(e)}function Vf(e){return typeof e==="object"&&e!==null}var vr="0.15",Tn="state-0.16";var B_=()=>{};function Zi(e){return{ok:!0,value:e}}function Jo(e){return{ok:!1,error:e}}function ys(e,t){return new We("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var We;var Xi=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,Yn(this.details),Object.freeze(this)}}});function g(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 Bf=(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)}}}},ue=(e)=>e,xs=(e)=>()=>e,Ss,no,zl,_s;var j=x(()=>{Ss=xs(!0),no=xs(!1),zl=xs(void 0),_s=zl});var ws=(e)=>(t,n)=>t===n||e(t,n),XI=(e,t)=>e===t,QI=()=>XI,eM,Kf,K_,z_=(e)=>ws((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 vs=x(()=>{j();eM=QI(),Kf=d(2,(e,t)=>ws((n,r)=>e(t(n),t(r)))),K_=Kf(eM,(e)=>e.getTime())});var Ts,V=(e,t)=>{if(!Ts)globalThis["effect/GlobalValue"]??=new Map,Ts=globalThis["effect/GlobalValue"];if(!Ts.has(e))Ts.set(e,t());return Ts.get(e)};var gt=(e)=>typeof e==="string",Qt=(e)=>typeof e==="number",Go=(e)=>typeof e==="boolean",ro=(e)=>typeof e==="bigint",Yo=(e)=>typeof e==="symbol",oo,W_=(e)=>e===void 0,J_=(e)=>!1,Es=(e)=>typeof e==="object"&&e!==null,qt=(e)=>Es(e)||oo(e),C,Os,Zo=(e)=>e===null||e===void 0,G_=(e)=>e!==null&&e!==void 0,Jl=(e)=>e instanceof Date,zf=(e)=>typeof e==="string"||C(e,Symbol.iterator),Wf=(e)=>Es(e)&&!Array.isArray(e),Y_=(e)=>C(e,"then")&&oo(e.then);var ye=x(()=>{j();oo=Bf,C=d(2,(e,t)=>qt(e)&&(t in e)),Os=d(2,(e,t)=>C(e,"_tag")&&e._tag===t)});var Xo=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Gf{_state;constructor(e,t,n,r){if(Zo(t)&&Zo(e))t=Math.random()*4294967295>>>0,e=0;else if(Zo(t))t=e,e=0;if(Zo(r)&&Zo(n))r=this._state?this._state[3]:nM,n=this._state?this._state[2]:tM;else if(Zo(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),Z_(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*aM+t)/iM}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;sM(this._state,e,t,rM,oM),Z_(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 sM(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 Z_(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 Yf(e){if(typeof e==="object"&&e!==null&&Jf in e)return e[Jf]();throw Error(Xo("yieldWrapGet"))}var ea,tM=335903614,nM=4150755663,rM=1481765933,oM=1284865837,iM=9007199254740992,aM=134217728,Jf,Tr,$t,X_,cM,lM,yt,v1;var io=x(()=>{ye();ea=class ea{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 ea(this.self)}};Jf=Symbol.for("effect/Utils/YieldWrap");Tr=class Tr{#e;constructor(e){this.#e=e}[Jf](){return this.#e}};$t=V("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),X_={effect_internal_function:(e)=>e()},cM={effect_internal_function:(e)=>{try{return e()}finally{}}},lM=X_.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,yt=lM?X_.effect_internal_function:cM.effect_internal_function,v1=function*(){}.constructor});var Zf,M,E=(e)=>{if($t.enabled===!0)return 0;switch(typeof e){case"number":return Yl(e);case"bigint":return he(e.toString(10));case"boolean":return he(String(e));case"symbol":return he(String(e));case"string":return he(e);case"undefined":return he("undefined");case"function":case"object":if(e===null)return he("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return he("Invalid Date");return E(e.toISOString())}else if(e instanceof URL)return E(e.href);else if(pM(e))return e[M]();else return Rs(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},Rs=(e)=>{if(!Zf.has(e))Zf.set(e,Yl(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Zf.get(e)},G=(e)=>(t)=>t*53^e,Gl=(e)=>e&3221225471|e>>>1&1073741824,pM=(e)=>C(e,M),Yl=(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 Gl(t)},he=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Gl(t)},dM=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=g(he(t[r]),G(E(e[t[r]])));return Gl(n)},Zl=(e)=>dM(e,Object.keys(e)),en=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=g(t,G(E(e[n])));return Gl(t)},ie=function(){if(arguments.length===1){let n=arguments[0];return function(r){return Object.defineProperty(n,M,{value(){return r},enumerable:!1}),r}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,M,{value(){return t},enumerable:!1}),t};var Me=x(()=>{j();ye();io();Zf=V(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),M=Symbol.for("effect/Hash")});function O(){if(arguments.length===1)return(e)=>Xl(e,arguments[0]);return Xl(arguments[0],arguments[1])}function Xl(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(ks(e)&&ks(t))if(E(e)===E(t)&&e[I](t))return!0;else return $t.enabled&&$t.tester?$t.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($t.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>Xl(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)&&Xl(e[i],t[i])))return $t.tester?$t.tester(e,t):!1;return!0}}return $t.tester?$t.tester(e,t):!1}}return $t.enabled&&$t.tester?$t.tester(e,t):!1}var I,ks=(e)=>C(e,I),Cs=()=>O;var pe=x(()=>{Me();ye();io();I=Symbol.for("effect/Equal")});function fM(e){try{return e.toISOString()}catch{return"Invalid Date"}}function mM(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function As(e){return gt(e)?JSON.stringify(e):String(e)}function Zn(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":Qt(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 Xf;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,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};function zr(e,t=new WeakSet){if(t.has(e))return;t.add(e);for(let r of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,r);if(n&&"value"in n&&qf(n.value))zr(n.value,t)}Object.freeze(e)}function qf(e){return typeof e==="object"&&e!==null}var xn="0.15",Tr="state-0.16";var Lb=()=>{};function Ki(e){return{ok:!0,value:e}}function Ko(e){return{ok:!1,error:e}}function ps(e,t){return new Je("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var Je;var Wi=x(()=>{Je=class Je extends Error{code;details;constructor(e,t,r={},n){super(t,n);this.name="CoreError",this.code=e,this.details=r,zr(this.details),Object.freeze(this)}}});function g(e,t,r,n,o,i,a,s,c){switch(arguments.length){case 1:return e;case 2:return t(e);case 3:return r(t(e));case 4:return n(r(t(e)));case 5:return o(n(r(t(e))));case 6:return i(o(n(r(t(e)))));case 7:return a(i(o(n(r(t(e))))));case 8:return s(a(i(o(n(r(t(e)))))));case 9:return c(s(a(i(o(n(r(t(e))))))));default:{let l=arguments[0];for(let u=1;u<arguments.length;u++)l=arguments[u](l);return l}}}var Uf=(e)=>typeof e==="function",d=function(e,t){if(typeof e==="function")return function(){if(e(arguments))return t.apply(this,arguments);return(r)=>t(r,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(r,n){if(arguments.length>=2)return t(r,n);return function(o){return t(o,r)}};case 3:return function(r,n,o){if(arguments.length>=3)return t(r,n,o);return function(i){return t(i,r,n)}};case 4:return function(r,n,o,i){if(arguments.length>=4)return t(r,n,o,i);return function(a){return t(a,r,n,o)}};case 5:return function(r,n,o,i,a){if(arguments.length>=5)return t(r,n,o,i,a);return function(s){return t(s,r,n,o,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let r=arguments;return function(n){return t(n,...r)}}}},ce=(e)=>e,ds=(e)=>()=>e,fs,Qn,Dl,ms;var H=x(()=>{fs=ds(!0),Qn=ds(!1),Dl=ds(void 0),ms=Dl});var gs=(e)=>(t,r)=>t===r||e(t,r),HI=(e,t)=>e===t,$I=()=>HI,jI,Hf,Db,qb=(e)=>gs((t,r)=>{if(t.length!==r.length)return!1;for(let n=0;n<t.length;n++)if(!e(t[n],r[n]))return!1;return!0});var ys=x(()=>{H();jI=$I(),Hf=d(2,(e,t)=>gs((r,n)=>e(t(r),t(n)))),Db=Hf(jI,(e)=>e.getTime())});var xs,j=(e,t)=>{if(!xs)globalThis["effect/GlobalValue"]??=new Map,xs=globalThis["effect/GlobalValue"];if(!xs.has(e))xs.set(e,t());return xs.get(e)};var xt=(e)=>typeof e==="string",Xt=(e)=>typeof e==="number",Wo=(e)=>typeof e==="boolean",eo=(e)=>typeof e==="bigint",Jo=(e)=>typeof e==="symbol",to,Ub=(e)=>e===void 0,Hb=(e)=>!1,Ss=(e)=>typeof e==="object"&&e!==null,Dt=(e)=>Ss(e)||to(e),k,bs,Go=(e)=>e===null||e===void 0,$b=(e)=>e!==null&&e!==void 0,Ul=(e)=>e instanceof Date,$f=(e)=>typeof e==="string"||k(e,Symbol.iterator),jf=(e)=>Ss(e)&&!Array.isArray(e),jb=(e)=>k(e,"then")&&to(e.then);var ge=x(()=>{H();to=Uf,k=d(2,(e,t)=>Dt(e)&&(t in e)),bs=d(2,(e,t)=>k(e,"_tag")&&e._tag===t)});var Yo=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Vf{_state;constructor(e,t,r,n){if(Go(t)&&Go(e))t=Math.random()*4294967295>>>0,e=0;else if(Go(t))t=e,e=0;if(Go(n)&&Go(r))n=this._state?this._state[3]:VI,r=this._state?this._state[2]:BI;else if(Go(n))n=r,r=0;return this._state=new Int32Array([0,0,r>>>0,((n||0)|1)>>>0]),this._next(),Bb(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*JI+t)/WI}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;GI(this._state,e,t,zI,KI),Bb(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let r=e>>>18,n=(t>>>18|e<<14)>>>0;r=(r^e)>>>0,n=(n^t)>>>0;let o=(n>>>27|r<<5)>>>0,i=e>>>27,a=(-i>>>0&31)>>>0;return(o>>>i|o<<a)>>>0}}function GI(e,t,r,n,o){let i=(r>>>16)*(o&65535)>>>0,a=(r&65535)*(o>>>16)>>>0,s=(r&65535)*(o&65535)>>>0,c=(r>>>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(r,n)>>>0,c=c+Math.imul(t,o)>>>0,e[0]=c,e[1]=s}function Bb(e,t,r,n,o){let i=t+n>>>0,a=r+o>>>0;if(a>>>0<r>>>0)i=i+1|0;e[0]=i,e[1]=a}function zf(e){if(typeof e==="object"&&e!==null&&Bf in e)return e[Bf]();throw Error(Yo("yieldWrapGet"))}var Gi,BI=335903614,VI=4150755663,zI=1481765933,KI=1284865837,WI=9007199254740992,JI=134217728,Bf,Sn,Ht,Vb,YI,ZI,St,a1;var ro=x(()=>{ge();Gi=class Gi{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 Gi(this.self)}};Bf=Symbol.for("effect/Utils/YieldWrap");Sn=class Sn{#e;constructor(e){this.#e=e}[Bf](){return this.#e}};Ht=j("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),Vb={effect_internal_function:(e)=>e()},YI={effect_internal_function:(e)=>{try{return e()}finally{}}},ZI=Vb.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,St=ZI?Vb.effect_internal_function:YI.effect_internal_function,a1=function*(){}.constructor});var Kf,M,v=(e)=>{if(Ht.enabled===!0)return 0;switch(typeof e){case"number":return $l(e);case"bigint":return me(e.toString(10));case"boolean":return me(String(e));case"symbol":return me(String(e));case"string":return me(e);case"undefined":return me("undefined");case"function":case"object":if(e===null)return me("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return me("Invalid Date");return v(e.toISOString())}else if(e instanceof URL)return v(e.href);else if(QI(e))return e[M]();else return _s(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},_s=(e)=>{if(!Kf.has(e))Kf.set(e,$l(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Kf.get(e)},J=(e)=>(t)=>t*53^e,Hl=(e)=>e&3221225471|e>>>1&1073741824,QI=(e)=>k(e,M),$l=(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 Hl(t)},me=(e)=>{let t=5381,r=e.length;while(r)t=t*33^e.charCodeAt(--r);return Hl(t)},eM=(e,t)=>{let r=12289;for(let n=0;n<t.length;n++)r^=g(me(t[n]),J(v(e[t[n]])));return Hl(r)},jl=(e)=>eM(e,Object.keys(e)),Qt=(e)=>{let t=6151;for(let r=0;r<e.length;r++)t=g(t,J(v(e[r])));return Hl(t)},oe=function(){if(arguments.length===1){let r=arguments[0];return function(n){return Object.defineProperty(r,M,{value(){return n},enumerable:!1}),n}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,M,{value(){return t},enumerable:!1}),t};var Me=x(()=>{H();ge();ro();Kf=j(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),M=Symbol.for("effect/Hash")});function O(){if(arguments.length===1)return(e)=>Bl(e,arguments[0]);return Bl(arguments[0],arguments[1])}function Bl(e,t){if(e===t)return!0;let r=typeof e;if(r!==typeof t)return!1;if(r==="object"||r==="function"){if(e!==null&&t!==null){if(ws(e)&&ws(t))if(v(e)===v(t)&&e[I](t))return!0;else return Ht.enabled&&Ht.tester?Ht.tester(e,t):!1;else if(e instanceof Date&&t instanceof Date){let n=e.getTime(),o=t.getTime();return n===o||Number.isNaN(n)&&Number.isNaN(o)}else if(e instanceof URL&&t instanceof URL)return e.href===t.href}if(Ht.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,o)=>Bl(n,t[o]));if(Object.getPrototypeOf(e)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let n=Object.keys(e),o=Object.keys(t);if(n.length===o.length){for(let i of n)if(!((i in t)&&Bl(e[i],t[i])))return Ht.tester?Ht.tester(e,t):!1;return!0}}return Ht.tester?Ht.tester(e,t):!1}}return Ht.enabled&&Ht.tester?Ht.tester(e,t):!1}var I,ws=(e)=>k(e,I),Ts=()=>O;var le=x(()=>{Me();ge();ro();I=Symbol.for("effect/Equal")});function tM(e){try{return e.toISOString()}catch{return"Invalid Date"}}function rM(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function Es(e){return xt(e)?JSON.stringify(e):String(e)}function Kr(e,t){let r=t?.space??0,n=new WeakSet,o=!r?"":Xt(r)?" ".repeat(r):r,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(n.has(l))return Wf;if(n.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(Jl(l))return fM(l);if(!t?.ignoreToString&&C(l,"toString")&&oo(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let p=mM(l);if(l instanceof Error&&l.cause)return`${p} (cause: ${c(l.cause,u)})`;return p}if(gt(l))return JSON.stringify(l);if(Qt(l)||l==null||Go(l)||Yo(l))return String(l);if(ro(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return Xf;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(qt(l)){if(r.has(l))return Xf;r.add(l);let p=s(l);if(!o||p.length<=1){let h=`{${p.map((m)=>`${As(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,h)}let f=`{
7
- ${p.map((h)=>`${i(u+1)}${As(h)}: ${c(l[h],u+1)}`).join(`,
6
+ ${i(u)}]`}if(Ul(l))return tM(l);if(!t?.ignoreToString&&k(l,"toString")&&to(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let p=rM(l);if(l instanceof Error&&l.cause)return`${p} (cause: ${c(l.cause,u)})`;return p}if(xt(l))return JSON.stringify(l);if(Xt(l)||l==null||Wo(l)||Jo(l))return String(l);if(eo(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(n.has(l))return Wf;return n.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(Dt(l)){if(n.has(l))return Wf;n.add(l);let p=s(l);if(!o||p.length<=1){let h=`{${p.map((m)=>`${Es(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,h)}let f=`{
7
+ ${p.map((h)=>`${i(u+1)}${Es(h)}: ${c(l[h],u+1)}`).join(`,
8
8
  `)}
9
- ${i(u)}}`;return a(l,f)}return String(l)}return c(e,0)}var ne,de=(e)=>{try{if(C(e,"toJSON")&&oo(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(de)}catch{return{}}return tb(e)},Xf="[Circular]",ge=(e)=>JSON.stringify(e,null,2),P1,Er=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?Ql(e,t):String(e)}catch{return String(e)}},Ql=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(Qo.fiberRefs!==void 0&&Q_(i)?i[Qf](Qo.fiberRefs):i):i,t);return n=void 0,r},Qf,Q_=(e)=>typeof e==="object"&&e!==null&&(Qf in e),Qo,eb=(e,t)=>{let n=Qo.fiberRefs;Qo.fiberRefs=e;try{return t()}finally{Qo.fiberRefs=n}},tb=(e)=>{if(Q_(e)&&Qo.fiberRefs!==void 0)return e[Qf](Qo.fiberRefs);return e};var Ve=x(()=>{ye();ne=Symbol.for("nodejs.util.inspect.custom");P1={toJSON(){return de(this)},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},Qf=Symbol.for("effect/Inspectable/Redactable"),Qo=V("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var T=(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 be=()=>{};var ti="Async",ni="Commit",jt="Failure",Ps="OnFailure",ta="OnSuccess",na="OnSuccessAndFailure",Vt="Success",eu="Sync",nb="Tag",ri="UpdateRuntimeFlags",ra="While",oa="Iterator",tu="WithRuntime",ia="Yield",Is="RevertFlags";var hM="3.22.1",Ms=()=>hM;var ob,ib,ab,sb,ao,gM,yM,Or,Ns,so,tm,cb;var Rr=x(()=>{pe();Me();be();io();ob=Symbol.for("effect/Effect"),ib=Symbol.for("effect/Stream"),ab=Symbol.for("effect/Sink"),sb=Symbol.for("effect/Channel"),ao={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Ms()},gM={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},yM={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},Or={[ob]:ao,[ib]:ao,[ab]:gM,[sb]:yM,[I](e){return this===e},[M](){return ie(this,Rs(this))},[Symbol.iterator](){return new ea(new Tr(this))},pipe(){return T(this,arguments)}},Ns={[M](){return ie(this,Zl(this))},[I](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)&&O(this[r],e[r])))return!1;return!0}},so={...Or,_op:ni},tm={...so,...Ns},cb=function(){function e(){}return e.prototype=so,e}()});var ub,pb,xM,SM,_M,nm=(e)=>C(e,ub),rm=(e)=>e._tag==="None",om=(e)=>e._tag==="Some",nu,Fs=(e)=>{let t=Object.create(xM);return t.value=e,t};var im=x(()=>{pe();Me();Ve();ye();Rr();ub=Symbol.for("effect/Option"),pb={...Or,[ub]:{_A:(e)=>e},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},xM=Object.assign(Object.create(pb),{_tag:"Some",_op:"Some",[I](e){return nm(e)&&om(e)&&O(this.value,e.value)},[M](){return ie(this,G(E(this._tag))(E(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:de(this.value)}}}),SM=E("None"),_M=Object.assign(Object.create(pb),{_tag:"None",_op:"None",[I](e){return nm(e)&&rm(e)},[M](){return SM},toJSON(){return{_id:"Option",_tag:this._tag}}}),nu=Object.create(_M)});var am,fb,bM,wM,ru=(e)=>C(e,am),sm=(e)=>e._tag==="Left",cm=(e)=>e._tag==="Right",mb=(e)=>{let t=Object.create(wM);return t.left=e,t},hb=(e)=>{let t=Object.create(bM);return t.right=e,t};var gb=x(()=>{pe();Me();Ve();ye();Rr();am=Symbol.for("effect/Either"),fb={...Or,[am]:{_R:(e)=>e},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},bM=Object.assign(Object.create(fb),{_tag:"Right",_op:"Right",[I](e){return ru(e)&&cm(e)&&O(this.right,e.right)},[M](){return G(E(this._tag))(E(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:de(this.right)}}}),wM=Object.assign(Object.create(fb),{_tag:"Left",_op:"Left",[I](e){return ru(e)&&sm(e)&&O(this.left,e.left)},[M](){return G(E(this._tag))(E(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:de(this.left)}}})});var Q,W,lm,Ee,Ot,ou,yb,Ls,xb,um,Sb;var tn=x(()=>{j();gb();Q=hb,W=mb,lm=ru,Ee=sm,Ot=cm,ou=d(2,(e,t)=>Ee(e)?W(t(e.left)):Q(e.right)),yb=d(2,(e,t)=>Ot(e)?Q(t(e.right)):W(e.left)),Ls=d(2,(e,{onLeft:t,onRight:n})=>Ee(e)?t(e.left):n(e.right)),xb=Ls({onLeft:ue,onRight:ue}),um=d(2,(e,t)=>{if(Ot(e))return e.right;throw t(e.left)}),Sb=um(()=>Error("getOrThrow called on a Left"))});var pm=(e)=>e.length>0;var _b=(e)=>(t,n)=>t===n?0:e(t,n),bb,iu,dm=(e)=>d(2,(t,n)=>e(t,n)===1);var au=x(()=>{j();bb=_b((e,t)=>e<t?-1:1),iu=d(2,(e,t)=>_b((n,r)=>e(t(n),t(r))))});var A=()=>nu,F,Ne,Re,Je,Oe,En,wb,kr=(e)=>e==null?A():F(e),Bt,vb=(e)=>(...t)=>{try{return F(e(...t))}catch{return A()}},On,Rn,Tb,OM=(e)=>d(2,(t,n)=>Ne(t)?!1:e(t.value,n)),RM,Eb,Ob;var Ge=x(()=>{pe();j();im();F=Fs,Ne=rm,Re=om,Je=d(2,(e,{onNone:t,onSome:n})=>Ne(e)?t():n(e.value)),Oe=d(2,(e,t)=>Ne(e)?t():e.value),En=d(2,(e,t)=>Ne(e)?t():e),wb=d(2,(e,t)=>Ne(e)?F(t()):e),Bt=Oe(zl),On=d(2,(e,t)=>Ne(e)?A():F(t(e.value))),Rn=d(2,(e,t)=>Ne(e)?A():t(e.value)),Tb=d(2,(e,t)=>Ne(e)?A():kr(t(e.value))),RM=Cs(),Eb=OM(RM),Ob=d(2,(e,t)=>Ne(e)?!1:t(e.value))});var Rb=(...e)=>e;var kb=()=>{};var oi=(e)=>Array(e),mm,ke=(e)=>Array.isArray(e)?e:Array.from(e),hm=(e)=>Array.isArray(e)?e:[e],Cb,aa,Ab,gm,ym,CM=(e)=>e.length===0,Pb,co,we,Ib=(e,t)=>e<0||e>=t.length,AM=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),PM,xm,Cr,et,Mb=(e)=>we(e)?F(Sm(e)):A(),Sm=(e)=>e[e.length-1],kn=(e)=>e.slice(1),IM=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},Nb,Fb,_m=(e)=>Array.from(e).reverse(),Ar,bm,Lb,MM,NM,FM,sa=(e)=>e.slice(),LM,lo,Pr=()=>[],Rt=(e)=>[e],Cn,Ds,su,cu,ca,wm=(e,t)=>{let n=[],r=e,o;while(Re(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},uo,Db,vm=(e)=>Db(e,Cs()),Ir;var Be=x(()=>{pe();vs();j();Ge();kb();mm=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}),Cb=d(2,(e,{onEmpty:t,onNonEmpty:n})=>we(e)?n(et(e),kn(e)):t()),aa=d(2,(e,t)=>[t,...e]),Ab=d(2,(e,t)=>[...e,t]),gm=d(2,(e,t)=>ke(e).concat(ke(t))),ym=Array.isArray,Pb=CM,co=pm,we=pm,PM=d(2,(e,t)=>{let n=Math.floor(t);return Ib(n,e)?A():F(e[n])}),xm=d(2,(e,t)=>{let n=Math.floor(t);if(Ib(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),Cr=PM(0),et=xm(0),Nb=d(2,(e,t)=>NM(e,IM(e,t))),Fb=d(2,(e,t)=>{let n=ke(e);return n.slice(AM(t,n),n.length)}),Ar=d(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),bm=d(2,(e,t)=>Lb(e,t,Rb)),Lb=d(3,(e,t,n)=>{let r=ke(e),o=ke(t);if(we(r)&&we(o)){let i=[n(et(r),et(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[]}),MM=Cs(),NM=d(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(we(n)){if(r>=1)return FM(n,r);return[[],n]}return[n,[]]}),FM=d(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[sa(e),[]]:[aa(e.slice(1,n),et(e)),e.slice(n)]}),LM=d(3,(e,t,n)=>{let r=ke(e),o=ke(t);if(we(r)){if(we(o))return Db(n)(gm(r,o));return r}return o}),lo=d(2,(e,t)=>LM(e,t,MM)),Cn=d(2,(e,t)=>e.map(t)),Ds=d(2,(e,t)=>{if(Pb(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}),su=Ds(ue),cu=d(2,(e,t)=>{let n=ke(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if(Re(i))r.push(i.value)}return r}),ca=d(3,(e,t,n)=>ke(e).reduce((r,o,i)=>n(r,o,i),t)),uo=z_,Db=d(2,(e,t)=>{let n=ke(e);if(we(n)){let r=[et(n)],o=kn(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),Ir=d(2,(e,t)=>ke(e).join(t))});function HM(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 Ub,Hb,$M=(e)=>ws((t,n)=>t.length===n.length&&Mr(t).every((r,o)=>e(r,la(n,o)))),jM,VM,ot=(e)=>{let t=Object.create(VM);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=Xn,t.right=Xn;break}case"ISingleton":{t.length=1,t.depth=0,t.left=Xn,t.right=Xn;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=Xn,t.right=Xn;break}}return t},$b=(e)=>C(e,Ub),Xn,dn=()=>Xn,qs=(...e)=>zM(e),tt=(e)=>ot({_tag:"ISingleton",a:e}),lu=(e)=>$b(e)?e:Us(ke(e)),Tm=(e,t,n)=>{switch(e.backing._tag){case"IArray":{HM(e.backing.array,0,t,n,e.length);break}case"IConcat":{Tm(e.left,t,n),Tm(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}}},BM=(e)=>{switch(e.backing._tag){case"IEmpty":return Hb;case"IArray":return e.backing.array;default:{let t=Array(e.length);return Tm(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Xn,e.right=Xn,e.depth=0,t}}},Mr,KM=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return ot({_tag:"IArray",array:_m(e.backing.array)});case"IConcat":return ot({_tag:"IConcat",left:po(e.backing.right),right:po(e.backing.left)});case"ISlice":return Us(_m(Mr(e)))}},po,Us=(e)=>e.length===0?dn():e.length===1?tt(e[0]):ot({_tag:"IArray",array:e}),zM=(e)=>Us(e),la,jb,kt,Em,nn,Vb=(e)=>e.length===0,An=(e)=>e.length>0,Om=(e)=>la(e,0),Pn,In=(e)=>Em(e,1);var Qn=x(()=>{Be();pe();vs();j();Me();Ve();be();ye();Ub=Symbol.for("effect/Chunk");Hb=[],jM=$M(O),VM={[Ub]:{_A:(e)=>e},toString(){return ge(this.toJSON())},toJSON(){return{_id:"Chunk",values:Mr(this).map(de)}},[ne](){return this.toJSON()},[I](e){return $b(e)&&jM(this,e)},[M](){return ie(this,en(Mr(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return Hb[Symbol.iterator]();default:return Mr(this)[Symbol.iterator]()}},pipe(){return T(this,arguments)}},Xn=ot({_tag:"IEmpty"}),Mr=BM,po=KM,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)}}),jb=d(2,(e,t)=>nn(e,tt(t))),kt=d(2,(e,t)=>nn(tt(t),e)),Em=d(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return Xn;else switch(e.backing._tag){case"ISlice":return ot({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return Em(e.right,t-e.left.length);return ot({_tag:"IConcat",left:Em(e.left,t),right:e.right})}default:return ot({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),nn=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 ot({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=nn(e.right,t);return ot({_tag:"IConcat",left:e.left,right:r})}else{let r=nn(e.right.right,t);if(r.depth===e.depth-3){let o=ot({_tag:"IConcat",left:e.right.left,right:r});return ot({_tag:"IConcat",left:e.left,right:o})}else{let o=ot({_tag:"IConcat",left:e.left,right:e.right.left});return ot({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=nn(e,t.left);return ot({_tag:"IConcat",left:r,right:t.right})}else{let r=nn(e,t.left.left);if(r.depth===t.depth-3){let o=ot({_tag:"IConcat",left:r,right:t.left.right});return ot({_tag:"IConcat",left:o,right:t.right})}else{let o=ot({_tag:"IConcat",left:t.left.right,right:t.right});return ot({_tag:"IConcat",left:r,right:o})}}}),Pn=Om});var fo=5,Rm,Bb,Kb,zb;var uu=x(()=>{Rm=Math.pow(2,5),Bb=Rm-1,Kb=Rm/2,zb=Rm/4});function WM(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 mo(e,t){return t>>>e&Bb}function ho(e){return 1<<e}function pu(e,t){return WM(e&t-1)}var km=x(()=>{uu()});var Wb=(e,t)=>({value:e,previous:t});function ii(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 Cm(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 Jb(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 Fr{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(A());if(Ne(a))return new Fr;return++i.value,new ai(e,r,o,a)}}function fn(e){return Os(e,"EmptyNode")}function GM(e){return fn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function du(e,t){return fn(e)?!1:t===e.edit}class ai{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(O(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Ne(s))return--i.value,new Fr;if(du(this,e))return this.value=s,this;return new ai(e,r,o,s)}let a=n(A());if(Ne(a))return this;return++i.value,Gb(e,t,this.hash,this,r,new ai(e,r,o,a))}}class Am{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=du(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 Am(e,this.hash,c):c[0]}let a=n(A());if(Ne(a))return this;return++i.value,Gb(e,t,this.hash,this,r,new ai(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&&O(i,u.key)){let p=u.value,f=o(p);if(f===p)return r;if(Ne(f))return--a.value,Cm(e,l,r);return ii(e,l,new ai(t,n,i,f),r)}}let c=o(A());if(Ne(c))return r;return++a.value,ii(e,s,new ai(t,n,i,c),r)}}class ua{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=mo(t,r),l=ho(c),u=pu(a,l),p=a&l,f=du(this,e);if(!p){let y=new Fr().modify(e,t+fo,n,r,o,i);if(!y)return this;return s.length>=Kb?ZM(e,c,y,a,s):new ua(e,a|l,Jb(f,u,y,s))}let h=s[u],m=h.modify(e,t+fo,n,r,o,i);if(h===m)return this;let w=a,S;if(fn(m)){if(w&=~l,!w)return new Fr;if(s.length<=2&&GM(s[u^1]))return s[u^1];S=Cm(f,u,s)}else S=ii(f,u,m,s);if(f)return this.mask=w,this.children=S,this;return new ua(e,w,S)}}class Pm{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=mo(t,r),l=s[c],u=(l||new Fr).modify(e,t+fo,n,r,o,i);if(l===u)return this;let p=du(this,e),f;if(fn(l)&&!fn(u))++a,f=ii(p,c,u,s);else if(!fn(l)&&fn(u)){if(--a,a<=zb)return YM(e,a,c,s);f=ii(p,c,new Fr,s)}else f=ii(p,c,u,s);if(p)return this.size=a,this.children=f,this;return new Pm(e,a,f)}}function YM(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&&!fn(l))o[i++]=l,a|=1<<s}return new ua(e,a,o)}function ZM(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 Pm(e,s+1,i)}function XM(e,t,n,r,o,i){if(n===o)return new Am(e,n,[i,r]);let a=mo(t,n),s=mo(t,o);if(a===s)return(c)=>new ua(e,ho(a)|ho(s),[c]);else{let c=a<s?[r,i]:[i,r];return new ua(e,ho(a)|ho(s),c)}}function Gb(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=XM(e,s,n,r,o,i);if(typeof c==="function")a=Wb(c,a),s=s+fo;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var Yb=x(()=>{pe();Ge();ye();km();uu()});var Zb="effect/HashMap",fu,eN,Im=(e,t,n,r)=>{let o=Object.create(eN);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},hu,mu=(e)=>e?Qb(e[0],e[1],e[2],e[3],e[4]):A(),Xb=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if(Re(e.value))return F({value:t(e.key,e.value.value),cont:n});return mu(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return Qb(r.length,r,0,t,n)}default:return mu(n)}},Qb=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!fn(i))return Xb(i,r,[e,t,n,r,o])}return mu(o)},tN,pa=()=>tN,ew=(e)=>{let t=xu(pa());for(let n of e)si(t,n[0],n[1]);return ow(t)},tw=(e)=>C(e,fu),nw=(e)=>e&&fn(e._root),rw,gu,Mm,si,nN,yu=(e)=>new hu(e,(t)=>t),Hs=(e)=>e._size,xu=(e)=>Im(!0,e._edit+1,e._root,e._size),ow=(e)=>(e._editable=!1,e),Su,iw,_u,aw,Nm,da;var Fm=x(()=>{pe();j();j();Me();Ve();Ge();be();ye();km();uu();Yb();fu=Symbol.for(Zb),eN={[fu]:fu,[Symbol.iterator](){return new hu(this,(e,t)=>[e,t])},[M](){let e=E(Zb);for(let t of this)e^=g(E(t[0]),G(E(t[1])));return ie(this,e)},[I](e){if(tw(e)){if(e._size!==this._size)return!1;for(let t of this){let n=g(e,gu(t[0],E(t[0])));if(Ne(n))return!1;else if(!O(t[1],n.value))return!1}return!0}return!1},toString(){return ge(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(de)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}};hu=class hu{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=Xb(this.map._root,this.f,void 0)}next(){if(Ne(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=mu(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new hu(this.map,this.f)}};tN=Im(!1,0,new Fr,0),rw=d(2,(e,t)=>gu(e,t,E(t))),gu=d(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return O(t,r.key)?r.value:A();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&&O(t,c.key))return c.value}}return A()}case"IndexedNode":{let i=mo(o,n),a=ho(i);if(r.mask&a){r=r.children[pu(r.mask,a)],o+=fo;break}return A()}case"ArrayNode":{if(r=r.children[mo(o,n)],r){o+=fo;break}return A()}default:return A()}}),Mm=d(2,(e,t)=>Re(gu(e,t,E(t)))),si=d(3,(e,t,n)=>Su(e,t,()=>F(n))),nN=d(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:Im(e._editable,e._edit,t,n)}),Su=d(3,(e,t,n)=>iw(e,t,E(t),n)),iw=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 g(e,nN(i,o.value))}),_u=d(2,(e,t)=>Su(e,t,A)),aw=d(2,(e,t)=>da(e,pa(),(n,r,o)=>si(n,o,t(r,o)))),Nm=d(2,(e,t)=>da(e,void 0,(n,r,o)=>t(r,o))),da=d(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return Re(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&&!fn(c))if(c._tag==="LeafNode"){if(Re(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var cw="effect/HashSet",bu,rN,wu=(e)=>{let t=Object.create(rN);return t._keyMap=e,t},lw=(e)=>C(e,bu),oN,$s=()=>oN,uw=(e)=>{let t=vu($s());for(let n of e)fa(t,n);return Tu(t)},pw=(...e)=>{let t=vu($s());for(let n of e)fa(t,n);return Tu(t)},dw,fw=(e)=>Hs(e._keyMap),vu=(e)=>wu(xu(e._keyMap)),Tu=(e)=>(e._keyMap._editable=!1,e),Lm,fa,Dm,mw,hw,gw,yw;var xw=x(()=>{pe();j();Me();Ve();be();ye();Fm();bu=Symbol.for(cw),rN={[bu]:bu,[Symbol.iterator](){return yu(this._keyMap)},[M](){return ie(this,G(E(this._keyMap))(E(cw)))},[I](e){if(lw(e))return Hs(this._keyMap)===Hs(e._keyMap)&&O(this._keyMap,e._keyMap);return!1},toString(){return ge(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(de)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},oN=wu(pa()),dw=d(2,(e,t)=>Mm(e._keyMap,t)),Lm=d(2,(e,t)=>{let n=vu(e);return t(n),Tu(n)}),fa=d(2,(e,t)=>e._keyMap._editable?(si(t,!0)(e._keyMap),e):wu(si(t,!0)(e._keyMap))),Dm=d(2,(e,t)=>e._keyMap._editable?(_u(t)(e._keyMap),e):wu(_u(t)(e._keyMap))),mw=d(2,(e,t)=>Lm(e,(n)=>{for(let r of t)Dm(n,r)})),hw=d(2,(e,t)=>Lm($s(),(n)=>{gw(e,(r)=>fa(n,r));for(let r of t)fa(n,r)})),gw=d(2,(e,t)=>Nm(e._keyMap,(n,r)=>t(r))),yw=d(3,(e,t,n)=>da(e._keyMap,t,(r,o,i)=>n(r,i)))});var er,Sw,ci,_w,js,li,qm,Um,Lr,ui;var pi=x(()=>{xw();er=$s,Sw=uw,ci=pw,_w=dw,js=fw,li=fa,qm=Dm,Um=mw,Lr=hw,ui=yw});var ha="Die",go="Empty",yo="Fail",di="Interrupt",fi="Parallel",mi="Sequential";var vw="effect/Cause",jm,sN,ga,Dr,ya=(e)=>{let t=Object.create(ga);return t._tag=yo,t.error=e,t},rn=(e)=>{let t=Object.create(ga);return t._tag=ha,t.defect=e,t},Mn=(e)=>{let t=Object.create(ga);return t._tag=di,t.fiberId=e,t},yi=(e,t)=>{let n=Object.create(ga);return n._tag=fi,n.left=e,n.right=t,n},Ct=(e,t)=>{let n=Object.create(ga);return n._tag=mi,n.left=e,n.right=t,n},Tw=(e)=>C(e,jm),Vm=(e)=>e._tag===go,Ew=(e)=>e._tag===yo,Eu=(e)=>{if(e._tag===go)return!0;return hi(e,!0,(t,n)=>{switch(n._tag){case go:return F(t);case ha:case yo:case di:return F(!1);default:return A()}})},Ou=(e)=>Re(Ow(e)),xa=(e)=>Cu(void 0,pN)(e),Bm=(e)=>po(hi(e,dn(),(t,n)=>n._tag===yo?F(g(t,kt(n.error))):A())),Km=(e)=>po(hi(e,dn(),(t,n)=>n._tag===ha?F(g(t,kt(n.defect))):A())),zm=(e)=>hi(e,er(),(t,n)=>n._tag===di?F(g(t,li(n.fiberId))):A()),Wm=(e)=>Jm(e,(t)=>t._tag===yo?F(t.error):A()),Ru=(e)=>{let t=Wm(e);switch(t._tag){case"None":return Q(e);case"Some":return W(t.value)}},Ow=(e)=>Jm(e,(t)=>t._tag===di?F(t.fiberId):A()),ku=(e)=>Gm(e,{onEmpty:Dr,onFail:()=>Dr,onDie:rn,onInterrupt:Mn,onSequential:Ct,onParallel:yi}),Rw=(e)=>Gm(e,{onEmpty:Dr,onFail:rn,onDie:rn,onInterrupt:Mn,onSequential:Ct,onParallel:yi}),cN=(e,t)=>{let n=tt(e),r=tt(t);while(An(n)&&An(r)){let[o,i]=g(Pn(n),hi([er(),dn()],([c,l],u)=>{let[p,f]=Hm(u);return F([g(c,Lr(p)),g(l,nn(f))])})),[a,s]=g(Pn(r),hi([er(),dn()],([c,l],u)=>{let[p,f]=Hm(u);return F([g(c,Lr(p)),g(l,nn(f))])}));if(!O(o,a))return!1;n=i,r=s}return!0},lN=(e)=>uN(tt(e),dn()),uN=(e,t)=>{while(!0){let[n,r]=g(e,ca([er(),dn()],([i,a],s)=>{let[c,l]=Hm(s);return[g(i,Lr(c)),g(a,nn(l))]})),o=js(n)>0?g(t,kt(n)):t;if(Vb(r))return po(o);e=r,t=o}throw Error(Xo("Cause.flattenCauseLoop"))},Jm,Hm=(e)=>{let t=e,n=[],r=er(),o=dn();while(t!==void 0)switch(t._tag){case go:{if(n.length===0)return[r,o];t=n.pop();break}case yo:{if(r=li(r,qs(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case ha:{if(r=li(r,qs(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case di:{if(r=li(r,qs(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case mi:{switch(t.left._tag){case go:{t=t.right;break}case mi:{t=Ct(t.left.left,Ct(t.left.right,t.right));break}case fi:{t=yi(Ct(t.left.left,t.right),Ct(t.left.right,t.right));break}default:{o=kt(o,t.right),t=t.left;break}}break}case fi:{n.push(t.right),t=t.left;break}}throw Error(Xo("Cause.evaluateCauseLoop"))},pN,bw="SequentialCase",ww="ParallelCase",Gm,hi,Cu,Nn=(e,t)=>{if(xa(e))return"All fibers interrupted without errors.";return Vs(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
- ${kw(n.cause," ")}
9
+ ${i(u)}}`;return a(l,f)}return String(l)}return c(e,0)}var re,ue=(e)=>{try{if(k(e,"toJSON")&&to(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(ue)}catch{return{}}return Wb(e)},Wf="[Circular]",he=(e)=>JSON.stringify(e,null,2),m1,bn=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?Vl(e,t):String(e)}catch{return String(e)}},Vl=(e,t)=>{let r=[],n=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?r.includes(i)?void 0:r.push(i)&&(Zo.fiberRefs!==void 0&&zb(i)?i[Jf](Zo.fiberRefs):i):i,t);return r=void 0,n},Jf,zb=(e)=>typeof e==="object"&&e!==null&&(Jf in e),Zo,Kb=(e,t)=>{let r=Zo.fiberRefs;Zo.fiberRefs=e;try{return t()}finally{Zo.fiberRefs=r}},Wb=(e)=>{if(zb(e)&&Zo.fiberRefs!==void 0)return e[Jf](Zo.fiberRefs);return e};var Be=x(()=>{ge();re=Symbol.for("nodejs.util.inspect.custom");m1={toJSON(){return ue(this)},[re](){return this.toJSON()},toString(){return he(this.toJSON())}},Jf=Symbol.for("effect/Inspectable/Redactable"),Zo=j("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var E=(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 r=e;for(let n=0,o=t.length;n<o;n++)r=t[n](r);return r}}};var _e=()=>{};var Qo="Async",ei="Commit",$t="Failure",vs="OnFailure",Yi="OnSuccess",Zi="OnSuccessAndFailure",jt="Success",zl="Sync",Jb="Tag",ti="UpdateRuntimeFlags",Xi="While",Qi="Iterator",Kl="WithRuntime",ea="Yield",Os="RevertFlags";var nM="3.22.1",Rs=()=>nM;var Yb,Zb,Xb,Qb,no,oM,iM,_n,ks,oo,Yf,e_;var wn=x(()=>{le();Me();_e();ro();Yb=Symbol.for("effect/Effect"),Zb=Symbol.for("effect/Stream"),Xb=Symbol.for("effect/Sink"),Qb=Symbol.for("effect/Channel"),no={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Rs()},oM={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},iM={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},_n={[Yb]:no,[Zb]:no,[Xb]:oM,[Qb]:iM,[I](e){return this===e},[M](){return oe(this,_s(this))},[Symbol.iterator](){return new Gi(new Sn(this))},pipe(){return E(this,arguments)}},ks={[M](){return oe(this,jl(this))},[I](e){let t=Object.keys(this),r=Object.keys(e);if(t.length!==r.length)return!1;for(let n of t)if(!((n in e)&&O(this[n],e[n])))return!1;return!0}},oo={..._n,_op:ei},Yf={...oo,...ks},e_=function(){function e(){}return e.prototype=oo,e}()});var r_,n_,aM,sM,cM,Zf=(e)=>k(e,r_),Xf=(e)=>e._tag==="None",Qf=(e)=>e._tag==="Some",Wl,Cs=(e)=>{let t=Object.create(aM);return t.value=e,t};var em=x(()=>{le();Me();Be();ge();wn();r_=Symbol.for("effect/Option"),n_={..._n,[r_]:{_A:(e)=>e},[re](){return this.toJSON()},toString(){return he(this.toJSON())}},aM=Object.assign(Object.create(n_),{_tag:"Some",_op:"Some",[I](e){return Zf(e)&&Qf(e)&&O(this.value,e.value)},[M](){return oe(this,J(v(this._tag))(v(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:ue(this.value)}}}),sM=v("None"),cM=Object.assign(Object.create(n_),{_tag:"None",_op:"None",[I](e){return Zf(e)&&Xf(e)},[M](){return sM},toJSON(){return{_id:"Option",_tag:this._tag}}}),Wl=Object.create(cM)});var tm,i_,lM,uM,Jl=(e)=>k(e,tm),rm=(e)=>e._tag==="Left",nm=(e)=>e._tag==="Right",a_=(e)=>{let t=Object.create(uM);return t.left=e,t},s_=(e)=>{let t=Object.create(lM);return t.right=e,t};var c_=x(()=>{le();Me();Be();ge();wn();tm=Symbol.for("effect/Either"),i_={..._n,[tm]:{_R:(e)=>e},[re](){return this.toJSON()},toString(){return he(this.toJSON())}},lM=Object.assign(Object.create(i_),{_tag:"Right",_op:"Right",[I](e){return Jl(e)&&nm(e)&&O(this.right,e.right)},[M](){return J(v(this._tag))(v(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:ue(this.right)}}}),uM=Object.assign(Object.create(i_),{_tag:"Left",_op:"Left",[I](e){return Jl(e)&&rm(e)&&O(this.left,e.left)},[M](){return J(v(this._tag))(v(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:ue(this.left)}}})});var Z,K,om,Ee,Rt,Gl,l_,As,u_,im,p_;var er=x(()=>{H();c_();Z=s_,K=a_,om=Jl,Ee=rm,Rt=nm,Gl=d(2,(e,t)=>Ee(e)?K(t(e.left)):Z(e.right)),l_=d(2,(e,t)=>Rt(e)?Z(t(e.right)):K(e.left)),As=d(2,(e,{onLeft:t,onRight:r})=>Ee(e)?t(e.left):r(e.right)),u_=As({onLeft:ce,onRight:ce}),im=d(2,(e,t)=>{if(Rt(e))return e.right;throw t(e.left)}),p_=im(()=>Error("getOrThrow called on a Left"))});var am=(e)=>e.length>0;var d_=(e)=>(t,r)=>t===r?0:e(t,r),f_,Yl,sm=(e)=>d(2,(t,r)=>e(t,r)===1);var Zl=x(()=>{H();f_=d_((e,t)=>e<t?-1:1),Yl=d(2,(e,t)=>d_((r,n)=>e(t(r),t(n))))});var C=()=>Wl,N,Ne,Re,Ge,ve,Er,m_,Tn=(e)=>e==null?C():N(e),Bt,h_=(e)=>(...t)=>{try{return N(e(...t))}catch{return C()}},vr,Or,g_,mM=(e)=>d(2,(t,r)=>Ne(t)?!1:e(t.value,r)),hM,y_,x_;var Ye=x(()=>{le();H();em();N=Cs,Ne=Xf,Re=Qf,Ge=d(2,(e,{onNone:t,onSome:r})=>Ne(e)?t():r(e.value)),ve=d(2,(e,t)=>Ne(e)?t():e.value),Er=d(2,(e,t)=>Ne(e)?t():e),m_=d(2,(e,t)=>Ne(e)?N(t()):e),Bt=ve(Dl),vr=d(2,(e,t)=>Ne(e)?C():N(t(e.value))),Or=d(2,(e,t)=>Ne(e)?C():t(e.value)),g_=d(2,(e,t)=>Ne(e)?C():Tn(t(e.value))),hM=Ts(),y_=mM(hM),x_=d(2,(e,t)=>Ne(e)?!1:t(e.value))});var S_=(...e)=>e;var b_=()=>{};var ri=(e)=>Array(e),lm,ke=(e)=>Array.isArray(e)?e:Array.from(e),um=(e)=>Array.isArray(e)?e:[e],__,ta,w_,pm,dm,yM=(e)=>e.length===0,T_,io,we,E_=(e,t)=>e<0||e>=t.length,xM=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),SM,fm,En,tt,v_=(e)=>we(e)?N(mm(e)):C(),mm=(e)=>e[e.length-1],Rr=(e)=>e.slice(1),bM=(e,t)=>{let r=0;for(let n of e){if(!t(n,r))break;r++}return r},O_,R_,hm=(e)=>Array.from(e).reverse(),vn,gm,k_,_M,wM,TM,ra=(e)=>e.slice(),EM,ao,On=()=>[],kt=(e)=>[e],kr,Ps,Xl,Ql,na,ym=(e,t)=>{let r=[],n=e,o;while(Re(o=t(n))){let[i,a]=o.value;r.push(i),n=a}return r},so,C_,xm=(e)=>C_(e,Ts()),Rn;var Ve=x(()=>{le();ys();H();Ye();b_();lm=d(2,(e,t)=>{let r=Math.max(1,Math.floor(e)),n=Array(r);for(let o=0;o<r;o++)n[o]=t(o);return n}),__=d(2,(e,{onEmpty:t,onNonEmpty:r})=>we(e)?r(tt(e),Rr(e)):t()),ta=d(2,(e,t)=>[t,...e]),w_=d(2,(e,t)=>[...e,t]),pm=d(2,(e,t)=>ke(e).concat(ke(t))),dm=Array.isArray,T_=yM,io=am,we=am,SM=d(2,(e,t)=>{let r=Math.floor(t);return E_(r,e)?C():N(e[r])}),fm=d(2,(e,t)=>{let r=Math.floor(t);if(E_(r,e))throw Error(`Index ${r} out of bounds`);return e[r]}),En=SM(0),tt=fm(0),O_=d(2,(e,t)=>wM(e,bM(e,t))),R_=d(2,(e,t)=>{let r=ke(e);return r.slice(xM(t,r),r.length)}),vn=d(2,(e,t)=>{let r=Array.from(e);return r.sort(t),r}),gm=d(2,(e,t)=>k_(e,t,S_)),k_=d(3,(e,t,r)=>{let n=ke(e),o=ke(t);if(we(n)&&we(o)){let i=[r(tt(n),tt(o))],a=Math.min(n.length,o.length);for(let s=1;s<a;s++)i[s]=r(n[s],o[s]);return i}return[]}),_M=Ts(),wM=d(2,(e,t)=>{let r=Array.from(e),n=Math.floor(t);if(we(r)){if(n>=1)return TM(r,n);return[[],r]}return[r,[]]}),TM=d(2,(e,t)=>{let r=Math.max(1,Math.floor(t));return r>=e.length?[ra(e),[]]:[ta(e.slice(1,r),tt(e)),e.slice(r)]}),EM=d(3,(e,t,r)=>{let n=ke(e),o=ke(t);if(we(n)){if(we(o))return C_(r)(pm(n,o));return n}return o}),ao=d(2,(e,t)=>EM(e,t,_M)),kr=d(2,(e,t)=>e.map(t)),Ps=d(2,(e,t)=>{if(T_(e))return[];let r=[];for(let n=0;n<e.length;n++){let o=t(e[n],n);for(let i=0;i<o.length;i++)r.push(o[i])}return r}),Xl=Ps(ce),Ql=d(2,(e,t)=>{let r=ke(e),n=[];for(let o=0;o<r.length;o++){let i=t(r[o],o);if(Re(i))n.push(i.value)}return n}),na=d(3,(e,t,r)=>ke(e).reduce((n,o,i)=>r(n,o,i),t)),so=qb,C_=d(2,(e,t)=>{let r=ke(e);if(we(r)){let n=[tt(r)],o=Rr(r);for(let i of o)if(n.every((a)=>!t(i,a)))n.push(i);return n}return[]}),Rn=d(2,(e,t)=>ke(e).join(t))});function kM(e,t,r,n,o){for(let i=t;i<Math.min(e.length,t+o);i++)r[n+i-t]=e[i];return r}var P_,I_,CM=(e)=>gs((t,r)=>t.length===r.length&&kn(t).every((n,o)=>e(n,oa(r,o)))),AM,PM,it=(e)=>{let t=Object.create(PM);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=Wr,t.right=Wr;break}case"ISingleton":{t.length=1,t.depth=0,t.left=Wr,t.right=Wr;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=Wr,t.right=Wr;break}}return t},M_=(e)=>k(e,P_),Wr,pr=()=>Wr,Is=(...e)=>NM(e),rt=(e)=>it({_tag:"ISingleton",a:e}),eu=(e)=>M_(e)?e:Ms(ke(e)),Sm=(e,t,r)=>{switch(e.backing._tag){case"IArray":{kM(e.backing.array,0,t,r,e.length);break}case"IConcat":{Sm(e.left,t,r),Sm(e.right,t,r+e.left.length);break}case"ISingleton":{t[r]=e.backing.a;break}case"ISlice":{let n=0,o=r;while(n<e.length)t[o]=oa(e,n),n+=1,o+=1;break}}},IM=(e)=>{switch(e.backing._tag){case"IEmpty":return I_;case"IArray":return e.backing.array;default:{let t=Array(e.length);return Sm(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Wr,e.right=Wr,e.depth=0,t}}},kn,MM=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return it({_tag:"IArray",array:hm(e.backing.array)});case"IConcat":return it({_tag:"IConcat",left:co(e.backing.right),right:co(e.backing.left)});case"ISlice":return Ms(hm(kn(e)))}},co,Ms=(e)=>e.length===0?pr():e.length===1?rt(e[0]):it({_tag:"IArray",array:e}),NM=(e)=>Ms(e),oa,N_,Ct,bm,tr,F_=(e)=>e.length===0,Cr=(e)=>e.length>0,_m=(e)=>oa(e,0),Ar,Pr=(e)=>bm(e,1);var Jr=x(()=>{Ve();le();ys();H();Me();Be();_e();ge();P_=Symbol.for("effect/Chunk");I_=[],AM=CM(O),PM={[P_]:{_A:(e)=>e},toString(){return he(this.toJSON())},toJSON(){return{_id:"Chunk",values:kn(this).map(ue)}},[re](){return this.toJSON()},[I](e){return M_(e)&&AM(this,e)},[M](){return oe(this,Qt(kn(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return I_[Symbol.iterator]();default:return kn(this)[Symbol.iterator]()}},pipe(){return E(this,arguments)}},Wr=it({_tag:"IEmpty"}),kn=IM,co=MM,oa=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?oa(e.left,t):oa(e.right,t-e.left.length);case"ISlice":return oa(e.backing.chunk,t+e.backing.offset)}}),N_=d(2,(e,t)=>tr(e,rt(t))),Ct=d(2,(e,t)=>tr(rt(t),e)),bm=d(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return Wr;else switch(e.backing._tag){case"ISlice":return it({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return bm(e.right,t-e.left.length);return it({_tag:"IConcat",left:bm(e.left,t),right:e.right})}default:return it({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),tr=d(2,(e,t)=>{if(e.backing._tag==="IEmpty")return t;if(t.backing._tag==="IEmpty")return e;let r=t.depth-e.depth;if(Math.abs(r)<=1)return it({_tag:"IConcat",left:e,right:t});else if(r<-1)if(e.left.depth>=e.right.depth){let n=tr(e.right,t);return it({_tag:"IConcat",left:e.left,right:n})}else{let n=tr(e.right.right,t);if(n.depth===e.depth-3){let o=it({_tag:"IConcat",left:e.right.left,right:n});return it({_tag:"IConcat",left:e.left,right:o})}else{let o=it({_tag:"IConcat",left:e.left,right:e.right.left});return it({_tag:"IConcat",left:o,right:n})}}else if(t.right.depth>=t.left.depth){let n=tr(e,t.left);return it({_tag:"IConcat",left:n,right:t.right})}else{let n=tr(e,t.left.left);if(n.depth===t.depth-3){let o=it({_tag:"IConcat",left:n,right:t.left.right});return it({_tag:"IConcat",left:o,right:t.right})}else{let o=it({_tag:"IConcat",left:t.left.right,right:t.right});return it({_tag:"IConcat",left:n,right:o})}}}),Ar=_m});var lo=5,wm,L_,D_,q_;var tu=x(()=>{wm=Math.pow(2,5),L_=wm-1,D_=wm/2,q_=wm/4});function FM(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 uo(e,t){return t>>>e&L_}function po(e){return 1<<e}function ru(e,t){return FM(e&t-1)}var Tm=x(()=>{tu()});var U_=(e,t)=>({value:e,previous:t});function ni(e,t,r,n){let o=n;if(!e){let i=n.length;o=Array(i);for(let a=0;a<i;++a)o[a]=n[a]}return o[t]=r,o}function Em(e,t,r){let n=r.length-1,o=0,i=0,a=r;if(e)o=i=t;else{a=Array(n);while(o<t)a[i++]=r[o++]}++o;while(o<=n)a[i++]=r[o++];if(e)a.length=n;return a}function H_(e,t,r,n){let o=n.length;if(e){let c=o;while(c>=t)n[c--]=n[c];return n[t]=r,n}let i=0,a=0,s=Array(o+1);while(i<t)s[a++]=n[i++];s[t]=r;while(i<o)s[++a]=n[i++];return s}class An{_tag="EmptyNode";modify(e,t,r,n,o,i){let a=r(C());if(Ne(a))return new An;return++i.value,new oi(e,n,o,a)}}function dr(e){return bs(e,"EmptyNode")}function DM(e){return dr(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function nu(e,t){return dr(e)?!1:t===e.edit}class oi{edit;hash;key;value;_tag="LeafNode";constructor(e,t,r,n){this.edit=e,this.hash=t,this.key=r,this.value=n}modify(e,t,r,n,o,i){if(O(o,this.key)){let s=r(this.value);if(s===this.value)return this;else if(Ne(s))return--i.value,new An;if(nu(this,e))return this.value=s,this;return new oi(e,n,o,s)}let a=r(C());if(Ne(a))return this;return++i.value,$_(e,t,this.hash,this,n,new oi(e,n,o,a))}}class vm{edit;hash;children;_tag="CollisionNode";constructor(e,t,r){this.edit=e,this.hash=t,this.children=r}modify(e,t,r,n,o,i){if(n===this.hash){let s=nu(this,e),c=this.updateCollisionList(s,e,this.hash,this.children,r,o,i);if(c===this.children)return this;return c.length>1?new vm(e,this.hash,c):c[0]}let a=r(C());if(Ne(a))return this;return++i.value,$_(e,t,this.hash,this,n,new oi(e,n,o,a))}updateCollisionList(e,t,r,n,o,i,a){let s=n.length;for(let l=0;l<s;++l){let u=n[l];if("key"in u&&O(i,u.key)){let p=u.value,f=o(p);if(f===p)return n;if(Ne(f))return--a.value,Em(e,l,n);return ni(e,l,new oi(t,r,i,f),n)}}let c=o(C());if(Ne(c))return n;return++a.value,ni(e,s,new oi(t,r,i,c),n)}}class ia{edit;mask;children;_tag="IndexedNode";constructor(e,t,r){this.edit=e,this.mask=t,this.children=r}modify(e,t,r,n,o,i){let a=this.mask,s=this.children,c=uo(t,n),l=po(c),u=ru(a,l),p=a&l,f=nu(this,e);if(!p){let y=new An().modify(e,t+lo,r,n,o,i);if(!y)return this;return s.length>=D_?UM(e,c,y,a,s):new ia(e,a|l,H_(f,u,y,s))}let h=s[u],m=h.modify(e,t+lo,r,n,o,i);if(h===m)return this;let w=a,S;if(dr(m)){if(w&=~l,!w)return new An;if(s.length<=2&&DM(s[u^1]))return s[u^1];S=Em(f,u,s)}else S=ni(f,u,m,s);if(f)return this.mask=w,this.children=S,this;return new ia(e,w,S)}}class Om{edit;size;children;_tag="ArrayNode";constructor(e,t,r){this.edit=e,this.size=t,this.children=r}modify(e,t,r,n,o,i){let a=this.size,s=this.children,c=uo(t,n),l=s[c],u=(l||new An).modify(e,t+lo,r,n,o,i);if(l===u)return this;let p=nu(this,e),f;if(dr(l)&&!dr(u))++a,f=ni(p,c,u,s);else if(!dr(l)&&dr(u)){if(--a,a<=q_)return qM(e,a,c,s);f=ni(p,c,new An,s)}else f=ni(p,c,u,s);if(p)return this.size=a,this.children=f,this;return new Om(e,a,f)}}function qM(e,t,r,n){let o=Array(t-1),i=0,a=0;for(let s=0,c=n.length;s<c;++s)if(s!==r){let l=n[s];if(l&&!dr(l))o[i++]=l,a|=1<<s}return new ia(e,a,o)}function UM(e,t,r,n,o){let i=[],a=n,s=0;for(let c=0;a;++c){if(a&1)i[c]=o[s++];a>>>=1}return i[t]=r,new Om(e,s+1,i)}function HM(e,t,r,n,o,i){if(r===o)return new vm(e,r,[i,n]);let a=uo(t,r),s=uo(t,o);if(a===s)return(c)=>new ia(e,po(a)|po(s),[c]);else{let c=a<s?[n,i]:[i,n];return new ia(e,po(a)|po(s),c)}}function $_(e,t,r,n,o,i){let a=void 0,s=t;while(!0){let c=HM(e,s,r,n,o,i);if(typeof c==="function")a=U_(c,a),s=s+lo;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var j_=x(()=>{le();Ye();ge();Tm();tu()});var B_="effect/HashMap",ou,jM,Rm=(e,t,r,n)=>{let o=Object.create(jM);return o._editable=e,o._edit=t,o._root=r,o._size=n,o},au,iu=(e)=>e?z_(e[0],e[1],e[2],e[3],e[4]):C(),V_=(e,t,r=void 0)=>{switch(e._tag){case"LeafNode":{if(Re(e.value))return N({value:t(e.key,e.value.value),cont:r});return iu(r)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let n=e.children;return z_(n.length,n,0,t,r)}default:return iu(r)}},z_=(e,t,r,n,o)=>{while(r<e){let i=t[r++];if(i&&!dr(i))return V_(i,n,[e,t,r,n,o])}return iu(o)},BM,aa=()=>BM,K_=(e)=>{let t=lu(aa());for(let r of e)ii(t,r[0],r[1]);return Y_(t)},W_=(e)=>k(e,ou),J_=(e)=>e&&dr(e._root),G_,su,km,ii,VM,cu=(e)=>new au(e,(t)=>t),Ns=(e)=>e._size,lu=(e)=>Rm(!0,e._edit+1,e._root,e._size),Y_=(e)=>(e._editable=!1,e),uu,Z_,pu,X_,Cm,sa;var Am=x(()=>{le();H();H();Me();Be();Ye();_e();ge();Tm();tu();j_();ou=Symbol.for(B_),jM={[ou]:ou,[Symbol.iterator](){return new au(this,(e,t)=>[e,t])},[M](){let e=v(B_);for(let t of this)e^=g(v(t[0]),J(v(t[1])));return oe(this,e)},[I](e){if(W_(e)){if(e._size!==this._size)return!1;for(let t of this){let r=g(e,su(t[0],v(t[0])));if(Ne(r))return!1;else if(!O(t[1],r.value))return!1}return!0}return!1},toString(){return he(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(ue)}},[re](){return this.toJSON()},pipe(){return E(this,arguments)}};au=class au{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=V_(this.map._root,this.f,void 0)}next(){if(Ne(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=iu(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new au(this.map,this.f)}};BM=Rm(!1,0,new An,0),G_=d(2,(e,t)=>su(e,t,v(t))),su=d(3,(e,t,r)=>{let n=e._root,o=0;while(!0)switch(n._tag){case"LeafNode":return O(t,n.key)?n.value:C();case"CollisionNode":{if(r===n.hash){let i=n.children;for(let a=0,s=i.length;a<s;++a){let c=i[a];if("key"in c&&O(t,c.key))return c.value}}return C()}case"IndexedNode":{let i=uo(o,r),a=po(i);if(n.mask&a){n=n.children[ru(n.mask,a)],o+=lo;break}return C()}case"ArrayNode":{if(n=n.children[uo(o,r)],n){o+=lo;break}return C()}default:return C()}}),km=d(2,(e,t)=>Re(su(e,t,v(t)))),ii=d(3,(e,t,r)=>uu(e,t,()=>N(r))),VM=d(3,(e,t,r)=>{if(e._editable)return e._root=t,e._size=r,e;return t===e._root?e:Rm(e._editable,e._edit,t,r)}),uu=d(3,(e,t,r)=>Z_(e,t,v(t),r)),Z_=d(4,(e,t,r,n)=>{let o={value:e._size},i=e._root.modify(e._editable?e._edit:NaN,0,n,r,t,o);return g(e,VM(i,o.value))}),pu=d(2,(e,t)=>uu(e,t,C)),X_=d(2,(e,t)=>sa(e,aa(),(r,n,o)=>ii(r,o,t(n,o)))),Cm=d(2,(e,t)=>sa(e,void 0,(r,n,o)=>t(n,o))),sa=d(3,(e,t,r)=>{let n=e._root;if(n._tag==="LeafNode")return Re(n.value)?r(t,n.value.value,n.key):t;if(n._tag==="EmptyNode")return t;let o=[n.children],i;while(i=o.pop())for(let a=0,s=i.length;a<s;){let c=i[a++];if(c&&!dr(c))if(c._tag==="LeafNode"){if(Re(c.value))t=r(t,c.value.value,c.key)}else o.push(c.children)}return t})});var ew="effect/HashSet",du,zM,fu=(e)=>{let t=Object.create(zM);return t._keyMap=e,t},tw=(e)=>k(e,du),KM,Fs=()=>KM,rw=(e)=>{let t=mu(Fs());for(let r of e)ca(t,r);return hu(t)},nw=(...e)=>{let t=mu(Fs());for(let r of e)ca(t,r);return hu(t)},ow,iw=(e)=>Ns(e._keyMap),mu=(e)=>fu(lu(e._keyMap)),hu=(e)=>(e._keyMap._editable=!1,e),Pm,ca,Im,aw,sw,cw,lw;var uw=x(()=>{le();H();Me();Be();_e();ge();Am();du=Symbol.for(ew),zM={[du]:du,[Symbol.iterator](){return cu(this._keyMap)},[M](){return oe(this,J(v(this._keyMap))(v(ew)))},[I](e){if(tw(e))return Ns(this._keyMap)===Ns(e._keyMap)&&O(this._keyMap,e._keyMap);return!1},toString(){return he(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(ue)}},[re](){return this.toJSON()},pipe(){return E(this,arguments)}},KM=fu(aa()),ow=d(2,(e,t)=>km(e._keyMap,t)),Pm=d(2,(e,t)=>{let r=mu(e);return t(r),hu(r)}),ca=d(2,(e,t)=>e._keyMap._editable?(ii(t,!0)(e._keyMap),e):fu(ii(t,!0)(e._keyMap))),Im=d(2,(e,t)=>e._keyMap._editable?(pu(t)(e._keyMap),e):fu(pu(t)(e._keyMap))),aw=d(2,(e,t)=>Pm(e,(r)=>{for(let n of t)Im(r,n)})),sw=d(2,(e,t)=>Pm(Fs(),(r)=>{cw(e,(n)=>ca(r,n));for(let n of t)ca(r,n)})),cw=d(2,(e,t)=>Cm(e._keyMap,(r,n)=>t(n))),lw=d(3,(e,t,r)=>sa(e._keyMap,t,(n,o,i)=>r(n,i)))});var Gr,pw,ai,dw,Ls,si,Mm,Nm,Pn,ci;var li=x(()=>{uw();Gr=Fs,pw=rw,ai=nw,dw=ow,Ls=iw,si=ca,Mm=Im,Nm=aw,Pn=sw,ci=lw});var ua="Die",fo="Empty",mo="Fail",ui="Interrupt",pi="Parallel",di="Sequential";var hw="effect/Cause",Dm,GM,pa,In,da=(e)=>{let t=Object.create(pa);return t._tag=mo,t.error=e,t},rr=(e)=>{let t=Object.create(pa);return t._tag=ua,t.defect=e,t},Ir=(e)=>{let t=Object.create(pa);return t._tag=ui,t.fiberId=e,t},hi=(e,t)=>{let r=Object.create(pa);return r._tag=pi,r.left=e,r.right=t,r},At=(e,t)=>{let r=Object.create(pa);return r._tag=di,r.left=e,r.right=t,r},gw=(e)=>k(e,Dm),qm=(e)=>e._tag===fo,yw=(e)=>e._tag===mo,gu=(e)=>{if(e._tag===fo)return!0;return fi(e,!0,(t,r)=>{switch(r._tag){case fo:return N(t);case ua:case mo:case ui:return N(!1);default:return C()}})},yu=(e)=>Re(xw(e)),fa=(e)=>bu(void 0,QM)(e),Um=(e)=>co(fi(e,pr(),(t,r)=>r._tag===mo?N(g(t,Ct(r.error))):C())),Hm=(e)=>co(fi(e,pr(),(t,r)=>r._tag===ua?N(g(t,Ct(r.defect))):C())),$m=(e)=>fi(e,Gr(),(t,r)=>r._tag===ui?N(g(t,si(r.fiberId))):C()),jm=(e)=>Bm(e,(t)=>t._tag===mo?N(t.error):C()),xu=(e)=>{let t=jm(e);switch(t._tag){case"None":return Z(e);case"Some":return K(t.value)}},xw=(e)=>Bm(e,(t)=>t._tag===ui?N(t.fiberId):C()),Su=(e)=>Vm(e,{onEmpty:In,onFail:()=>In,onDie:rr,onInterrupt:Ir,onSequential:At,onParallel:hi}),Sw=(e)=>Vm(e,{onEmpty:In,onFail:rr,onDie:rr,onInterrupt:Ir,onSequential:At,onParallel:hi}),YM=(e,t)=>{let r=rt(e),n=rt(t);while(Cr(r)&&Cr(n)){let[o,i]=g(Ar(r),fi([Gr(),pr()],([c,l],u)=>{let[p,f]=Fm(u);return N([g(c,Pn(p)),g(l,tr(f))])})),[a,s]=g(Ar(n),fi([Gr(),pr()],([c,l],u)=>{let[p,f]=Fm(u);return N([g(c,Pn(p)),g(l,tr(f))])}));if(!O(o,a))return!1;r=i,n=s}return!0},ZM=(e)=>XM(rt(e),pr()),XM=(e,t)=>{while(!0){let[r,n]=g(e,na([Gr(),pr()],([i,a],s)=>{let[c,l]=Fm(s);return[g(i,Pn(c)),g(a,tr(l))]})),o=Ls(r)>0?g(t,Ct(r)):t;if(F_(n))return co(o);e=n,t=o}throw Error(Yo("Cause.flattenCauseLoop"))},Bm,Fm=(e)=>{let t=e,r=[],n=Gr(),o=pr();while(t!==void 0)switch(t._tag){case fo:{if(r.length===0)return[n,o];t=r.pop();break}case mo:{if(n=si(n,Is(t._tag,t.error)),r.length===0)return[n,o];t=r.pop();break}case ua:{if(n=si(n,Is(t._tag,t.defect)),r.length===0)return[n,o];t=r.pop();break}case ui:{if(n=si(n,Is(t._tag,t.fiberId)),r.length===0)return[n,o];t=r.pop();break}case di:{switch(t.left._tag){case fo:{t=t.right;break}case di:{t=At(t.left.left,At(t.left.right,t.right));break}case pi:{t=hi(At(t.left.left,t.right),At(t.left.right,t.right));break}default:{o=Ct(o,t.right),t=t.left;break}}break}case pi:{r.push(t.right),t=t.left;break}}throw Error(Yo("Cause.evaluateCauseLoop"))},QM,fw="SequentialCase",mw="ParallelCase",Vm,fi,bu,Mr=(e,t)=>{if(fa(e))return"All fibers interrupted without errors.";return Ds(e).map(function(r){if(t?.renderErrorCause!==!0||r.cause===void 0)return r.stack;return`${r.stack} {
10
+ ${bw(r.cause," ")}
11
11
  }`}).join(`
12
- `)},kw=(e,t)=>{let n=e.stack.split(`
13
- `),r=`${t}[cause]: ${n[0]}`;for(let o=1,i=n.length;o<i;o++)r+=`
14
- ${t}${n[o]}`;if(e.cause)r+=` {
15
- ${kw(e.cause,`${t} `)}
16
- ${t}}`;return r},$m=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(dN(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:$m(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(gi in e)r.span=e[gi];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=hN(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},dN=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(C(e,"toString")&&oo(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return Ql(e)},fN,mN,hN=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
12
+ `)},bw=(e,t)=>{let r=e.stack.split(`
13
+ `),n=`${t}[cause]: ${r[0]}`;for(let o=1,i=r.length;o<i;o++)n+=`
14
+ ${t}${r[o]}`;if(e.cause)n+=` {
15
+ ${bw(e.cause,`${t} `)}
16
+ ${t}}`;return n},Lm=(e)=>{let t=typeof e==="object"&&e!==null,r=Error.stackTraceLimit;Error.stackTraceLimit=1;let n=Error(eN(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:Lm(e.cause)}:void 0);if(Error.stackTraceLimit=r,n.message==="")n.message="An error has occurred";if(Error.stackTraceLimit=r,n.name=e instanceof Error?e.name:"Error",t){if(mi in e)n.span=e[mi];Object.keys(e).forEach((o)=>{if(!(o in n))n[o]=e[o]})}return n.stack=nN(`${n.name}: ${n.message}`,e instanceof Error&&e.stack?e.stack:"",n.span),n},eN=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(k(e,"toString")&&to(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return Vl(e)},tN,rN,nN=(e,t,r)=>{let n=[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=mN.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(fN),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=Bt(i.parent),a++}}return r.join(`
19
- `)},gi,Vs=(e)=>Cu(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[$m(n)],failCase:(t,n)=>[$m(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Sa=x(()=>{Be();Qn();tn();pe();j();Me();pi();Ve();Ge();be();ye();jm=Symbol.for(vw),sN={_E:(e)=>e},ga={[jm]:sN,[M](){return g(E(vw),G(E(lN(this))),ie(this))},[I](e){return Tw(e)&&cN(this,e)},pipe(){return T(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:de(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:de(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:de(this.left),right:de(this.right)}}},toString(){return Nn(this)},[ne](){return this.toJSON()}},Dr=(()=>{let e=Object.create(ga);return e._tag=go,e})(),Jm=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 mi:case fi:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return A()}),pN={emptyCase:Ss,failCase:no,dieCase:no,interruptCase:Ss,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},Gm=d(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>Cu(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)})),hi=d(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=Re(a)?a.value:r,o._tag){case mi:{i.push(o.right),o=o.left;break}case fi:{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}),Cu=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case go:{o.push(Q(n.emptyCase(t)));break}case yo:{o.push(Q(n.failCase(t,a.error)));break}case ha:{o.push(Q(n.dieCase(t,a.defect)));break}case di:{o.push(Q(n.interruptCase(t,a.fiberId)));break}case mi:{r.push(a.right),r.push(a.left),o.push(W({_tag:bw}));break}case fi:{r.push(a.right),r.push(a.left),o.push(W({_tag:ww}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case bw:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case ww:{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()}),fN=/\((.*)\)/g,mN=V("effect/Tracer/spanToTrace",()=>new WeakMap),gi=Symbol.for("effect/SpanAnnotation")});var Cw,Ks,gN="effect/STM",yN,Aw,xN,Pw=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(Aw);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},Iw=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,xN),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},Zm,SN,xo=(e)=>{let t=Object.create(SN);return t.unsafeMap=e,t},_N=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(e.stack){let n=e.stack.split(`
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
- `);n.splice(1,3),t.stack=n.join(`
22
- `)}return t},Mw=(e)=>C(e,Zm),Nw=(e)=>C(e,Ks),bN,Fw=()=>bN,Xm=(e,t)=>xo(new Map([[e.key,t]])),Lw,Ym,Qm=(e)=>{if(Ym.has(e.key))return Ym.get(e.key);let t=e.defaultValue();return Ym.set(e.key,t),t},Dw=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Qm(t),eh,qw,Uw,Hw;var Au=x(()=>{pe();j();Me();Ve();be();ye();Rr();im();Cw=Symbol.for("effect/Context/Tag"),Ks=Symbol.for("effect/Context/Reference"),yN=Symbol.for(gN),Aw={...Or,_op:"Tag",[yN]:ao,[Cw]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return ge(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[ne](){return this.toJSON()},of(e){return e},context(e){return Xm(this,e)}},xN={...Aw,[Ks]:Ks},Zm=Symbol.for("effect/Context"),SN={[Zm]:{_Services:(e)=>e},[I](e){if(Mw(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!O(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[M](){return ie(this,Yl(this.unsafeMap.size))},pipe(){return T(this,arguments)},toString(){return ge(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(de)}},[ne](){return this.toJSON()}},bN=xo(new Map),Lw=d(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),xo(r)}),Ym=V("effect/Context/defaultValueCache",()=>new Map),eh=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(Ks in t)return Qm(t);throw _N(t)}return e.unsafeMap.get(t.key)}),qw=eh,Uw=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return Nw(t)?Fs(Qm(t)):nu;return Fs(e.unsafeMap.get(t.key))}),Hw=d(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return xo(n)})});var Kt,So,jw,tr,zs,Ws,_o,Js,Gs;var mn=x(()=>{Au();Kt=Pw,So=Fw,jw=Xm,tr=Lw,zs=qw,Ws=eh,_o=Uw,Js=Hw,Gs=Iw});var nh,Ww,Vw,Pu,rh,Bw,Kw,wN,qr=(e)=>{if(Jw(e))return e;else if(Qt(e))return Iu(e);else if(ro(e))return th(e);else if(Array.isArray(e)&&e.length===2&&e.every(Qt)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return oh;if(e[0]===1/0||e[1]===1/0)return ON;return th(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(gt(e)){let t=wN.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return th(BigInt(r));case"micro":case"micros":return RN(BigInt(r));case"milli":case"millis":return Iu(i);case"second":case"seconds":return kN(i);case"minute":case"minutes":return CN(i);case"hour":case"hours":return AN(i);case"day":case"days":return PN(i);case"week":case"weeks":return IN(i)}}}throw Error("Invalid DurationInput")},zw,vN,TN,nr=(e)=>{let t=Object.create(TN);if(Qt(e))if(isNaN(e)||e<=0)t.value=zw;else if(!Number.isFinite(e))t.value=vN;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<=Ww)t.value=zw;else t.value={_tag:"Nanos",nanos:e};return t},Jw=(e)=>C(e,nh),EN=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Ww;case"Infinity":return!1}},oh,ON,th=(e)=>nr(e),RN=(e)=>nr(e*rh),Iu=(e)=>nr(e),kN=(e)=>nr(e*1000),CN=(e)=>nr(e*60000),AN=(e)=>nr(e*3600000),PN=(e)=>nr(e*86400000),IN=(e)=>nr(e*604800000),Mu=(e)=>FN(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),MN=(e)=>{let t=qr(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))}},NN=(e)=>{let t=qr(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/Kw),Number(t.value.nanos%Kw)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},FN,ih,LN=(e,t)=>ih(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),Gw,Yw,DN,qN=(e)=>{let t=qr(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=MN(t),r=n/Bw,o=r/rh,i=o/Pu,a=i/Pu,s=a/Vw;return{days:Number(s),hours:Number(a%Vw),minutes:Number(i%Pu),seconds:Number(o%Pu),millis:Number(r%rh),nanos:Number(n%Bw)}},UN=(e)=>{let t=qr(e);if(t.value._tag==="Infinity")return"Infinity";if(EN(t))return"0";let n=qN(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 ah=x(()=>{pe();j();Me();Ve();be();ye();nh=Symbol.for("effect/Duration"),Ww=BigInt(0),Vw=BigInt(24),Pu=BigInt(60),rh=BigInt(1000),Bw=BigInt(1e6),Kw=BigInt(1e9),wN=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,zw={_tag:"Millis",millis:0},vN={_tag:"Infinity"},TN={[nh]:nh,[M](){return ie(this,Zl(this.value))},[I](e){return Jw(e)&&DN(this,e)},toString(){return`Duration(${UN(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:NN(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},oh=nr(0),ON=nr(1/0),FN=d(2,(e,t)=>{let n=qr(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)}}),ih=d(3,(e,t,n)=>{let r=qr(e),o=qr(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(Mu(r),Mu(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)}),Gw=d(2,(e,t)=>ih(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),Yw=d(2,(e,t)=>ih(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),DN=d(2,(e,t)=>LN(qr(e),qr(t)))});var Xw,HN,Nu=(e)=>{let t=Object.create(HN);return t.current=e,t},_a=(e)=>e.current,Fu;var sh=x(()=>{j();Ve();be();Xw=Symbol.for("effect/MutableRef"),HN={[Xw]:Xw,toString(){return ge(this.toJSON())},toJSON(){return{_id:"MutableRef",current:de(this.current)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},Fu=d(2,(e,t)=>(e.current=t,e))});var lh="effect/FiberId",ba,Lu="None",ch="Runtime",$N="Composite",jN,tv,nv,rv,uh=(e)=>C(e,ba),Du=(e)=>{switch(e._tag){case Lu:return er();case ch:return ci(e.id);case $N:return g(Du(e.left),Lr(Du(e.right)))}},ev,qu=(e)=>Array.from(Du(e)).map((n)=>`#${n}`).join(","),ov=()=>{let e=_a(ev);return g(ev,Fu(e+1)),new nv(e,Date.now())};var ph=x(()=>{pe();j();Me();pi();Ve();sh();ye();ba=Symbol.for(lh),jN=he(`${lh}-${Lu}`);tv=class tv{[ba]=ba;_tag=Lu;id=-1;startTimeMillis=-1;[M](){return jN}[I](e){return uh(e)&&e._tag===Lu}toString(){return ge(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[ne](){return this.toJSON()}};nv=class nv{id;startTimeMillis;[ba]=ba;_tag=ch;constructor(e,t){this.id=e,this.startTimeMillis=t}[M](){return ie(this,he(`${lh}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[I](e){return uh(e)&&e._tag===ch&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return ge(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[ne](){return this.toJSON()}};rv=new tv,ev=V(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Nu(0))});var hn,av,Uu;var wa=x(()=>{ph();hn=rv,av=qu,Uu=ov});var va,sv,cv,dh,fh,mh,lv,uv,hh;var Hu=x(()=>{Fm();va=pa,sv=ew,cv=nw,dh=rw,fh=si,mh=yu,lv=Su,uv=aw,hh=da});var Zs,yh=(e)=>ke(e),VN=(e)=>Kf(uo(e),yh),BN,KN,$u=(e,t)=>{let n=Object.create(KN);return n.head=e,n.tail=t,n},zN,WN,pv,dv=(e)=>C(e,Zs),rr=(e)=>e._tag==="Nil",xh=(e)=>e._tag==="Cons",JN=()=>pv,Ur=(e,t)=>$u(e,t),bo,Xs=(e)=>$u(e,pv),fv,GN,YN,mv,hv=(e)=>{let t=bo(),n=e;while(!rr(n))t=GN(t,n.head),n=n.tail;return t};var ju=x(()=>{Be();pe();vs();j();Me();Ve();be();ye();Zs=Symbol.for("effect/List"),BN=VN(O),KN={[Zs]:Zs,_tag:"Cons",toString(){return ge(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:yh(this).map(de)}},[ne](){return this.toJSON()},[I](e){return dv(e)&&this._tag===e._tag&&BN(this,e)},[M](){return ie(this,en(yh(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 T(this,arguments)}},zN=he("Nil"),WN={[Zs]:Zs,_tag:"Nil",toString(){return ge(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[ne](){return this.toJSON()},[M](){return zN},[I](e){return dv(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return T(this,arguments)}},pv=Object.create(WN),bo=JN,fv=d(2,(e,t)=>YN(t,e)),GN=d(2,(e,t)=>Ur(t,e)),YN=d(2,(e,t)=>{if(rr(e))return t;else if(rr(t))return e;else{let n=$u(t.head,e),r=n,o=t.tail;while(!rr(o)){let i=$u(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),mv=d(3,(e,t,n)=>{let r=t,o=e;while(!rr(o))r=n(r,o.head),o=o.tail;return r})});var rK,Ta;var Vu=x(()=>{pe();Me();Rr();rK=Object.assign(Object.create(Array.prototype),{[M](){return ie(this,en(this))},[I](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>O(t,e[n]));else return!1}}),Ta=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=Ns,e}()});function gv(e){return e}var XN,ec,QN,e0,_h=()=>e0,t0,n0=(e,t)=>{let n=Object.create(t0);return n.first=e,n.second=t,n},r0,o0=(e,t)=>{let n=Object.create(r0);return n.key=e,n.service=t,n},i0,a0=(e)=>{let t=Object.create(i0);return t.key=e,t},s0,c0=(e,t)=>{let n=Object.create(s0);return n.key=e,n.update=t,n},yv=(e,t)=>{let n=new Map(e.unsafeMap),r=_h();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!O(a,i))r=Qs(c0(o,()=>i))(r)}else n.delete(o),r=Qs(o0(o,i))(r);for(let[o]of n.entries())r=Qs(a0(o))(r);return r},Qs,xv;var Sv=x(()=>{Qn();pe();j();Au();Vu();XN=Symbol.for("effect/DifferContextPatch");ec={...Ta.prototype,[XN]:{_Value:gv,_Patch:gv}},QN=Object.assign(Object.create(ec),{_tag:"Empty"}),e0=Object.create(QN),t0=Object.assign(Object.create(ec),{_tag:"AndThen"}),r0=Object.assign(Object.create(ec),{_tag:"AddService"}),i0=Object.assign(Object.create(ec),{_tag:"RemoveService"}),s0=Object.assign(Object.create(ec),{_tag:"UpdateService"}),Qs=d(2,(e,t)=>n0(e,t)),xv=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=tt(e),o=new Map(t.unsafeMap);while(An(r)){let a=Pn(r),s=In(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=kt(kt(s,a.second),a.first);break}case"RemoveService":{o.delete(a.key),r=s;break}case"UpdateService":{o.set(a.key,a.update(o.get(a.key))),n=!0,r=s;break}}}if(!n)return xo(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 xo(i)})});function bh(e){return e}var u0,Ku,p0,d0,wh=()=>d0,f0,m0=(e,t)=>{let n=Object.create(f0);return n.first=e,n.second=t,n},h0,g0=(e)=>{let t=Object.create(h0);return t.value=e,t},y0,x0=(e)=>{let t=Object.create(y0);return t.value=e,t},_v=(e,t)=>{let[n,r]=ui([e,wh()],([o,i],a)=>{if(_w(a)(o))return[qm(a)(o),i];return[o,Bu(g0(a))(i)]})(t);return ui(r,(o,i)=>Bu(x0(i))(o))(n)},Bu,bv;var wv=x(()=>{Qn();j();pi();Vu();u0=Symbol.for("effect/DifferHashSetPatch");Ku={...Ta.prototype,[u0]:{_Value:bh,_Key:bh,_Patch:bh}},p0=Object.assign(Object.create(Ku),{_tag:"Empty"}),d0=Object.create(p0),f0=Object.assign(Object.create(Ku),{_tag:"AndThen"}),h0=Object.assign(Object.create(Ku),{_tag:"Add"}),y0=Object.assign(Object.create(Ku),{_tag:"Remove"}),Bu=d(2,(e,t)=>m0(e,t)),bv=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=tt(e);while(An(r)){let o=Pn(r),i=In(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=kt(o.first)(kt(o.second)(i));break}case"Add":{n=li(o.value)(n),r=i;break}case"Remove":n=qm(o.value)(n),r=i}}return n})});function vv(e){return e}var _0,nc,b0,w0,vh=()=>w0,v0,T0=(e,t)=>{let n=Object.create(v0);return n.first=e,n.second=t,n},E0,O0=(e)=>{let t=Object.create(E0);return t.values=e,t},R0,k0=(e,t)=>{let n=Object.create(R0);return n.from=e,n.until=t,n},C0,A0=(e,t)=>{let n=Object.create(C0);return n.index=e,n.patch=t,n},Tv=(e)=>{let t=0,n=vh();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(!O(i,e.differ.empty))n=tc(n,A0(t,i));t=t+1}if(t<e.oldValue.length)n=tc(n,k0(0,t));if(t<e.newValue.length)n=tc(n,O0(Fb(t)(e.newValue)));return n},tc,Ev;var Ov=x(()=>{Be();pe();j();Vu();_0=Symbol.for("effect/DifferReadonlyArrayPatch");nc={...Ta.prototype,[_0]:{_Value:vv,_Patch:vv}},b0=Object.assign(Object.create(nc),{_tag:"Empty"}),w0=Object.create(b0),v0=Object.assign(Object.create(nc),{_tag:"AndThen"}),E0=Object.assign(Object.create(nc),{_tag:"Append"}),R0=Object.assign(Object.create(nc),{_tag:"Slice"}),C0=Object.assign(Object.create(nc),{_tag:"Update"}),tc=d(2,(e,t)=>T0(e,t)),Ev=d(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=Rt(e);while(co(o)){let i=et(o),a=kn(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 Rv,I0,wo=(e)=>{let t=Object.create(I0);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},Th=()=>wo({empty:_h(),combine:(e,t)=>Qs(t)(e),diff:(e,t)=>yv(e,t),patch:(e,t)=>xv(t)(e)}),Eh=()=>wo({empty:wh(),combine:(e,t)=>Bu(t)(e),diff:(e,t)=>_v(e,t),patch:(e,t)=>bv(t)(e)}),Oh=(e)=>wo({empty:vh(),combine:(t,n)=>tc(t,n),diff:(t,n)=>Tv({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>Ev(t,n,e)}),zu=()=>kv((e,t)=>t),kv=(e)=>wo({empty:ue,combine:(t,n)=>{if(t===ue)return n;if(n===ue)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(O(t,n))return ue;return xs(n)},patch:(t,n)=>e(n,t(n))});var Wu=x(()=>{pe();j();be();Sv();wv();Ov();Rv=Symbol.for("effect/Differ"),I0={[Rv]:{_P:ue,_V:ue},pipe(){return T(this,arguments)}}});var rc=255,Cv=8,Ju=(e)=>e&rc,Gu=(e)=>e>>Cv&rc,xi=(e,t)=>(e&rc)+((t&e&rc)<<Cv),kh,Av=(e)=>xi(e,e),Pv=(e)=>xi(e,0),Iv,Ch,Mv=(e)=>~e>>>0&rc;var Ah=x(()=>{j();kh=xi(0,0),Iv=d(2,(e,t)=>xi(Ju(e)&~t,Gu(e))),Ch=d(2,(e,t)=>e|t)});var M0=0,Hr=1,Fv=2,Ph=4,Yu=16,Ih=32,Lv=(e)=>Zu(e,Ih),Mh,$r=(e)=>Nh(e)&&!N0(e),Nh=(e)=>Zu(e,Hr),Zu,Fh=(...e)=>e.reduce((t,n)=>t|n,0),Dv,Lh=(e)=>Zu(e,Ph),N0=(e)=>Zu(e,Yu),oc,ic,Dh;var ac=x(()=>{j();Wu();Ah();Mh=d(2,(e,t)=>e|t),Zu=d(2,(e,t)=>(e&t)!==0),Dv=Fh(M0),oc=d(2,(e,t)=>xi(e^t,t)),ic=d(2,(e,t)=>e&(Mv(Ju(t))|Gu(t))|Ju(t)&Gu(t)),Dh=wo({empty:kh,diff:(e,t)=>oc(e,t),combine:(e,t)=>Ch(t)(e),patch:(e,t)=>ic(t,e)})});var qv,Uh,Hh;var $h=x(()=>{Ah();qv=Av,Uh=Pv,Hh=Iv});var Vh=(e,t)=>({_tag:"Par",left:e,right:t}),Xu=(e,t)=>({_tag:"Seq",left:e,right:t}),Hv=(e)=>{let t=Xs(e),n=bo();while(!0){let[r,o]=mv(t,[$v(),bo()],([i,a],s)=>{let[c,l]=F0(s);return[H0(i,c),fv(a,l)]});if(n=L0(n,r),rr(o))return hv(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},F0=(e)=>{let t=e,n=$v(),r=bo(),o=bo();while(!0)switch(t._tag){case"Empty":{if(rr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Ur(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=Vh(Xu(s,a),Xu(c,a));break}case"Seq":{let{left:s,right:c}=i;t=Xu(s,Xu(c,a));break}case"Single":{t=i,o=Ur(a,o);break}}break}case"Single":{if(n=U0(n,t),rr(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")},L0=(e,t)=>{if(rr(e))return Xs(jh(t));if($0(t))return e;let n=W0(e.head),r=j0(t);if(n.length===1&&r.length===1&&O(n[0],r[0]))return Ur(z0(e.head,jh(t)),e.tail);return Ur(jh(t),e)},D0,q0,Qu,$v=()=>new Qu(va()),U0=(e,t)=>new Qu(lv(e.map,t.dataSource,(n)=>wb(On(n,jb(t.blockedRequest)),()=>tt(t.blockedRequest)))),H0=(e,t)=>new Qu(hh(e.map,t.map,(n,r,o)=>fh(n,o,Je(dh(n,o),{onNone:()=>r,onSome:(i)=>nn(r,i)})))),$0=(e)=>cv(e.map),j0=(e)=>Array.from(mh(e.map)),jh=(e)=>K0(uv(e.map,(t)=>tt(t))),V0,B0,Bh,K0=(e)=>new Bh(e),z0=(e,t)=>new Bh(hh(t.map,e.map,(n,r,o)=>fh(n,o,Je(dh(n,o),{onNone:()=>dn(),onSome:(i)=>nn(i,r)})))),W0=(e)=>Array.from(mh(e.map)),jv=(e)=>Array.from(e.map);var Vv=x(()=>{Qn();pe();Hu();ju();Ge();D0=Symbol.for("effect/RequestBlock/RequestBlockParallel"),q0={_R:(e)=>e};Qu=class Qu{map;[D0]=q0;constructor(e){this.map=e}};V0=Symbol.for("effect/RequestBlock/RequestBlockSequential"),B0={_R:(e)=>e};Bh=class Bh{map;[V0]=B0;constructor(e){this.map=e}}});var Ea="Pending",ep="Done";var G0="effect/Deferred",Kv,zv,Wv=(e)=>({_tag:Ea,joiners:e}),Jv=(e)=>({_tag:ep,effect:e});var Gv=x(()=>{Kv=Symbol.for(G0),zv={_E:(e)=>e,_A:(e)=>e}});var Oa;var Yv=x(()=>{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)}}});class Jh{patch;op;_op=Is;constructor(e,t){this.patch=e,this.op=t}}var rp=(e,t)=>{let n=new pt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},Wh=(e)=>{let t=new pt("RunBlocked");return t.effect_instruction_i0=e,t},vo,pt,Gh,Yh,Ra=(e)=>C(e,vo),xt=(e)=>{let t=new pt(tu);return t.effect_instruction_i0=e,t},iT,jr,Vr=(e)=>jr(e,void 0),Zh=function(){let e=new pt(ni);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(Xo("you're not supposed to end up here"))}return e},sc=(e,t=hn)=>{let n=new pt(ti),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,pc(n,(o)=>Ra(r)?r:nt)},aT=(e,t=hn)=>Ce(()=>sc(e,t)),To=(e,t=hn)=>Zh(e,function(){let n=void 0,r=void 0;function o(c){if(n)n(c);else if(r===void 0)r=c}let i=new pt(ti);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=yt(()=>this.effect_instruction_i0(o,s.signal));else a=yt(()=>this.effect_instruction_i0(o));return a||s?pc(i,(c)=>{if(s)s.abort();return a??nt}):i}),cc,Zv,op=(e,t)=>{if(Re(t))return new Proxy(e,{has(n,r){return r===gi||r===Zv||r in n},get(n,r){if(r===gi)return t.value;if(r===Zv)return e;return n[r]}});return e},ip=(e)=>qt(e)&&!(gi in e)?xt((t)=>At(rn(op(e,bp(t))))):At(rn(e)),Xh=(e)=>sT(()=>rn(new oF(e))),Si=(e)=>ka(e,{onFailure:(t)=>fe(W(t)),onSuccess:(t)=>fe(Q(t))}),Eo=(e)=>cT(e,{onFailure:ve,onSuccess:Ie}),dt=(e)=>qt(e)&&!(gi in e)?xt((t)=>At(ya(op(e,bp(t))))):At(ya(e)),Qh=(e)=>B(D(e),dt),At=(e)=>{let t=new Gh(jt);return t.effect_instruction_i0=e,t},sT=(e)=>B(D(e),At),eg,lc=(e)=>xt((t)=>e(t.id())),B,tg=(e)=>{let t=new pt("OnStep");return t.effect_instruction_i0=e,t},uc=(e)=>B(e,ue),cT,gn,ka,yn,_i,ap=(e)=>{let t=new pt(ri);return t.effect_instruction_i0=qv(Hr),t.effect_instruction_i1=()=>e,t},Ke,sp,bi,Ca,pc,fe=(e)=>{let t=new Yh(Vt);return t.effect_instruction_i0=e,t},Ce=(e)=>{let t=new pt(ni);return t.commit=e,t},D=(e)=>{let t=new pt(eu);return t.effect_instruction_i0=e,t},cp,ng=(e)=>xt((t)=>{let n=t.getFiberRef(np),r=g(n,Oe(()=>t.scope()));return e(ko(np,F(r)))}),lp=(e)=>{let t=new pt(ri);return t.effect_instruction_i0=Uh(Hr),t.effect_instruction_i1=()=>e,t},Oo=(e)=>Zh(e,function(){let t=new pt(ri);return t.effect_instruction_i0=Uh(Hr),t.effect_instruction_i1=(n)=>Nh(n)?yt(()=>this.effect_instruction_i0(ap)):yt(()=>this.effect_instruction_i0(lp)),t}),nt,rg=(e)=>{let t=new pt(ri);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},dc=(e)=>{let t=new pt(ra);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},fc=(e)=>{let t=new pt(ia);return typeof e?.priority<"u"?ST(t,e.priority):t},up,pp,Ro,mc,lT=(e)=>B(eg,(t)=>g(e,hc(t))),hc,uT,pT,dT,og,ig,ag,fT,mT,Q0="effect/FiberRef",eF,tF,dp=(e)=>xt((t)=>Ie(t.getFiberRef(e))),wi,Kh,nF,ko,St=(e,t)=>vi(e,{differ:zu(),fork:t?.fork??ue,join:t?.join}),hT=(e)=>{let t=Eh();return vi(e,{differ:t,fork:t.empty})},rF=(e)=>{let t=Oh(zu());return vi(e,{differ:t,fork:t.empty})},fp=(e)=>{let t=Th();return vi(e,{differ:t,fork:t.empty})},vi=(e,t)=>({...so,[eF]:tF,initial:e,commit(){return dp(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)}),gT=(e)=>vi(e,{differ:Dh,fork:Dh.empty}),Ti,Aa,sg,yT,cg,xT,ST,_T,bT,wT,vT,gc,np,yc,mp,hp,gp=(e,t)=>e.addFinalizer(()=>Vr(t)),lg=(e,t)=>e.close(t),Pa=(e,t)=>e.fork(t),yp,Ei=(e,t)=>{class n extends yp{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},Xv,oF,zh,NK,TT=(e)=>C(e,zh),Qv,iF,eT,xc,tT,FK,nT,LK,rT,DK,oT,aF,Ia=(e)=>Ra(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),ug=(e)=>e._tag==="Success",ET,Sc=(e)=>ET(e,void 0),Oi=(e,t)=>sF(e,t?.parallel?yi:Ct),pg=(e)=>ve(rn(e)),_c=(e)=>ve(ya(e)),ve=(e)=>{let t=new Gh(jt);return t.effect_instruction_i0=e,t},dg=(e)=>ve(Mn(e)),tp,xp,Ie=(e)=>{let t=new Yh(Vt);return t.effect_instruction_i0=e,t},xn,fg,sF=(e,t)=>{let n=lu(e);if(!An(n))return A();return g(In(n),ca(g(Pn(n),tp(tt)),(r,o)=>g(r,fg(o,{onSuccess:(i,a)=>g(i,kt(a)),onFailure:t}))),tp(po),tp((r)=>Mr(r)),F)},OT=(e)=>({...so,[Kv]:zv,state:Nu(Wv([])),commit(){return Sp(this)},blockingOn:e}),Sp=(e)=>aT((t)=>{let n=_a(e.state);switch(n._tag){case ep:return t(n.effect);case Ea:return n.joiners.push(t),cF(e,t)}},e.blockingOn),_p=(e,t)=>{let n=_a(e.state);if(n._tag===Ea){Fu(e.state,Jv(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},cF=(e,t)=>D(()=>{let n=_a(e.state);if(n._tag===Ea){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),lF,RT=()=>lF,Ri=(e)=>B(RT(),e),uF,mg,bp=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?F(t):A()};var rt=x(()=>{Be();Qn();mn();tn();pe();wa();j();Me();Hu();Ve();ju();sh();Ge();be();ye();$h();io();Sa();Gv();Wu();Rr();ac();Yv();vo=Symbol.for("effect/Effect");pt=class pt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[vo]=ao;constructor(e){this._op=e}[I](e){return this===e}[M](){return ie(this,Rs(this))}pipe(){return T(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:de(this.effect_instruction_i0),effect_instruction_i1:de(this.effect_instruction_i1),effect_instruction_i2:de(this.effect_instruction_i2)}}toString(){return ge(this.toJSON())}[ne](){return this.toJSON()}[Symbol.iterator](){return new Oa(new Tr(this))}};Gh=class Gh{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[vo]=ao;constructor(e){this._op=e,this._tag=e}[I](e){return Ia(e)&&e._op==="Failure"&&O(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(he(this._tag),G(E(this.effect_instruction_i0)),ie(this))}get cause(){return this.effect_instruction_i0}pipe(){return T(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return ge(this.toJSON())}[ne](){return this.toJSON()}[Symbol.iterator](){return new Oa(new Tr(this))}};Yh=class Yh{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[vo]=ao;constructor(e){this._op=e,this._tag=e}[I](e){return Ia(e)&&e._op==="Success"&&O(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(he(this._tag),G(E(this.effect_instruction_i0)),ie(this))}get value(){return this.effect_instruction_i0}pipe(){return T(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:de(this.value)}}toString(){return ge(this.toJSON())}[ne](){return this.toJSON()}[Symbol.iterator](){return new Oa(new Tr(this))}};iT=d(3,(e,t,n)=>Oo((r)=>B(e,(o)=>B(Eo(Ce(()=>r(t(o)))),(i)=>Ce(()=>n(o,i)).pipe(gn({onFailure:(a)=>{switch(i._tag){case jt:return At(Ct(i.effect_instruction_i0,a));case Vt:return At(a)}},onSuccess:()=>i})))))),jr=d(2,(e,t)=>B(e,()=>fe(t))),cc=d(2,(e,t)=>ka(e,{onFailure:t,onSuccess:fe})),Zv=Symbol.for("effect/OriginalAnnotation"),eg=xt((e)=>fe(e.id())),B=d(2,(e,t)=>{let n=new pt(ta);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),cT=d(2,(e,t)=>gn(e,{onFailure:(n)=>fe(t.onFailure(n)),onSuccess:(n)=>fe(t.onSuccess(n))})),gn=d(2,(e,t)=>{let n=new pt(na);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),ka=d(2,(e,t)=>gn(e,{onFailure:(n)=>{if(Km(n).length>0)return At(Rw(n));let o=Bm(n);if(o.length>0)return t.onFailure(Om(o));return At(n)},onSuccess:t.onSuccess})),yn=d(2,(e,t)=>Ce(()=>{let n=ke(e),r=oi(n.length),o=0;return jr(dc({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),_i=d(2,(e,t)=>Ce(()=>{let n=ke(e),r=0;return dc({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),Ke=d(2,(e,t)=>B(e,(n)=>D(()=>t(n)))),sp=d(2,(e,t)=>ka(e,{onFailure:(n)=>Qh(()=>t.onFailure(n)),onSuccess:(n)=>D(()=>t.onSuccess(n))})),bi=d(2,(e,t)=>gn(e,{onFailure:(n)=>{let r=Ru(n);switch(r._tag){case"Left":return Qh(()=>t(r.left));case"Right":return At(r.right)}},onSuccess:fe})),Ca=d(2,(e,t)=>Oo((n)=>gn(n(e),{onFailure:(r)=>{let o=ve(r);return gn(t(o),{onFailure:(i)=>ve(Ct(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=Ie(r);return Ro(t(o),o)}}))),pc=d(2,(e,t)=>Ca(e,xp({onFailure:(n)=>xa(n)?Vr(t(zm(n))):nt,onSuccess:()=>nt}))),cp=d((e)=>e.length===3||e.length===2&&!(qt(e[1])&&("onlyEffect"in e[1])),(e,t)=>B(e,(n)=>{let r=typeof t==="function"?t(n):t;if(Ra(r))return jr(r,n);else if(Y_(r))return sc((o)=>{r.then((i)=>o(fe(n)),(i)=>o(dt(new aF(i,"An unknown error occurred in Effect.tap"))))});return fe(n)})),nt=fe(void 0),up=d(2,(e,t)=>B(e,(n)=>Ke(t,(r)=>[n,r]))),pp=d(2,(e,t)=>B(e,(n)=>jr(t,n))),Ro=d(2,(e,t)=>B(e,()=>t)),mc=aT(()=>{let e=setInterval(()=>{},2147483647);return D(()=>clearInterval(e))}),hc=d(2,(e,t)=>B(e.interruptAsFork(t),()=>e.await)),uT={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return T(this,arguments)}},pT={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return T(this,arguments)}},dT={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return T(this,arguments)}},og={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return T(this,arguments)}},ig={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return T(this,arguments)}},ag={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return T(this,arguments)}},fT={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return T(this,arguments)}},mT={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return T(this,arguments)}},eF=Symbol.for(Q0),tF={_A:(e)=>e},wi=d(2,(e,t)=>B(dp(e),t)),Kh=d(2,(e,t)=>nF(e,()=>[void 0,t])),nF=d(2,(e,t)=>xt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),fe(r)})),ko=d(3,(e,t,n)=>iT(pp(dp(t),Kh(t,n)),()=>e,(r)=>Kh(t,r))),Ti=V(Symbol.for("effect/FiberRef/currentContext"),()=>fp(So())),Aa=V(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>St(0)),sg=V(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>St(2048)),yT=V(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>St(va())),cg=V(Symbol.for("effect/FiberRef/currentLogLevel"),()=>St(ig)),xT=V(Symbol.for("effect/FiberRef/currentLogSpan"),()=>St(bo())),ST=d(2,(e,t)=>ko(e,Aa,t)),_T=V(Symbol.for("effect/FiberRef/currentConcurrency"),()=>St("unbounded")),bT=V(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>St(!0)),wT=V(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>St(F(ag))),vT=V(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>St(F(og))),gc=V(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>rF(Pr())),np=V(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>St(A(),{fork:()=>A(),join:(e,t)=>e})),yc=V(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>St(Dr,{fork:()=>Dr,join:(e,t)=>e})),mp=Symbol.for("effect/Scope"),hp=Symbol.for("effect/CloseableScope"),yp=function(){class e extends globalThis.Error{commit(){return dt(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[ne](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
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;n.push(o[i].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(r){let i=r,a=0;while(i&&i._tag==="Span"&&a<10){let s=rN.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(tN),u=!1;for(let[,p]of l)u=!0,n.push(` at ${i.name} (${p})`);if(!u)n.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else n.push(` at ${i.name}`)}else n.push(` at ${i.name}`);i=Bt(i.parent),a++}}return n.join(`
19
+ `)},mi,Ds=(e)=>bu(e,void 0,{emptyCase:()=>[],dieCase:(t,r)=>[Lm(r)],failCase:(t,r)=>[Lm(r)],interruptCase:()=>[],parallelCase:(t,r,n)=>[...r,...n],sequentialCase:(t,r,n)=>[...r,...n]});var ma=x(()=>{Ve();Jr();er();le();H();Me();li();Be();Ye();_e();ge();Dm=Symbol.for(hw),GM={_E:(e)=>e},pa={[Dm]:GM,[M](){return g(v(hw),J(v(ZM(this))),oe(this))},[I](e){return gw(e)&&YM(this,e)},pipe(){return E(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:ue(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:ue(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:ue(this.left),right:ue(this.right)}}},toString(){return Mr(this)},[re](){return this.toJSON()}},In=(()=>{let e=Object.create(pa);return e._tag=fo,e})(),Bm=d(2,(e,t)=>{let r=[e];while(r.length>0){let n=r.pop(),o=t(n);switch(o._tag){case"None":{switch(n._tag){case di:case pi:{r.push(n.right),r.push(n.left);break}}break}case"Some":return o}}return C()}),QM={emptyCase:fs,failCase:Qn,dieCase:Qn,interruptCase:fs,sequentialCase:(e,t,r)=>t&&r,parallelCase:(e,t,r)=>t&&r},Vm=d(2,(e,{onDie:t,onEmpty:r,onFail:n,onInterrupt:o,onParallel:i,onSequential:a})=>bu(e,void 0,{emptyCase:()=>r,failCase:(s,c)=>n(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)})),fi=d(3,(e,t,r)=>{let n=t,o=e,i=[];while(o!==void 0){let a=r(n,o);switch(n=Re(a)?a.value:n,o._tag){case di:{i.push(o.right),o=o.left;break}case pi:{i.push(o.right),o=o.left;break}default:{o=void 0;break}}if(o===void 0&&i.length>0)o=i.pop()}return n}),bu=d(3,(e,t,r)=>{let n=[e],o=[];while(n.length>0){let a=n.pop();switch(a._tag){case fo:{o.push(Z(r.emptyCase(t)));break}case mo:{o.push(Z(r.failCase(t,a.error)));break}case ua:{o.push(Z(r.dieCase(t,a.defect)));break}case ui:{o.push(Z(r.interruptCase(t,a.fiberId)));break}case di:{n.push(a.right),n.push(a.left),o.push(K({_tag:fw}));break}case pi:{n.push(a.right),n.push(a.left),o.push(K({_tag:mw}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case fw:{let s=i.pop(),c=i.pop(),l=r.sequentialCase(t,s,c);i.push(l);break}case mw:{let s=i.pop(),c=i.pop(),l=r.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()}),tN=/\((.*)\)/g,rN=j("effect/Tracer/spanToTrace",()=>new WeakMap),mi=Symbol.for("effect/SpanAnnotation")});var _w,Us,oN="effect/STM",iN,ww,aN,Tw=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=t;let n=Object.create(ww);return Object.defineProperty(n,"stack",{get(){return r.stack}}),n.key=e,n},Ew=()=>(e,t)=>{let r=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=r;function o(){}return Object.setPrototypeOf(o,aN),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return n.stack}}),o},Km,sN,ho=(e)=>{let t=Object.create(sN);return t.unsafeMap=e,t},cN=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(e.stack){let r=e.stack.split(`
20
+ `);if(r.length>2){let n=r[2].match(/at (.*)/);if(n)t.message=t.message+` (defined at ${n[1]})`}}if(t.stack){let r=t.stack.split(`
21
+ `);r.splice(1,3),t.stack=r.join(`
22
+ `)}return t},vw=(e)=>k(e,Km),Ow=(e)=>k(e,Us),lN,Rw=()=>lN,Wm=(e,t)=>ho(new Map([[e.key,t]])),kw,zm,Jm=(e)=>{if(zm.has(e.key))return zm.get(e.key);let t=e.defaultValue();return zm.set(e.key,t),t},Cw=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Jm(t),Gm,Aw,Pw,Iw;var _u=x(()=>{le();H();Me();Be();_e();ge();wn();em();_w=Symbol.for("effect/Context/Tag"),Us=Symbol.for("effect/Context/Reference"),iN=Symbol.for(oN),ww={..._n,_op:"Tag",[iN]:no,[_w]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return he(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[re](){return this.toJSON()},of(e){return e},context(e){return Wm(this,e)}},aN={...ww,[Us]:Us},Km=Symbol.for("effect/Context"),sN={[Km]:{_Services:(e)=>e},[I](e){if(vw(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!O(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[M](){return oe(this,$l(this.unsafeMap.size))},pipe(){return E(this,arguments)},toString(){return he(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(ue)}},[re](){return this.toJSON()}},lN=ho(new Map),kw=d(3,(e,t,r)=>{let n=new Map(e.unsafeMap);return n.set(t.key,r),ho(n)}),zm=j("effect/Context/defaultValueCache",()=>new Map),Gm=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(Us in t)return Jm(t);throw cN(t)}return e.unsafeMap.get(t.key)}),Aw=Gm,Pw=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return Ow(t)?Cs(Jm(t)):Wl;return Cs(e.unsafeMap.get(t.key))}),Iw=d(2,(e,t)=>{let r=new Map(e.unsafeMap);for(let[n,o]of t.unsafeMap)r.set(n,o);return ho(r)})});var Vt,go,Nw,Yr,Hs,$s,yo,js,Bs;var fr=x(()=>{_u();Vt=Tw,go=Rw,Nw=Wm,Yr=kw,Hs=Aw,$s=Gm,yo=Pw,js=Iw,Bs=Ew});var Zm,Uw,Fw,wu,Xm,Lw,Dw,uN,Mn=(e)=>{if(Hw(e))return e;else if(Xt(e))return Tu(e);else if(eo(e))return Ym(e);else if(Array.isArray(e)&&e.length===2&&e.every(Xt)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return Qm;if(e[0]===1/0||e[1]===1/0)return mN;return Ym(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(xt(e)){let t=uN.exec(e);if(t){let[r,n,o]=t,i=Number(n);switch(o){case"nano":case"nanos":return Ym(BigInt(n));case"micro":case"micros":return hN(BigInt(n));case"milli":case"millis":return Tu(i);case"second":case"seconds":return gN(i);case"minute":case"minutes":return yN(i);case"hour":case"hours":return xN(i);case"day":case"days":return SN(i);case"week":case"weeks":return bN(i)}}}throw Error("Invalid DurationInput")},qw,pN,dN,Zr=(e)=>{let t=Object.create(dN);if(Xt(e))if(isNaN(e)||e<=0)t.value=qw;else if(!Number.isFinite(e))t.value=pN;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<=Uw)t.value=qw;else t.value={_tag:"Nanos",nanos:e};return t},Hw=(e)=>k(e,Zm),fN=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Uw;case"Infinity":return!1}},Qm,mN,Ym=(e)=>Zr(e),hN=(e)=>Zr(e*Xm),Tu=(e)=>Zr(e),gN=(e)=>Zr(e*1000),yN=(e)=>Zr(e*60000),xN=(e)=>Zr(e*3600000),SN=(e)=>Zr(e*86400000),bN=(e)=>Zr(e*604800000),Eu=(e)=>TN(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),_N=(e)=>{let t=Mn(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))}},wN=(e)=>{let t=Mn(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/Dw),Number(t.value.nanos%Dw)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},TN,eh,EN=(e,t)=>eh(e,t,{onMillis:(r,n)=>r===n,onNanos:(r,n)=>r===n}),$w,jw,vN,ON=(e)=>{let t=Mn(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 r=_N(t),n=r/Lw,o=n/Xm,i=o/wu,a=i/wu,s=a/Fw;return{days:Number(s),hours:Number(a%Fw),minutes:Number(i%wu),seconds:Number(o%wu),millis:Number(n%Xm),nanos:Number(r%Lw)}},RN=(e)=>{let t=Mn(e);if(t.value._tag==="Infinity")return"Infinity";if(fN(t))return"0";let r=ON(t),n=[];if(r.days!==0)n.push(`${r.days}d`);if(r.hours!==0)n.push(`${r.hours}h`);if(r.minutes!==0)n.push(`${r.minutes}m`);if(r.seconds!==0)n.push(`${r.seconds}s`);if(r.millis!==0)n.push(`${r.millis}ms`);if(r.nanos!==0)n.push(`${r.nanos}ns`);return n.join(" ")};var th=x(()=>{le();H();Me();Be();_e();ge();Zm=Symbol.for("effect/Duration"),Uw=BigInt(0),Fw=BigInt(24),wu=BigInt(60),Xm=BigInt(1000),Lw=BigInt(1e6),Dw=BigInt(1e9),uN=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,qw={_tag:"Millis",millis:0},pN={_tag:"Infinity"},dN={[Zm]:Zm,[M](){return oe(this,jl(this.value))},[I](e){return Hw(e)&&vN(this,e)},toString(){return`Duration(${RN(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:wN(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[re](){return this.toJSON()},pipe(){return E(this,arguments)}},Qm=Zr(0),mN=Zr(1/0),TN=d(2,(e,t)=>{let r=Mn(e);switch(r.value._tag){case"Nanos":return t.onNanos(r.value.nanos);case"Infinity":return t.onMillis(1/0);case"Millis":return t.onMillis(r.value.millis)}}),eh=d(3,(e,t,r)=>{let n=Mn(e),o=Mn(t);if(n.value._tag==="Infinity"||o.value._tag==="Infinity")return r.onMillis(Eu(n),Eu(o));else if(n.value._tag==="Nanos"||o.value._tag==="Nanos"){let i=n.value._tag==="Nanos"?n.value.nanos:BigInt(Math.round(n.value.millis*1e6)),a=o.value._tag==="Nanos"?o.value.nanos:BigInt(Math.round(o.value.millis*1e6));return r.onNanos(i,a)}return r.onMillis(n.value.millis,o.value.millis)}),$w=d(2,(e,t)=>eh(e,t,{onMillis:(r,n)=>r<=n,onNanos:(r,n)=>r<=n})),jw=d(2,(e,t)=>eh(e,t,{onMillis:(r,n)=>r>=n,onNanos:(r,n)=>r>=n})),vN=d(2,(e,t)=>EN(Mn(e),Mn(t)))});var Vw,kN,vu=(e)=>{let t=Object.create(kN);return t.current=e,t},ha=(e)=>e.current,Ou;var rh=x(()=>{H();Be();_e();Vw=Symbol.for("effect/MutableRef"),kN={[Vw]:Vw,toString(){return he(this.toJSON())},toJSON(){return{_id:"MutableRef",current:ue(this.current)}},[re](){return this.toJSON()},pipe(){return E(this,arguments)}},Ou=d(2,(e,t)=>(e.current=t,e))});var oh="effect/FiberId",ga,Ru="None",nh="Runtime",CN="Composite",AN,Ww,Jw,Gw,ih=(e)=>k(e,ga),ku=(e)=>{switch(e._tag){case Ru:return Gr();case nh:return ai(e.id);case CN:return g(ku(e.left),Pn(ku(e.right)))}},Kw,Cu=(e)=>Array.from(ku(e)).map((r)=>`#${r}`).join(","),Yw=()=>{let e=ha(Kw);return g(Kw,Ou(e+1)),new Jw(e,Date.now())};var ah=x(()=>{le();H();Me();li();Be();rh();ge();ga=Symbol.for(oh),AN=me(`${oh}-${Ru}`);Ww=class Ww{[ga]=ga;_tag=Ru;id=-1;startTimeMillis=-1;[M](){return AN}[I](e){return ih(e)&&e._tag===Ru}toString(){return he(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[re](){return this.toJSON()}};Jw=class Jw{id;startTimeMillis;[ga]=ga;_tag=nh;constructor(e,t){this.id=e,this.startTimeMillis=t}[M](){return oe(this,me(`${oh}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[I](e){return ih(e)&&e._tag===nh&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return he(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[re](){return this.toJSON()}};Gw=new Ww,Kw=j(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>vu(0))});var mr,Xw,Au;var ya=x(()=>{ah();mr=Gw,Xw=Cu,Au=Yw});var xa,Qw,eT,sh,ch,lh,tT,rT,uh;var Pu=x(()=>{Am();xa=aa,Qw=K_,eT=J_,sh=G_,ch=ii,lh=cu,tT=uu,rT=X_,uh=sa});var zs,dh=(e)=>ke(e),PN=(e)=>Hf(so(e),dh),IN,MN,Iu=(e,t)=>{let r=Object.create(MN);return r.head=e,r.tail=t,r},NN,FN,nT,oT=(e)=>k(e,zs),Xr=(e)=>e._tag==="Nil",fh=(e)=>e._tag==="Cons",LN=()=>nT,Nn=(e,t)=>Iu(e,t),xo,Ks=(e)=>Iu(e,nT),iT,DN,qN,aT,sT=(e)=>{let t=xo(),r=e;while(!Xr(r))t=DN(t,r.head),r=r.tail;return t};var Mu=x(()=>{Ve();le();ys();H();Me();Be();_e();ge();zs=Symbol.for("effect/List"),IN=PN(O),MN={[zs]:zs,_tag:"Cons",toString(){return he(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:dh(this).map(ue)}},[re](){return this.toJSON()},[I](e){return oT(e)&&this._tag===e._tag&&IN(this,e)},[M](){return oe(this,Qt(dh(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 r=t.head;return t=t.tail,{done:e,value:r}},return(r){if(!e)e=!0;return{done:!0,value:r}}}},pipe(){return E(this,arguments)}},NN=me("Nil"),FN={[zs]:zs,_tag:"Nil",toString(){return he(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[re](){return this.toJSON()},[M](){return NN},[I](e){return oT(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return E(this,arguments)}},nT=Object.create(FN),xo=LN,iT=d(2,(e,t)=>qN(t,e)),DN=d(2,(e,t)=>Nn(t,e)),qN=d(2,(e,t)=>{if(Xr(e))return t;else if(Xr(t))return e;else{let r=Iu(t.head,e),n=r,o=t.tail;while(!Xr(o)){let i=Iu(o.head,e);n.tail=i,n=i,o=o.tail}return r}}),aT=d(3,(e,t,r)=>{let n=t,o=e;while(!Xr(o))n=r(n,o.head),o=o.tail;return n})});var HV,Sa;var Nu=x(()=>{le();Me();wn();HV=Object.assign(Object.create(Array.prototype),{[M](){return oe(this,Qt(this))},[I](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,r)=>O(t,e[r]));else return!1}}),Sa=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=ks,e}()});function cT(e){return e}var HN,Js,$N,jN,hh=()=>jN,BN,VN=(e,t)=>{let r=Object.create(BN);return r.first=e,r.second=t,r},zN,KN=(e,t)=>{let r=Object.create(zN);return r.key=e,r.service=t,r},WN,JN=(e)=>{let t=Object.create(WN);return t.key=e,t},GN,YN=(e,t)=>{let r=Object.create(GN);return r.key=e,r.update=t,r},lT=(e,t)=>{let r=new Map(e.unsafeMap),n=hh();for(let[o,i]of t.unsafeMap.entries())if(r.has(o)){let a=r.get(o);if(r.delete(o),!O(a,i))n=Ws(YN(o,()=>i))(n)}else r.delete(o),n=Ws(KN(o,i))(n);for(let[o]of r.entries())n=Ws(JN(o))(n);return n},Ws,uT;var pT=x(()=>{Jr();le();H();_u();Nu();HN=Symbol.for("effect/DifferContextPatch");Js={...Sa.prototype,[HN]:{_Value:cT,_Patch:cT}},$N=Object.assign(Object.create(Js),{_tag:"Empty"}),jN=Object.create($N),BN=Object.assign(Object.create(Js),{_tag:"AndThen"}),zN=Object.assign(Object.create(Js),{_tag:"AddService"}),WN=Object.assign(Object.create(Js),{_tag:"RemoveService"}),GN=Object.assign(Object.create(Js),{_tag:"UpdateService"}),Ws=d(2,(e,t)=>VN(e,t)),uT=d(2,(e,t)=>{if(e._tag==="Empty")return t;let r=!1,n=rt(e),o=new Map(t.unsafeMap);while(Cr(n)){let a=Ar(n),s=Pr(n);switch(a._tag){case"Empty":{n=s;break}case"AddService":{o.set(a.key,a.service),n=s;break}case"AndThen":{n=Ct(Ct(s,a.second),a.first);break}case"RemoveService":{o.delete(a.key),n=s;break}case"UpdateService":{o.set(a.key,a.update(o.get(a.key))),r=!0,n=s;break}}}if(!r)return ho(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 ho(i)})});function gh(e){return e}var XN,Lu,QN,e0,yh=()=>e0,t0,r0=(e,t)=>{let r=Object.create(t0);return r.first=e,r.second=t,r},n0,o0=(e)=>{let t=Object.create(n0);return t.value=e,t},i0,a0=(e)=>{let t=Object.create(i0);return t.value=e,t},dT=(e,t)=>{let[r,n]=ci([e,yh()],([o,i],a)=>{if(dw(a)(o))return[Mm(a)(o),i];return[o,Fu(o0(a))(i)]})(t);return ci(n,(o,i)=>Fu(a0(i))(o))(r)},Fu,fT;var mT=x(()=>{Jr();H();li();Nu();XN=Symbol.for("effect/DifferHashSetPatch");Lu={...Sa.prototype,[XN]:{_Value:gh,_Key:gh,_Patch:gh}},QN=Object.assign(Object.create(Lu),{_tag:"Empty"}),e0=Object.create(QN),t0=Object.assign(Object.create(Lu),{_tag:"AndThen"}),n0=Object.assign(Object.create(Lu),{_tag:"Add"}),i0=Object.assign(Object.create(Lu),{_tag:"Remove"}),Fu=d(2,(e,t)=>r0(e,t)),fT=d(2,(e,t)=>{if(e._tag==="Empty")return t;let r=t,n=rt(e);while(Cr(n)){let o=Ar(n),i=Pr(n);switch(o._tag){case"Empty":{n=i;break}case"AndThen":{n=Ct(o.first)(Ct(o.second)(i));break}case"Add":{r=si(o.value)(r),n=i;break}case"Remove":r=Mm(o.value)(r),n=i}}return r})});function hT(e){return e}var c0,Ys,l0,u0,xh=()=>u0,p0,d0=(e,t)=>{let r=Object.create(p0);return r.first=e,r.second=t,r},f0,m0=(e)=>{let t=Object.create(f0);return t.values=e,t},h0,g0=(e,t)=>{let r=Object.create(h0);return r.from=e,r.until=t,r},y0,x0=(e,t)=>{let r=Object.create(y0);return r.index=e,r.patch=t,r},gT=(e)=>{let t=0,r=xh();while(t<e.oldValue.length&&t<e.newValue.length){let n=e.oldValue[t],o=e.newValue[t],i=e.differ.diff(n,o);if(!O(i,e.differ.empty))r=Gs(r,x0(t,i));t=t+1}if(t<e.oldValue.length)r=Gs(r,g0(0,t));if(t<e.newValue.length)r=Gs(r,m0(R_(t)(e.newValue)));return r},Gs,yT;var xT=x(()=>{Ve();le();H();Nu();c0=Symbol.for("effect/DifferReadonlyArrayPatch");Ys={...Sa.prototype,[c0]:{_Value:hT,_Patch:hT}},l0=Object.assign(Object.create(Ys),{_tag:"Empty"}),u0=Object.create(l0),p0=Object.assign(Object.create(Ys),{_tag:"AndThen"}),f0=Object.assign(Object.create(Ys),{_tag:"Append"}),h0=Object.assign(Object.create(Ys),{_tag:"Slice"}),y0=Object.assign(Object.create(Ys),{_tag:"Update"}),Gs=d(2,(e,t)=>d0(e,t)),yT=d(3,(e,t,r)=>{if(e._tag==="Empty")return t;let n=t.slice(),o=kt(e);while(io(o)){let i=tt(o),a=Rr(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)n.push(s);o=a;break}case"Slice":{n=n.slice(i.from,i.until),o=a;break}case"Update":{n[i.index]=r.patch(i.patch,n[i.index]),o=a;break}}}return n})});var ST,b0,So=(e)=>{let t=Object.create(b0);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},Sh=()=>So({empty:hh(),combine:(e,t)=>Ws(t)(e),diff:(e,t)=>lT(e,t),patch:(e,t)=>uT(t)(e)}),bh=()=>So({empty:yh(),combine:(e,t)=>Fu(t)(e),diff:(e,t)=>dT(e,t),patch:(e,t)=>fT(t)(e)}),_h=(e)=>So({empty:xh(),combine:(t,r)=>Gs(t,r),diff:(t,r)=>gT({oldValue:t,newValue:r,differ:e}),patch:(t,r)=>yT(t,r,e)}),Du=()=>bT((e,t)=>t),bT=(e)=>So({empty:ce,combine:(t,r)=>{if(t===ce)return r;if(r===ce)return t;return(n)=>r(t(n))},diff:(t,r)=>{if(O(t,r))return ce;return ds(r)},patch:(t,r)=>e(r,t(r))});var qu=x(()=>{le();H();_e();pT();mT();xT();ST=Symbol.for("effect/Differ"),b0={[ST]:{_P:ce,_V:ce},pipe(){return E(this,arguments)}}});var Zs=255,_T=8,Uu=(e)=>e&Zs,Hu=(e)=>e>>_T&Zs,gi=(e,t)=>(e&Zs)+((t&e&Zs)<<_T),Th,wT=(e)=>gi(e,e),TT=(e)=>gi(e,0),ET,Eh,vT=(e)=>~e>>>0&Zs;var vh=x(()=>{H();Th=gi(0,0),ET=d(2,(e,t)=>gi(Uu(e)&~t,Hu(e))),Eh=d(2,(e,t)=>e|t)});var _0=0,Fn=1,RT=2,Oh=4,$u=16,Rh=32,kT=(e)=>ju(e,Rh),kh,Ln=(e)=>Ch(e)&&!w0(e),Ch=(e)=>ju(e,Fn),ju,Ah=(...e)=>e.reduce((t,r)=>t|r,0),CT,Ph=(e)=>ju(e,Oh),w0=(e)=>ju(e,$u),Xs,Qs,Ih;var ec=x(()=>{H();qu();vh();kh=d(2,(e,t)=>e|t),ju=d(2,(e,t)=>(e&t)!==0),CT=Ah(_0),Xs=d(2,(e,t)=>gi(e^t,t)),Qs=d(2,(e,t)=>e&(vT(Uu(t))|Hu(t))|Uu(t)&Hu(t)),Ih=So({empty:Th,diff:(e,t)=>Xs(e,t),combine:(e,t)=>Eh(t)(e),patch:(e,t)=>Qs(t,e)})});var AT,Nh,Fh;var Lh=x(()=>{vh();AT=wT,Nh=TT,Fh=ET});var qh=(e,t)=>({_tag:"Par",left:e,right:t}),Bu=(e,t)=>({_tag:"Seq",left:e,right:t}),IT=(e)=>{let t=Ks(e),r=xo();while(!0){let[n,o]=aT(t,[MT(),xo()],([i,a],s)=>{let[c,l]=T0(s);return[k0(i,c),iT(a,l)]});if(r=E0(r,n),Xr(o))return sT(r);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},T0=(e)=>{let t=e,r=MT(),n=xo(),o=xo();while(!0)switch(t._tag){case"Empty":{if(Xr(n))return[r,o];t=n.head,n=n.tail;break}case"Par":{n=Nn(t.right,n),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=qh(Bu(s,a),Bu(c,a));break}case"Seq":{let{left:s,right:c}=i;t=Bu(s,Bu(c,a));break}case"Single":{t=i,o=Nn(a,o);break}}break}case"Single":{if(r=R0(r,t),Xr(n))return[r,o];t=n.head,n=n.tail;break}}throw Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues")},E0=(e,t)=>{if(Xr(e))return Ks(Dh(t));if(C0(t))return e;let r=F0(e.head),n=A0(t);if(r.length===1&&n.length===1&&O(r[0],n[0]))return Nn(N0(e.head,Dh(t)),e.tail);return Nn(Dh(t),e)},v0,O0,Vu,MT=()=>new Vu(xa()),R0=(e,t)=>new Vu(tT(e.map,t.dataSource,(r)=>m_(vr(r,N_(t.blockedRequest)),()=>rt(t.blockedRequest)))),k0=(e,t)=>new Vu(uh(e.map,t.map,(r,n,o)=>ch(r,o,Ge(sh(r,o),{onNone:()=>n,onSome:(i)=>tr(n,i)})))),C0=(e)=>eT(e.map),A0=(e)=>Array.from(lh(e.map)),Dh=(e)=>M0(rT(e.map,(t)=>rt(t))),P0,I0,Uh,M0=(e)=>new Uh(e),N0=(e,t)=>new Uh(uh(t.map,e.map,(r,n,o)=>ch(r,o,Ge(sh(r,o),{onNone:()=>pr(),onSome:(i)=>tr(i,n)})))),F0=(e)=>Array.from(lh(e.map)),NT=(e)=>Array.from(e.map);var FT=x(()=>{Jr();le();Pu();Mu();Ye();v0=Symbol.for("effect/RequestBlock/RequestBlockParallel"),O0={_R:(e)=>e};Vu=class Vu{map;[v0]=O0;constructor(e){this.map=e}};P0=Symbol.for("effect/RequestBlock/RequestBlockSequential"),I0={_R:(e)=>e};Uh=class Uh{map;[P0]=I0;constructor(e){this.map=e}}});var ba="Pending",zu="Done";var D0="effect/Deferred",DT,qT,UT=(e)=>({_tag:ba,joiners:e}),HT=(e)=>({_tag:zu,effect:e});var $T=x(()=>{DT=Symbol.for(D0),qT={_E:(e)=>e,_A:(e)=>e}});var _a;var jT=x(()=>{_a=class _a{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 _a(this.self)}}});class Bh{patch;op;_op=Os;constructor(e,t){this.patch=e,this.op=t}}var Ju=(e,t)=>{let r=new dt("Blocked");return r.effect_instruction_i0=e,r.effect_instruction_i1=t,r},jh=(e)=>{let t=new dt("RunBlocked");return t.effect_instruction_i0=e,t},bo,dt,Vh,zh,wa=(e)=>k(e,bo),bt=(e)=>{let t=new dt(Kl);return t.effect_instruction_i0=e,t},ZT,Dn,qn=(e)=>Dn(e,void 0),Kh=function(){let e=new dt(ei);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(Yo("you're not supposed to end up here"))}return e},tc=(e,t=mr)=>{let r=new dt(Qo),n=void 0;return r.effect_instruction_i0=(o)=>{n=e(o)},r.effect_instruction_i1=t,ic(r,(o)=>wa(n)?n:nt)},XT=(e,t=mr)=>Ce(()=>tc(e,t)),_o=(e,t=mr)=>Kh(e,function(){let r=void 0,n=void 0;function o(c){if(r)r(c);else if(n===void 0)n=c}let i=new dt(Qo);i.effect_instruction_i0=(c)=>{if(r=c,n)c(n)},i.effect_instruction_i1=t;let a=void 0,s=void 0;if(this.effect_instruction_i0.length!==1)s=new AbortController,a=St(()=>this.effect_instruction_i0(o,s.signal));else a=St(()=>this.effect_instruction_i0(o));return a||s?ic(i,(c)=>{if(s)s.abort();return a??nt}):i}),rc,BT,Gu=(e,t)=>{if(Re(t))return new Proxy(e,{has(r,n){return n===mi||n===BT||n in r},get(r,n){if(n===mi)return t.value;if(n===BT)return e;return r[n]}});return e},Yu=(e)=>Dt(e)&&!(mi in e)?bt((t)=>Pt(rr(Gu(e,dp(t))))):Pt(rr(e)),Wh=(e)=>QT(()=>rr(new K0(e))),yi=(e)=>Ta(e,{onFailure:(t)=>pe(K(t)),onSuccess:(t)=>pe(Z(t))}),wo=(e)=>eE(e,{onFailure:Te,onSuccess:Ie}),ft=(e)=>Dt(e)&&!(mi in e)?bt((t)=>Pt(da(Gu(e,dp(t))))):Pt(da(e)),Jh=(e)=>B(L(e),ft),Pt=(e)=>{let t=new Vh($t);return t.effect_instruction_i0=e,t},QT=(e)=>B(L(e),Pt),Gh,nc=(e)=>bt((t)=>e(t.id())),B,Yh=(e)=>{let t=new dt("OnStep");return t.effect_instruction_i0=e,t},oc=(e)=>B(e,ce),eE,hr,Ta,gr,xi,Zu=(e)=>{let t=new dt(ti);return t.effect_instruction_i0=AT(Fn),t.effect_instruction_i1=()=>e,t},ze,Xu,Si,Ea,ic,pe=(e)=>{let t=new zh(jt);return t.effect_instruction_i0=e,t},Ce=(e)=>{let t=new dt(ei);return t.commit=e,t},L=(e)=>{let t=new dt(zl);return t.effect_instruction_i0=e,t},Qu,Zh=(e)=>bt((t)=>{let r=t.getFiberRef(Wu),n=g(r,ve(()=>t.scope()));return e(vo(Wu,N(n)))}),ep=(e)=>{let t=new dt(ti);return t.effect_instruction_i0=Nh(Fn),t.effect_instruction_i1=()=>e,t},To=(e)=>Kh(e,function(){let t=new dt(ti);return t.effect_instruction_i0=Nh(Fn),t.effect_instruction_i1=(r)=>Ch(r)?St(()=>this.effect_instruction_i0(Zu)):St(()=>this.effect_instruction_i0(ep)),t}),nt,Xh=(e)=>{let t=new dt(ti);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},ac=(e)=>{let t=new dt(Xi);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},sc=(e)=>{let t=new dt(ea);return typeof e?.priority<"u"?pE(t,e.priority):t},tp,rp,Eo,cc,tE=(e)=>B(Gh,(t)=>g(e,lc(t))),lc,rE,nE,oE,Qh,eg,tg,iE,aE,$0="effect/FiberRef",j0,B0,np=(e)=>bt((t)=>Ie(t.getFiberRef(e))),bi,Hh,V0,vo,_t=(e,t)=>_i(e,{differ:Du(),fork:t?.fork??ce,join:t?.join}),sE=(e)=>{let t=bh();return _i(e,{differ:t,fork:t.empty})},z0=(e)=>{let t=_h(Du());return _i(e,{differ:t,fork:t.empty})},op=(e)=>{let t=Sh();return _i(e,{differ:t,fork:t.empty})},_i=(e,t)=>({...oo,[j0]:B0,initial:e,commit(){return np(this)},diff:(n,o)=>t.differ.diff(n,o),combine:(n,o)=>t.differ.combine(n,o),patch:(n)=>(o)=>t.differ.patch(n,o),fork:t.fork,join:t.join??((n,o)=>o)}),cE=(e)=>_i(e,{differ:Ih,fork:Ih.empty}),wi,va,rg,lE,ng,uE,pE,dE,fE,mE,hE,uc,Wu,pc,ip,ap,sp=(e,t)=>e.addFinalizer(()=>qn(t)),og=(e,t)=>e.close(t),Oa=(e,t)=>e.fork(t),cp,Ti=(e,t)=>{class r extends cp{_tag=t}return Object.assign(r.prototype,e),r.prototype.name=t,r},VT,K0,$h,yz,gE=(e)=>k(e,$h),zT,W0,KT,dc,WT,xz,JT,Sz,GT,bz,YT,J0,Ra=(e)=>wa(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),ig=(e)=>e._tag==="Success",yE,fc=(e)=>yE(e,void 0),Ei=(e,t)=>G0(e,t?.parallel?hi:At),ag=(e)=>Te(rr(e)),mc=(e)=>Te(da(e)),Te=(e)=>{let t=new Vh($t);return t.effect_instruction_i0=e,t},sg=(e)=>Te(Ir(e)),Ku,lp,Ie=(e)=>{let t=new zh(jt);return t.effect_instruction_i0=e,t},yr,cg,G0=(e,t)=>{let r=eu(e);if(!Cr(r))return C();return g(Pr(r),na(g(Ar(r),Ku(rt)),(n,o)=>g(n,cg(o,{onSuccess:(i,a)=>g(i,Ct(a)),onFailure:t}))),Ku(co),Ku((n)=>kn(n)),N)},xE=(e)=>({...oo,[DT]:qT,state:vu(UT([])),commit(){return up(this)},blockingOn:e}),up=(e)=>XT((t)=>{let r=ha(e.state);switch(r._tag){case zu:return t(r.effect);case ba:return r.joiners.push(t),Y0(e,t)}},e.blockingOn),pp=(e,t)=>{let r=ha(e.state);if(r._tag===ba){Ou(e.state,HT(t));for(let n=0,o=r.joiners.length;n<o;n++)r.joiners[n](t)}},Y0=(e,t)=>L(()=>{let r=ha(e.state);if(r._tag===ba){let n=r.joiners.indexOf(t);if(n>=0)r.joiners.splice(n,1)}}),Z0,SE=()=>Z0,vi=(e)=>B(SE(),e),X0,lg,dp=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?N(t):C()};var ot=x(()=>{Ve();Jr();fr();er();le();ya();H();Me();Pu();Be();Mu();rh();Ye();_e();ge();Lh();ro();ma();$T();qu();wn();ec();jT();bo=Symbol.for("effect/Effect");dt=class dt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[bo]=no;constructor(e){this._op=e}[I](e){return this===e}[M](){return oe(this,_s(this))}pipe(){return E(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:ue(this.effect_instruction_i0),effect_instruction_i1:ue(this.effect_instruction_i1),effect_instruction_i2:ue(this.effect_instruction_i2)}}toString(){return he(this.toJSON())}[re](){return this.toJSON()}[Symbol.iterator](){return new _a(new Sn(this))}};Vh=class Vh{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[bo]=no;constructor(e){this._op=e,this._tag=e}[I](e){return Ra(e)&&e._op==="Failure"&&O(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(me(this._tag),J(v(this.effect_instruction_i0)),oe(this))}get cause(){return this.effect_instruction_i0}pipe(){return E(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return he(this.toJSON())}[re](){return this.toJSON()}[Symbol.iterator](){return new _a(new Sn(this))}};zh=class zh{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[bo]=no;constructor(e){this._op=e,this._tag=e}[I](e){return Ra(e)&&e._op==="Success"&&O(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(me(this._tag),J(v(this.effect_instruction_i0)),oe(this))}get value(){return this.effect_instruction_i0}pipe(){return E(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:ue(this.value)}}toString(){return he(this.toJSON())}[re](){return this.toJSON()}[Symbol.iterator](){return new _a(new Sn(this))}};ZT=d(3,(e,t,r)=>To((n)=>B(e,(o)=>B(wo(Ce(()=>n(t(o)))),(i)=>Ce(()=>r(o,i)).pipe(hr({onFailure:(a)=>{switch(i._tag){case $t:return Pt(At(i.effect_instruction_i0,a));case jt:return Pt(a)}},onSuccess:()=>i})))))),Dn=d(2,(e,t)=>B(e,()=>pe(t))),rc=d(2,(e,t)=>Ta(e,{onFailure:t,onSuccess:pe})),BT=Symbol.for("effect/OriginalAnnotation"),Gh=bt((e)=>pe(e.id())),B=d(2,(e,t)=>{let r=new dt(Yi);return r.effect_instruction_i0=e,r.effect_instruction_i1=t,r}),eE=d(2,(e,t)=>hr(e,{onFailure:(r)=>pe(t.onFailure(r)),onSuccess:(r)=>pe(t.onSuccess(r))})),hr=d(2,(e,t)=>{let r=new dt(Zi);return r.effect_instruction_i0=e,r.effect_instruction_i1=t.onFailure,r.effect_instruction_i2=t.onSuccess,r}),Ta=d(2,(e,t)=>hr(e,{onFailure:(r)=>{if(Hm(r).length>0)return Pt(Sw(r));let o=Um(r);if(o.length>0)return t.onFailure(_m(o));return Pt(r)},onSuccess:t.onSuccess})),gr=d(2,(e,t)=>Ce(()=>{let r=ke(e),n=ri(r.length),o=0;return Dn(ac({while:()=>o<r.length,body:()=>t(r[o],o),step:(i)=>{n[o++]=i}}),n)})),xi=d(2,(e,t)=>Ce(()=>{let r=ke(e),n=0;return ac({while:()=>n<r.length,body:()=>t(r[n],n),step:()=>{n++}})})),ze=d(2,(e,t)=>B(e,(r)=>L(()=>t(r)))),Xu=d(2,(e,t)=>Ta(e,{onFailure:(r)=>Jh(()=>t.onFailure(r)),onSuccess:(r)=>L(()=>t.onSuccess(r))})),Si=d(2,(e,t)=>hr(e,{onFailure:(r)=>{let n=xu(r);switch(n._tag){case"Left":return Jh(()=>t(n.left));case"Right":return Pt(n.right)}},onSuccess:pe})),Ea=d(2,(e,t)=>To((r)=>hr(r(e),{onFailure:(n)=>{let o=Te(n);return hr(t(o),{onFailure:(i)=>Te(At(n,i)),onSuccess:()=>o})},onSuccess:(n)=>{let o=Ie(n);return Eo(t(o),o)}}))),ic=d(2,(e,t)=>Ea(e,lp({onFailure:(r)=>fa(r)?qn(t($m(r))):nt,onSuccess:()=>nt}))),Qu=d((e)=>e.length===3||e.length===2&&!(Dt(e[1])&&("onlyEffect"in e[1])),(e,t)=>B(e,(r)=>{let n=typeof t==="function"?t(r):t;if(wa(n))return Dn(n,r);else if(jb(n))return tc((o)=>{n.then((i)=>o(pe(r)),(i)=>o(ft(new J0(i,"An unknown error occurred in Effect.tap"))))});return pe(r)})),nt=pe(void 0),tp=d(2,(e,t)=>B(e,(r)=>ze(t,(n)=>[r,n]))),rp=d(2,(e,t)=>B(e,(r)=>Dn(t,r))),Eo=d(2,(e,t)=>B(e,()=>t)),cc=XT(()=>{let e=setInterval(()=>{},2147483647);return L(()=>clearInterval(e))}),lc=d(2,(e,t)=>B(e.interruptAsFork(t),()=>e.await)),rE={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return E(this,arguments)}},nE={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return E(this,arguments)}},oE={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return E(this,arguments)}},Qh={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return E(this,arguments)}},eg={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return E(this,arguments)}},tg={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return E(this,arguments)}},iE={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return E(this,arguments)}},aE={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return E(this,arguments)}},j0=Symbol.for($0),B0={_A:(e)=>e},bi=d(2,(e,t)=>B(np(e),t)),Hh=d(2,(e,t)=>V0(e,()=>[void 0,t])),V0=d(2,(e,t)=>bt((r)=>{let[n,o]=t(r.getFiberRef(e));return r.setFiberRef(e,o),pe(n)})),vo=d(3,(e,t,r)=>ZT(rp(np(t),Hh(t,r)),()=>e,(n)=>Hh(t,n))),wi=j(Symbol.for("effect/FiberRef/currentContext"),()=>op(go())),va=j(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>_t(0)),rg=j(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>_t(2048)),lE=j(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>_t(xa())),ng=j(Symbol.for("effect/FiberRef/currentLogLevel"),()=>_t(eg)),uE=j(Symbol.for("effect/FiberRef/currentLogSpan"),()=>_t(xo())),pE=d(2,(e,t)=>vo(e,va,t)),dE=j(Symbol.for("effect/FiberRef/currentConcurrency"),()=>_t("unbounded")),fE=j(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>_t(!0)),mE=j(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>_t(N(tg))),hE=j(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>_t(N(Qh))),uc=j(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>z0(On())),Wu=j(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>_t(C(),{fork:()=>C(),join:(e,t)=>e})),pc=j(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>_t(In,{fork:()=>In,join:(e,t)=>e})),ip=Symbol.for("effect/Scope"),ap=Symbol.for("effect/CloseableScope"),cp=function(){class e extends globalThis.Error{commit(){return ft(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[re](){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 Nn(ya(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,tm),e}(),Xv=Symbol.for("effect/Cause/errors/RuntimeException"),oF=Ei({[Xv]:Xv},"RuntimeException"),zh=Symbol.for("effect/Cause/errors/InterruptedException"),NK=Ei({[zh]:zh},"InterruptedException"),Qv=Symbol.for("effect/Cause/errors/IllegalArgument"),iF=Ei({[Qv]:Qv},"IllegalArgumentException"),eT=Symbol.for("effect/Cause/errors/NoSuchElement"),xc=Ei({[eT]:eT},"NoSuchElementException"),tT=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),FK=Ei({[tT]:tT},"InvalidPubSubCapacityException"),nT=Symbol.for("effect/Cause/errors/ExceededCapacityException"),LK=Ei({[nT]:nT},"ExceededCapacityException"),rT=Symbol.for("effect/Cause/errors/Timeout"),DK=Ei({[rT]:rT},"TimeoutException"),oT=Symbol.for("effect/Cause/errors/UnknownException"),aF=function(){class e extends yp{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[oT]:oT,name:"UnknownException"}),e}(),ET=d(2,(e,t)=>{switch(e._tag){case jt:return ve(e.effect_instruction_i0);case Vt:return Ie(t)}}),tp=d(2,(e,t)=>{switch(e._tag){case jt:return ve(e.effect_instruction_i0);case Vt:return Ie(t(e.effect_instruction_i0))}}),xp=d(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case jt:return t(e.effect_instruction_i0);case Vt:return n(e.effect_instruction_i0)}}),xn=Ie(void 0),fg=d(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case jt:switch(t._tag){case Vt:return ve(e.effect_instruction_i0);case jt:return ve(n(e.effect_instruction_i0,t.effect_instruction_i0))}case Vt:switch(t._tag){case Vt:return Ie(r(e.effect_instruction_i0,t.effect_instruction_i0));case jt:return ve(t.effect_instruction_i0)}}}),lF=xt((e)=>Ie(e.currentContext)),uF=d(2,(e,t)=>ko(Ti,t)(e)),mg=d(2,(e,t)=>Ri((n)=>uF(e,t(n))))});var kT,CT;var AT=x(()=>{Sa();kT=Ew,CT=Nn});var wp="And",vp="Or",Tp="InvalidData",Ep="MissingData",Op="SourceUnavailable",Rp="Unsupported";var fF="effect/ConfigError",PT,Ma,kp=(e,t)=>{let n=Object.create(Ma);return n._op=wp,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},Cp=(e,t)=>{let n=Object.create(Ma);return n._op=vp,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},hg=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ma);return r._op=Tp,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${g(this.path,Ir(n.pathDelim))}: "${this.message}")`}}),r},or=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ma);return r._op=Ep,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${g(this.path,Ir(n.pathDelim))}: "${this.message}")`}}),r},gg=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(Ma);return o._op=Op,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${g(this.path,Ir(r.pathDelim))}: "${this.message}")`}}),o},yg=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ma);return r._op=Rp,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${g(this.path,Ir(n.pathDelim))}: "${this.message}")`}}),r},Co,IT;var xg=x(()=>{Be();tn();j();PT=Symbol.for(fF),Ma={_tag:"ConfigError",[PT]:PT},Co=d(2,(e,t)=>{switch(e._op){case wp:return kp(Co(e.left,t),Co(e.right,t));case vp:return Cp(Co(e.left,t),Co(e.right,t));case Tp:return hg([...t,...e.path],e.message);case Ep:return or([...t,...e.path],e.message);case Op:return gg([...t,...e.path],e.message,e.cause);case Rp:return yg([...t,...e.path],e.message)}}),IT=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case wp:{r.push(a.right),r.push(a.left),o.push(W({_op:"AndCase"}));break}case vp:{r.push(a.right),r.push(a.left),o.push(W({_op:"OrCase"}));break}case Tp:{o.push(Q(n.invalidDataCase(t,a.path,a.message)));break}case Ep:{o.push(Q(n.missingDataCase(t,a.path,a.message)));break}case Op:{o.push(Q(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case Rp:{o.push(Q(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 mF="effect/Clock",NT,bc,hF=2147483647,FT,LT,gF,DT,qT=()=>new DT;var Sg=x(()=>{mn();ah();j();rt();NT=Symbol.for(mF),bc=Kt("effect/Clock"),FT={unsafeSchedule(e,t){let n=Mu(t);if(n>hF)return no;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},LT=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))}}(),gF=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return LT;let t=LT()-e.bigint();return()=>t+e.bigint()}();DT=class DT{[NT]=NT;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return gF()}currentTimeMillis=D(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=D(()=>this.unsafeCurrentTimeNanos());scheduler(){return fe(FT)}sleep(e){return To((t)=>{let n=FT.unsafeSchedule(()=>t(nt),e);return Vr(D(n))})}}});var ir;var wc=x(()=>{au();ir=bb});var Na=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var _g=()=>{};var $T,Pp;var jT=x(()=>{Be();tn();j();ju();Ge();xg();$T={_tag:"Empty"},Pp=d(2,(e,t)=>{let n=Xs(t),r=e;while(xh(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Ur(o.first,Ur(o.second,n.tail));break}case"MapName":{r=Cn(r,o.f),n=n.tail;break}case"Nested":{r=aa(r,o.name),n=n.tail;break}case"Unnested":{if(g(Cr(r),Eb(o.name)))r=kn(r),n=n.tail;else return W(or(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return Q(r)})});var VT="Constant",BT="Fail",KT="Fallback",zT="Described",WT="Lazy",JT="MapOrFail",GT="Nested",YT="Primitive",ZT="Redacted",XT="Sequence",QT="HashMap",eE="ZipWith";var Ip=(e,t)=>[...e,...t],vF="effect/ConfigProvider",tE,rE,TF="effect/ConfigProviderFlat",nE,EF=(e)=>({[tE]:tE,pipe(){return T(this,arguments)},...e}),OF=(e)=>({[nE]:nE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),RF=(e)=>EF({load:(t)=>B(on(e,Pr(),t,!1),(n)=>Je(Cr(n),{onNone:()=>dt(or(Pr(),`Expected a single value having structure: ${t}`)),onSome:fe})),flattened:e}),oE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>g(c,Ir(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return RF(OF({load:(c,l,u=!0)=>{let p=r(c),f=i(),h=p in f?F(f[p]):A();return g(h,bi(()=>or(c,`Expected ${p} to exist in the process context`)),B((m)=>NF(m,c,l,n,u)))},enumerateChildren:(c)=>D(()=>{let l=i(),f=Object.keys(l).map((h)=>o(h.toUpperCase())).filter((h)=>{for(let m=0;m<c.length;m++){let w=g(c,xm(m)),S=h[m];if(S===void 0||w!==S)return!1}return!0}).flatMap((h)=>h.slice(c.length,c.length+1));return Sw(f)}),patch:$T}))},kF=(e,t,n,r)=>{let o=wm(n.length,(c)=>c>=r.length?A():F([e(c),c+1])),i=wm(r.length,(c)=>c>=n.length?A():F([t(c),c+1])),a=Ip(n,o),s=Ip(r,i);return[a,s]},CF=(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},AF,PF=(e)=>IT(e,void 0,AF),on=(e,t,n,r)=>{let o=n;switch(o._tag){case VT:return fe(Rt(o.value));case zT:return Ce(()=>on(e,t,o.config,r));case BT:return dt(or(t,o.message));case KT:return g(Ce(()=>on(e,t,o.first,r)),cc((i)=>{if(o.condition(i))return g(on(e,t,o.second,r),cc((a)=>dt(Cp(i,a))));return dt(i)}));case WT:return Ce(()=>on(e,t,o.config(),r));case JT:return Ce(()=>g(on(e,t,o.original,r),B(yn((i)=>g(o.mapOrFail(i),bi(Co(CF(t,o.original))))))));case GT:return Ce(()=>on(e,Ip(t,Rt(o.name)),o.config,r));case YT:return g(Pp(t,e.patch),B((i)=>g(e.load(i,o,r),B((a)=>{if(a.length===0){let s=g(Mb(i),Oe(()=>"<n/a>"));return dt(or([],`Expected ${o.description} with name ${s}`))}return fe(a)}))));case ZT:return Ce(()=>g(on(e,t,o.original,r),bi(PF),Ke(Cn(o.redact))));case XT:return g(Pp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B(LF),B((a)=>{if(a.length===0)return Ce(()=>Ke(on(e,t,o.config,!0),Rt));return g(yn(a,(s)=>on(e,Ab(t,`[${s}]`),o.config,!0)),Ke((s)=>{let c=su(s);if(c.length===0)return Rt(Pr());return Rt(c)}))}))));case QT:return Ce(()=>g(Pp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B((a)=>g(a,yn((s)=>on(e,Ip(i,Rt(s)),o.valueConfig,r)),Ke((s)=>{if(s.length===0)return Rt(va());return g(FF(s),Cn((c)=>sv(bm(ke(a),c))))})))))));case eE:return Ce(()=>g(on(e,t,o.left,r),Si,B((i)=>g(on(e,t,o.right,r),Si,B((a)=>{if(Ee(i)&&Ee(a))return dt(kp(i.left,a.left));if(Ee(i)&&Ot(a))return dt(i.left);if(Ot(i)&&Ee(a))return dt(a.left);if(Ot(i)&&Ot(a)){let s=g(t,Ir(".")),c=IF(t,s),[l,u]=kF(c,c,g(i.right,Cn(Q)),g(a.right,Cn(Q)));return g(l,bm(u),yn(([p,f])=>g(up(p,f),Ke(([h,m])=>o.zip(h,m)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},IF=(e,t)=>(n)=>W(or(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),MF=(e,t)=>e.split(new RegExp(`\\s*${Na(t)}\\s*`)),NF=(e,t,n,r,o)=>{if(!o)return g(n.parse(e),sp({onFailure:Co(t),onSuccess:Rt}));return g(MF(e,r),yn((i)=>n.parse(i.trim())),bi(Co(t)))},FF=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),LF=(e)=>g(yn(e,qF),sp({onFailure:()=>Pr(),onSuccess:Ar(ir)}),Si,Ke(xb)),DF,qF=(e)=>{let t=e.match(DF);if(t!==null){let n=t[2];return g(n!==void 0&&n.length>0?F(n):A(),Rn(UF))}return A()},UF=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?A():F(t)};var iE=x(()=>{Be();mn();tn();j();Hu();pi();wc();Ge();be();_g();xg();jT();rt();tE=Symbol.for(vF),rE=Kt("effect/ConfigProvider"),nE=Symbol.for(TF),AF={andCase:(e,t,n)=>kp(t,n),orCase:(e,t,n)=>Cp(t,n),invalidDataCase:(e,t)=>hg(t,"<redacted>"),missingDataCase:(e,t)=>or(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>gg(t,"<redacted>",r),unsupportedCase:(e,t)=>yg(t,"<redacted>")},DF=/^(\[(\d+)\])$/});var aE,Mp,sE;var bg=x(()=>{mn();rt();aE=Symbol.for("effect/Console"),Mp=Kt("effect/Console"),sE={[aE]:aE,assert(e,...t){return D(()=>{console.assert(e,...t)})},clear:D(()=>{console.clear()}),count(e){return D(()=>{console.count(e)})},countReset(e){return D(()=>{console.countReset(e)})},debug(...e){return D(()=>{console.debug(...e)})},dir(e,t){return D(()=>{console.dir(e,t)})},dirxml(...e){return D(()=>{console.dirxml(...e)})},error(...e){return D(()=>{console.error(...e)})},group(e){return e?.collapsed?D(()=>console.groupCollapsed(e?.label)):D(()=>console.group(e?.label))},groupEnd:D(()=>{console.groupEnd()}),info(...e){return D(()=>{console.info(...e)})},log(...e){return D(()=>{console.log(...e)})},table(e,t){return D(()=>{console.table(e,t)})},time(e){return D(()=>console.time(e))},timeEnd(e){return D(()=>console.timeEnd(e))},timeLog(e,...t){return D(()=>{console.timeLog(e,...t)})},trace(...e){return D(()=>{console.trace(...e)})},warn(...e){return D(()=>{console.warn(...e)})},unsafe:console}});var jF="effect/Random",cE,lE,uE,VF=(e,t)=>Ce(()=>g(D(()=>Array.from(e)),B((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return g(r,_i((o)=>g(t(o),Ke((i)=>BF(n,o-1,i)))),jr(lu(n)))}))),BF=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},pE=(e)=>new uE(E(e));var dE=x(()=>{Qn();mn();j();Me();io();rt();cE=Symbol.for(jF),lE=Kt("effect/Random");uE=class uE{seed;[cE]=cE;PRNG;constructor(e){this.seed=e,this.PRNG=new Gf(e)}get next(){return D(()=>this.PRNG.number())}get nextBoolean(){return Ke(this.next,(e)=>e>0.5)}get nextInt(){return D(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return Ke(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return D(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return VF(e,(t)=>this.nextIntBetween(0,t))}}});class hE{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:mE(32),this.spanId=mE(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 fE,zF=(e)=>({[fE]:fE,...e}),vc,Np,mE,gE,yE;var Fp=x(()=>{mn();j();fE=Symbol.for("effect/Tracer"),vc=Kt("effect/Tracer"),Np=Kt("effect/ParentSpan"),mE=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();gE=zF({span:(e,t,n,r,o,i)=>new hE(e,t,n,r,o,i),context:(e)=>e()}),yE=Gs()("effect/Tracer/DisablePropagation",{defaultValue:no})});var GF,Tc;var xE=x(()=>{mn();j();Sg();iE();rt();bg();dE();Fp();GF=g(So(),tr(bc,qT()),tr(Mp,sE),tr(lE,pE(Math.random())),tr(rE,oE()),tr(vc,gE)),Tc=V(Symbol.for("effect/DefaultServices/currentServices"),()=>fp(GF))});var ZF,SE=(e)=>{let t={BaseEffectError:class extends ZF{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var _E=x(()=>{rt();ZF=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends yp{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 bE,XF,vg;var Tg=x(()=>{Rr();bE=Or,XF=cb;vg=class vg extends XF{}});var vE="Sequential",TE="Parallel",QF="ParallelN",Fa,EE,OE=(e)=>({_tag:QF,parallelism:e}),Eg=(e)=>e._tag===vE,Og=(e)=>e._tag===TE;var Lp=x(()=>{Fa={_tag:vE},EE={_tag:TE}});var Dp,qp,Up;var RE=x(()=>{Lp();Dp=Fa,qp=EE,Up=OE});function kE(e){return new Br(e)}function CE(){return kE(new Map)}var kg,Br,tL=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(we(i)&&we(a)){let l=et(i)[0],u=kn(i),p=et(a)[0],f=et(a)[1],h=kn(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},Ag,Pg,AE=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(O(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},Ec,Ig,Ao,La,Cg=(e,t,n,r)=>{let o=e.get(n)??[],i;if(we(o)){let[a,s]=et(o);if(a[I](t))if(O(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},PE;var Hp=x(()=>{Be();pe();j();Ge();be();kg=Symbol.for("effect/FiberRefs");Br=class Br{locals;[kg]=kg;constructor(e){this.locals=e}pipe(){return T(this,arguments)}};Ag=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][I](t)){if(!r.has(i)){if(O(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=tL(i,s,o);if(l){let u=i.diff(c,a),p=s[0][1],f=i.join(p,i.patch(u)(p));if(!O(p,f)){let h,m=s[0][0];if(m[I](t))h=[[m,f],...s.slice(1)];else h=[[t,f],...s];r.set(i,h)}}}}),new Br(r)}),Pg=d(2,(e,t)=>{let n=new Map;return AE(e,n,t),new Br(n)}),Ec=d(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new Br(n)}),Ig=d(2,(e,t)=>{if(!e.locals.has(t))return A();return F(et(e.locals.get(t))[1])}),Ao=d(2,(e,t)=>g(Ig(e,t),Oe(()=>t.initial))),La=d(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new Br(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return Cg(o,t,n,r),new Br(o)}),PE=d(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new Br(new Map(t));let r=new Map(e.locals);if(n!==void 0)AE(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)Cg(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{Cg(r,a,o,s)})}),new Br(r)})});var IE,ME,NE;var Ng=x(()=>{Hp();IE=Ao,ME=PE,NE=CE});var LE="Empty",DE="Add",qE="Remove",UE="Update",HE="AndThen",$E,jE=(e,t)=>{let n=new Map(e.locals),r=$E;for(let[o,i]of t.locals.entries()){let a=et(i)[1],s=n.get(o);if(s!==void 0){let c=et(s)[1];if(!O(c,a))r=$p({_tag:UE,fiberRef:o,patch:o.diff(c,a)})(r)}else r=$p({_tag:DE,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=$p({_tag:qE,fiberRef:o})(r);return r},$p,VE;var BE=x(()=>{Be();pe();j();Hp();$E={_tag:LE},$p=d(2,(e,t)=>({_tag:HE,first:e,second:t})),VE=d(3,(e,t,n)=>{let r=n,o=Rt(e);while(we(o)){let i=et(o),a=kn(o);switch(i._tag){case LE:{o=a;break}case DE:{r=La(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case qE:{r=Ec(r,i.fiberRef),o=a;break}case UE:{let s=Ao(r,i.fiberRef);r=La(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case HE:{o=aa(i.first)(aa(i.second)(a));break}}}return r})});var KE,zE;var WE=x(()=>{BE();KE=jE,zE=VE});var Vp="effect/FiberStatus",Po,jp="Done",JE="Running",GE="Suspended",oL,YE,ZE,XE,QE,eO=(e)=>new ZE(e),tO=(e,t)=>new XE(e,t),Bp=(e)=>C(e,Po),nO=(e)=>e._tag===jp;var rO=x(()=>{pe();j();Me();ye();Po=Symbol.for(Vp),oL=he(`${Vp}-${jp}`);YE=class YE{[Po]=Po;_tag=jp;[M](){return oL}[I](e){return Bp(e)&&e._tag===jp}};ZE=class ZE{runtimeFlags;[Po]=Po;_tag=JE;constructor(e){this.runtimeFlags=e}[M](){return g(E(Vp),G(E(this._tag)),G(E(this.runtimeFlags)),ie(this))}[I](e){return Bp(e)&&e._tag===JE&&this.runtimeFlags===e.runtimeFlags}};XE=class XE{runtimeFlags;blockingOn;[Po]=Po;_tag=GE;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[M](){return g(E(Vp),G(E(this._tag)),G(E(this.runtimeFlags)),G(E(this.blockingOn)),ie(this))}[I](e){return Bp(e)&&e._tag===GE&&this.runtimeFlags===e.runtimeFlags&&O(this.blockingOn,e.blockingOn)}};QE=new YE});var oO,Fg,iO,aO;var sO=x(()=>{rO();oO=QE,Fg=eO,iO=tO,aO=nO});var sL,cL,lL,uL,pL,dL,fL,mL,hL,cO,lO=(e)=>{switch(e){case"All":return sL;case"Debug":return dL;case"Error":return lL;case"Fatal":return cL;case"Info":return pL;case"Trace":return fL;case"None":return mL;case"Warning":return uL}};var uO=x(()=>{j();rt();wc();au();sL=uT,cL=pT,lL=dT,uL=og,pL=ig,dL=ag,fL=fT,mL=mT,hL=g(ir,iu((e)=>e.ordinal)),cO=dm(hL)});function EL(e){return Dg("Micro.evaluate: Not implemented")}class Bg{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,IL(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(wO)}flush(){while(this.tasks.length>0)this.runTasks()}}var yL,zp,pO,xL,qg,mO,SL=(e,t=[])=>new mO(e,t),hO,_L=(e=[])=>new hO(e),bL=(e)=>e._tag==="Interrupt",dO,wL,gO,fO,yO,it,Lg,qa,Da,Wp,Kp,vL,TL,Gp=(e)=>({...TL,[yO]:e.op,[Lg]:e.eval??EL,[qa]:e.contA,[Da]:e.contE,[Wp]:e.ensure}),Ug=(e)=>{let t=Gp(e);return function(){let n=Object.create(t);return n[it]=e.single===!1?arguments:arguments[0],n}},xO=(e)=>{let t={...Gp(e),[zp]:zp,_tag:e.op,get[e.prop](){return this[it]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[it]}},[I](n){return AL(n)&&n._tag===e.op&&O(this[it],n[it])},[M](){return ie(this,G(he(e.op))(E(this[it])))}};return function(n){let r=Object.create(t);return r[it]=n,r[qa]=void 0,r[Da]=void 0,r[Wp]=void 0,r}},Hg,SO,OL,RL,kL,$g,Jp,CL,AL=(e)=>C(e,zp),_O,jg,Vg,Dg=(e)=>jg(SL(e)),PL,IL,ML,bO,wO,Yp,NL,FL,LL,vO,DL=(e)=>$g((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(vO(!1)),t._interrupted)return Vg;return e}),qL=(e)=>$g((t)=>{if(!t.interruptible)return e(ue);return t.interruptible=!1,t._stack.push(vO(!0)),e(DL)}),TO=(e,t)=>{let n=new gO(Yp.context(t?.scheduler??new Bg));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 EO=x(()=>{mn();Tg();pe();j();Me();Ve();Au();be();ye();io();yL=Symbol.for("effect/Micro"),zp=Symbol.for("effect/Micro/MicroExit"),pO=Symbol.for("effect/Micro/MicroCause"),xL={_E:ue};qg=class qg extends globalThis.Error{_tag;traces;[pO];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
- `).length;a=t.stack?`(${r}) ${t.stack.split(`
25
+ `)}`:this.toString();else if("Bun"in globalThis)return Mr(da(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,Yf),e}(),VT=Symbol.for("effect/Cause/errors/RuntimeException"),K0=Ti({[VT]:VT},"RuntimeException"),$h=Symbol.for("effect/Cause/errors/InterruptedException"),yz=Ti({[$h]:$h},"InterruptedException"),zT=Symbol.for("effect/Cause/errors/IllegalArgument"),W0=Ti({[zT]:zT},"IllegalArgumentException"),KT=Symbol.for("effect/Cause/errors/NoSuchElement"),dc=Ti({[KT]:KT},"NoSuchElementException"),WT=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),xz=Ti({[WT]:WT},"InvalidPubSubCapacityException"),JT=Symbol.for("effect/Cause/errors/ExceededCapacityException"),Sz=Ti({[JT]:JT},"ExceededCapacityException"),GT=Symbol.for("effect/Cause/errors/Timeout"),bz=Ti({[GT]:GT},"TimeoutException"),YT=Symbol.for("effect/Cause/errors/UnknownException"),J0=function(){class e extends cp{_tag="UnknownException";error;constructor(t,r){super(r??"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 $t:return Te(e.effect_instruction_i0);case jt:return Ie(t)}}),Ku=d(2,(e,t)=>{switch(e._tag){case $t:return Te(e.effect_instruction_i0);case jt:return Ie(t(e.effect_instruction_i0))}}),lp=d(2,(e,{onFailure:t,onSuccess:r})=>{switch(e._tag){case $t:return t(e.effect_instruction_i0);case jt:return r(e.effect_instruction_i0)}}),yr=Ie(void 0),cg=d(3,(e,t,{onFailure:r,onSuccess:n})=>{switch(e._tag){case $t:switch(t._tag){case jt:return Te(e.effect_instruction_i0);case $t:return Te(r(e.effect_instruction_i0,t.effect_instruction_i0))}case jt:switch(t._tag){case jt:return Ie(n(e.effect_instruction_i0,t.effect_instruction_i0));case $t:return Te(t.effect_instruction_i0)}}}),Z0=bt((e)=>Ie(e.currentContext)),X0=d(2,(e,t)=>vo(wi,t)(e)),lg=d(2,(e,t)=>vi((r)=>X0(e,t(r))))});var bE,_E;var wE=x(()=>{ma();bE=yw,_E=Mr});var fp="And",mp="Or",hp="InvalidData",gp="MissingData",yp="SourceUnavailable",xp="Unsupported";var tF="effect/ConfigError",TE,ka,Sp=(e,t)=>{let r=Object.create(ka);return r._op=fp,r.left=e,r.right=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),Object.defineProperty(r,"message",{enumerable:!1,get(){return this.toString()}}),r},bp=(e,t)=>{let r=Object.create(ka);return r._op=mp,r.left=e,r.right=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(r,"message",{enumerable:!1,get(){return this.toString()}}),r},ug=(e,t,r={pathDelim:"."})=>{let n=Object.create(ka);return n._op=hp,n.path=e,n.message=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`(Invalid data at ${g(this.path,Rn(r.pathDelim))}: "${this.message}")`}}),n},Qr=(e,t,r={pathDelim:"."})=>{let n=Object.create(ka);return n._op=gp,n.path=e,n.message=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`(Missing data at ${g(this.path,Rn(r.pathDelim))}: "${this.message}")`}}),n},pg=(e,t,r,n={pathDelim:"."})=>{let o=Object.create(ka);return o._op=yp,o.path=e,o.message=t,o.cause=r,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${g(this.path,Rn(n.pathDelim))}: "${this.message}")`}}),o},dg=(e,t,r={pathDelim:"."})=>{let n=Object.create(ka);return n._op=xp,n.path=e,n.message=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${g(this.path,Rn(r.pathDelim))}: "${this.message}")`}}),n},Oo,EE;var fg=x(()=>{Ve();er();H();TE=Symbol.for(tF),ka={_tag:"ConfigError",[TE]:TE},Oo=d(2,(e,t)=>{switch(e._op){case fp:return Sp(Oo(e.left,t),Oo(e.right,t));case mp:return bp(Oo(e.left,t),Oo(e.right,t));case hp:return ug([...t,...e.path],e.message);case gp:return Qr([...t,...e.path],e.message);case yp:return pg([...t,...e.path],e.message,e.cause);case xp:return dg([...t,...e.path],e.message)}}),EE=d(3,(e,t,r)=>{let n=[e],o=[];while(n.length>0){let a=n.pop();switch(a._op){case fp:{n.push(a.right),n.push(a.left),o.push(K({_op:"AndCase"}));break}case mp:{n.push(a.right),n.push(a.left),o.push(K({_op:"OrCase"}));break}case hp:{o.push(Z(r.invalidDataCase(t,a.path,a.message)));break}case gp:{o.push(Z(r.missingDataCase(t,a.path,a.message)));break}case yp:{o.push(Z(r.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case xp:{o.push(Z(r.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=r.andCase(t,s,c);i.push(l);break}case"OrCase":{let s=i.pop(),c=i.pop(),l=r.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 rF="effect/Clock",OE,hc,nF=2147483647,RE,kE,oF,CE,AE=()=>new CE;var mg=x(()=>{fr();th();H();ot();OE=Symbol.for(rF),hc=Vt("effect/Clock"),RE={unsafeSchedule(e,t){let r=Eu(t);if(r>nF)return Qn;let n=!1,o=setTimeout(()=>{n=!0,e()},r);return()=>(clearTimeout(o),!n)}},kE=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))}}(),oF=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return kE;let t=kE()-e.bigint();return()=>t+e.bigint()}();CE=class CE{[OE]=OE;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return oF()}currentTimeMillis=L(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=L(()=>this.unsafeCurrentTimeNanos());scheduler(){return pe(RE)}sleep(e){return _o((t)=>{let r=RE.unsafeSchedule(()=>t(nt),e);return qn(L(r))})}}});var en;var gc=x(()=>{Zl();en=f_});var Ca=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var hg=()=>{};var ME,wp;var NE=x(()=>{Ve();er();H();Mu();Ye();fg();ME={_tag:"Empty"},wp=d(2,(e,t)=>{let r=Ks(t),n=e;while(fh(r)){let o=r.head;switch(o._tag){case"Empty":{r=r.tail;break}case"AndThen":{r=Nn(o.first,Nn(o.second,r.tail));break}case"MapName":{n=kr(n,o.f),r=r.tail;break}case"Nested":{n=ta(n,o.name),r=r.tail;break}case"Unnested":{if(g(En(n),y_(o.name)))n=Rr(n),r=r.tail;else return K(Qr(n,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return Z(n)})});var FE="Constant",LE="Fail",DE="Fallback",qE="Described",UE="Lazy",HE="MapOrFail",$E="Nested",jE="Primitive",BE="Redacted",VE="Sequence",zE="HashMap",KE="ZipWith";var Tp=(e,t)=>[...e,...t],pF="effect/ConfigProvider",WE,GE,dF="effect/ConfigProviderFlat",JE,fF=(e)=>({[WE]:WE,pipe(){return E(this,arguments)},...e}),mF=(e)=>({[JE]:JE,patch:e.patch,load:(t,r,n=!0)=>e.load(t,r,n),enumerateChildren:e.enumerateChildren}),hF=(e)=>fF({load:(t)=>B(nr(e,On(),t,!1),(r)=>Ge(En(r),{onNone:()=>ft(Qr(On(),`Expected a single value having structure: ${t}`)),onSome:pe})),flattened:e}),YE=(e)=>{let{pathDelim:t,seqDelim:r}=Object.assign({},{pathDelim:"_",seqDelim:","},e),n=(c)=>g(c,Rn(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return hF(mF({load:(c,l,u=!0)=>{let p=n(c),f=i(),h=p in f?N(f[p]):C();return g(h,Si(()=>Qr(c,`Expected ${p} to exist in the process context`)),B((m)=>wF(m,c,l,r,u)))},enumerateChildren:(c)=>L(()=>{let l=i(),f=Object.keys(l).map((h)=>o(h.toUpperCase())).filter((h)=>{for(let m=0;m<c.length;m++){let w=g(c,fm(m)),S=h[m];if(S===void 0||w!==S)return!1}return!0}).flatMap((h)=>h.slice(c.length,c.length+1));return pw(f)}),patch:ME}))},gF=(e,t,r,n)=>{let o=ym(r.length,(c)=>c>=n.length?C():N([e(c),c+1])),i=ym(n.length,(c)=>c>=r.length?C():N([t(c),c+1])),a=Tp(r,o),s=Tp(n,i);return[a,s]},yF=(e,t)=>{let r=t;if(r._tag==="Nested"){let n=e.slice();while(r._tag==="Nested")n.push(r.name),r=r.config;return n}return e},xF,SF=(e)=>EE(e,void 0,xF),nr=(e,t,r,n)=>{let o=r;switch(o._tag){case FE:return pe(kt(o.value));case qE:return Ce(()=>nr(e,t,o.config,n));case LE:return ft(Qr(t,o.message));case DE:return g(Ce(()=>nr(e,t,o.first,n)),rc((i)=>{if(o.condition(i))return g(nr(e,t,o.second,n),rc((a)=>ft(bp(i,a))));return ft(i)}));case UE:return Ce(()=>nr(e,t,o.config(),n));case HE:return Ce(()=>g(nr(e,t,o.original,n),B(gr((i)=>g(o.mapOrFail(i),Si(Oo(yF(t,o.original))))))));case $E:return Ce(()=>nr(e,Tp(t,kt(o.name)),o.config,n));case jE:return g(wp(t,e.patch),B((i)=>g(e.load(i,o,n),B((a)=>{if(a.length===0){let s=g(v_(i),ve(()=>"<n/a>"));return ft(Qr([],`Expected ${o.description} with name ${s}`))}return pe(a)}))));case BE:return Ce(()=>g(nr(e,t,o.original,n),Si(SF),ze(kr(o.redact))));case VE:return g(wp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B(EF),B((a)=>{if(a.length===0)return Ce(()=>ze(nr(e,t,o.config,!0),kt));return g(gr(a,(s)=>nr(e,w_(t,`[${s}]`),o.config,!0)),ze((s)=>{let c=Xl(s);if(c.length===0)return kt(On());return kt(c)}))}))));case zE:return Ce(()=>g(wp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B((a)=>g(a,gr((s)=>nr(e,Tp(i,kt(s)),o.valueConfig,n)),ze((s)=>{if(s.length===0)return kt(xa());return g(TF(s),kr((c)=>Qw(gm(ke(a),c))))})))))));case KE:return Ce(()=>g(nr(e,t,o.left,n),yi,B((i)=>g(nr(e,t,o.right,n),yi,B((a)=>{if(Ee(i)&&Ee(a))return ft(Sp(i.left,a.left));if(Ee(i)&&Rt(a))return ft(i.left);if(Rt(i)&&Ee(a))return ft(a.left);if(Rt(i)&&Rt(a)){let s=g(t,Rn(".")),c=bF(t,s),[l,u]=gF(c,c,g(i.right,kr(Z)),g(a.right,kr(Z)));return g(l,gm(u),gr(([p,f])=>g(tp(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")})))))}},bF=(e,t)=>(r)=>K(Qr(e,`The element at index ${r} in a sequence at path "${t}" was missing`)),_F=(e,t)=>e.split(new RegExp(`\\s*${Ca(t)}\\s*`)),wF=(e,t,r,n,o)=>{if(!o)return g(r.parse(e),Xu({onFailure:Oo(t),onSuccess:kt}));return g(_F(e,n),gr((i)=>r.parse(i.trim())),Si(Oo(t)))},TF=(e)=>Object.keys(e[0]).map((t)=>e.map((r)=>r[t])),EF=(e)=>g(gr(e,OF),Xu({onFailure:()=>On(),onSuccess:vn(en)}),yi,ze(u_)),vF,OF=(e)=>{let t=e.match(vF);if(t!==null){let r=t[2];return g(r!==void 0&&r.length>0?N(r):C(),Or(RF))}return C()},RF=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?C():N(t)};var ZE=x(()=>{Ve();fr();er();H();Pu();li();gc();Ye();_e();hg();fg();NE();ot();WE=Symbol.for(pF),GE=Vt("effect/ConfigProvider"),JE=Symbol.for(dF),xF={andCase:(e,t,r)=>Sp(t,r),orCase:(e,t,r)=>bp(t,r),invalidDataCase:(e,t)=>ug(t,"<redacted>"),missingDataCase:(e,t)=>Qr(t,"<redacted>"),sourceUnavailableCase:(e,t,r,n)=>pg(t,"<redacted>",n),unsupportedCase:(e,t)=>dg(t,"<redacted>")},vF=/^(\[(\d+)\])$/});var XE,Ep,QE;var gg=x(()=>{fr();ot();XE=Symbol.for("effect/Console"),Ep=Vt("effect/Console"),QE={[XE]:XE,assert(e,...t){return L(()=>{console.assert(e,...t)})},clear:L(()=>{console.clear()}),count(e){return L(()=>{console.count(e)})},countReset(e){return L(()=>{console.countReset(e)})},debug(...e){return L(()=>{console.debug(...e)})},dir(e,t){return L(()=>{console.dir(e,t)})},dirxml(...e){return L(()=>{console.dirxml(...e)})},error(...e){return L(()=>{console.error(...e)})},group(e){return e?.collapsed?L(()=>console.groupCollapsed(e?.label)):L(()=>console.group(e?.label))},groupEnd:L(()=>{console.groupEnd()}),info(...e){return L(()=>{console.info(...e)})},log(...e){return L(()=>{console.log(...e)})},table(e,t){return L(()=>{console.table(e,t)})},time(e){return L(()=>console.time(e))},timeEnd(e){return L(()=>console.timeEnd(e))},timeLog(e,...t){return L(()=>{console.timeLog(e,...t)})},trace(...e){return L(()=>{console.trace(...e)})},warn(...e){return L(()=>{console.warn(...e)})},unsafe:console}});var AF="effect/Random",ev,tv,rv,PF=(e,t)=>Ce(()=>g(L(()=>Array.from(e)),B((r)=>{let n=[];for(let o=r.length;o>=2;o=o-1)n.push(o);return g(n,xi((o)=>g(t(o),ze((i)=>IF(r,o-1,i)))),Dn(eu(r)))}))),IF=(e,t,r)=>{let n=e[t];return e[t]=e[r],e[r]=n,e},nv=(e)=>new rv(v(e));var ov=x(()=>{Jr();fr();H();Me();ro();ot();ev=Symbol.for(AF),tv=Vt("effect/Random");rv=class rv{seed;[ev]=ev;PRNG;constructor(e){this.seed=e,this.PRNG=new Vf(e)}get next(){return L(()=>this.PRNG.number())}get nextBoolean(){return ze(this.next,(e)=>e>0.5)}get nextInt(){return L(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return ze(this.next,(r)=>(t-e)*r+e)}nextIntBetween(e,t){return L(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return PF(e,(t)=>this.nextIntBetween(0,t))}}});class sv{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(e,t,r,n,o,i){this.name=e,this.parent=t,this.context=r,this.startTime=o,this.kind=i,this.status={_tag:"Started",startTime:o},this.attributes=new Map,this.traceId=t._tag==="Some"?t.value.traceId:av(32),this.spanId=av(16),this.links=Array.from(n)}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,r){this.events.push([e,t,r??{}])}addLinks(e){this.links.push(...e)}}var iv,NF=(e)=>({[iv]:iv,...e}),yc,vp,av,cv,lv;var Op=x(()=>{fr();H();iv=Symbol.for("effect/Tracer"),yc=Vt("effect/Tracer"),vp=Vt("effect/ParentSpan"),av=function(){return function(r){let n="";for(let o=0;o<r;o++)n+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return n}}();cv=NF({span:(e,t,r,n,o,i)=>new sv(e,t,r,n,o,i),context:(e)=>e()}),lv=Bs()("effect/Tracer/DisablePropagation",{defaultValue:Qn})});var DF,xc;var uv=x(()=>{fr();H();mg();ZE();ot();gg();ov();Op();DF=g(go(),Yr(hc,AE()),Yr(Ep,QE),Yr(tv,nv(Math.random())),Yr(GE,YE()),Yr(yc,cv)),xc=j(Symbol.for("effect/DefaultServices/currentServices"),()=>op(DF))});var UF,pv=(e)=>{let t={BaseEffectError:class extends UF{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var dv=x(()=>{ot();UF=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends cp{constructor(r){super(r?.message,r?.cause?{cause:r.cause}:void 0);if(r)Object.assign(this,r),Object.defineProperty(this,e,{value:r,enumerable:!1})}toJSON(){return{...this[e],...this}}}}.BaseEffectError}()});var fv,HF,xg;var Sg=x(()=>{wn();fv=_n,HF=e_;xg=class xg extends HF{}});var hv="Sequential",gv="Parallel",$F="ParallelN",Aa,yv,xv=(e)=>({_tag:$F,parallelism:e}),bg=(e)=>e._tag===hv,_g=(e)=>e._tag===gv;var Rp=x(()=>{Aa={_tag:hv},yv={_tag:gv}});var kp,Cp,Ap;var Sv=x(()=>{Rp();kp=Aa,Cp=yv,Ap=xv});function bv(e){return new Un(e)}function _v(){return bv(new Map)}var Tg,Un,BF=(e,t,r,n=!1)=>{let o=e,i=t,a=r,s=n,c=void 0;while(c===void 0)if(we(i)&&we(a)){let l=tt(i)[0],u=Rr(i),p=tt(a)[0],f=tt(a)[1],h=Rr(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},vg,Og,wv=(e,t,r)=>{e.locals.forEach((n,o)=>{let i=n[0][1],a=o.patch(o.fork)(i);if(O(i,a))t.set(o,n);else t.set(o,[[r,a],...n])})},Sc,Rg,Ro,Pa,Eg=(e,t,r,n)=>{let o=e.get(r)??[],i;if(we(o)){let[a,s]=tt(o);if(a[I](t))if(O(s,n))return;else i=[[t,n],...o.slice(1)];else i=[[t,n],...o]}else i=[[t,n]];e.set(r,i)},Tv;var Pp=x(()=>{Ve();le();H();Ye();_e();Tg=Symbol.for("effect/FiberRefs");Un=class Un{locals;[Tg]=Tg;constructor(e){this.locals=e}pipe(){return E(this,arguments)}};vg=d(3,(e,t,r)=>{let n=new Map(e.locals);return r.locals.forEach((o,i)=>{let a=o[0][1];if(!o[0][0][I](t)){if(!n.has(i)){if(O(a,i.initial))return;n.set(i,[[t,i.join(i.initial,a)]]);return}let s=n.get(i),[c,l]=BF(i,s,o);if(l){let u=i.diff(c,a),p=s[0][1],f=i.join(p,i.patch(u)(p));if(!O(p,f)){let h,m=s[0][0];if(m[I](t))h=[[m,f],...s.slice(1)];else h=[[t,f],...s];n.set(i,h)}}}}),new Un(n)}),Og=d(2,(e,t)=>{let r=new Map;return wv(e,r,t),new Un(r)}),Sc=d(2,(e,t)=>{let r=new Map(e.locals);return r.delete(t),new Un(r)}),Rg=d(2,(e,t)=>{if(!e.locals.has(t))return C();return N(tt(e.locals.get(t))[1])}),Ro=d(2,(e,t)=>g(Rg(e,t),ve(()=>t.initial))),Pa=d(2,(e,{fiberId:t,fiberRef:r,value:n})=>{if(e.locals.size===0)return new Un(new Map([[r,[[t,n]]]]));let o=new Map(e.locals);return Eg(o,t,r,n),new Un(o)}),Tv=d(2,(e,{entries:t,forkAs:r})=>{if(e.locals.size===0)return new Un(new Map(t));let n=new Map(e.locals);if(r!==void 0)wv(e,n,r);return t.forEach(([o,i])=>{if(i.length===1)Eg(n,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{Eg(n,a,o,s)})}),new Un(n)})});var Ev,vv,Ov;var Cg=x(()=>{Pp();Ev=Ro,vv=Tv,Ov=_v});var kv="Empty",Cv="Add",Av="Remove",Pv="Update",Iv="AndThen",Mv,Nv=(e,t)=>{let r=new Map(e.locals),n=Mv;for(let[o,i]of t.locals.entries()){let a=tt(i)[1],s=r.get(o);if(s!==void 0){let c=tt(s)[1];if(!O(c,a))n=Ip({_tag:Pv,fiberRef:o,patch:o.diff(c,a)})(n)}else n=Ip({_tag:Cv,fiberRef:o,value:a})(n);r.delete(o)}for(let[o]of r.entries())n=Ip({_tag:Av,fiberRef:o})(n);return n},Ip,Fv;var Lv=x(()=>{Ve();le();H();Pp();Mv={_tag:kv},Ip=d(2,(e,t)=>({_tag:Iv,first:e,second:t})),Fv=d(3,(e,t,r)=>{let n=r,o=kt(e);while(we(o)){let i=tt(o),a=Rr(o);switch(i._tag){case kv:{o=a;break}case Cv:{n=Pa(n,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case Av:{n=Sc(n,i.fiberRef),o=a;break}case Pv:{let s=Ro(n,i.fiberRef);n=Pa(n,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case Iv:{o=ta(i.first)(ta(i.second)(a));break}}}return n})});var Dv,qv;var Uv=x(()=>{Lv();Dv=Nv,qv=Fv});var Np="effect/FiberStatus",ko,Mp="Done",Hv="Running",$v="Suspended",KF,jv,Bv,Vv,zv,Kv=(e)=>new Bv(e),Wv=(e,t)=>new Vv(e,t),Fp=(e)=>k(e,ko),Jv=(e)=>e._tag===Mp;var Gv=x(()=>{le();H();Me();ge();ko=Symbol.for(Np),KF=me(`${Np}-${Mp}`);jv=class jv{[ko]=ko;_tag=Mp;[M](){return KF}[I](e){return Fp(e)&&e._tag===Mp}};Bv=class Bv{runtimeFlags;[ko]=ko;_tag=Hv;constructor(e){this.runtimeFlags=e}[M](){return g(v(Np),J(v(this._tag)),J(v(this.runtimeFlags)),oe(this))}[I](e){return Fp(e)&&e._tag===Hv&&this.runtimeFlags===e.runtimeFlags}};Vv=class Vv{runtimeFlags;blockingOn;[ko]=ko;_tag=$v;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[M](){return g(v(Np),J(v(this._tag)),J(v(this.runtimeFlags)),J(v(this.blockingOn)),oe(this))}[I](e){return Fp(e)&&e._tag===$v&&this.runtimeFlags===e.runtimeFlags&&O(this.blockingOn,e.blockingOn)}};zv=new jv});var Yv,Ag,Zv,Xv;var Qv=x(()=>{Gv();Yv=zv,Ag=Kv,Zv=Wv,Xv=Jv});var GF,YF,ZF,XF,QF,eL,tL,rL,nL,eO,tO=(e)=>{switch(e){case"All":return GF;case"Debug":return eL;case"Error":return ZF;case"Fatal":return YF;case"Info":return QF;case"Trace":return tL;case"None":return rL;case"Warning":return XF}};var rO=x(()=>{H();ot();gc();Zl();GF=rE,YF=nE,ZF=oE,XF=Qh,QF=eg,eL=tg,tL=iE,rL=aE,nL=g(en,Yl((e)=>e.ordinal)),eO=sm(nL)});function fL(e){return Ig("Micro.evaluate: Not implemented")}class Ug{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,bL(this.afterScheduled)}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let e=this.tasks;this.tasks=[];for(let t=0,r=e.length;t<r;t++)e[t]()}shouldYield(e){return e.currentOpCount>=e.getRef(mO)}flush(){while(this.tasks.length>0)this.runTasks()}}var iL,Dp,nO,aL,Mg,aO,sL=(e,t=[])=>new aO(e,t),sO,cL=(e=[])=>new sO(e),lL=(e)=>e._tag==="Interrupt",oO,uL,cO,iO,lO,at,Pg,Ma,Ia,qp,Lp,pL,dL,Hp=(e)=>({...dL,[lO]:e.op,[Pg]:e.eval??fL,[Ma]:e.contA,[Ia]:e.contE,[qp]:e.ensure}),Ng=(e)=>{let t=Hp(e);return function(){let r=Object.create(t);return r[at]=e.single===!1?arguments:arguments[0],r}},uO=(e)=>{let t={...Hp(e),[Dp]:Dp,_tag:e.op,get[e.prop](){return this[at]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[at]}},[I](r){return xL(r)&&r._tag===e.op&&O(this[at],r[at])},[M](){return oe(this,J(me(e.op))(v(this[at])))}};return function(r){let n=Object.create(t);return n[at]=r,n[Ma]=void 0,n[Ia]=void 0,n[qp]=void 0,n}},Fg,pO,mL,hL,gL,Lg,Up,yL,xL=(e)=>k(e,Dp),dO,Dg,qg,Ig=(e)=>Dg(sL(e)),SL,bL,_L,fO,mO,$p,wL,TL,EL,hO,vL=(e)=>Lg((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(hO(!1)),t._interrupted)return qg;return e}),OL=(e)=>Lg((t)=>{if(!t.interruptible)return e(ce);return t.interruptible=!1,t._stack.push(hO(!0)),e(vL)}),gO=(e,t)=>{let r=new cO($p.context(t?.scheduler??new Ug));if(r.evaluate(e),t?.signal)if(t.signal.aborted)r.unsafeInterrupt();else{let n=()=>r.unsafeInterrupt();t.signal.addEventListener("abort",n,{once:!0}),r.addObserver(()=>t.signal.removeEventListener("abort",n))}return r};var yO=x(()=>{fr();Sg();le();H();Me();Be();_u();_e();ge();ro();iL=Symbol.for("effect/Micro"),Dp=Symbol.for("effect/Micro/MicroExit"),nO=Symbol.for("effect/Micro/MicroCause"),aL={_E:ce};Mg=class Mg extends globalThis.Error{_tag;traces;[nO];constructor(e,t,r){let n=`MicroCause.${e}`,o,i,a;if(t instanceof globalThis.Error){o=`(${n}) ${t.name}`,i=t.message;let s=i.split(`
26
+ `).length;a=t.stack?`(${n}) ${t.stack.split(`
27
27
  `).slice(0,s+3).join(`
28
- `)}`:`${o}: ${i}`}else o=r,i=Er(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
29
- ${n.join(`
30
- `)}`;super(i);this._tag=e,this.traces=n,this[pO]=xL,this.name=o,this.stack=a}pipe(){return T(this,arguments)}toString(){return this.stack}[ne](){return this.stack}};mO=class mO extends qg{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};hO=class hO extends qg{constructor(e=[]){super("Interrupt","interrupted",e)}};dO=Symbol.for("effect/Micro/MicroFiber"),wL={_A:ue,_E:ue};gO=class gO{context;interruptible;[dO];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[dO]=wL}getRef(e){return Dw(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),_s;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(Vg)}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===Kp)return;let n=fO.interruptChildren&&fO.interruptChildren(this);if(n!==void 0)return this.evaluate(Jp(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(Yp).shouldYield(this)){t=!0;let r=n;n=Jp(RL,()=>r)}if(n=n[Lg](this),n===Kp){let r=this._yielded;if(zp in r)return this._yielded=void 0,r;return Kp}}}catch(r){if(!C(n,Lg))return Dg(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return Dg(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[Wp]&&t[Wp](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Kp}children(){return this._children??=new Set}};fO=V("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),yO=Symbol.for("effect/Micro/identifier"),it=Symbol.for("effect/Micro/args"),Lg=Symbol.for("effect/Micro/evaluate"),qa=Symbol.for("effect/Micro/successCont"),Da=Symbol.for("effect/Micro/failureCont"),Wp=Symbol.for("effect/Micro/ensureCont"),Kp=Symbol.for("effect/Micro/Yield"),vL={_A:ue,_E:ue,_R:ue},TL={...bE,_op:"Micro",[yL]:vL,pipe(){return T(this,arguments)},[Symbol.iterator](){return new ea(new Tr(this))},toJSON(){return{_id:"Micro",op:this[yO],...it in this?{args:this[it]}:void 0}},toString(){return ge(this)},[ne](){return ge(this)}};Hg=xO({op:"Success",prop:"value",eval(e){let t=e.getCont(qa);return t?t[qa](this[it],e):e.yieldWith(this)}}),SO=xO({op:"Failure",prop:"cause",eval(e){let t=e.getCont(Da);while(bL(this[it])&&t&&e.interruptible)t=e.getCont(Da);return t?t[Da](this[it],e):e.yieldWith(this)}}),OL=Ug({op:"Yield",eval(e){let t=!1;return e.getRef(Yp).scheduleTask(()=>{if(t)return;e.evaluate(PL)},this[it]??0),e.yieldWith(()=>{t=!0})}}),RL=OL(0),kL=Hg(void 0),$g=Ug({op:"WithMicroFiber",eval(e){return this[it](e)}}),Jp=d(2,(e,t)=>{let n=Object.create(CL);return n[it]=e,n[qa]=t,n}),CL=Gp({op:"OnSuccess",eval(e){return e._stack.push(this),this[it]}}),_O=Hg,jg=SO,Vg=jg(_L()),PL=_O(void 0),IL="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);ML=d(2,(e,t)=>$g((n)=>{let r=n.context;return n.context=t(r),LL(e,()=>(n.context=r,kL))})),bO=d(2,(e,t)=>ML(e,Js(t)));wO=class wO extends Gs()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};Yp=class Yp extends Gs()("effect/Micro/currentScheduler",{defaultValue:()=>new Bg}){};NL=d(2,(e,t)=>{let n=Object.create(FL);return n[it]=e,n[qa]=t.onSuccess,n[Da]=t.onFailure,n}),FL=Gp({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[it]}}),LL=d(2,(e,t)=>qL((n)=>NL(n(e),{onFailure:(r)=>Jp(t(jg(r)),()=>SO(r)),onSuccess:(r)=>Jp(t(_O(r)),()=>Hg(r))}))),vO=Ug({op:"SetInterruptible",ensure(e){if(e.interruptible=this[it],e._interrupted&&e.interruptible)return()=>Vg}})});class Zp{scheduleDrain;running=!1;tasks=new Kg;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 Zp(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new Zp(e),n.set(r,o);return o}}}class Kg{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 OO{maxNextTickBeforeTimer;getRunner=Zp.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(sg)?e.getFiberRef(Aa):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class Oc{tasks=new Kg;deferred=!1;scheduleTask(e,t,n){if(this.deferred)RO.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(sg)?e.getFiberRef(Aa):!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 RO,Xp;var Qp=x(()=>{rt();RO=V(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new OO(2048));Xp=V(Symbol.for("effect/FiberRef/currentScheduler"),()=>St(RO))});var ed;var zg=x(()=>{rt();ed=V(Symbol.for("effect/FiberRef/currentRequestMap"),()=>St(new Map))});var Wg=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return wi(_T,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var CO=x(()=>{rt()});var Jg=(e)=>e.replace(/[\s="]/g,"_"),AO=(e)=>(t)=>`${Jg(t.label)}=${e-t.startTime}ms`;var PO="effect/MetricLabel",Gg,IO,MO=(e,t)=>new IO(e,t),VL=(e)=>C(e,Gg);var NO=x(()=>{pe();Me();be();ye();Gg=Symbol.for(PO);IO=class IO{key;value;[Gg]=Gg;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=he(PO+this.key+this.value)}[M](){return this._hash}[I](e){return VL(e)&&this.key===e.key&&this.value===e.value}pipe(){return T(this,arguments)}}});var Yg;var FO=x(()=>{mn();Ge();Fp();Yg=Rn((e)=>zs(e.context,yE)?e._tag==="Span"?Yg(e.parent):A():F(e))});var LO;var DO=x(()=>{rt();LO=ug});var Zg="InterruptSignal",Xg="Stateful",Qg="Resume",ey="YieldNow",td=(e)=>({_tag:"InterruptSignal",cause:e}),Ua=(e)=>({_tag:"Stateful",onFiber:e}),ki=(e)=>({_tag:"Resume",effect:e}),qO=()=>({_tag:"YieldNow"});var GL="effect/FiberScope",nd,HO,$O,jO=(e)=>new $O(e.id(),e),Rc;var ty=x(()=>{wa();nd=Symbol.for(GL);HO=class HO{[nd]=nd;fiberId=hn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};$O=class $O{fiberId;parent;[nd]=nd;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(Ua((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};Rc=V(Symbol.for("effect/FiberScope/Global"),()=>new HO)});var XL="effect/Fiber",ny,ry,QL,eD="effect/Fiber",BO,rd=(e)=>pp(uc(e.await),e.inheritAll),xW,Io="effect/FiberCurrent";var KO=x(()=>{wa();Ge();be();rt();Rr();ny=Symbol.for(XL),ry={_E:(e)=>e,_A:(e)=>e},QL={[ny]:ry,pipe(){return T(this,arguments)}},BO=Symbol.for(eD),xW={...so,commit(){return rd(this)},...QL,id:()=>hn,await:mc,children:fe([]),inheritAll:mc,poll:fe(A()),interruptAsFork:()=>mc}});var nD="effect/Logger",zO,WO,od=(e)=>({[zO]:WO,log:e,pipe(){return T(this,arguments)}}),bW,rD,oD=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(rD)?m:e(m),u=(m,w)=>`${Jg(m)}=${l(w)}`,p=(m,w)=>" "+u(m,w),f=u("timestamp",o.toISOString());f+=p("level",a.label),f+=p("fiber",qu(i));let h=hm(s);for(let m=0;m<h.length;m++)f+=p("message",Er(h[m],t));if(!Vm(r))f+=p("cause",Nn(r,{renderErrorCause:!0}));for(let m of c)f+=" "+AO(o.getTime())(m);for(let[m,w]of n)f+=p(m,Er(w,t));return f},iD=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,JO,Ci,wW,GO,vW,TW;var YO=x(()=>{Be();j();Ve();be();Sa();ph();zO=Symbol.for(nD),WO={_Message:(e)=>e,_Output:(e)=>e},bW={[zO]:WO,log:_s,pipe(){return T(this,arguments)}},rD=/^[^\s"=]*$/,JO=od(oD(iD)),Ci={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},wW={None:[],All:[],Trace:[Ci.gray],Debug:[Ci.blue],Info:[Ci.green],Warning:[Ci.yellow],Error:[Ci.red],Fatal:[Ci.bgBrightRed,Ci.black]},GO=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,vW=GO&&process.stdout.isTTY===!0,TW=GO||"Deno"in globalThis});var ZO="effect/MetricBoundaries",oy,XO,sD=(e)=>C(e,oy),cD=(e)=>{let t=g(e,gm(tt(Number.POSITIVE_INFINITY)),vm);return new XO(t)},QO=(e)=>g(mm(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Us,cD);var eR=x(()=>{Be();Qn();pe();j();Me();be();ye();oy=Symbol.for(ZO);XO=class XO{values;[oy]=oy;constructor(e){this.values=e,this._hash=g(he(ZO),G(en(this.values)))}_hash;[M](){return this._hash}[I](e){return sD(e)&&O(this.values,e.values)}pipe(){return T(this,arguments)}}});var uD="effect/MetricKeyType",tR,nR="effect/MetricKeyType/Counter",iy,pD="effect/MetricKeyType/Frequency",dD,fD="effect/MetricKeyType/Gauge",mD,rR="effect/MetricKeyType/Histogram",ay,hD="effect/MetricKeyType/Summary",gD,oR,iR,aR,sR=(e)=>new iR(e?.incremental??!1,e?.bigint??!1),cR=(e)=>new aR(e),sy=(e)=>C(e,iy),lR=(e)=>C(e,dD),uR=(e)=>C(e,mD),cy=(e)=>C(e,ay),pR=(e)=>C(e,gD);var ly=x(()=>{pe();j();Me();be();ye();tR=Symbol.for(uD),iy=Symbol.for(nR),dD=Symbol.for(pD),mD=Symbol.for(fD),ay=Symbol.for(rR),gD=Symbol.for(hD),oR={_In:(e)=>e,_Out:(e)=>e};iR=class iR{incremental;bigint;[tR]=oR;[iy]=iy;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=he(nR)}_hash;[M](){return this._hash}[I](e){return sy(e)}pipe(){return T(this,arguments)}};aR=class aR{boundaries;[tR]=oR;[ay]=ay;constructor(e){this.boundaries=e,this._hash=g(he(rR),G(E(this.boundaries)))}_hash;[M](){return this._hash}[I](e){return cy(e)&&O(this.boundaries,e.boundaries)}pipe(){return T(this,arguments)}}});var yD="effect/MetricKey",fR,xD,SD,id,_D=(e)=>C(e,fR),mR=(e,t)=>new id(e,sR(t),kr(t?.description)),hR=(e,t,n)=>new id(e,cR(t),kr(n)),gR;var yR=x(()=>{Be();pe();j();Me();Ge();be();ye();ly();fR=Symbol.for(yD),xD={_Type:(e)=>e},SD=uo(O);id=class id{name;keyType;description;tags;[fR]=xD;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=g(he(this.name+this.description),G(E(this.keyType)),G(en(this.tags)))}_hash;[M](){return this._hash}[I](e){return _D(e)&&this.name===e.name&&O(this.keyType,e.keyType)&&O(this.description,e.description)&&SD(this.tags,e.tags)}pipe(){return T(this,arguments)}};gR=d(2,(e,t)=>t.length===0?e:new id(e.name,e.keyType,e.description,lo(e.tags,t)))});class SR{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 xR,wD,uy,_R=()=>{let e=Object.create(wD);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},Mo,vD=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[I](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return F(a)}return A()},Ha,$a,TD=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[I](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var bR=x(()=>{pe();j();Me();Ve();Ge();be();xR=Symbol.for("effect/MutableHashMap"),wD={[xR]:xR,[Symbol.iterator](){return new uy(this)},toString(){return ge(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(de)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}};uy=class uy{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 SR(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new uy(this.self)}};Mo=d(2,(e,t)=>{if(ks(t)===!1)return e.referential.has(t)?F(e.referential.get(t)):A();let n=t[M](),r=e.buckets.get(n);if(r===void 0)return A();return vD(e,r,t)}),Ha=d(2,(e,t)=>Re(Mo(e,t))),$a=d(3,(e,t,n)=>{if(ks(t)===!1)return e.referential.set(t,n),e;let r=t[M](),o=e.buckets.get(r);if(o===void 0)return e.buckets.set(r,[[t,n]]),e.bucketsSize++,e;return TD(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var OD="effect/MetricState",kc,wR="effect/MetricState/Counter",py,vR="effect/MetricState/Frequency",dy,TR="effect/MetricState/Gauge",fy,ER="effect/MetricState/Histogram",my,OR="effect/MetricState/Summary",hy,Cc,RR,RD,kR,CR,AR,PR,IR=(e)=>new RR(e),MR=(e)=>new kR(e),NR=(e)=>new CR(e),FR=(e)=>new AR(e.buckets,e.count,e.min,e.max,e.sum),LR=(e)=>new PR(e.error,e.quantiles,e.count,e.min,e.max,e.sum),kD=(e)=>C(e,py),CD=(e)=>C(e,dy),AD=(e)=>C(e,fy),PD=(e)=>C(e,my),ID=(e)=>C(e,hy);var DR=x(()=>{Be();pe();j();Me();be();ye();kc=Symbol.for(OD),py=Symbol.for(wR),dy=Symbol.for(vR),fy=Symbol.for(TR),my=Symbol.for(ER),hy=Symbol.for(OR),Cc={_A:(e)=>e};RR=class RR{count;[kc]=Cc;[py]=py;constructor(e){this.count=e}[M](){return g(E(wR),G(E(this.count)),ie(this))}[I](e){return kD(e)&&this.count===e.count}pipe(){return T(this,arguments)}};RD=uo(O);kR=class kR{occurrences;[kc]=Cc;[dy]=dy;constructor(e){this.occurrences=e}_hash;[M](){return g(he(vR),G(en(ke(this.occurrences.entries()))),ie(this))}[I](e){return CD(e)&&RD(ke(this.occurrences.entries()),ke(e.occurrences.entries()))}pipe(){return T(this,arguments)}};CR=class CR{value;[kc]=Cc;[fy]=fy;constructor(e){this.value=e}[M](){return g(E(TR),G(E(this.value)),ie(this))}[I](e){return AD(e)&&this.value===e.value}pipe(){return T(this,arguments)}};AR=class AR{buckets;count;min;max;sum;[kc]=Cc;[my]=my;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[M](){return g(E(ER),G(E(this.buckets)),G(E(this.count)),G(E(this.min)),G(E(this.max)),G(E(this.sum)),ie(this))}[I](e){return PD(e)&&O(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return T(this,arguments)}};PR=class PR{error;quantiles;count;min;max;sum;[kc]=Cc;[hy]=hy;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}[M](){return g(E(OR),G(E(this.error)),G(E(this.quantiles)),G(E(this.count)),G(E(this.min)),G(E(this.max)),G(E(this.sum)),ie(this))}[I](e){return ID(e)&&this.error===e.error&&O(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return T(this,arguments)}}});var ND="effect/MetricHook",FD,LD,Ac=(e)=>({[FD]:LD,pipe(){return T(this,arguments)},...e}),qR,HR=(e)=>{let t=e.keyType.bigint?qR:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=qR:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return Ac({get:()=>IR(t),update:r,modify:r})},$R=(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 Ac({get:()=>MR(t),update:n,modify:n})},jR=(e,t)=>{let n=t;return Ac({get:()=>NR(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},VR=(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;g(t,Ar(ir),Cn((p,f)=>{o[f]=p}));let l=(p)=>{let f=0,h=n;while(f!==h){let m=Math.floor(f+(h-f)/2),w=o[m];if(p<=w)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=oi(n),f=0;for(let h=0;h<n;h++){let m=o[h],w=r[h];f=f+w,p[h]=[m,f]}return p};return Ac({get:()=>FR({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},BR=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=g(o,Ar(ir)),a=oi(r),s=0,c=0,l=0,u=0,p=0,f=(m)=>{let w=[],S=0;while(S!==r-1){let y=a[S];if(y!=null){let[R,P]=y,z=Iu(m-R);if(Yw(z,oh)&&Gw(z,n))w.push(P)}S=S+1}return DD(t,i,Ar(w,ir))},h=(m,w)=>{if(r>0){s=s+1;let S=s%r;a[S]=[w,m]}u=c===0?m:Math.min(u,m),p=c===0?m:Math.max(p,m),c=c+1,l=l+m};return Ac({get:()=>LR({error:t,quantiles:f(Date.now()),count:c,min:u,max:p,sum:l}),update:([m,w])=>h(m,w),modify:([m,w])=>h(m,w)})},DD=(e,t,n)=>{let r=n.length;if(!we(t))return Pr();let o=t[0],i=t.slice(1),a=UR(e,r,A(),0,o,n),s=Rt(a);return i.forEach((c)=>{s.push(UR(e,r,a.value,a.consumed,c,a.rest))}),Cn(s,(c)=>[c.quantile,c.value])},UR=(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,w=r,S=o,y=i;while(!0){if(!we(p))return{quantile:u,value:A(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:F(Sm(p)),consumed:l+p.length,rest:[]};let R=et(p),P=Nb(p,(L)=>L===R),z=u*s,X=a/2*z,U=l+P[0].length,te=Math.abs(U-z);if(U<z-X){f=a,h=s,m=Cr(p),w=U,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}if(U>z+X){let L=Ne(c)?F(R):c;return{quantile:u,value:L,consumed:l,rest:p}}switch(c._tag){case"None":{f=a,h=s,m=Cr(p),w=U,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}case"Some":{let L=Math.abs(z-c.value);if(te<L){f=a,h=s,m=Cr(p),w=U,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}return{quantile:u,value:F(c.value),consumed:l,rest:p}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var KR=x(()=>{Be();ah();j();wc();Ge();be();DR();FD=Symbol.for(ND),LD={_In:(e)=>e,_Out:(e)=>e},qR=BigInt(0)});var UD="effect/MetricPair",HD,$D,zR=(e,t)=>({[HD]:$D,metricKey:e,metricState:t,pipe(){return T(this,arguments)}});var WR=x(()=>{be();HD=Symbol.for(UD),$D={_Type:(e)=>e}});var VD="effect/MetricRegistry",JR,GR,YR=()=>new GR;var ZR=x(()=>{j();bR();Ge();KR();ly();WR();JR=Symbol.for(VD);GR=class GR{[JR]=JR;map=_R();snapshot(){let e=[];for(let[t,n]of this.map)e.push(zR(t,n.get()));return e}get(e){let t=g(this.map,Mo(e),Bt);if(t==null){if(sy(e.keyType))return this.getCounter(e);if(uR(e.keyType))return this.getGauge(e);if(lR(e.keyType))return this.getFrequency(e);if(cy(e.keyType))return this.getHistogram(e);if(pR(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=g(this.map,Mo(e),Bt);if(t==null){let n=HR(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getFrequency(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=$R(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getGauge(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=jR(e,e.keyType.bigint?BigInt(0):0);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getHistogram(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=VR(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getSummary(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=BR(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}}});var KD="effect/Metric",zD,WD,XR,QR=function(e,t,n,r){let o=Object.assign((i)=>cp(i,(a)=>GD(o,a)),{[zD]:WD,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return T(this,arguments)}});return o},Pc=(e,t)=>ek(mR(e,t)),ek=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=XR.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=XR.get(gR(e,o)),n.set(o,i),i};return QR(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},tk=(e,t,n)=>ek(hR(e,t,n)),nk,JD,GD;var rk=x(()=>{Be();j();be();rt();yR();NO();ZR();zD=Symbol.for(KD),WD={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},XR=V(Symbol.for("effect/Metric/globalMetricRegistry"),()=>YR()),nk=d(3,(e,t,n)=>JD(e,[MO(t,n)])),JD=d(2,(e,t)=>QR(e.keyType,(n,r)=>e.unsafeUpdate(n,lo(t,r)),(n)=>e.unsafeValue(lo(t,n)),(n,r)=>e.unsafeModify(n,lo(t,r)))),GD=d(2,(e,t)=>wi(gc,(n)=>D(()=>e.unsafeUpdate(t,n))))});var ZD="effect/Request",XD,QD,tJ,ok;var ik=x(()=>{j();zg();rt();Rr();XD=Symbol.for(ZD),QD={_E:(e)=>e,_A:(e)=>e},tJ={...Ns,[XD]:QD},ok=d(2,(e,t)=>wi(ed,(n)=>D(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,_p(r.result,t)}})))});var eq="effect/Supervisor",ad,gy,sd,cd,yy=(e)=>C(e,ad)&&Os(e,"Zip"),ak,tq=(e)=>new ak(e),Ai;var ld=x(()=>{j();ye();rt();ad=Symbol.for(eq),gy={_T:(e)=>e};sd=class sd{underlying;value0;[ad]=gy;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 sd(this,g(this.value,Ke(e)))}zip(e){return new cd(this,e)}};cd=class cd{left;right;_tag="Zip";[ad]=gy;constructor(e,t){this.left=e,this.right=t}get value(){return up(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 sd(this,g(this.value,Ke(e)))}zip(e){return new cd(this,e)}};ak=class ak{effect;[ad]=gy;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 sd(this,g(this.value,Ke(e)))}zip(e){return new cd(this,e)}onRun(e,t){return e()}};Ai=V("effect/Supervisor/none",()=>tq(nt))});var sk;var ck=x(()=>{Wu();sk=wo});var lk="Empty",uk="AddSupervisor",pk="RemoveSupervisor",dk="AndThen",ja,ud=(e,t)=>({_tag:dk,first:e,second:t}),rq=(e,t)=>oq(t,tt(e)),oq=(e,t)=>{let n=e,r=t;while(An(r)){let o=Pn(r);switch(o._tag){case lk:{r=In(r);break}case uk:{n=n.zip(o.supervisor),r=In(r);break}case pk:{n=Sy(n,o.supervisor),r=In(r);break}case dk:{r=kt(o.first)(kt(o.second)(In(r)));break}}}return n},Sy=(e,t)=>{if(O(e,t))return Ai;else if(yy(e))return Sy(e.left,t).zip(Sy(e.right,t));else return e},pd=(e)=>{if(O(e,Ai))return er();else if(yy(e))return g(pd(e.left),Lr(pd(e.right)));else return ci(e)},iq=(e,t)=>{if(O(e,t))return ja;let n=pd(e),r=pd(t),o=g(r,Um(n),ui(ja,(a,s)=>ud(a,{_tag:uk,supervisor:s}))),i=g(n,Um(r),ui(ja,(a,s)=>ud(a,{_tag:pk,supervisor:s})));return ud(o,i)},fk;var mk=x(()=>{Qn();ck();pe();j();pi();ld();ja={_tag:lk},fk=sk({empty:ja,patch:rq,combine:ud,diff:iq})});var hq,hk,gq,yq,xq,Ic="Continue",Sq="Done",gk="Yield",_q,dd=(e)=>{throw Error(`BUG: FiberRuntime - ${Er(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Kr,zr,Mc,bq,wq=(e)=>_i(Hv(e),(t)=>Pi(jv(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(Mr(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return ko(Dq(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),ed,o)},!1,!1)),vq,fd,Tq,Eq=(e)=>od((t)=>{let n=IE(t.context,Tc);zs(n,Mp).unsafe.log(e.log(t))}),Oq,Rq,kq,Sk,_k=(e,t,n)=>Ce(()=>{let r=ke(e),o=Array(r.length);return Ro(Pi(r,(a,s)=>B(t(a,s),(c)=>D(()=>o[s]=c)),n,!1),fe(o))}),Pi=(e,t,n,r,o)=>Oo((i)=>ng((a)=>xt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return nt;let u=0,p=!1,f=o?Math.min(c.length,o):c.length,h=new Set,m=[],w=()=>h.forEach((L)=>{L.currentScheduler.scheduleTask(()=>{L.unsafeInterruptAsFork(s.id())},0,L)}),S=[],y=[],R=[],P=()=>{let L=m.filter(({exit:se})=>se._tag==="Failure").sort((se,ce)=>se.index<ce.index?-1:se.index===ce.index?0:1).map(({exit:se})=>se);if(L.length===0)L.push(xn);return L},z=(L,se=!1)=>{let ce=lp(a(L)),ee=Aq(ce,s,s.currentRuntimeFlags,Rc);return s.currentScheduler.scheduleTask(()=>{if(se)ee.unsafeInterruptAsFork(s.id());ee.resume(ce)},0,ee),ee},X=()=>{if(!r)l-=c.length,c=[];p=!0,w()},U=n?tg:Eo,te=z(To((L)=>{let se=(ee,Ae)=>{if(ee._op==="Blocked")R.push(ee);else if(m.push({index:Ae,exit:ee}),ee._op==="Failure"&&!p)X()},ce=()=>{if(c.length>0){let ee=c.pop(),Ae=u++,vt=()=>{let je=c.pop();return Ae=u++,B(fc(),()=>B(U(i(t(je,Ae))),Ft))},Ft=(je)=>{if(c.length>0){if(se(je,Ae),c.length>0)return vt()}return fe(je)},Lt=B(U(i(t(ee,Ae))),Ft),De=z(Lt);if(S.push(De),h.add(De),p)De.currentScheduler.scheduleTask(()=>{De.unsafeInterruptAsFork(s.id())},0,De);De.addObserver((je)=>{let Tt;if(je._op==="Failure")Tt=je;else Tt=je.effect_instruction_i0;if(y.push(De),h.delete(De),se(Tt,Ae),m.length===l)L(fe(Oe(Oi(P(),{parallel:!0}),()=>xn)));else if(R.length+m.length===l){let Et=P(),Gi=R.map((to)=>to.effect_instruction_i0).reduce(Vh);L(fe(rp(Gi,Pi([Oe(Oi(Et,{parallel:!0}),()=>xn),...R.map((to)=>to.effect_instruction_i1)],(to)=>to,n,!0,o))))}else ce()})}};for(let ee=0;ee<f;ee++)ce()}));return Vr(Ca(uc(i(rd(te))),xp({onFailure:(L)=>{X();let se=R.length+1,ce=Math.min(typeof o==="number"?o:R.length,R.length),ee=Array.from(R);return To((Ae)=>{let vt=[],Ft=0,Lt=0,De=(Tt,Et)=>(Gi)=>{if(vt[Tt]=Gi,Ft++,Ft===se)Ae(Ie(ve(L)));if(ee.length>0&&Et)je()},je=()=>{z(ee.pop(),!0).addObserver(De(Lt,!0)),Lt++};te.addObserver(De(Lt,!1)),Lt++;for(let Tt=0;Tt<ce;Tt++)je()})},onSuccess:()=>yn(y,(L)=>L.inheritAll)})))}))),_y=(e,t,n,r)=>Ce(()=>{let o=ke(e),i=Array(o.length);return Ro(Pi(o,(s,c)=>Ke(n(s,c),(l)=>i[c]=l),r,!1,t),fe(i))}),vy=(e)=>Pq(e,Rc),Cq=(e,t,n,r=null)=>{let o=bk(e,t,n,r);return o.resume(e),o},Aq=(e,t,n,r=null)=>bk(e,t,n,r),bk=(e,t,n,r=null)=>{let o=Uu(),i=t.getFiberRefs(),a=Pg(i,o),s=new fd(o,a,n),c=Ao(a,Ti),l=s.currentSupervisor;return l.onStart(c,e,F(t),s),s.addObserver((p)=>l.onEnd(p,s)),(r!==null?r:g(t.getFiberRef(np),Oe(()=>t.scope()))).add(n,s),s},Pq=(e,t)=>xt((n,r)=>fe(Cq(e,n,r.runtimeFlags,t))),by=(e)=>Ri((t)=>Je(_o(t,Nc),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return B(Pa(n,qp),(r)=>Ty(e,r))}}})),yk=(e)=>(t)=>Ri((n)=>Je(_o(n,Nc),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return B(Pa(r,Up(e)),(o)=>Ty(t,o))}})),Va=(e,t)=>(n)=>Ri((r)=>Je(_o(r,Nc),{onNone:()=>n(ue),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?by:e._tag==="Sequential"?wy:yk(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(by));case"Sequential":return i(n(wy));case"ParallelN":return i(n(yk(o.strategy.parallelism)))}}else return n(ue)}})),wy=(e)=>Ri((t)=>Je(_o(t,Nc),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return B(Pa(n,Dp),(r)=>Ty(e,r))}}})),Nc,Iq=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},Mq,Nq=(e=Fa)=>{let t=Object.create(Mq);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},Ty,Fq=(e)=>vi(e,{differ:fk,fork:ja}),xk,Lq,wk,Dq=(e,t,n)=>lc((r)=>wk(B(vy(ap(e)),(o)=>To((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"&&Ia(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&Ou(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(lT(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(),D(()=>{c.forEach((l)=>l())})})),Ce(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return _i(o,(i)=>ok(i.request,dg(r)))})));var Ey=x(()=>{Be();Qn();mn();Tg();RE();wa();Ng();WE();sO();j();pi();Ve();uO();EO();Ge();be();ye();$h();Qp();io();Vv();Sa();Sg();zg();CO();FO();rt();xE();bg();Lp();KO();Hp();ty();YO();rk();eR();ik();ac();ac();ld();mk();Fp();hq=Pc("effect_fiber_started",{incremental:!0}),hk=Pc("effect_fiber_active"),gq=Pc("effect_fiber_successes",{incremental:!0}),yq=Pc("effect_fiber_failures",{incremental:!0}),xq=nk(tk("effect_fiber_lifetimes",QO({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),_q={_E:(e)=>e,_A:(e)=>e},Kr=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),zr=V("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Mc={[ta]:(e,t,n)=>yt(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>Ie(Ie(n)),[na]:(e,t,n)=>yt(()=>t.effect_instruction_i2(n)),[Is]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),$r(e.currentRuntimeFlags)&&e.isInterrupted())return ve(e.getInterruptedCause());else return Ie(n)},[ra]:(e,t,n)=>{if(yt(()=>t.effect_instruction_i2(n)),yt(()=>t.effect_instruction_i0()))return e.pushStack(t),yt(()=>t.effect_instruction_i1());else return nt},[oa]:(e,t,n)=>{while(!0){let r=yt(()=>t.effect_instruction_i0.next(n));if(r.done)return Ie(r.value);let o=Yf(r.value);if(!Ia(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},bq={[Zg]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),$r(t)?ve(r.cause):n),[Qg]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[Xg]:(e,t,n,r)=>(r.onFiber(e,Fg(t)),n),[ey]:(e,t,n,r)=>B(fc(),()=>n)},vq=Ms();fd=class fd extends vg{[ny]=ry;[BO]=_q;_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,Lh(n)){let r=this.getFiberRef(gc);hq.unsafeUpdate(1,r),hk.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return rd(this)}id(){return this._fiberId}resume(e){this.tell(ki(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(aO(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return jO(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(yc)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return Ce(()=>{let t=OT(this._fiberId);return this.tell(Ua((n,r)=>{_p(t,D(()=>e(n,r)))})),Sp(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return To((e)=>{let t=(n)=>e(fe(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(Ua((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),D(()=>this.tell(Ua((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return xt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=Ag(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(xk),c=g(oc(o,s),Hh(Hr),Hh(Yu));return rg(c)})}get poll(){return D(()=>kr(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return D(()=>this.tell(td(Mn(e))))}unsafeInterruptAsFork(e){this.tell(td(Mn(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(xk,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=Ec(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=La(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(Tc),this.currentTracer=this.currentDefaultServices.unsafeMap.get(vc.key),this.currentSupervisor=this.getFiberRef(Lq),this.currentScheduler=this.getFiberRef(Xp),this.currentContext=this.getFiberRef(Ti),this.currentSpan=this.currentContext.unsafeMap.get(Np.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=Ic,n=globalThis[Io];globalThis[Io]=this;try{while(t===Ic)t=this._queue.length===0?Sq:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Io]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===gk)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Aa),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=bq[r._tag](this,e,n,r)}return n}isInterrupted(){return!Eu(this.getFiberRef(yc))}addInterruptedCause(e){let t=this.getFiberRef(yc);this.setFiberRef(yc,Ct(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(td(Mn(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return dc({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Vr(r.value.await);else return D(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(Lh(this.currentRuntimeFlags)){let t=this.getFiberRef(gc),n=this.id().startTimeMillis,r=Date.now();switch(xq.unsafeUpdate(r-n,t),hk.unsafeUpdate(-1,t),e._tag){case Vt:{gq.unsafeUpdate(1,t);break}case jt:{yq.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(wT);if(!xa(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(kq)}log(e,t,n){let r=Re(n)?n.value:this.getFiberRef(cg),o=this.getFiberRef(Tq);if(cO(o,r))return;let i=this.getFiberRef(xT),a=this.getFiberRef(yT),s=this.getLoggers(),c=this.getFiberRefs();if(js(s)>0){let l=zs(this.getFiberRef(Tc),bc),u=new Date(l.unsafeCurrentTimeMillis());eb(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 ey:return gk;case Zg:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(ve(e.cause)),this._asyncInterruptor=null;return Ic}case Qg:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),Ic;case Xg:return e.onFiber(this,this._exitValue!==null?oO:iO(this.currentRuntimeFlags,this._asyncBlockingOn)),Ic;default:return dd(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=$r(this.currentRuntimeFlags)&&this.isInterrupted()?ve(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===Kr){let o=zr.currentOp;if(zr.currentOp=null,o._op===ia)if(Lv(this.currentRuntimeFlags))this.tell(qO()),this.tell(ki(xn)),t=null;else t=xn;else if(o._op===ti)t=null}else{this.currentRuntimeFlags=g(this.currentRuntimeFlags,Mh(Yu));let o=this.interruptAllChildren();if(o!==null)t=B(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(ki(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Io];globalThis[Io]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Io]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(ki(e))}startFork(e){this.tell(ki(e))}patchRuntimeFlags(e,t){let n=ic(e,t);return globalThis[Io]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(ki(o))};if($r(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(At(rn(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!==Ps)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==ta&&e._op!==ra&&e._op!==oa)return e;e=this.popStack()}}[nb](e){return D(()=>Ws(this.currentContext,e))}["Left"](e){return dt(e.left)}["None"](e){return dt(new xc)}["Right"](e){return Ie(e.right)}["Some"](e){return Ie(e.value)}["Micro"](e){return sc((t)=>{let n=t,r=TO(bO(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(Ie(o.value));switch(o.cause._tag){case"Interrupt":return n(ve(Mn(hn)));case"Fail":return n(dt(o.cause.error));case"Die":return n(ip(o.cause.defect))}}),sc((o)=>{n=(i)=>{o(nt)},r.unsafeInterrupt()})})}[eu](e){let t=yt(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Mc))dd(n);return Mc[n._op](this,n,t)}else return zr.currentOp=Ie(t),Kr}[Vt](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Mc))dd(n);return Mc[n._op](this,n,t.effect_instruction_i0)}else return zr.currentOp=t,Kr}[jt](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case Ps:case na:if(!($r(this.currentRuntimeFlags)&&this.isInterrupted()))return yt(()=>n.effect_instruction_i1(t));else return ve(ku(t));case"OnStep":if(!($r(this.currentRuntimeFlags)&&this.isInterrupted()))return Ie(ve(t));else return ve(ku(t));case Is:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),$r(this.currentRuntimeFlags)&&this.isInterrupted())return ve(Ct(t,this.getInterruptedCause()));else return ve(t);default:dd(n)}else return zr.currentOp=ve(t),Kr}[tu](e){return yt(()=>e.effect_instruction_i0(this,Fg(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=KE(o.refs,t),s=oc(o.flags,n);return Ie(rp(e.effect_instruction_i0,xt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(zE(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=ic(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return Oo((r)=>B(vy(Wh(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return wq(e.effect_instruction_i0)}[ri](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=ic(n,t);if($r(r)&&this.isInterrupted())return ve(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=oc(r,n);return this.pushStack(new Jh(o,e)),yt(()=>e.effect_instruction_i1(n))}else return xn}[ta](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[Ps](e){return this.pushStack(e),e.effect_instruction_i0}[na](e){return this.pushStack(e),e.effect_instruction_i0}[ti](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),zr.currentOp=e,Kr}[ia](e){return this._isYielding=!1,zr.currentOp=e,Kr}[ra](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return xn}[oa](e){return Mc[oa](this,e,void 0)}[ni](e){return yt(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&Fv)!==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=B(fc({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(vq!==t[vo]._V){let n=this.getFiberRef(vT);if(n._tag==="Some"){let r=t[vo]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${Ms()}, 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`,Dr,n)}}return this[t._op](t)},this),t===Kr){let n=zr.currentOp;if(n._op===ia||n._op===ti)return Kr;return zr.currentOp=null,n._op===Vt||n._op===jt?n:ve(rn(n))}}catch(n){if(t!==Kr&&!C(t,"_op")||!(t._op in this))t=Xh(`Not a valid effect: ${Er(t)}`);else if(TT(n))t=ve(Ct(rn(n),Mn(hn)));else t=ip(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};Tq=V("effect/FiberRef/currentMinimumLogLevel",()=>St(lO("Info"))),Oq=V(Symbol.for("effect/Logger/defaultLogger"),()=>Eq(JO)),Rq=V(Symbol.for("effect/Logger/tracerLogger"),()=>od(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=Yg(_o(Ao(n,Ti),Np));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=Ws(Ao(n,Tc),bc),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=av(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=Nn(t,{renderErrorCause:!0});a.value.event(Er(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),kq=V(Symbol.for("effect/FiberRef/currentLoggers"),()=>hT(ci(Oq,Rq))),Sk=d((e)=>zf(e[0]),(e,t,n)=>xt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(bT);if(n?.discard)return Wg(n.concurrency,()=>Va(Dp,n?.concurrentFinalizers)((i)=>o?Pi(e,(a,s)=>i(t(a,s)),!0,!1,1):_i(e,(a,s)=>i(t(a,s)))),()=>Va(qp,n?.concurrentFinalizers)((i)=>Pi(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>Va(Up(i),n?.concurrentFinalizers)((a)=>Pi(e,(s,c)=>a(t(s,c)),o,!1,i)));return Wg(n?.concurrency,()=>Va(Dp,n?.concurrentFinalizers)((i)=>o?_y(e,1,(a,s)=>i(t(a,s)),!0):yn(e,(a,s)=>i(t(a,s)))),()=>Va(qp,n?.concurrentFinalizers)((i)=>_k(e,(a,s)=>i(t(a,s)),o)),(i)=>Va(Up(i),n?.concurrentFinalizers)((a)=>_y(e,i,(s,c)=>a(t(s,c)),o)))})),Nc=Kt("effect/Scope"),Mq={[mp]:mp,[hp]:hp,pipe(){return T(this,arguments)},fork(e){return D(()=>{let t=Nq(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),Iq(t,(o)=>D(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return Ce(()=>{if(this.state._tag==="Closed")return nt;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return nt;return Eg(this.strategy)?g(yn(t,(n)=>Eo(n(e))),B((n)=>g(Oi(n),On(Sc),Oe(()=>xn)))):Og(this.strategy)?g(_k(t,(n)=>Eo(n(e)),!1),B((n)=>g(Oi(n,{parallel:!0}),On(Sc),Oe(()=>xn)))):g(_y(t,this.strategy.parallelism,(n)=>Eo(n(e)),!1),B((n)=>g(Oi(n,{parallel:!0}),On(Sc),Oe(()=>xn))))})},addFinalizer(e){return Ce(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),nt})}},Ty=d(2,(e,t)=>mg(e,Js(jw(Nc,t)))),xk=gT(Dv),Lq=Fq(Ai),wk=d(2,(e,t)=>Oo((n)=>gn(n(e),{onFailure:(r)=>gn(t,{onFailure:(o)=>At(Ct(r,o)),onSuccess:()=>At(r)}),onSuccess:(r)=>jr(t,r)})))});var Tk,Ek;var Ok=x(()=>{rt();Tk=lg,Ek=Pa});class Ak{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return T(this,arguments)}}var Ry=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},Rk,$q,kk,jq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new kk(e);return Error.stackTraceLimit=t,n},Oy,md,Ck,Vq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new Ck(e);return Error.stackTraceLimit=t,n},Bq=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return _c(t.left);case"Right":return Ie(t.right);case"Some":return Ie(t.value);case"None":return _c(new xc)}},Kq,zq=(e)=>new Ak(e.context,e.runtimeFlags,e.fiberRefs),Wq,Pk,Ik,Mk;var Nk=x(()=>{mn();pe();wa();Ng();Ve();Ge();be();Qp();Ok();Sa();rt();Lp();Ey();ty();ac();ld();Rk=Ry((e,t,n)=>{let r=Uu(),o=[[Ti,[[r,e.context]]]];if(n?.scheduler)o.push([Xp,[[r,n.scheduler]]]);let i=ME(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new fd(r,i,e.runtimeFlags),s=t;if(n?.scope)s=B(Ek(n.scope,Fa),(l)=>Ro(gp(l,lc((u)=>O(u,a.id())?nt:hc(a,u))),Ca(t,(u)=>Tk(l,u))));let c=a.currentSupervisor;if(c!==Ai)c.onStart(e.context,s,A(),a),a.addObserver((l)=>c.onEnd(l,a));if(Rc.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),$q=Ry((e,t)=>{let n=Kq(e)(t);if(n._tag==="Failure")throw Vq(n.effect_instruction_i0);return n.effect_instruction_i0});kk=class kk 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}};Oy=Symbol.for("effect/Runtime/FiberFailure"),md=Symbol.for("effect/Runtime/FiberFailure/Cause");Ck=class Ck extends Error{[Oy];[md];constructor(e){let t=Vs(e)[0];super(t?.message||"An error has occurred");if(this[Oy]=Oy,this[md]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[md].toJSON()}}toString(){return"(FiberFailure) "+Nn(this[md],{renderErrorCause:!0})}[ne](){return this.toString()}};Kq=Ry((e,t)=>{let n=Bq(t);if(n)return n;let r=new Oc,o=Rk(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return pg(op(jq(o),bp(o)))});Wq=Fh(Hr,Ih,Ph),Pk=zq({context:So(),runtimeFlags:Wq,fiberRefs:NE()}),Ik=Rk(Pk),Mk=$q(Pk)});var Fk,Fc,Lc,an,Lk,hd,Dk,Ii,Ln,qk,Uk;var Hk=x(()=>{rt();Ey();Nk();Fk=Ra,Fc=Sk,Lc=Ce,an=nt,Lk=cc,hd=Ke,Dk=bi,Ii=Si,Ln=B,qk=Ik,Uk=Mk});var ky=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return ky(e,t.from)}},Dc=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},Cy=(e)=>Array.isArray(e),jk=(e)=>!Array.isArray(e),$k=(e)=>`[${As(e)}]`,gd=(e)=>Cy(e)?e.map($k).join(""):$k(e);var qc=x(()=>{Ve()});var No=(e,t,n,r)=>{let o=e;if(n&&we(n))o+=`
31
- at path: ${gd(n)}`;if(t!==void 0)o+=`
32
- details: ${t}`;if(r)o+=`
33
- schema (${r._tag}): ${r}`;return o},Vk=(e)=>No("Invalid Argument",e),Bk=(e)=>No("Unsupported key schema",void 0,void 0,e),Kk=(e)=>No("Unsupported literal",`literal value: ${Zn(e)}`),Ay=(e)=>No("Duplicate index signature",`${e} index signature`),zk,Wk,Py=(e)=>No("Duplicate property signature transformation",`Duplicate key ${Zn(e)}`),Iy=(e)=>No("Duplicate property signature",`Duplicate key ${Zn(e)}`);var My=x(()=>{Be();Ve();qc();zk=No("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),Wk=No("Invalid element","A required element cannot follow an optional element. ts(1257)")});var Gk,Yk,Zk,Xk,Qk,eC,tC;var nC=x(()=>{Gk=Symbol.for("effect/SchemaId/DateFromSelf"),Yk=Symbol.for("effect/SchemaId/GreaterThan"),Zk=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),Xk=Symbol.for("effect/SchemaId/Int"),Qk=Symbol.for("effect/SchemaId/MinLength"),eC=Symbol.for("effect/SchemaId/MaxLength"),tC=Symbol.for("effect/SchemaId/MinItems")});class Ba{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 Oe(sr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Mi{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Oe(sr(this),()=>Zn(this.literal))}toJSON(){return{_tag:this._tag,literal:ro(this.literal)?String(this.literal):this.literal,annotations:He(this.annotations)}}}class wd{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Oe(sr(this),()=>Zn(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:He(this.annotations)}}}class hC{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class gC{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class yC{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class xC{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class SC{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class bC{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class vC{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class EC{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class RC{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class kC{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class AC{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class Ka{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 $c{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(Wk)}toString(){return Oe(sr(this),()=>o2(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 za{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,IC(e))this.parameter=e;else throw Error(zk)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class cr{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(Iy(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=px(t[i].parameter);if(Ed(a)){if(o.string)throw Error(Ay("string"));o.string=!0}else if(CC(a)){if(o.symbol)throw Error(Ay("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Oe(sr(this),()=>i2(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 Ut{types;annotations;static make=(e,t)=>Od(e)?new Ut(e,t):e.length===1?e[0]:Td;static unify=(e,t)=>Ut.make(c2(MC(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Oe(sr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Rd{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=Dc(e)}toString(){return sr(this).pipe(En(()=>Rn(vb(this.f)(),(e)=>sr(e))),Oe(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=Ny.get(e);if(t)return t;return Ny.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:He(this.annotations)},Ny.set(e,t),t}}class jc{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return Uc(this).pipe(Oe(()=>Je(qC(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Vc(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:He(this.annotations)}}}class ax{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 Oe(sr(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 sx{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class cx{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(Py(o));t[o]=!0;let i=r.to;if(n[i])throw Error(Py(i));n[i]=!0}}}function Sn(e,t){let n=!1,r=oi(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 f2(e){return Je(Zy(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Zn(n)}>`).join("")})}var oC,Ly,iC,Dy,xd,Sd,zt,_d,Wr,qy,Uy,Hy,$y,jy,Vy,aC,By,Ky,zy,Wy,Jy,Gy,Yy,Pt,Zy,sC,cC,Xy,Qy,Uc,ex,lC,uC,pC,dC,fC,tx,Zq,nx=(e)=>Ob(Zq(e),(t)=>t===!0),rx,Xq,Qq=(e)=>En(Xq(e),()=>Uc(e)),Hc=(e)=>(t)=>t._tag===e,bd,mC,vd,e2,Td,ox,_C,wC,Ed,TC,OC,t2,n2,CC,r2,Fo,PC=(e)=>e.map((t)=>t.type),o2=(e)=>{let t=e.elements.map(String).join(", ");return Cb(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}>`}})},st,IC=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return IC(e.from)}return!1},rC=(e)=>e.map(String).join("; "),i2=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${rC(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${rC(e.indexSignatures)} }`;else return"{}"},a2,s2,MC=(e)=>Ds(e,(t)=>ix(t)?MC(t.types):[t]),c2=(e)=>{let t=a2(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[_C];case"UnknownKeyword":return[ox];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=s2[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},NC=(e,t)=>e.map(t),Od=(e)=>e.length>1,ix,Ny,Vc,kd,Bc=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[Sd];let o={...r,...t},i=tx(e);if(Re(i))o[Gy]=Bc(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},l2="[\\s\\S]*?",u2="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",FC=(e,t)=>{switch(e._tag){case"Literal":return Na(String(e.literal));case"StringKeyword":return l2;case"NumberKeyword":return u2;case"TemplateLiteral":return LC(e,t,!1);case"Union":return e.types.map((n)=>FC(n,t)).join("|")}},p2=(e,t,n,r)=>{if(ix(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},LC=(e,t,n)=>{let r="";if(e.head!==""){let o=Na(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=FC(o.type,t);if(r+=p2(o.type,i,t,n),o.literal!==""){let a=Na(o.literal);r+=t&&n?`(${a})`:a}}return r},DC=(e)=>new RegExp(`^${LC(e,!1,!0)}$`),lx=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new za(i,t,!0));break;case"Literal":if(gt(i.literal)||Qt(i.literal))n.push(new st(i.literal,t,!1,!0));else throw Error(Kk(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new st(s,t,!1,!0));break}case"UniqueSymbol":n.push(new st(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(Bk(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},ux=(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},d2,at=(e)=>{switch(e._tag){case"Declaration":{let t=Sn(e.typeParameters,at);return t===e.typeParameters?e:new Ba(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Sn(e.elements,(o)=>{let i=at(o.type);return i===o.type?o:new Fo(i,o.isOptional)}),n=PC(e.rest),r=Sn(n,at);return t===e.elements&&r===n?e:new $c(t,r.map((o)=>new Ka(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Sn(e.propertySignatures,(r)=>{let o=at(r.type);return o===r.type?r:new st(r.name,o,r.isOptional,r.isReadonly)}),n=Sn(e.indexSignatures,(r)=>{let o=at(r.type);return o===r.type?r:new za(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new cr(t,n,e.annotations)}case"Union":{let t=Sn(e.types,at);return t===e.types?e:Ut.make(t,e.annotations)}case"Suspend":return new Rd(()=>at(e.f()),e.annotations);case"Refinement":{let t=at(e.from);return t===e.from?e:new jc(t,e.filter,e.annotations)}case"Transformation":{let t=d2(e);return at(t!==void 0?Bc(e.to,t):e.to)}}return e},Fy=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return Fy(e.from);case"Suspend":return Fy(e.f())}},ar=(e,t)=>{switch(e._tag){case"Declaration":{let n=Sn(e.typeParameters,(r)=>ar(r,t));return n===e.typeParameters?e:new Ba(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=Sn(e.elements,(i)=>{let a=ar(i.type,t);return a===i.type?i:new Fo(a,i.isOptional)}),r=PC(e.rest),o=Sn(r,(i)=>ar(i,t));return n===e.elements&&o===r?e:new $c(n,o.map((i)=>new Ka(i)),e.isReadonly)}case"TypeLiteral":{let n=Sn(e.propertySignatures,(o)=>{let i=ar(o.type,t);return i===o.type?o:new st(o.name,i,o.isOptional,o.isReadonly)}),r=Sn(e.indexSignatures,(o)=>{let i=ar(o.type,t);return i===o.type?o:new za(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new cr(n,r)}case"Union":{let n=Sn(e.types,(r)=>ar(r,t));return n===e.types?e:Ut.make(n)}case"Suspend":{let n=void 0,r=Qq(e);if(Re(r)){let o=t?"Bound":"";n={[rx]:`${r.value}Encoded${o}`}}return new Rd(()=>ar(e.f(),t),n)}case"Refinement":{let n=ar(e.from,t);if(t){if(n===e.from)return e;if(Fy(e.from)===void 0&&nx(e))return new jc(n,e.filter,e.annotations);return n}else return n}case"Transformation":return ar(e.from,t)}return e},Cd=(e)=>ar(e,!1),He=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},px=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return px(e.from)}},Dn=(e)=>Oe(sr(e),()=>e._tag),qC=(e)=>Xy(e).pipe(En(()=>ex(e)),En(()=>Qy(e)),On((t)=>t+f2(e))),sr=(e)=>En(Uc(e),()=>qC(e));var dx=x(()=>{Be();j();Ve();My();qc();wc();Ge();au();ye();_g();oC=Symbol.for("effect/annotation/TypeConstructor"),Ly=Symbol.for("effect/annotation/Brand"),iC=Symbol.for("effect/annotation/SchemaId"),Dy=Symbol.for("effect/annotation/Message"),xd=Symbol.for("effect/annotation/MissingMessage"),Sd=Symbol.for("effect/annotation/Identifier"),zt=Symbol.for("effect/annotation/Title"),_d=Symbol.for("effect/annotation/AutoTitle"),Wr=Symbol.for("effect/annotation/Description"),qy=Symbol.for("effect/annotation/Examples"),Uy=Symbol.for("effect/annotation/Default"),Hy=Symbol.for("effect/annotation/JSONSchema"),$y=Symbol.for("effect/annotation/Arbitrary"),jy=Symbol.for("effect/annotation/Pretty"),Vy=Symbol.for("effect/annotation/Equivalence"),aC=Symbol.for("effect/annotation/Documentation"),By=Symbol.for("effect/annotation/Concurrency"),Ky=Symbol.for("effect/annotation/Batching"),zy=Symbol.for("effect/annotation/ParseIssueTitle"),Wy=Symbol.for("effect/annotation/ParseOptions"),Jy=Symbol.for("effect/annotation/DecodingFallback"),Gy=Symbol.for("effect/annotation/Surrogate"),Yy=Symbol.for("effect/annotation/StableFilter"),Pt=d(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?F(e.annotations[t]):A()),Zy=Pt(Ly),sC=Pt(Dy),cC=Pt(xd),Xy=Pt(zt),Qy=Pt(_d),Uc=Pt(Sd),ex=Pt(Wr),lC=Pt(By),uC=Pt(Ky),pC=Pt(zy),dC=Pt(Wy),fC=Pt(Jy),tx=Pt(Gy),Zq=Pt(Yy),rx=Symbol.for("effect/annotation/JSONIdentifier"),Xq=Pt(rx);bd=Hc("Literal"),mC=new Mi(null);vd=new hC({[zt]:"undefined"});e2=new gC({[zt]:"void"});Td=new yC({[zt]:"never"});ox=new xC({[zt]:"unknown"});_C=new SC({[zt]:"any"});wC=new bC({[zt]:"string",[Wr]:"a string"}),Ed=Hc("StringKeyword");TC=new vC({[zt]:"number",[Wr]:"a number"});OC=new EC({[zt]:"boolean",[Wr]:"a boolean"});t2=new RC({[zt]:"bigint",[Wr]:"a bigint"});n2=new kC({[zt]:"symbol",[Wr]:"a symbol"}),CC=Hc("SymbolKeyword");r2=new AC({[zt]:"object",[Wr]:"an object in the TypeScript meaning, i.e. the `object` type"});Fo=class Fo extends Ka{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?"?":"")}};st=class st extends Fo{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)}}};a2=Ar(iu(ir,(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})),s2={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};ix=Hc("Union"),Ny=V(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Vc=Hc("Refinement"),kd={};d2=ux([qy,Uy,Hy,$y,jy,Vy])});class ct{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class hx{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class Wa{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class $e{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class Pd{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Id{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class _n{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class gx{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function qn(e){return e.sort(x2).map((t)=>t[1])}function T2(e){return ex(e).pipe(En(()=>Xy(e)),En(()=>Qy(e)),En(()=>Uc(e)),Oe(()=>`{ ${e.from} | filter }`))}function E2(e){if(e.message!==void 0)return e.message;return`Expected ${Vc(e.ast)?T2(e.ast):String(e.ast)}, actual ${Zn(e.actual)}`}var HC,VC,xx=(e)=>new VC({issue:e}),BC,KC,Jt,Jr,Un,Md,zC,WC=(e,t)=>{if(t===void 0||Qt(t))return e;if(e===void 0)return t;return{...e,...t}},JC=(e,t,n)=>{let r=It(e,t);return(o,i)=>r(o,WC(n,i))},m2=(e,t,n)=>{let r=JC(e,t,n);return(o,i)=>um(r(o,i),xx)},GC=(e,t)=>JC(e.ast,!0,t),Nd=(e,t)=>m2(at(e.ast),!0,t),h2,g2,It=(e,t)=>{let n=t?h2:g2,r=n.get(e);if(r)return r;let o=y2(e,t),i=dC(e),a=Re(i)?(l,u)=>o(l,WC(u,i.value)):o,s=fC(e),c=t&&Re(s)?(l,u)=>zc(zC(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},fx=(e)=>Bt(lC(e)),mx=(e)=>Bt(uC(e)),y2=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=It(e.from,!0);return(r,o)=>{o=o??kd;let i=o?.errors==="all",a=Jr(zC(n(r,o),(s)=>{let c=new Pd(e,r,"From",s);if(i&&nx(e)&&eA(s))return Je(e.filter(r,o,e),{onNone:()=>W(c),onSome:(l)=>W(new $e(e,r,[c,new Pd(e,r,"Predicate",l)]))});return W(c)}),(s)=>Je(e.filter(s,o,e),{onNone:()=>Q(s),onSome:(c)=>W(new Pd(e,r,"Predicate",c))}));return zc(a,e,r,o)}}else{let n=It(at(e),!0),r=It(ZC(e.from),!1);return(o,i)=>zc(Jr(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=S2(e.transformation,t),r=t?It(e.from,!0):It(e.to,!1),o=t?It(e.to,!0):It(e.from,!1);return(i,a)=>zc(Jr(Md(r(i,a),(s)=>new Id(e,i,t?"Encoded":"Type",s)),(s)=>Jr(Md(n(s,a??kd,e,i),(c)=>new Id(e,i,"Transformation",c)),(c)=>Md(o(c,a),(l)=>new Id(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)=>zc(n(r,o??kd,e),e,r,o)}case"Literal":return Wt(e,(n)=>n===e.literal);case"UniqueSymbol":return Wt(e,(n)=>n===e.symbol);case"UndefinedKeyword":return Wt(e,W_);case"NeverKeyword":return Wt(e,J_);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return Q;case"StringKeyword":return Wt(e,gt);case"NumberKeyword":return Wt(e,Qt);case"BooleanKeyword":return Wt(e,Go);case"BigIntKeyword":return Wt(e,ro);case"SymbolKeyword":return Wt(e,Yo);case"ObjectKeyword":return Wt(e,qt);case"Enums":return Wt(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>Ed(r.type)))return Wt(e,(r)=>{if(!gt(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=DC(e);return Wt(e,(r)=>gt(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>It(l.type,t)),r=e.rest.map((l)=>It(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=fx(e),c=mx(e);return(l,u)=>{if(!ym(l))return W(new _n(e,l));let p=u?.errors==="all",f=[],h=0,m=[],w=l.length;for(let P=w;P<=i-1;P++){let z=new ct(P,l,new Wa(o[P-w]));if(p){f.push([h++,z]);continue}else return W(new $e(e,l,z,m))}if(e.rest.length===0)for(let P=e.elements.length;P<=w-1;P++){let z=new ct(P,l,new hx(l[P],`is unexpected, expected: ${a}`));if(p){f.push([h++,z]);continue}else return W(new $e(e,l,z,m))}let S=0,y=void 0;for(;S<n.length;S++)if(w<S+1){if(e.elements[S].isOptional)continue}else{let P=n[S],z=P(l[S],u);if(Jt(z)){if(Ee(z)){let X=new ct(S,l,z.left);if(p){f.push([h++,X]);continue}else return W(new $e(e,l,X,qn(m)))}m.push([h++,z.right])}else{let X=h++,U=S;if(!y)y=[];y.push(({es:te,output:L})=>Ln(Ii(z),(se)=>{if(Ee(se)){let ce=new ct(U,l,se.left);if(p)return te.push([X,ce]),an;else return W(new $e(e,l,ce,qn(L)))}return L.push([X,se.right]),an}))}}if(we(r)){let[P,...z]=r;for(;S<w-z.length;S++){let X=P(l[S],u);if(Jt(X))if(Ee(X)){let U=new ct(S,l,X.left);if(p){f.push([h++,U]);continue}else return W(new $e(e,l,U,qn(m)))}else m.push([h++,X.right]);else{let U=h++,te=S;if(!y)y=[];y.push(({es:L,output:se})=>Ln(Ii(X),(ce)=>{if(Ee(ce)){let ee=new ct(te,l,ce.left);if(p)return L.push([U,ee]),an;else return W(new $e(e,l,ee,qn(se)))}else return se.push([U,ce.right]),an}))}}for(let X=0;X<z.length;X++){let U=S+X;if(w<U+1)continue;else{let te=z[X](l[U],u);if(Jt(te)){if(Ee(te)){let L=new ct(U,l,te.left);if(p){f.push([h++,L]);continue}else return W(new $e(e,l,L,qn(m)))}m.push([h++,te.right])}else{let L=h++;if(!y)y=[];y.push(({es:se,output:ce})=>Ln(Ii(te),(ee)=>{if(Ee(ee)){let Ae=new ct(U,l,ee.left);if(p)return se.push([L,Ae]),an;else return W(new $e(e,l,Ae,qn(ce)))}return ce.push([L,ee.right]),an}))}}}}let R=({es:P,output:z})=>co(P)?W(new $e(e,l,qn(P),qn(z))):Q(qn(z));if(y&&y.length>0){let P=y;return Lc(()=>{let z={es:sa(f),output:sa(m)};return Ln(Fc(P,(X)=>X(z),{concurrency:s,batching:c,discard:!0}),()=>R(z))})}return R({output:m,es:f})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Wt(e,G_);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([It(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[It(u.parameter,t),It(u.type,t),u.parameter]),a=Ut.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>Yo(u)?new wd(u):new Mi(u)))),s=It(a,t),c=fx(e),l=mx(e);return(u,p)=>{if(!Wf(u))return W(new _n(e,u));let f=p?.errors==="all",h=[],m=0,w=p?.onExcessProperty==="error",S=p?.onExcessProperty==="preserve",y={},R;if(w||S){R=Reflect.ownKeys(u);for(let U of R){let te=s(U,p);if(Jt(te)&&Ee(te))if(w){let L=new ct(U,u,new hx(u[U],`is unexpected, expected: ${String(a)}`));if(f){h.push([m++,L]);continue}else return W(new $e(e,u,L,y))}else y[U]=u[U]}}let P=void 0,z=p?.exact===!0;for(let U=0;U<n.length;U++){let te=n[U][1],L=te.name,se=Object.prototype.hasOwnProperty.call(u,L);if(!se){if(te.isOptional)continue;else if(z){let Ae=new ct(L,u,new Wa(te));if(f){h.push([m++,Ae]);continue}else return W(new $e(e,u,Ae,y))}}let ce=n[U][0],ee=ce(u[L],p);if(Jt(ee)){if(Ee(ee)){let Ae=new ct(L,u,se?ee.left:new Wa(te));if(f){h.push([m++,Ae]);continue}else return W(new $e(e,u,Ae,y))}y[L]=ee.right}else{let Ae=m++,vt=L;if(!P)P=[];P.push(({es:Ft,output:Lt})=>Ln(Ii(ee),(De)=>{if(Ee(De)){let je=new ct(vt,u,se?De.left:new Wa(te));if(f)return Ft.push([Ae,je]),an;else return W(new $e(e,u,je,Lt))}return Lt[vt]=De.right,an}))}}for(let U=0;U<i.length;U++){let te=i[U],L=te[0],se=te[1],ce=ky(u,te[2]);for(let ee of ce){let Ae=L(ee,p);if(Jt(Ae)&&Ot(Ae)){let vt=se(u[ee],p);if(Jt(vt)){if(Ee(vt)){let Ft=new ct(ee,u,vt.left);if(f){h.push([m++,Ft]);continue}else return W(new $e(e,u,Ft,y))}else if(!Object.prototype.hasOwnProperty.call(r,ee))y[ee]=vt.right}else{let Ft=m++,Lt=ee;if(!P)P=[];P.push(({es:De,output:je})=>Ln(Ii(vt),(Tt)=>{if(Ee(Tt)){let Et=new ct(Lt,u,Tt.left);if(f)return De.push([Ft,Et]),an;else return W(new $e(e,u,Et,je))}else{if(!Object.prototype.hasOwnProperty.call(r,ee))je[ee]=Tt.right;return an}}))}}}}let X=({es:U,output:te})=>{if(co(U))return W(new $e(e,u,qn(U),te));if(p?.propertyOrder==="original"){let L=R||Reflect.ownKeys(u);for(let ce of o)if(L.indexOf(ce)===-1)L.push(ce);let se={};for(let ce of L)if(Object.prototype.hasOwnProperty.call(te,ce))se[ce]=te[ce];return Q(se)}return Q(te)};if(P&&P.length>0){let U=P;return Lc(()=>{let te={es:sa(h),output:Object.assign({},y)};return Ln(Fc(U,(L)=>L(te),{concurrency:c,batching:l,discard:!0}),()=>X(te))})}return X({es:h,output:y})}}case"Union":{let n=YC(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],It(e.types[l],t));let s=fx(e)??1,c=mx(e);return(l,u)=>{let p=[],f=0,h=[];if(o>0)if(Es(l))for(let S=0;S<o;S++){let y=r[S],R=n.keys[y].buckets;if(Object.prototype.hasOwnProperty.call(l,y)){let P=String(l[y]);if(Object.prototype.hasOwnProperty.call(R,P))h=h.concat(R[P]);else{let{candidates:z,literals:X}=n.keys[y],U=Ut.make(X),te=z.length===i?new cr([new st(y,U,!1,!0)],[]):Ut.make(z);p.push([f++,new $e(te,l,new ct(y,l,new _n(U,l[y])))])}}else{let{candidates:P,literals:z}=n.keys[y],X=new st(y,Ut.make(z),!1,!0),U=P.length===i?new cr([X],[]):Ut.make(P);p.push([f++,new $e(U,l,new ct(y,l,new Wa(X)))])}}else{let S=n.candidates.length===i?e:Ut.make(n.candidates);p.push([f++,new _n(S,l)])}if(n.otherwise.length>0)h=h.concat(n.otherwise);let m=void 0;for(let S=0;S<h.length;S++){let y=h[S],R=a.get(y)(l,u);if(Jt(R)&&(!m||m.length===0))if(Ot(R))return R;else p.push([f++,R.left]);else{let P=f++;if(!m)m=[];m.push((z)=>Lc(()=>{if("finalResult"in z)return an;else return Ln(Ii(R),(X)=>{if(Ot(X))z.finalResult=X;else z.es.push([P,X.left]);return an})}))}}let w=(S)=>co(S)?S.length===1&&S[0][1]._tag==="Type"?W(S[0][1]):W(new $e(e,l,qn(S))):W(new _n(e,l));if(m&&m.length>0){let S=m;return Lc(()=>{let y={es:sa(p)};return Ln(Fc(S,(R)=>R(y),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in y)return y.finalResult;return w(y.es)})})}return w(p)}}case"Suspend":{let n=Dc(()=>It(e.f(),t));return(r,o)=>n()(r,o)}}},Wt=(e,t)=>(n)=>t(n)?Q(n):W(new _n(e,n)),Kc=(e,t)=>{switch(e._tag){case"Declaration":{let n=tx(e);if(Re(n))return Kc(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?Cd(o.type):at(o.type);if(bd(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?Cd(o.type):at(o.type);if(bd(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return Kc(e.from,t);case"Suspend":return Kc(e.f(),t);case"Transformation":return Kc(t?e.from:e.to,t)}return[]},YC=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=Kc(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}},ZC=(e)=>Vc(e)?ZC(e.from):e,zc=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(Jt(e))return e;let o=new Oc,i=qk(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(LO(a))return Q(a.value);let s=a.cause;if(kT(s))return W(s.error);return W(new gx(t,n,CT(s)))}return W(new gx(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},x2=([e],[t])=>e>t?1:e<t?-1:0,S2=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return Q;case"TypeLiteralTransformation":return(n)=>{let r=Q(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=Un(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?F(l[i]):A());if(delete l[i],Re(u))l[a]=u.value;return l})}return r}}},Ht=(e,t=[])=>({value:e,forest:t}),Wc,_2=(e)=>e.value+XC(`
34
- `,e.forest),XC=(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+=XC(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},b2=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},w2=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},QC=(e)=>("ast"in e)?F(e.ast):A(),yx,v2=(e)=>QC(e).pipe(Rn(sC),Je({onNone:()=>yx,onSome:(t)=>{let n=t(e);if(gt(n))return Q({message:n,override:!1});if(Fk(n))return hd(n,(r)=>({message:r,override:!1}));if(gt(n.message))return Q({message:n.message,override:n.override});return hd(n.message,(r)=>({message:r,override:n.override}))}})),Sx=(e)=>(t)=>t._tag===e,eA,$C,jC,Jc=(e)=>Jr(v2(e),(t)=>{if(t!==void 0)return!t.override&&(eA(e)||$C(e)&&e.kind==="From"||jC(e)&&e.kind!=="Transformation")?jC(e)||$C(e)?Jc(e.issue):yx:Q(t.message);return yx}),tA=(e)=>QC(e).pipe(Rn(pC),Tb((t)=>t(e)),Bt),O2=(e)=>Un(Jc(e),(t)=>t??tA(e)??E2(e)),Ad=(e)=>tA(e)??String(e.ast),R2=(e)=>e.message??"is forbidden",k2=(e)=>e.message??"is unexpected",C2=(e)=>{let t=cC(e.ast);if(Re(t)){let n=t.value();return gt(n)?Q(n):n}return Q(e.message??"is missing")},Ja=(e)=>{switch(e._tag){case"Type":return Un(O2(e),Ht);case"Forbidden":return Q(Ht(Ad(e),[Ht(R2(e))]));case"Unexpected":return Q(Ht(k2(e)));case"Missing":return Un(C2(e),Ht);case"Transformation":return Jr(Jc(e),(t)=>{if(t!==void 0)return Q(Ht(t));return Un(Ja(e.issue),(n)=>Ht(Ad(e),[Ht(b2(e.kind),[n])]))});case"Refinement":return Jr(Jc(e),(t)=>{if(t!==void 0)return Q(Ht(t));return Un(Ja(e.issue),(n)=>Ht(Ad(e),[Ht(w2(e.kind),[n])]))});case"Pointer":return Un(Ja(e.issue),(t)=>Ht(gd(e.path),[t]));case"Composite":return Jr(Jc(e),(t)=>{if(t!==void 0)return Q(Ht(t));let n=Ad(e);return Cy(e.issues)?Un(Fc(e.issues,Ja),(r)=>Ht(n,r)):Un(Ja(e.issues),(r)=>Ht(n,[r]))})}};var nA=x(()=>{Be();AT();_E();Hk();tn();DO();j();Ve();qc();Ge();ye();Qp();dx();HC=Symbol.for("effect/Schema/ParseErrorTypeId");VC=class VC extends SE("ParseError"){[HC]=HC;get message(){return this.toString()}toString(){return Wc.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[ne](){return this.toJSON()}};BC=Q,KC=W,Jt=lm,Jr=d(2,(e,t)=>Jt(e)?Ls(e,{onLeft:W,onRight:t}):Ln(e,t)),Un=d(2,(e,t)=>Jt(e)?yb(e,t):hd(e,t)),Md=d(2,(e,t)=>Jt(e)?ou(e,t):Dk(e,t)),zC=d(2,(e,t)=>Jt(e)?Ls(e,{onLeft:t,onRight:Q}):Lk(e,t)),h2=V(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),g2=V(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);Wc={formatIssue:(e)=>Un(Ja(e),_2),formatIssueSync:(e)=>{let t=Wc.formatIssue(e);return Jt(t)?Sb(t):Uk(t)},formatError:(e)=>Wc.formatIssue(e.issue),formatErrorSync:(e)=>Wc.formatIssueSync(e.issue)},yx=Q(void 0),eA=Sx("Composite"),$C=Sx("Refinement"),jC=Sx("Transformation")});var rA,oA;var iA=x(()=>{j();ye();rA=d((e)=>qt(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),oA=d((e)=>qt(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function _t(e){return class{[Gc]=aA;static ast=e;static annotations(n){return _t(lr(this.ast,n))}static pipe(){return T(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Gc]=aA}}function I2(e){return Od(e)?Ut.make(NC(e,(t)=>new Mi(t))):new Mi(e[0])}function mA(e,t=I2(e)){return class extends _t(t){static annotations(r){return mA(this.literals,lr(this.ast,r))}static literals=[...e]}}function v(...e){return we(e)?mA(e):wx}function bx(e,t){return class extends _t(t){static annotations(r){return bx(this.typeParameters,lr(this.ast,r))}static typeParameters=[...e]}}function gA(e,t=F2(e)){return class extends _t(t){static annotations(r){return gA(this.members,lr(this.ast,r))}static members=[...e]}}function xe(...e){return Od(e)?gA(e):we(e)?e[0]:wx}function Fd(e,t,n=D2(e,t)){return class extends _t(n){static annotations(o){return Fd(this.elements,this.rest,lr(this.ast,o))}static elements=[...e];static rest=[...t]}}function yA(...e){return Array.isArray(e[0])?Fd(e[0],e.slice(1)):Fd(e,[])}function xA(e,t){return class extends Fd([],[e],t){static annotations(r){return xA(this.value,lr(this.ast,r))}static value=e}}class _A{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<${_x(this.to.isOptional)}, ${this.to.type}, ${q2(this.from.fromKey)}, ${_x(this.from.isOptional)}, ${this.from.type}>`}}function Rx(e,t,n=H2(e,t)){return class extends _t(n){static annotations(o){return Rx(this.fields,this.records,lr(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=$2(e,{...o});return Px(i)?a:Nd(this)(a)};static pick(...o){return _(rA(e,...o))}static omit(...o){return _(oA(e,...o))}}}function _(e,...t){return Rx(e,t)}function TA(e,t,n){return class extends Rx({},[{key:e,value:t}],n){static annotations(o){return TA(e,t,lr(this.ast,o))}static key=e;static value=t}}function EA(e,t){return class extends _t(t){static annotations(r){return EA(this.from,lr(this.ast,r))}static make=(r,o)=>Px(o)?r:Nd(this)(r);static from=e}}function OA(e,t,n){return class extends _t(n){static annotations(o){return OA(this.from,this.filter,lr(this.ast,o))}static[j2]=e;static from=e;static filter=t;static make=(o,i)=>Px(i)?o:Nd(this)(o)}}function Ze(e,t){return(n)=>{function r(i,a,s){return V2(e(i,a,s),s,i)}let o=new jc(n.ast,r,Ni(t));return OA(n,r,o)}}function Px(e){return Go(e)?e:e?.disableValidation??!1}var Gc,aA,sA,Ni=(e)=>{if(!e)return{};let t={...e};for(let n in sA)if(n in e){let r=sA[n];t[r]=e[n],delete t[n]}return t},lr=(e,t)=>Bc(e,Ni(t)),fA=(e,t)=>{let n=GC(e,t);return(r,o)=>ou(n(r,o),xx)},cA=(e)=>C(e,Gc)&&qt(e[Gc]),M2=(e,t,n)=>bx(e,new Ba(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(_t)),(...r)=>t.encode(...r.map(_t)),Ni(n))),N2=(e,t)=>{let n=()=>(o,i,a)=>e(o)?BC(o):KC(new _n(a,o));return bx([],new Ba([],n,n,Ni(t)))},H=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return M2(n,r,o)}let e=arguments[0],t=arguments[1];return N2(e,t)},hA,lt,wx,vx,k,Gt,J,F2=(e)=>Ut.make(e.map((t)=>t.ast)),L2=(e)=>xe(e,hA),D2=(e,t)=>new $c(e.map((n)=>cA(n)?new Fo(n.ast,!1):n.ast),t.map((n)=>cA(n)?new Ka(n.ast):n.ast),!0),q=(e)=>xA(e),_x=(e)=>e?'"?:"':'":"',Tx,SA,q2=(e)=>{if(e===void 0)return"never";if(gt(e))return JSON.stringify(e);return String(e)},bA=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new Tx(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new _A(e.from,new SA(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},wA,vA=(e)=>C(e,wA),Ex,Ox,b=(e)=>{let t=e.ast===vd||e.ast===Td?vd:L2(e).ast;return new Ox(new Tx(t,!0,!0,{},void 0),e)},U2,H2=(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(vA(u)){let p=u.ast;switch(p._tag){case"PropertySignatureDeclaration":{let{type:f,isOptional:h,annotations:m}=p;i.push(new st(l,f,h,!0,U2(p))),a.push(new st(l,at(f),h,!0,m)),r.push(new st(l,f,h,!0,m));break}case"PropertySignatureTransformation":{let f=p.from.fromKey??l;i.push(new st(f,p.from.type,p.from.isOptional,!0,p.from.annotations)),a.push(new st(l,p.to.type,p.to.isOptional,!0,p.to.annotations)),s.push(new sx(f,l,p.decode,p.encode));break}}}else i.push(new st(l,u.ast,!1,!0)),a.push(new st(l,at(u.ast),!1,!0)),r.push(new st(l,u.ast,!1,!0))}if(we(s)){let c=[],l=[];for(let u of t){let{indexSignatures:p,propertySignatures:f}=lx(u.key.ast,u.value.ast);f.forEach((h)=>{i.push(h),a.push(new st(h.name,at(h.type),h.isOptional,h.isReadonly,h.annotations))}),p.forEach((h)=>{c.push(h),l.push(new za(h.parameter,at(h.type),h.isReadonly))})}return new ax(new cr(i,c,{[_d]:"Struct (Encoded side)"}),new cr(a,l,{[_d]:"Struct (Type side)"}),new cx(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=lx(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new cr(r,o)},$2=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&vA(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},Ld=(e)=>TA(e.key,e.value),Yc=(e,t)=>(n)=>{let r=Je(Zy(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=Bc(n.ast,Ni({[Ly]:r,...t}));return EA(n,o)},j2,lA=(e,t,n)=>{if(Go(e))return e?A():F(new _n(t,n));if(gt(e))return F(new _n(t,n,e));if(e!==void 0){if("_tag"in e)return F(e);let r=new _n(t,n,e.message);return F(we(e.path)?new ct(e.path,n,r):r)}return A()},V2=(e,t,n)=>{if(jk(e))return lA(e,t,n);if(we(e)){let r=cu(e,(o)=>lA(o,t,n));if(we(r))return F(r.length===1?r[0]:new $e(t,n,r))}return A()},B2,kx=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length<=e,{schemaId:B2,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),K2,Ga=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length>=e,{schemaId:K2,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),uA,le=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ze((o)=>(e.lastIndex=0,e.test(o)),{schemaId:uA,[uA]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},z2,pA,W2,J2,Cx=(e,t)=>(n)=>n.pipe(Ze((r)=>r>e,{schemaId:J2,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),G2,RA=(e,t)=>(n)=>n.pipe(Ze((r)=>r>=e,{schemaId:G2,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),Y2,Dd=(e)=>(t)=>t.pipe(Ze((n)=>Number.isSafeInteger(n),{schemaId:Y2,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),Ax=(e)=>Cx(0,{title:"positive",...e}),qd,Z2,Zc=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(Vk(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ze((o)=>o.length>=r,{schemaId:Z2,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[Yy]:!0,...t}))},dA,X2;var bt=x(()=>{Be();tn();vs();My();nC();qc();Ge();nA();be();ye();dx();iA();Gc=Symbol.for("effect/Schema");aA={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},sA={typeConstructor:oC,schemaId:iC,message:Dy,missingMessage:xd,identifier:Sd,title:zt,description:Wr,examples:qy,default:Uy,documentation:aC,jsonSchema:Hy,arbitrary:$y,pretty:jy,equivalence:Vy,concurrency:By,batching:Ky,parseIssueTitle:zy,parseOptions:Wy,decodingFallback:Jy};hA=class hA extends _t(vd){};lt=class lt extends _t(mC){};wx=class wx extends _t(Td){};vx=class vx extends _t(ox){};k=class k extends _t(wC){};Gt=class Gt extends _t(TC){};J=class J extends _t(OC){};Tx=class Tx extends Fo{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=_x(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};SA=class SA extends Fo{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};wA=Symbol.for("effect/PropertySignature");Ex=class Ex{ast;[Gc];[wA]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return T(this,arguments)}annotations(e){return new Ex(bA(this.ast,Ni(e)))}toString(){return String(this.ast)}};Ox=class Ox extends Ex{from;constructor(e,t){super(e);this.from=t}annotations(e){return new Ox(bA(this.ast,Ni(e)),this.from)}};U2=ux([xd]);j2=Symbol.for("effect/SchemaId/Refine");B2=eC,K2=Qk,uA=Symbol.for("effect/SchemaId/Pattern"),z2=Symbol.for("effect/SchemaId/UUID"),pA=/^[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;W2=class W2 extends k.pipe(le(pA,{schemaId:z2,identifier:"UUID",jsonSchema:{format:"uuid",pattern:pA.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};J2=Yk,G2=Zk,Y2=Xk;qd=class qd extends Gt.pipe(Dd({identifier:"Int"})){};Z2=tC,dA=Gk;X2=class X2 extends H(Jl,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:dA,[dA]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>K_}){}});function bn(e,t){return fA(e,Q2)(t)}var Q2;var Ya=x(()=>{bt();Q2={onExcessProperty:"error"}});function Mx(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(!AA(r)||!CA(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function Hn(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);return AA(n)&&CA(r)?`${n}@openai-curated`:void 0}function CA(e){return kA.includes(e)}function AA(e){return Ud.includes(e)}function Nx(e,t){let n=t??ur;return{computer_use:e?.computer_use??n.computer_use,work:e?.work??n.work,frontend:e?.frontend??n.frontend,security:e?.security??n.security}}function Qc(e,t=[]){let n=[],r=new Set;for(let o of PA){if(!e[o])continue;for(let i of Xc[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 Ix,eU,tU,nU,kA,Ud,Gr,rU,Xc,PA,ur;var Fx=x(()=>{bt();Ix=v("computer_use","work","frontend","security"),eU=v("computer_use","work","frontend","security"),tU=v("installed","disabled","missing","uncertain"),nU=v("healthy","missing","disabled","uncertain"),kA=Object.freeze(["openai-curated","openai-curated-remote"]),Ud=Object.freeze(["build-web-apps","codex-security"]);Gr=Object.freeze({coding:!0,computer_use:!1,work:!1,frontend:!0,security:!0}),rU={work:{name:"work",pluginIds:["documents@openai-primary-runtime","pdf@openai-primary-runtime","presentations@openai-primary-runtime","spreadsheets@openai-primary-runtime","template-creator@openai-primary-runtime"],defaultSelected:Gr.work,migrationKey:"work",semanticSkillIds:["documents:documents","pdf:pdf","presentations:Presentations","spreadsheets:Spreadsheets","template-creator:template-creator"],ownership:"shared-preserve"},frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Gr.frontend,migrationKey:"frontend",semanticSkillIds:["build-web-apps:frontend-app-builder","build-web-apps:frontend-testing-debugging","build-web-apps:react-best-practices"],ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Gr.security,migrationKey:"security",semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Gr.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],ownership:"shared-preserve"}},Xc=Object.freeze(rU),PA=Object.freeze(["computer_use","work","frontend","security"]),ur=Object.freeze({computer_use:Gr.computer_use,work:Gr.work,frontend:Gr.frontend,security:Gr.security})});function pr(e){return _({identifier:v(e),label:k,requiresRootApproval:J})}function IA(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 MA(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var NA,oU,iU,Lx,aU,FA,sU,cU,lU;var LA=x(()=>{bt();NA=v("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"),oU=_({identifier:NA,label:k,requiresRootApproval:J});iU=_({localRepositoryEdit:pr("local.repository.edit"),localRepositoryCheck:pr("local.repository.check"),localRepositoryLint:pr("local.repository.lint"),localRepositoryFormat:pr("local.repository.format"),localRepositoryCommit:pr("local.repository.commit"),externalRead:pr("external.read"),specialistDispatch:pr("specialist.dispatch"),versionControlServerMutation:pr("vcs.server.mutation"),versionControlServerCiTrigger:pr("vcs.server.ci-trigger"),unknownEffect:pr("unknown.effect")}),Lx={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}};Yn(Lx);aU=v("never","root"),FA=Object.values(Lx);sU=FA.filter((e)=>!e.requiresRootApproval),cU=FA.filter((e)=>e.requiresRootApproval),lU=Object.freeze({noRootApproval:`${MA(IA(sU))} actions do not require Root approval.`,rootApproval:`${MA(IA(cU))} require Root approval.`})});function Hd(e){let t=bn(uU,e);if(Ee(t))return Jo(ys("sha256 digest",t.left));return Zi(t.right)}var $n,Dx,Y6,Z6,X6,uU,pU,dU,fU,mU;var $d=x(()=>{tn();bt();Xi();Ya();$n=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Dx=k.pipe(le(/^[0-9a-f]{64}$/u)),Y6=$n.pipe(Yc("RunId")),Z6=$n.pipe(Yc("ProjectId")),X6=$n.pipe(Yc("TrustId")),uU=Dx.pipe(Yc("Sha256Digest"));pU=_({run_id:$n,objective_lineage:$n,parent_run_id:b(xe($n,lt))}),dU=_({project_id:$n,trust_id:$n,trust_digest:Dx}),fU=_({project_id:$n,project_digest:Dx}),mU=k.pipe(le(/^state-[0-9]+\.[0-9]+$/u))});function qx(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 HA(e){return typeof e==="string"&&gU.has(e)}function xU(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!HA(t)||typeof n!=="string")return!1;return el.get(t)?.tasks.some((r)=>r.name===n)===!0}function Vd(e,t){return typeof t==="string"&&el.get(e)?.tasks.some((n)=>n.name===t)===!0}function $A(e){return typeof e==="string"&&yU.has(e)}function jx(e){let t=`${e.role}.${e.task}`;if(!Hx.has(t))throw Error("Unknown native specialist agent type.");return t}function Vx(e){let t=el.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.instruction}function Bx(e){let t=el.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function VA(e){let t=el.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function Kx(e){let t=VA(e.role),n=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":t.permissions.network?"current_sources":"disabled";return Object.freeze({network:n!=="disabled",write:t.permissions.write,networkScope:n})}var Lo,DA,jd,Fi,hU,qA="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.",jn,el,gU,Ux,yU,UA,Hx,$x,SU,_U,bU,wU,tl,Li,jA,Za,vU,BA,TU,Do;var nl=x(()=>{bt();Lo=v("low","default","high"),DA=v("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),jd=xe(Lo,DA);Fi=v("standard","fast","fast-all"),hU=v("low","medium","high","xhigh","max"),jn=[{role:"Explorer",tasks:[{name:"lookup",description:"Repository fact lookup specialist.",instruction:"Locate the exact requested repository fact."},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:"Trace the complete in-scope execution or reference path."}],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,write:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:"Locate the exact requested authoritative external fact."},{name:"research",description:"Current authoritative-source research specialist.",instruction:"Synthesize the assigned current sources with citations."}],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:!0,write:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply only deterministic, already-decided edits."},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Implement and verify the bounded behavior seam."},{name:"integration",description:"Decided seam integration specialist.",instruction:"Integrate the decided seams and verify them together."},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:"Observe the assigned post-VCS external gate."},{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."}],capability:"bounded-write",authority:"Change only the delegated Assignment seam; 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,write:!0}},{role:"Reviewer",tasks:[{name:"plan",description:"Adversarial implementation-plan review specialist.",instruction:"Review the complete plan to a fixed point."},{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point."},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Review and repair the produced artifact to a fixed point."}],capability:"bounded-review",authority:"Inspect and repair only reviewer-owned defects within the delegated Assignment; 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,write:!0}}];Yn(jn);el=new Map(jn.map((e)=>[e.role,e])),gU=new Set(jn.map((e)=>e.role)),Ux=jn.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),yU=new Set(Ux),UA=Ux.map((e)=>e.replace(":",".")),Hx=new Set(UA);$x=H(HA),SU=H((e)=>Vd("Explorer",e)),_U=H((e)=>Vd("Librarian",e)),bU=H((e)=>Vd("Worker",e)),wU=H((e)=>Vd("Reviewer",e)),tl=H(xU),Li=Object.freeze(Ux.filter((e)=>$A(e))),jA=H($A),Za=Object.freeze(UA.filter((e)=>Hx.has(e))),vU=H((e)=>typeof e==="string"&&Hx.has(e));BA=_({profile:Lo,service_tier:b(Fi)}),TU=v("git_vcs","computer_use"),Do=Object.freeze({requiresDelegation:!0,trivialWorkRequiresDelegation:!0,directExecutionExceptions:Object.freeze(["git_vcs","computer_use"]),requestUserInputGates:Object.freeze(["plan_approval","installation_profile_approval","remote_origin_server_vcs_mutation","public_publication_or_release","ambiguity_or_missing_material_input"]),surgicalMutationRule:qA,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Nt(e,t){return new We("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function zx(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw Nt(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw Nt(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw Nt(t,"invalid number");return r}case"undefined":throw Nt(t,"undefined is not JSON");case"bigint":throw Nt(t,"bigint is not JSON");case"function":throw Nt(t,"function is not JSON");case"symbol":throw Nt(t,"symbol is not JSON");case"object":break}if(n.has(e))throw Nt(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw Nt(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 Nt(`${t}[${s}]`,"sparse or accessor array item");a.push(zx(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 Nt(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw Nt(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Nt(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw Nt(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 Nt(`${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 Nt(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${zx(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function dr(e){return zx(e,"$",new Set)}function Yr(e){return new TextEncoder().encode(dr(e))}function KA(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 OU(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function Zr(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",RU(KA(e,t)));return OU(new Uint8Array(r))}function RU(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var Wx=x(()=>{Xi();$d()});function JA(e){try{return dr(e)!==void 0}catch{return!1}}function Kd(e){let t=bn(tP,e);if(Ee(t))return Jo(ys("CLI envelope",t.left));return Zi(t.right)}var zA,WA,GA,kU,CU,Jx="holycodex-specialist-outcome-2",Yt,rl,AU,PU,IU,MU,NU,FU,Bd,LU,DU,qU,UU,HU,YA,ZA,XA,$U,QA,eP,tP;var nP=x(()=>{tn();bt();Wx();Fx();Xi();$d();nl();Ya();zA=v("blocked","completed","failed","partial"),WA=xe(v("high","max","xhigh"),lt);GA=H((e)=>JA(e)),kU=H((e)=>Vf(e)&&!Array.isArray(e)&&JA(e)),CU=_({blocked:J,changed_files:q(k),confidence:Gt,context_owner:xe(k,lt),material_findings:q(k),needs_more_context:J,needs_root_decision:J,needs_verification:J,relevant_files:q(k),remaining_risk:q(k),reuse_recommended:J,status:zA,suggested_followup:xe(k,lt),suggested_luna_effort:WA,suggested_specialist:xe($x,lt),verification:q(k),verification_passed:J}),Yt=k.pipe(Ga(1)),rl={protocol_version:v(Jx),route:tl,evidence:q(Yt)},AU=_(rl),PU=_({...rl,status:v("completed"),summary:Yt}),IU=_({...rl,status:v("blocked"),reason:Yt,needs_root_decision:J}),MU=_({...rl,status:v("partial"),summary:Yt,completed:q(Yt),remaining:q(Yt),needs_root_decision:J}),NU=_({...rl,status:v("failed"),error:Yt}),FU=xe(PU,IU,MU,NU),Bd={protocol_version:v(Jx),capability:Ix,route:xe(tl,lt),evidence:q(Yt),data:GA},LU=_({...Bd,status:v("completed"),summary:Yt}),DU=_({...Bd,status:v("blocked"),reason:Yt,needs_root_decision:J}),qU=_({...Bd,status:v("partial"),summary:Yt,completed:q(Yt),remaining:q(Yt),needs_root_decision:J}),UU=_({...Bd,status:v("failed"),error:Yt}),HU=xe(LU,DU,qU,UU),YA=q(k),ZA=k.pipe(le(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),XA=v(vr),$U=_({code:$n,message:k,details:kU}),QA=_({schema_version:XA,ok:v(!0),command:ZA,data:GA,warnings:YA}),eP=_({schema_version:XA,ok:v(!1),command:ZA,error:$U,warnings:YA}),tP=xe(QA,eP)});function jU(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:oP,effort:n}}function KU(e){let t=BU.get(e);if(t===void 0)throw new We("catalog_invalid","A profile has no route effort policy.",{profile:e});return jn.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 jU(n.role,r.name,i)}))}function Gx(e){return{name:e.name,root:{model:"gpt-6-astra",effort:e.effort},specialistModel:"gpt-5.6-luna",defaultServiceTier:"standard",routes:KU(e.name)}}function zU(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!==Li.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)||!VU.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!==Li.length)throw new We("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<Li.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||rP[i.effort]<r)throw new We("catalog_invalid","Profile route effort is not monotonic.",{route:Li[n]??"unknown"});r=rP[i.effort]}}}function fr(e){let t=bn(Lo,e);if(Ee(t))return Jo(new We("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=aP.get(t.right);if(!n)return Jo(new We("invalid_profile","Unknown profile selection.",{profile:t.right}));return Zi(n)}var oP="gpt-5.6-luna",VU,rP,Yx,BU,Zx,iP,aP,WU;var sP=x(()=>{tn();Xi();nl();Ya();VU=new Set(Li),rP={low:0,medium:1,high:2,xhigh:3,max:4},Yx=[{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","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","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","Reviewer:plan":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];Yn(Yx);BU=new Map(Yx.map((e)=>[e.profile,e]));Zx=[Gx({name:"low",effort:"low"}),Gx({name:"default",effort:"medium"}),Gx({name:"high",effort:"high"})];zU(Zx);Yn(Zx);iP=Zx,aP=new Map,WU=new Map;for(let e of iP){aP.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);WU.set(e.name,t)}});import{execFile as JU}from"child_process";import{promisify as GU}from"util";var lP="holycodex-intent-1",uP="holycodex-plan-1",pP="holycodex-assignment-1",zd="toon-4",Z,qo,Xx,dP,ol,Vn,Xe,wY,Qx,Di,eS,tS,YU,cP,ZU,XU,nS,fP,mP,QU,vY,eH,tH,nH,rH,oH,iH,aH,TY;var hP=x(()=>{bt();nl();Ya();Z=k.pipe(Ze((e)=>e.trim().length>0)),qo=k.pipe(le(/^[a-z0-9][a-z0-9-]{0,95}$/u)),Xx=k.pipe(le(/^[a-f0-9]{64}$/u)),dP=k.pipe(le(/^[a-f0-9]{40}$/u)),ol=qd.pipe(RA(1)),Vn=k.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),Xe=q(Z),wY=_({pid:qd.pipe(Cx(0)),token:Z}),Qx=_({role:v("Explorer","Librarian","Worker","Reviewer"),task:Z}).pipe(Ze((e)=>jn.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),Di=_({kind:v("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:Z,result:b(v("passed","failed","observed","unknown"))}),eS=_({root:Z,git_common_dir:Z,initial_head:Z,expected_head:Z,expected_changes:Xe,expected_status_digest:Xx,integrated_commit:b(dP),updated_at:Vn}),tS=v("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),YU=v("scoping","ready","executing","verifying","reviewing"),cP=_({required:J,status:v("not_required","missing","passed","failed","accepted","rejected"),evidence:q(Di)}),ZU=_({schema_version:v(lP),toon_compatibility:v(zd),id:qo,slug:qo,title:Z,goal:Z,acceptance_criteria:Xe,state:tS,revision:ol,plan_required:J,active_plan_revision:b(ol),active_plan_digest:b(Xx),blockers:Xe,resume_state:b(YU),verification:cP,review:cP,acceptance_met:J,root_readiness:J,evidence:q(Di),baseline:eS,created_at:Vn,updated_at:Vn}),XU=_({schema_version:v(uP),toon_compatibility:v(zd),intent_id:qo,revision:ol,predecessor_digest:b(Xx),approach:Z,scope:Xe,exclusions:Xe,assignments:Xe,dependencies:Xe,architecture:Xe,risks:Xe,assumptions:Xe,open_questions:Xe,verification:Xe,recovery:Xe,updated_at:Vn}),nS=v("completed","blocked","needs_root_input","failed"),fP=v("pending","executing","completed","blocked","needs_root_input","failed"),mP=_({id:qo,outcome:nS,started_at:Vn,finished_at:Vn,summary:Z,evidence:q(Di),blocker:b(Z),remaining_risk:Xe}),QU=_({schema_version:v(pP),toon_compatibility:v(zd),intent_id:qo,id:qo,objective:Z,owner:Qx,scope:Xe,constraints:Xe,exclusions:Xe,dependencies:Xe,acceptance_criteria:Xe,status:fP,revision:ol,invocations:q(mP),active_invocation_id:b(Z),active_started_at:b(Vn),evidence:q(Di),blocker:b(Z),remaining_risk:Xe,created_at:Vn,updated_at:Vn}),vY=_({schema_version:v("holycodex-intent-0"),id:qo,slug:qo,title:Z,goal:Z,acceptance_criteria:Xe,state:tS,revision:ol,baseline:eS,created_at:Vn,updated_at:Vn}),eH=_({title:Z,goal:Z,acceptanceCriteria:q(Z).pipe(Zc(1)),planRequired:b(J),verificationRequired:b(J),reviewRequired:b(J)}),tH=_({approach:Z,scope:b(q(Z)),exclusions:b(q(Z)),assignments:b(q(Z)),dependencies:b(q(Z)),architecture:b(q(Z)),risks:b(q(Z)),assumptions:b(q(Z)),openQuestions:b(q(Z)),verification:b(q(Z)),recovery:b(q(Z))}),nH=_({id:b(Z),objective:Z,owner:Qx,scope:q(Z).pipe(Zc(1)),constraints:b(q(Z)),exclusions:b(q(Z)),dependencies:b(q(Z)),acceptanceCriteria:q(Z).pipe(Zc(1))}),rH=_({scope:q(Z).pipe(Zc(1))}),oH=_({commit:dP}),iH=_({invocationId:b(Z),outcome:nS,startedAt:b(Z),summary:Z,evidence:b(q(Di)),blocker:b(Z),remainingRisk:b(q(Z))}),aH=_({evidence:b(q(Di)),verification:b(v("passed","failed")),review:b(v("accepted","rejected")),acceptanceMet:b(J),rootReadiness:b(J),clearBlockers:b(J)}),TY=GU(JU)});var ut=x(()=>{B_();Xi();Ya();Fx();LA();$d();nl();nP();sP();Wx();hP()});function re(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Fe(e){try{return dr(e),!0}catch{return!1}}function SH(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 xP(e){return{ok:!1,error:e}}function SP(e){return{ok:!0,value:e}}function sn(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 qi(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return sn(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>qi(n,t+1));if(re(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=sn(r,96);if(i.length>0)n[i]=qi(o,t+1)}return n}return"[redacted]"}function _P(e){let t=qi(e);return re(t)?t:{value:t}}function Le(e,t,n){return new K("invalid_external_data",`Invalid ${e}.`,{field:e,received:qi(t)},n===void 0?void 0:{cause:n})}function Pe(e,t,n){let r=bn(e,t);if(Ee(r))throw Le(n,t,String(r.left));return r.right}function bP(e,t){try{return Pe(e,t,"value"),!0}catch{return!1}}var iS,cl=1048576,aS=65536,cn,Uo,_5,Xr,xH,K;var mr=x(()=>{ut();tn();bt();iS=vr;cn=H((e)=>Fe(e)),Uo=H((e)=>re(e)&&Fe(e)),_5=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Xr=k.pipe(Ze((e)=>e.length>0&&e.length<=4096)),xH=Gt.pipe(Ze((e)=>Number.isFinite(e)&&e>=0));K=class K 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=SH(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var sS,ll,ul,cS,lS,uS,pS="turn/completed";var Yd=x(()=>{sS=["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"],ll=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],ul=["item/permissions/requestApproval"],cS=["mcpServer/elicitation/request"],lS=["item/tool/call"],uS={method:"initialized"}});function Xa(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)=>Xa(n,t));return re(e)&&Object.values(e).every((n)=>Xa(n,t))}finally{t.delete(e)}}function hr(e){return re(e)&&Xa(e)}function dS(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('"')?bH(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Za.includes(c))throw Le("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 Le("TOML key path",e);if(t.some((i)=>i==="__proto__"||i==="constructor"||i==="prototype"))throw Le("TOML key path",e);return t}function bH(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Le("TOML quoted key",e)}function Te(e,t){if(!hr(e))throw Le("TOML document",e);let n=e;for(let r of dS(t)){if(!hr(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function Zd(e){if(Array.isArray(e))return e.map(Zd);if(re(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Zd(n)]));return e}function Xd(e){return Zd(e)}function dl(e,t,n){if(!hr(e)||!Xa(n))throw Le("TOML write",{keyPath:t});let r=dS(t),o={...Xd(e)},i=o;for(let a of r.slice(0,-1)){let s=i[a];if(s!==void 0&&!hr(s))throw Le("TOML table path",t);let c=s===void 0?{}:{...s};i[a]=c,i=c}return i[r.at(-1)]=Zd(n),o}function fl(e,t){if(!hr(e))throw Le("TOML document",e);let n=dS(t),r={...Xd(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!hr(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(hr(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function ml(e){if(typeof e!=="string")return!1;if(vP.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Za.some((t)=>e===`agents."${t}".config_file`)}function Qd(e){return ml(e)}function Ho(e){return typeof e==="string"&&vH.test(e)}function fS(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 TH(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function mS(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function hS(e){if(!re(e)||!mS(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return fS(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&nf(e.value);case"digest":return TH(e.value);default:return!1}}function wP(e,t){switch(yS(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 RP(e){return re(e)&&e.kind==="absent"?Object.keys(e).length===1:hS(e)}function kP(e){return re(e)&&mS(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Ho(e.schema)&&Ho(e.installId)&&Qd(e.keyPath)&&RP(e.originalValue)&&hS(e.lastManagedValue)&&wP(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||wP(e.keyPath,e.originalValue))}function Qa(e){if(!re(e)||!mS(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Ho(e.schema)||!Ho(e.installId)||!re(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>Qd(t)&&kP(n)&&n.keyPath===t)}function tf(e){if(!Ho(e.schema)||!Ho(e.installId))throw Le("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 gS(e){if(!nf(e))throw Le("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function hl(e,t){let n=gS(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 yS(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_v2"||e==="features.context_management"||e==="features.context_management.experimental_mode")return"boolean";return"enum"}function EH(e,t){let n=yS(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"&&fS(t)}async function gr(e,t){if(!Qd(e)||!Xa(t))throw Le("managed config value",{keyPath:e});let n=yS(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:gS(t)};if(n==="enum"&&typeof t==="string"&&fS(t))return{kind:n,value:t};return{kind:"digest",value:await Zr("holycodex-managed-config-value",[Yr({keyPath:e,value:t})])}}function OH(e){if(e.kind==="enum"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function gl(e,t,n,r){if(!hr(e)||!Qa(t)||!Ho(r.schema)||!Ho(r.installId))throw Le("managed runtime config",{});let o={...t.managed},i=Xd(e),a=[];for(let[c,l]of Object.entries(n)){if(!ml(c)||typeof l!=="string"&&typeof l!=="boolean")throw Le("managed config key",c);let u=c,p=t.managed[u],f=Te(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 gr(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 gr(u,f));if(!EH(u,l))throw Le("managed config value",{keyPath:u});i=dl(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:h,lastManagedValue:await gr(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!Qa(s))throw Le("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Ui(e,t,n){if(!hr(e)||!Qa(t))throw Le("managed runtime config",{});let r=Xd(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!Qd(c))throw Le("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=Te(r,u);if(!(p!==void 0&&JSON.stringify(await gr(u,p))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=fl(r,u),i.push(u),delete o[u];else{let h=OH(l.originalValue);if(h===void 0){s.push(u),a.push(u);continue}r=dl(r,u,h),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function es(e,t,n){if(!ml(n)||!Qa(t))throw Le("managed config key",n);let r=t.managed[n],o=Te(e,n),i=o===void 0?void 0:await gr(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 _H,pl,vP,wH,TP,EP,OP,ef,vH;var rf=x(()=>{ut();ut();bt();mr();_H=H((e)=>Xa(e)),pl=H((e)=>hr(e));vP=["model","model_reasoning_effort","service_tier","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.default_mode_request_user_input","features.multi_agent_v2","features.context_management","features.context_management.experimental_mode"],wH=H((e)=>ml(e));TP=H((e)=>hS(e)),EP=H((e)=>RP(e)),OP=H((e)=>kP(e)),ef=H((e)=>Qa(e)),vH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function kH(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function CP(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)=>kH(e[i]))}function IP(e){if(!re(e)||!Fe(e))return!1;return CP(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||CP(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function of(e){return re(e)&&Fe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function MP(e){return re(e)&&Fe(e)&&of(e.thread)}function PH(e){return re(e)&&Fe(e)&&typeof e.id==="string"}function $o(e){return re(e)&&Fe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function NP(e){return re(e)&&Fe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||IP(e.usage))}function IH(e){return re(e)&&Fe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>re(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>re(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 FP(e){if(ul.some((t)=>t===e))return"permissions";if(ll.some((t)=>t===e))return"approval";if(cS.some((t)=>t===e))return"elicitation";if(lS.some((t)=>t===e))return"dynamic_tool";return"other"}var AP,yl,PP,xl,RH,xS,Sl,CH,af,SS,_S,AH,_l,bS,wS,vS,TS,ES,OS,RS,kS,CS,AS,PS,IS,MS,NS,FS,LS,DS,qS,US,HS,$S,jS,VS,BS,KS,zS,WS,JS,A5,MH,P5;var GS=x(()=>{bt();mr();Yd();rf();AP=k.pipe(le(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),yl=xe(k.pipe(Ga(1)),Gt.pipe(Ze((e)=>Number.isSafeInteger(e)))),PP=_({code:Gt.pipe(Ze((e)=>Number.isSafeInteger(e))),message:k,data:b(cn)}),xl=xe(_({id:yl,result:cn}),_({id:yl,error:PP})),RH=_({id:yl,error:PP}),xS=_({method:AP,params:b(cn)}),Sl=_({id:yl,method:AP,params:b(cn),trace:b(cn)});CH=H(IP),af=_({clientInfo:_({name:Xr,version:Xr,title:xe(Xr,lt)}),capabilities:xe(_({experimentalApi:J,requestAttestation:J,mcpServerOpenaiFormElicitation:b(J),optOutNotificationMethods:b(xe(q(k),lt)),extensions:b(Uo)}),lt)}),SS=H((e)=>re(e)&&Fe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),_S=_({method:v("initialized")});AH=H(of);_l=H((e)=>MP(e)||PH(e)),bS=_l,wS=_l,vS=H($o),TS=H((e)=>re(e)&&Fe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),ES=H((e)=>MP(e)),OS=H((e)=>{if(!re(e)||!Fe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>of(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>of(r));return t&&e.threads===void 0||n&&e.data===void 0}),RS=H((e)=>re(e)&&Fe(e));kS=H($o),CS=H($o),AS=H($o),PS=H((e)=>re(e)&&Fe(e));IS=H((e)=>$o(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Fe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),MS=H((e)=>$o(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Fe(t))),NS=H((e)=>re(e)&&Fe(e)&&(e.turn!==void 0&&NP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),FS=H((e)=>re(e)&&Fe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),LS=H((e)=>$o(e)&&typeof e.turnId==="string"&&e.turnId.length>0),DS=H((e)=>re(e)&&Fe(e)),qS=H((e)=>$o(e)&&(e.turn!==void 0&&NP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),US=H((e)=>re(e)&&Fe(e));HS=H((e)=>re(e)&&Fe(e)&&Array.isArray(e.data)&&e.data.every((t)=>IH(t))),$S=Uo,jS=Uo,VS=_({includeLayers:b(J),cwd:b(xe(k,lt))}),BS=_({config:pl,origins:Uo,layers:xe(q(Uo),lt)}),KS=Uo,zS=Uo,WS=H((e)=>re(e)&&Fe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&re(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),JS=cn,A5=H((e)=>re(e)&&Fe(e)&&typeof e.kind==="string"&&typeof e.method==="string");MH=xe(v("stable","experimental","disabled"),J),P5=Ld({key:k,value:MH})});class sf{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??cl,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new K("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new K("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=NH){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new K("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Pe(af,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",RS,e,_l)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",kS,t,bS)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",CS,t,ES)}async listThreads(e={}){return this.action("thread/list",PS,e,OS)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",AS,t,wS)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",vS,t,TS)}async startTurn(e){return this.action("turn/start",IS,e,NS)}async steerTurn(e){return this.action("turn/steer",MS,e,FS)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",LS,n,DS)}async listModels(e={}){return this.action("model/list",US,e,HS)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",$S,e,jS)}async readConfig(e={}){return this.action("config/read",VS,e,BS)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",KS,e,zS)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Pe(af,t,"initialize parameters"));return Pe(cn,r,"initialize result")}let n=Pe(Sl,{id:1,method:e,params:t},"App Server method");if(!FH.has(n.method))throw new K("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 K("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Pe(cn,e,"initialize parameters")),n=Pe(SS,t,"initialize result"),r=Pe(_S,uS,"initialized notification");return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(t){let n=t instanceof K?t:new K("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(n),n}}async action(e,t,n,r){let o=Pe(t,n,`${e} parameters`),i=Pe(cn,o,`${e} parameters`),a=await this.request(e,i);return Pe(r,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new K("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=Pe(Sl,{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 K("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let p=()=>l(new K("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 K?p:new K("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 K("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new K("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof K?e:new K("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 K("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let n=this.tryDecode(xl,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(Sl,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(xS,t);if(o!==void 0){this.handleNotification(o);return}throw Le("JSON-RPC message",t)}tryDecode(e,t){try{return Pe(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new K("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=DH(t.method);t.reject(new K(r,`The App Server rejected ${t.method}: ${sn(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:qi(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Pe(WS,{...e,params:t,category:FP(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,sn(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,sn(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Pe(JS,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,sn(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=Pe(xl,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Pe(xl,{id:e,error:{code:t,message:LH(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===pS){let n=Pe(qS,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:_P({params:qi(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 K("closed","The App Server client is closed.")}}function LH(e){let t=sn(e);return t.length>0?t:"server request failed"}function DH(e){if(ul.some((t)=>t===e))return"permission_denied";if(ll.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var NH,FH;var YS=x(()=>{mr();Yd();GS();NH={clientInfo:{name:"holycodex",title:null,version:iS},capabilities:null},FH=new Set(sS)});import{isAbsolute as qH}from"path";function jo(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 ZS(e=process.env){return Object.freeze(jo(e))}async function cf(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 K("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 lf(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new K("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}}function ts(e){return sn(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}class uf{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!qH(e.executablePath))throw new K("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??cl,this.maxDiagnosticBytes=e.maxDiagnosticBytes??aS,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new K("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:jo(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new K("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new K("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 K("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 K("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 K("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 K)throw t;throw new K("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new K("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new K("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 K("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 cf(this.stderrStream,this.maxDiagnosticBytes),t=lf(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=ts(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var pf=x(()=>{mr()});import{lstat as $5,mkdir as j5,readFile as UH,readdir as V5,realpath as HH,stat as $H}from"fs/promises";import{delimiter as jH,isAbsolute as K5,join as z5,relative as W5,resolve as LP}from"path";async function BH(e){let t=[];if(e.executablePath!==void 0)t.push(LP(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(jH).filter((i)=>i.length>0))for(let i of r)t.push(LP(o,i))}for(let n of t)try{let r=await $H(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await HH(n)}catch{if(e.executablePath!==void 0)throw new K("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new K("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function KH(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 K("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await WH(Promise.all([cf(n.stdout,16384),cf(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=sn(lf(r,"Codex version output"));if(i!==0||a.length===0){let s=ts(lf(o,"Codex version diagnostics"));throw new K("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 K)throw r;throw new K("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function zH(e){let t=await UH(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=Hd(r);if(!o.ok)throw new K("discovery_failed","The Codex executable digest was invalid.");return o.value}async function XS(e={}){let t=await BH(e),n=jo(e.environment),r=e.versionRunner?sn(await e.versionRunner(t,n)):await KH(t,n);if(r.length===0)throw new K("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await zH(t)}}async function WH(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new K("timeout",n))},VH)})])}finally{if(r!==void 0)clearTimeout(r)}}var VH=30000,Z5;var DP=x(()=>{ut();bt();mr();pf();Z5=_({exitCode:Gt.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:k.pipe(kx(1048576)),stderr:k.pipe(kx(1048576))})});var JH="packages/codex/generated",GH,YH,QS,t4,n4;var qP=x(()=>{ut();bt();mr();GH=/^codex-cli \d+\.\d+\.\d+$/u,YH=/^codex-app-server-\d+\.\d+\.\d+$/u,QS=k.pipe(le(/^[a-f0-9]{64}$/u)),t4=_({schema_version:v("holycodex-generated-v2"),artifact_root:v(JH),codex_cli_version:k.pipe(le(GH)),codex_cli_digest:QS,protocol_epoch:k.pipe(le(YH)),generator:_({command:yA(v("app-server"),v("generate-ts")),supported_surface:v("codex app-server generators")}),typescript_root:v("typescript"),files:_({count:Gt.pipe(Dd(),Ax()),digest:QS})}),n4=_({path:k.pipe(Ga(1)),size:Gt.pipe(Dd(),Ax()),sha256:QS})});var ZH;var UP=x(()=>{bt();rf();ZH=_({owner:v("holycodex"),schema:k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});import{spawn as XH}from"child_process";import{lstat as Bo,mkdir as QH,mkdtemp as e$,readFile as t$,readdir as n$,realpath as e_,rename as r$,rm as o$,stat as c4}from"fs/promises";import{dirname as $P,isAbsolute as i_,join as Vo,relative as jP,resolve as ff,sep as VP}from"path";async function KP(e){let t=l_(e.selectedPluginIds);if(t.length===0)return;if(GP(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new Se("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>c_(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&hf(r,t))return r;let o=e.initializeRuntime??(()=>h$(e)),i,a;try{i=await o()}catch(s){a=Y("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??s_,c=e.pollIntervalMs??i$,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new Se("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&hf(u,t))return u;let p=s-(Date.now()-l);if(p<=0)break;await(e.sleep??y$)(Math.min(c,p))}a=Y("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 Se&&s.code==="cancelled")throw s;a=s instanceof Se?s:Y("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await zP({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 Se)throw s;throw Y("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??Y("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function zP(e){let t=l_(e.selectedPluginIds);if(t.length===0)throw Y("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(GP(e.timeoutMs,void 0),!i_(e.codexHome))throw Y("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new Se("cancelled","Official Codex marketplace fallback was cancelled.");let n=jo(e.environment),r=e.gitRunner??XP("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??s_,i;try{i=await c$(r,o,e.signal)}catch(u){if(u instanceof Se)throw u;throw Y("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Vo(e.codexHome,"plugins"),s=Vo(a,a_[1]);if(await u$(a,e.codexHome),await Bo(s).catch((u)=>{if(Tl(u))return;throw Y("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw Y("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await e$(Vo(a,".openai-plugins-stage-"));try{if(await n_(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(Hi,l)}catch(m){if(g$(m))throw Y("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",Hi,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw Y("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await mf(l);let u=await WP(l,e.codexHome,t);if(u===void 0||!hf(u,t))throw Y("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await l$(r,l,o,e.signal)!==i)throw Y("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Bo(s).catch((m)=>{if(Tl(m))return;throw Y("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw Y("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await r$(l,s);let h=await c_(e.codexHome,e.selectedPluginIds);if(h===void 0||!hf(h,t))throw Y("marketplace_invalid","The published official marketplace failed validation.");return h}catch(u){if(u instanceof Se)throw u;throw Y("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await o$(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function c$(e,t,n){let r=await e.run(["ls-remote",Hi,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw Y("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 Y("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function l$(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 Y("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function u$(e,t){await t_(t,e),await QH(e,{recursive:!0}),await t_(t,e)}async function t_(e,t){let n=ff(e),r=ff(t);while(!0){if((await Bo(r).catch((a)=>{if(Tl(a))return;throw a}))?.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=$P(r);if(i===r||i!==n&&!p$(n,i))throw Y("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function p$(e,t){let n=jP(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${VP}`)&&!i_(n)}async function mf(e){let t=await Bo(e);if(t.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw Y("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await n$(e,{withFileTypes:!0});for(let r of n){let o=Vo(e,r.name),i=await Bo(o);if(i.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await mf(o)}}async function c_(e,t=[]){return await WP(Vo(e,...a_),e,l_(t))}async function WP(e,t,n=[]){if(t!==void 0)await t_(t,e);let r=await Bo(e).catch((l)=>{if(Tl(l))return;throw Y("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 Y("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await n_(t,e);else await mf(e);if(t!==void 0)await mf(e);let o=await e_(e),i=[Vo(o,".agents","plugins","marketplace.json"),Vo(o,".codex-plugin","marketplace.json"),Vo(o,"marketplace.json")],a,s;for(let l of i){let u=await Bo(l).catch((p)=>{if(Tl(p))return;throw Y("marketplace_invalid","The official marketplace manifest could not be read safely.",p)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw Y("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await n_(o,l),a!==void 0)throw Y("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await t$(l))}catch(p){throw Y("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 Y("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return JP(c,o,a,n)}function JP(e,t=`${a_.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!re(e)||e.name!==vl)throw Y("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");d$(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw Y("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!re(s)||typeof s.name!=="string"){if(r.length>0)continue;throw Y("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 Y("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw Y("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=f$(s);if(!m$(l))throw Y("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 Y("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:vl,source:Hi,rootPath:t,manifestPath:n,plugins:i}}function d$(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:re(n)&&typeof n.url==="string"?n.url:void 0)!==Hi)throw Y("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function f$(e){let t=e.source;if(typeof t==="string")return t;if(re(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function m$(e){if(e===void 0||e.length===0||i_(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 l_(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!==vl&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw Y("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!YP(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function hf(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 h$(e){let t=jo(e.environment),n;try{n=new uf({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new sf(n,{requestTimeoutMs:Math.min(e.timeoutMs??s_,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 GP(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw Y("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw Y("marketplace_invalid","The official marketplace poll interval is invalid.")}async function n_(e,t){let n=await e_(e),r=await e_(t),o=jP(n,r);if(o===""||o===".."||o.startsWith(`..${VP}`))throw Y("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=ff(e),a=ff(t);while(!0){if((await Bo(a)).isSymbolicLink())throw Y("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=$P(a);if(c===a)throw Y("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Tl(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function g$(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function y$(e){await new Promise((t)=>setTimeout(t,e))}function Y(e,t,n){return new Se(e,t,n instanceof Error?{cause:ts(n.message)}:{})}function yr(e,t){let n=Hn(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=Mx(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 YP(e){return Ud.includes(e)}function ZP(e){if(!bP(o_,e))return xP(Le("live official plugin list",e));return SP(Pe(o_,e,"live official plugin list"))}function gf(e){let t=e.runner??XP(e.executable,{environment:e.environment??jo(),...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 df("list",r);let o;try{o=JSON.parse(r.stdout)}catch{throw new Se("command_failed","Codex returned invalid plugin data.")}let i=ZP(o);if(!i.ok)throw new Se("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 Se("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await KP({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=Pe(wl,r,"plugin marketplace source");if(i===vl||i===Hi)throw new Se("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 df("marketplace add",a,i)},add:async(r,o)=>{let i=Pe(wl,r,"official plugin id"),a=await t.run(["plugin","add",i,"--json"],o===void 0?void 0:{signal:o});if(a.exitCode!==0)throw df("add",a,i);let s=await n(),c=yr(s,i),l=Hn(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 Se("readback_mismatch",`Codex did not report ${i} after installation.`,{plugin_id:i});if(!p.installed)throw new Se("plugin_missing",`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!p.enabled)throw new Se("plugin_disabled",`Codex installed ${i} but it is disabled; enable it in Codex and retry.`,{plugin_id:i})},remove:async(r,o)=>{let i=Pe(wl,r,"official plugin id"),a=i;if(Hn(i)===i){let u=await n(),p=yr(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 df("remove",s,a);let c=await n(),l=[...c.installed,...c.available].find((u)=>u.pluginId===a);if(l?.installed)throw new Se("readback_mismatch",`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:l.pluginId})}}}function df(e,t,n){let r=ts(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new Se("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function XP(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>S$(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 S$(e,t,n){if(n.signal?.aborted)throw new Se("cancelled","The Codex plugin command was cancelled.");let r=XH(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=HP(r.stdout,n.stdoutLimit),i=HP(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 Se("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 Se("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 Se)throw p;throw new Se("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function HP(e,t){if(e===null)return Promise.reject(new Se("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 Se("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new Se("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 vl="openai-curated",Hi="https://github.com/openai/plugins.git",a_,s_=30000,i$=100,BP,a$,bl,wl,s$,x$,r_,o_,Se;var u_=x(()=>{ut();bt();YS();mr();pf();a_=["plugins","openai-plugins"],BP=k.pipe(le(/^[a-z][a-z0-9._-]{1,63}$/u)),a$=k.pipe(le(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),bl=q(k),wl=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),s$=_({name:BP,version:a$,description:Xr,author:b(cn),license:b(Xr),homepage:b(Xr),repository:b(Xr),keywords:b(bl),skills:b(bl),commands:b(bl),hooks:b(bl),assets:b(bl),official:b(J)});x$=_({id:BP,selected:v(!0)}),r_=_({pluginId:wl,installed:J,enabled:J,name:b(xe(k,lt)),marketplaceName:b(xe(k,lt)),version:b(xe(k,lt))},Ld({key:k,value:vx})),o_=_({installed:q(r_),available:q(r_)});Se=class Se extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});var El=x(()=>{mr();mr();Yd();GS();YS();pf();DP();qP();UP();rf();u_();u_()});function Zt(e){if(!ns(e))throw Error("The value is not JSON serializable.");return dr(e),e}function ns(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)=>ns(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>ns(n,t))}finally{t.delete(e)}}var Ol=x(()=>{ut()});function mt(e,t){let n=bn(e,t);return Ot(n)?n.right:void 0}function nI(e){return mt(xf,e)!==void 0}var xf,Q4,p_,Sf,_$,os,b$,w$,v$,eI,Rl,_f,rs,d_,yf,T$,QP,E$,f_,is,O$,tI,R$,k$,ln;var as=x(()=>{El();ut();tn();bt();Ol();xf=H((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&ns(e)),Q4=H(ns),p_=k.pipe(le(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)),Sf=k.pipe(le(/^[0-9a-f]{64}$/u)),_$=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),os=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),b$=k.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),w$=_({path:k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:Sf}),v$=_({computer_use:J,work:J,frontend:J,security:J,coding:v(!0)}),eI=_({computer_use:b(J),work:b(J),frontend:b(J),security:b(J)}),Rl=_({profile:b(Lo),tier:b(Fi),optional:b(eI),officialPlugins:b(q(os))}),_f=Rl,rs=_({selected:J,status:v("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:q(os),reason:b(k)}),d_=_({computer_use:rs,work:rs,frontend:rs,security:rs}),yf=_({presence:v("absent","present"),digest:Sf,safe_value:b(xe(_({kind:v("boolean"),value:J}),_({kind:v("marketplace"),source_type:v("git"),source:v("https://github.com/davidbasilefilho/holycodex.git")})))}),T$=_({plugin_id:v("holycodex@holycodex"),before:_({preference:yf,marketplace:yf}),after:_({preference:yf,marketplace:yf})}),QP=_({presence:v("absent","present"),digest:Sf,safe_value:b(_({kind:v("boolean"),value:J}))}),E$=_({plugin_id:os,before:QP,after:QP}),f_={owner:v("holycodex"),schema_epoch:v(Tn),install_id:_$,version:p_,digest:Sf,profile:Lo,tier:Fi,optional_selections:v$,explicit_optional_selections:eI,official_plugins:b(q(os)),capability_state:b(d_),managed_artifacts:q(w$),installed_at:b$,status:b(v("active")),step:b(v("active")),managed_config:b(ef),plugin_snapshot:b(q(_({plugin_id:os,status:v("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:b(T$),provider_config:b(q(E$)),owned_plugins:b(q(os))},is=_(f_),O$=(({profile:e,...t})=>t)(f_),tI=xe(_({...f_,profile:jd}),_({...O$,plan:jd})),R$=v("preparing","conflicted"),k$=v("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),ln=_({...is.fields,status:R$,step:k$})});import{lstat as C$,mkdir as A$}from"fs/promises";import{homedir as P$}from"os";import{dirname as I$,join as $i,posix as rI,resolve as M$,sep as oI,win32 as iI}from"path";function ji(e={},t=process.env){let n=P$(),r=e.paths?.codexHome??t.CODEX_HOME??$i(n,".codex"),o=h_(r,"CODEX_HOME"),i=$i(o,N$);return{codexHome:o,stateRoot:i,activeRecord:$i(i,F$),preparingRecord:$i(i,L$),conflictedRecord:$i(i,D$),roleRoot:$i(i,"agents"),configFile:$i(o,"config.toml")}}function h_(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||U$(e))throw new wn("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?iI:rI,o=m_(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new wn("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":oI).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new wn("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new wn("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function U$(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function kl(e){h_(e,"owned path"),await xr(e),await A$(e,{recursive:!0}),await xr(e)}async function xr(e){let n=M$(e);while(!0){try{if((await C$(n)).isSymbolicLink())throw new wn("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof wn)throw o;if(!ht(o,"ENOENT"))throw o}let r=I$(n);if(r===n)break;n=r}}async function Cl(e){await xr(e)}function ss(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?iI:rI,o=r.resolve(m_(e,n)),i=r.resolve(m_(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":oI}`)&&a!==".."&&!r.isAbsolute(a)}function m_(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function ht(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var N$="holycodex",F$="active.json",L$="preparing.json",D$="conflicted.json",q$,wn;var Vi=x(()=>{ut();q$=Tn;wn=class wn extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as aI,open as H$,readFile as sI,rename as $$,unlink as j$,writeFile as V$}from"fs/promises";import{dirname as B$}from"path";async function cI(e){let t;try{t=await H$(e,"r"),await t.sync()}catch(n){if(!lI(n))throw n}finally{await t?.close().catch(()=>{return})}}async function z$(e){await cI(e).catch((t)=>{if(!lI(t))throw t})}async function Ko(e,t){await Qr(e,`${dr(t)}
36
- `)}async function Qr(e,t){let n=B$(e);await kl(n),await xr(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await V$(r,t,{encoding:"utf8",mode:384}),await cI(r),await $$(r,e),await z$(n)}catch(o){throw await j$(r).catch(()=>{return}),o}}async function W$(e,t){let n=await aI(e);if(!n.isFile()||n.isSymbolicLink())throw new Bi("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await sI(e,"utf8"))}catch(i){throw new Bi("state_corrupt","A persisted file is not valid JSON.",i)}let o=mt(t,r);if(o===void 0)throw new Bi("state_corrupt","A persisted file failed schema validation.");return o}async function Xt(e){try{let t=await aI(e);if(!t.isFile()||t.isSymbolicLink())throw new Bi("state_corrupt","A persisted file is not a regular file.");return await sI(e,"utf8")}catch(t){if(ht(t,"ENOENT"))return;throw t}}async function Bn(e,t){try{return await W$(e,t)}catch(n){if(ht(n,"ENOENT"))return;throw n}}function lI(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return K$.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var K$,Bi;var cs=x(()=>{ut();Vi();as();K$=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);Bi=class Bi extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as J$}from"fs/promises";import{dirname as G$,resolve as Y$}from"path";import{fileURLToPath as Z$}from"url";async function uI(e=Al){let t=JSON.parse(await J$(e,"utf8")),n=mt(Q$,t);if(n===void 0)throw new Pl("manifest_invalid","The public package manifest is invalid.");return n}async function bf(e=Al){return(await uI(e)).version}async function ls(e=Al){return(await bf(e)).split("-",1)[0]??""}async function g_(e,t,n=Al){let r=await uI(n),o=await ls(n),i=ej(e,o);if(!t)await Ko(n,{...r,version:i});return{previous:o,next:i}}function ej(e,t){if(e!=="patch"&&e!=="minor"){if(mt(p_,e)===void 0)throw new Pl("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 X$,Q$,Al,Pl;var Il=x(()=>{bt();as();cs();X$=k.pipe(le(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*\.[1-9]\d*)?$/u)),Q$=H((e)=>nI(e)&&e.name==="holycodex"&&mt(X$,e.version)!==void 0),Al=Y$(G$(Z$(import.meta.url)),"../package.json");Pl=class Pl extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{lstat as wf,readFile as vf,rm as Tf}from"fs/promises";import{join as un,relative as pI}from"path";function Ki(e,t="standard"){let n=fr(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:jx(o),rolePolicy:jn.find((i)=>i.role===r.role),description:Bx(o),taskInstruction:Vx(o),permissions:Kx(o),model:"gpt-5.6-luna",effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function x_(e,t="standard"){let n=fr(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 S_(e=!1){if(!Do.requiresDelegation||!Do.trivialWorkRequiresDelegation||!Do.codeReviewRequiredForImplementation||!Do.codeReviewRequiredBeforeVcs||!Do.externalVerificationMustBeTerminal)throw Error("The Root orchestration policy is incomplete.");let t=["You are the HolyCodex Root/session orchestrator running gpt-6-astra. Own the user goal, acceptance, material product or architecture choices, lifecycle, integration, external effects, and final completion.","Represent every specialist work unit, including trivial work, with one active bounded Assignment and dispatch it to the native Explorer, Librarian, Worker, or Reviewer route. Small work may use one Assignment. Git/VCS is Root-only; Computer Use is Root-only only when --computer-use was selected. Do the underlying implementation, research, testing, review, and CI observation through specialists.","Use holycodex-agent semantic operations for Intent, optional Plan, and Assignment state. Never edit TOON state or create standalone handoff, Decision, or blocker files.",`Surgical mutation rule: ${Do.surgicalMutationRule}`,"Infer routine safe choices and keep moving. Finish authorized read-only, reversible, preparatory, and independent work before asking. Use request_user_input only for a material unresolved choice, an explicit approval boundary such as plan approval, installation profile approval, remote/origin/server VCS mutation, or public publication/release, or a genuine blocker that can change the outcome, and persist the resulting needs_root_input state.","Dispatch independent non-overlapping Assignments concurrently when useful, keep dependent phases ordered, and serialize writes to one mutable seam. Use writing-for-agents to author compact Luna contracts without repeating effective receiver instructions.","For complex work, make each phase a coherent dependency, decision, or integration boundary. Resolve only choices needed by the current phase, persist its Plan and Assignment evidence, and advance after acceptance; do not ask later-phase questions prematurely.","Use proportional proof and inspect specialist evidence before integration. Worker.validation is an optional independent local proof route when risk or integration complexity warrants it; it does not replace implementation proof or Reviewer.code. Reviewer.code fixed-point review is mandatory after implementation or a major codebase change and before completion or VCS, with no recursive review or testing ceremony.","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(e)t.push("Interactive GUI, browser, and Computer Use execution is Root-only and must not be delegated.");else t.push("Computer Use is not selected for this installation; delegate GUI, browser, and Computer Use execution to an appropriate bounded specialist.");return t.join(`
37
- `)}async function __(e,t,n=[],r="standard"){let o=un(e,"holycodex","agents"),i=[],a=[],s=Ki(t,r).map((p)=>({path:un(o,`${p.name}.toml`),contents:Rf(p)})),c=new Map(n.map((p)=>[un(e,p.path),p])),l=new Map;for(let p of s){let f=await y_(p.path);l.set(p.path,f);let h=c.get(p.path);if(f!==void 0&&h===void 0&&f!==p.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${p.path}`)}let u=[];try{for(let m of s){let w=l.get(m.path),S=c.get(m.path);if(w!==void 0&&S!==void 0){if(await us(w)!==S.digest&&w!==m.contents){i.push(m.path),u.push({path:pI(e,m.path).replaceAll("\\","/"),digest:S.digest});continue}}if(w===void 0||w!==m.contents)await Qr(m.path,m.contents),a.push({path:m.path,previous:w,installedDigest:await us(m.contents)});u.push({path:pI(e,m.path).replaceAll("\\","/"),digest:await us(m.contents)})}let p=un(e,"agents","root.toml"),f=await y_(p),h=await dI(p);if(h==="preserved")i.push(p);if(h==="removed"&&f!==void 0)a.push({path:p,previous:f,installedDigest:void 0});for(let m of n){let w=un(e,m.path);if(!s.some((S)=>S.path===w)){if(!oj(e,w,m.path)){i.push(w);continue}let S=await ij(w,m.digest);if(S.status==="preserved")i.push(w);else if(S.previous!==void 0)a.push({path:w,previous:S.previous,installedDigest:void 0})}}for(let m of n){let w=un(e,m.path);if(i.includes(w)&&!u.some((S)=>un(e,S.path)===w))u.push(m)}return{managed_artifacts:u,preserved:i,rollback:a}}catch(p){throw await Ef(a).catch(()=>{return}),p}}async function Ef(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await y_(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await us(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await Tf(r.path,{force:!1}).catch((a)=>{if(!ht(a,"ENOENT"))throw a}),t.push(r.path);else await Qr(r.path,r.previous)}return{removed:t,preserved:n}}async function Of(e,t){let n=[],r=[],o=un(e,"agents"),i=un(e,"holycodex","agents");for(let c of t){let l=un(e,c.path);if(!ss(e,l)||!ss(o,l)&&!ss(i,l)&&l!==un(e,"config.toml")){r.push(l);continue}try{await xr(l);let u=await wf(l);if(u.isSymbolicLink()||!u.isFile()){r.push(l);continue}let p=await vf(l);if(await us(p)!==c.digest){r.push(l);continue}await Tf(l,{force:!1}),n.push(l)}catch(u){if(!ht(u,"ENOENT"))r.push(l)}}let a=un(e,"agents","root.toml"),s=await dI(a);if(s==="removed")n.push(a);if(s==="preserved")r.push(a);return{removed:n,preserved:r}}function Rf(e){let t=[tj,e.taskInstruction].join(`
38
- `);return[`name = ${JSON.stringify(e.name)}`,`description = ${JSON.stringify(e.description)}`,`model = ${JSON.stringify(e.model)}`,`model_reasoning_effort = ${JSON.stringify(e.effort)}`,`service_tier = ${JSON.stringify(e.serviceTier)}`,'model_reasoning_summary = "none"','model_verbosity = "low"',`sandbox_mode = ${JSON.stringify(e.permissions.write?"workspace-write":"read-only")}`,'approval_policy = "never"',`web_search = ${JSON.stringify(e.permissions.network?"live":"disabled")}`,`developer_instructions = ${JSON.stringify(t)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent_v2 = false","multi_agent = false","computer_use = false","browser_use = false","in_app_browser = false",""].join(`
39
- `)}function nj(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 ps(e){return rj.has(e)}function oj(e,t,n){if(n==="agents/root.toml")return!0;if(/^holycodex\/agents\/(?:explorer|librarian|worker|reviewer)\.toml$/u.test(n))return!0;return ss(un(e,"agents"),t)&&/^(?:Explorer|Librarian|Worker|Reviewer)\.(?:lookup|trace|research|mechanical|implementation|integration|operations|plan|code|artifact)\.toml$/u.test(n.slice(7))}async function dI(e){try{await xr(e);let t=await wf(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await vf(e,"utf8");if(!ps(n))return"preserved";return await Tf(e,{force:!1}),"removed"}catch(t){if(ht(t,"ENOENT"))return"absent";throw t}}async function y_(e){try{await xr(e);let t=await wf(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await vf(e))}catch(t){if(ht(t,"ENOENT"))return;throw t}}async function ij(e,t){try{await xr(e);let n=await wf(e);if(n.isSymbolicLink()||!n.isFile())return{status:"preserved"};let r=new TextDecoder("utf-8",{fatal:!0}).decode(await vf(e));if(await us(r)===t)return await Tf(e,{force:!1}),{status:"removed",previous:r};return{status:"preserved"}}catch(n){if(ht(n,"ENOENT"))return{status:"removed"};throw n}}async function us(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 tj="You are a HolyCodex GPT-5.6 Luna specialist executing one active bounded Assignment. Follow its exact boundary, exclusions, acceptance criteria, and evidence requirements. Make the smallest complete edit set within that boundary, preserve unrelated work, and perform no redundant writes. Do not delegate, message peers, mutate global Intent lifecycle, make material decisions, or perform Git/VCS. Return exactly one compact outcome (`completed`, `blocked`, `needs_root_input`, or `failed`) with changed paths, checks, observable evidence, blockers, and remaining risk.",rj;var kf=x(()=>{ut();Vi();cs();rj=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)=>nj(e,t,n))))});class zo{adapter;observedIdentities={};constructor(e){if("run"in e){let t=gf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await XS({environment:e}),n=gf({executable:t.path,environment:ZS(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new zo(n)}async list(){try{return await this.adapter.list()}catch(e){throw Ml("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw Ml("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw Ml("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw Ml("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw Ml("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=yr(t,i),s=Hn(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 Ml(e,t,n){if(t instanceof Sr)return t;let o=(t instanceof Se?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 Sr(i,a,t,n===void 0?{}:{plugin_id:n})}var Sr;var Nl=x(()=>{El();ut();Sr=class Sr 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 mI(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=sj(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=b_(o.slice(1,-1).trim()),aj(t,n);continue}let i=xI(o);if(i<1)throw Error("TOML assignment is invalid.");let a=b_(o.slice(0,i).trim()),s=Cf(o.slice(i+1).trim());yI(t,[...n,...a],s)}return t}function hI(e){let t=[];return gI(e,[],t),t.join(`
41
- `)}function gI(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(v_(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(fI).join(".")}]`)}for(let[i,a]of r)n.push(`${fI(i)} = ${SI(a)}`);for(let[i,a]of o)gI(a,[...t,i],n)}function Cf(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?[]:w_(t,",").map(Cf)}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 w_(t,",")){let o=xI(r);if(o<1)throw Error("TOML inline table entry is invalid.");yI(n,b_(r.slice(0,o).trim()),Cf(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 b_(e){let t=w_(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("'")?Cf(n):n)}function yI(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(v_(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 aj(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(v_(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function w_(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 xI(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 sj(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 v_(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function fI(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function SI(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(SI).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{rm as E_,rmdir as _I}from"fs/promises";async function k_(e={},t=process.env){let n=ji(e,t),r={};try{await Cl(n.codexHome),await Cl(n.stateRoot),r.paths=Fl({state_root:n.stateRoot})}catch(l){r.paths=wt(["path_symlink"],{error:_r(l)})}let[o,i,a]=await Promise.all([ms(n).catch((l)=>{r.configuration=wt(["state_corrupt"],{error:_r(l)});return}),Bn(n.preparingRecord,ln).catch((l)=>{r.transaction=wt(["state_corrupt"],{path:n.preparingRecord,error:_r(l)});return}),Bn(n.conflictedRecord,ln).catch((l)=>{r.transaction=wt(["state_corrupt"],{path:n.conflictedRecord,error:_r(l)});return})]);if(i!==void 0&&r.transaction?.status!=="failed")r.transaction=wt(["incomplete_install_state"]);if(a!==void 0&&r.transaction?.status!=="failed")r.transaction=wt(["conflicted_state"]);if(!r.configuration)if(!o)r.configuration=wt(["configuration_missing"]);else if(await Dl(o))r.configuration=Fl({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=wt(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await lj(n,o),r.native_roles=await uj(n,o.profile,o.tier);let l=Object.entries(o.capability_state??{}).find(([,u])=>u.selected&&u.status!=="healthy");if(l)r.capabilities=wt(["selected_capability_not_healthy"],{capability:l[0],status:l[1].status})}try{let l=await Xt(`${n.codexHome}/agents/root.toml`);if(l!==void 0&&ps(l)){let u=r.native_roles;r.native_roles={status:"failed",reasons:[...u?.reasons??[],"stale_legacy_root"],details:{...u?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(l){r.native_roles=wt(["native_role_invalid"],{error:_r(l)})}let s=e.officialPluginManager??await zo.discover({...t,CODEX_HOME:n.codexHome}).catch(()=>{return});if(o&&s?.status){let l=[...new Set([br,...Qc({computer_use:o.optional_selections.computer_use,work:o.optional_selections.work,frontend:o.optional_selections.frontend,security:o.optional_selections.security},o.official_plugins),...o.owned_plugins??[]])];try{let u=await s.status(l),p=Object.entries(u).filter(([,h])=>h!=="installed").map(([h])=>h),f=s.getObservedIdentities?.()??{};r.native_plugins=p.length===0?Fl({status:u,observed_identities:f}):wt(["native_plugin_disagreement"],{missing:p,status:u,observed_identities:f})}catch(u){r.native_plugins=wt(["native_plugin_status_failed"],{error:_r(u)})}}else r.native_plugins={status:"unsupported",reasons:["native_plugin_manager_unavailable"],details:{}};let c=Object.values(r).flatMap((l)=>l.reasons);return{healthy:Object.values(r).every((l)=>l.status!=="failed"),checks:r,reasons:[...new Set(c)]}}async function Ll(e={},t=process.env){let n=ji(e,t);await Cl(n.codexHome),await Cl(n.stateRoot);let r=await ms(n),[o,i]=await Promise.all([Bn(n.preparingRecord,ln),Bn(n.conflictedRecord,ln)]),a=i??o??r;T_(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(pj(a)),c=[],l=[],u=[];if(r&&!await Dl(r))return l.push(n.activeRecord),u.push("configuration_changed"),{removed:c,preserved:l,reasons:u};if(a===void 0)return T_(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let p=await Xt(n.configFile),f=eo(p),h=a?.managed_config;if(h){let y=await Ui(f,h,{schema:h.schema,installId:h.installId});if(y.preservedKeys.length>0||y.unresolvedKeys.length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u}}if(a?.plugin_config){if((await O_(f,a.plugin_config)).preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u}}if(a?.provider_config){if((await R_(f,a.provider_config,s)).preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u}}let m;try{m=e.officialPluginManager??await zo.discover({...t,CODEX_HOME:n.codexHome})}catch(y){throw new N("capability_denied","Native Codex plugin removal is unavailable.",y,{recovery:"Install or expose Codex, then retry."})}if(m===void 0||!m.remove||!m.list)throw new N("capability_denied","Native Codex plugin removal and readback are unavailable.");let w=await Of(n.codexHome,a?.managed_artifacts??[]);if(c.push(...w.removed),l.push(...w.preserved),w.preserved.length>0)u.push("managed_artifact_changed");for(let y of s)try{let R=await m.list(),P=dj(R,y);if(P?.entry.installed!==!0)continue;let z=P.entry.pluginId;await m.remove(z);let X=await m.list();if(yr(X,y)?.entry?.installed===!0||[...X.installed,...X.available].some((L)=>L.pluginId===y&&L.installed))throw new N("capability_denied",`Codex still reports ${y} after removal.`);c.push(y)}catch(R){throw u.push("native_plugin_remove_failed"),await Kn(n,a??ds()),new N("capability_denied",`Codex native plugin removal did not converge for ${y}: ${_r(R)}`,R)}if(w.preserved.length>0)return await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u};let S;try{let y=f,R=h;if(R){let P=await Ui(y,R,{schema:R.schema,installId:R.installId});if(P.preservedKeys.length>0||P.unresolvedKeys.length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u};y=P.document,R=P.state}if(a?.plugin_config){let P=await O_(y,a.plugin_config,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u};y=P.document}if(a?.provider_config){let P=await R_(y,a.provider_config,s,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u};y=P.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)S=R===void 0?{document:y}:{document:y,state:R};if(S!==void 0)if(Object.keys(S.document).length===0&&p===void 0)await E_(n.configFile,{force:!1});else await Qr(n.configFile,A_(S.document))}catch(y){if(y instanceof N)throw await Kn(n,a??ds()),y;return l.push(n.configFile),u.push("managed_config_write_failed"),await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u}}if(r)try{await E_(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(y){if(!ht(y,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await Kn(n,a??r),{removed:c,preserved:l,reasons:u}}if(l.length===0)for(let[y,R]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0]]){if(!R)continue;try{await fj(y),c.push(y)}catch{l.push(y),u.push("state_remove_failed")}}if(l.length===0)try{await _I(n.roleRoot),c.push(n.roleRoot)}catch(y){if(!ht(y,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await _I(n.stateRoot),c.push(n.stateRoot)}catch(y){if(ht(y,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return T_(e,{stage:"removal",status:"completed",message:"HolyCodex removal complete"}),{removed:c,preserved:l,reasons:u}}async function C_(e={},t=process.env,n={}){let r=ji(e,t),[o,i,a]=await Promise.all([ms(r),Bn(r.preparingRecord,ln),Bn(r.conflictedRecord,ln)]),s=a??i??o;if(s===void 0)throw new N("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});if(o!==void 0&&!await Dl(o))throw new N("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});let c;try{c=await ls()}catch(f){throw new N("upgrade_failed","The running HolyCodex version is unavailable.",f)}let l=cj(c,s.version);if(l<0)throw new N("upgrade_downgrade",`The running HolyCodex version ${c} is older than the installed version ${s.version}.`,void 0,{installed_version:s.version,running_version:c});let u=s.managed_config?.managed["features.context_management.experimental_mode"]!==void 0,p=[...l>0?["version"]:[],...u?["context-management configuration migration"]:[],...l>0||u?["Root/session configuration","Luna role definitions"]:[],...a??i?["interrupted transaction recovery"]:[]];if(p.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:s.version,to_version:c,changes:[],record:o,preserved:[],warnings:[]};if(n.dryRun===!0)return{status:"dry_run",from_version:s.version,to_version:c,changes:p,record:o,preserved:[],warnings:[]};try{let f=await fs({profile:s.profile,tier:s.tier,optional:s.explicit_optional_selections,officialPlugins:s.official_plugins},e,t);return{status:"upgraded",from_version:s.version,to_version:c,changes:p,record:f.record,preserved:f.preserved,warnings:f.warnings}}catch(f){if(f instanceof N)throw f;throw new N("upgrade_failed",`HolyCodex upgrade failed: ${_r(f)}`,f)}}function cj(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 lj(e,t){if(!t.managed_config)return wt(["incomplete_install_state"]);try{let n=eo(await Xt(e.configFile)),r=Pf(t.profile,t.tier,t.optional_selections.computer_use),o=[];for(let[i,a]of Object.entries(r))if((await es(n,t.managed_config,i)).status!=="unchanged"||i!=="developer_instructions"&&Te(n,i)!==a)o.push(i);return o.length===0?Fl({managed_keys:Object.keys(r).length}):wt(["changed_holycodex_config"],{keys:o})}catch(n){return wt(["config_unreadable"],{error:_r(n)})}}async function uj(e,t,n){try{let r=eo(await Xt(e.configFile)),o=[];for(let a of Ki(t,n)){let s=Te(r,`agents."${a.name}".config_file`),c=`${e.roleRoot}/${a.name}.toml`.replaceAll("\\","/");if(typeof s!=="string"||hl(e.configFile,s).replaceAll("\\","/")!==c){o.push(`${a.name}:registration`);continue}let l=await Xt(`${e.roleRoot}/${a.name}.toml`);if(l===void 0){o.push(`${a.name}:missing`);continue}if(l!==Rf(a)){o.push(`${a.name}:changed`);continue}let u=eo(l);if(u.name!==a.name||typeof u.description!=="string"||typeof u.developer_instructions!=="string"||u.model!=="gpt-5.6-luna"||u.model_reasoning_summary!=="none"||u.model_verbosity!=="low"||u.tool_output_token_limit!==void 0||u.service_tier!==(n==="standard"?"default":"fast")||u.sandbox_mode!==(a.permissions.write?"workspace-write":"read-only")||u.approval_policy!=="never"||u.web_search!==(a.permissions.network?"live":"disabled")||Te(u,"agents.enabled")!==!1||Te(u,"features.multi_agent_v2")!==!1||Te(u,"features.multi_agent")!==!1||Te(u,"features.computer_use")!==!1||Te(u,"features.browser_use")!==!1||Te(u,"features.in_app_browser")!==!1)o.push(`${a.name}:malformed`)}let i=await Xt(`${e.codexHome}/agents/root.toml`);if(i!==void 0&&ps(i))o.push("root:stale");return o.length===0?Fl({role_root:e.roleRoot,agent_types:Ki(t,n).map((a)=>a.name)}):wt(["native_role_disagreement"],{roles:o})}catch(r){return wt(["native_role_invalid"],{error:_r(r)})}}async function Kn(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(mt(ln,n)!==void 0)await Ko(e.conflictedRecord,Zt(n))}function ds(){return{owner:"holycodex",schema_epoch:"state-0.16",install_id:"remove-conflict",version:"0.0.0",digest:"0".repeat(64),profile:"default",tier:"standard",optional_selections:{computer_use:!1,work:!1,frontend:!1,security:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function pj(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"?[br]:[],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 dj(e,t){let n=yr(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 Fl(e){return{status:"healthy",reasons:[],details:e}}function wt(e,t={}){return{status:"failed",reasons:e,details:t}}async function fj(e){await E_(e,{force:!1}).catch((t)=>{if(!ht(t,"ENOENT"))throw t})}function _r(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function T_(e,t){try{e.onProgress?.(t)}catch{}}var Af=x(()=>{El();ut();ql();Ol();Il();kf();Nl();Vi();as();cs()});import{rm as AI}from"fs/promises";import{join as mj}from"path";function wr(e){let t=mt(_f,e);if(t===void 0)throw new N("install_failed","The installation options are invalid.");return t}async function fs(e={},t={},n=process.env){if(mt(Rl,e)===void 0)throw new N("install_failed","The installation options are invalid.");let r=ji(t,n);zn(t,{stage:"validation",status:"started",message:"Validating Codex target"}),await kl(r.stateRoot);let o=await Bn(r.preparingRecord,ln),a=await Bn(r.conflictedRecord,ln)??o;if(a!==void 0){await Promise.resolve().then(() => Af());let qe=await Ll(t,n);if(qe.preserved.length>0||qe.reasons.length>0)throw new N("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:qe.preserved.join(","),reasons:qe.reasons.join(",")});return await fs({profile:e.profile??a.profile,tier:e.tier??a.tier,optional:{computer_use:e.optional?.computer_use??a.optional_selections.computer_use,work:e.optional?.work??a.optional_selections.work,frontend:e.optional?.frontend??a.optional_selections.frontend,security:e.optional?.security??a.optional_selections.security},officialPlugins:e.officialPlugins??OI(a)},t,n)}let s=await ms(r);if(s!==void 0&&!await Dl(s))throw new N("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:r.activeRecord});let c=kj(e.profile,s?.profile),l=Cj(e.tier,s?.tier),u=Aj(e.optional,s?.optional_selections),p=Ej(s?.explicit_optional_selections,e.optional),f=e.officialPlugins??OI(s),h=[...new Set(Qc(MI(u),f).map((ae)=>Hn(ae)??ae))],m;try{m=t.officialPluginManager??await zo.discover({...n,CODEX_HOME:r.codexHome})}catch(ae){throw new N("capability_denied","Native Codex plugin installation is unavailable.",ae,{recovery:"Install or expose Codex, then retry."})}if(!m.addMarketplace||!m.add||!m.list)throw new N("install_failed","Native Codex plugin installation and verification are unavailable.");let w;try{w=await m.list()}catch(ae){throw new N("capability_denied","Native Codex plugin state could not be read safely.",ae)}let S=h.filter((ae)=>{if(Hn(ae)!==ae)return!1;let qe=$l(w,ae);return!(qe?.installed&&qe.enabled)});if(m.ensureOfficialMarketplace!==void 0&&S.length>0)try{await m.ensureOfficialMarketplace(S)}catch(ae){throw new N("capability_denied",`The selected official Codex provider marketplace is unavailable: ${CI(ae)}`,ae,{recovery:"Check Codex network and marketplace policy, then retry."})}zn(t,{stage:"validation",status:"completed",message:"Codex target validated"});let y=s?.install_id??crypto.randomUUID().replaceAll("-",""),R=await ls(),P=(t.now?.()??new Date).toISOString(),z=await Xt(r.configFile),X=eo(z),U=s?.plugin_config?.before??await wI(X),te=[...new Set([...h,...(s?.provider_config??[]).map((ae)=>ae.plugin_id),...s?.owned_plugins??[]])].filter((ae)=>ae!==br),se=(await vI(X,te)).map((ae)=>{let qe=s?.provider_config?.find((Gn)=>Gn.plugin_id===ae.plugin_id);return qe===void 0?ae:{plugin_id:ae.plugin_id,before:qe.before,after:qe.before}}),ce=s?.managed_config??tf({schema:Tn,installId:y}),ee=await TI(X,ce,s),Ae=await EI(ee.document,ee.state),{document:vt,state:Ft}=Ae;_j(vt,Ft);let Lt=Pf(c,l,u.computer_use),De;try{De=await gl(vt,Ft,Lt,{schema:Tn,installId:y})}catch(ae){if(ae instanceof N)throw ae;throw new N("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",ae,{recovery:"Converge the conflicting Codex setting, then retry."})}if(De.driftedKeys.length>0)throw new N("state_corrupt","HolyCodex-owned Codex settings changed and cannot be replaced safely.",void 0,{keys:De.driftedKeys.join(",")});let je;try{je=await bj({list:()=>m.list()},[...new Set([br,...h,...s?.owned_plugins??[]])])}catch(ae){throw new N("capability_denied","Native Codex plugin state could not be read safely.",ae)}let Tt={owner:"holycodex",schema_epoch:Tn,install_id:y,version:R,digest:s?.digest??"0".repeat(64),profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:kI(u),managed_artifacts:s?.managed_artifacts??[],installed_at:P,status:"preparing",step:"validated",managed_config:De.state,plugin_snapshot:je,plugin_config:{plugin_id:br,before:U,after:U},provider_config:se,owned_plugins:[...new Set(s?.owned_plugins??[])]};await Ul(r.preparingRecord,Tt);let Et,Gi=!1,to=new Set,Yi=new Set(s?.owned_plugins??[]),Df=new Set,Dt=Tt,q_=!1,U_=!1,qf=z,gs=De.state;try{zn(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await kl(r.roleRoot),Et=await __(r.codexHome,c,s?.managed_artifacts,l),Dt={...Tt,step:"roles_prepared",managed_artifacts:Et.managed_artifacts},await Ul(r.preparingRecord,Dt),zn(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),zn(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),q_=!0,await m.addMarketplace(hj),await Rj({list:()=>m.list(),add:(vn)=>m.add(vn)},[br,...h],(vn,jf)=>{if(jf==="new")to.add(vn),Yi.add(vn),Dt={...Dt,owned_plugins:[...Yi]};else Df.add(vn),Yi.add(vn),Dt={...Dt,owned_plugins:[...Yi]}}),Dt={...Dt,step:"plugins_installed"},await Ul(r.preparingRecord,Dt),zn(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let qe=await Xt(r.configFile);qf=qe;let Gn=eo(qe),H_=await TI(Gn,ce,s),$_=await EI(H_.document,H_.state),{document:Bl,state:j_}=$_,Uf=await wI(Bl),Hf=(await vI(Bl,te)).map((vn)=>({plugin_id:vn.plugin_id,before:se.find((jf)=>jf.plugin_id===vn.plugin_id)?.before??vn.before,after:vn.before}));await Sj(Bl,vt,j_,Lt);let Kl=await gl(Bl,j_,Lt,{schema:Tn,installId:y});if(Kl.driftedKeys.length>0)throw new N("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Kl.driftedKeys.join(",")});U_=!0,zn(t,{stage:"config",status:"started",message:"Configuring Root"}),gs=Kl.state,Dt={...Dt,managed_config:gs,plugin_config:{plugin_id:br,before:U,after:Uf},provider_config:Hf},await Qr(r.configFile,A_(Kl.document)),Gi=!0,Dt={...Dt,step:"config_published"},await Ul(r.preparingRecord,Dt),zn(t,{stage:"config",status:"completed",message:"Root configuration published"}),zn(t,{stage:"verification",status:"started",message:"Verifying installation"}),await vj(r,c,l,u.computer_use,gs,Et.preserved),zn(t,{stage:"verification",status:"completed",message:"Installation verified"});let V_=kI(u),ZI=await If({owner:"holycodex",install_id:y,version:R,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:V_,managed_artifacts:Et.managed_artifacts,managed_config:gs,plugin_config:{plugin_id:br,before:U,after:Uf},provider_config:Hf,plugin_snapshot:je,owned_plugins:[...Yi]}),$f={owner:"holycodex",schema_epoch:Tn,install_id:y,version:R,digest:ZI,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:V_,managed_artifacts:Et.managed_artifacts,installed_at:P,status:"active",step:"active",managed_config:gs,plugin_snapshot:je,plugin_config:{plugin_id:br,before:U,after:Uf},provider_config:Hf,owned_plugins:[...Yi]};if(mt(is,$f)===void 0)throw new N("state_corrupt","The HolyCodex configuration is invalid.");return await Ko(r.activeRecord,Zt($f)),await P_(r.preparingRecord),await P_(r.conflictedRecord),zn(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:$f,optional_plugins:h,preserved:Et.preserved,warnings:Et.preserved.length===0?[]:["modified managed files were preserved"]}}catch(ae){let qe=[];if(Gi)try{await wj(r.configFile,qf)}catch{qe.push("config")}if(q_&&!U_){if(await Xt(r.configFile).catch(()=>{return})!==qf)qe.push("config")}if(Et!==void 0)try{if((await Ef(Et.rollback)).preserved.length>0)qe.push("roles")}catch{qe.push("roles")}if(Df.size>0)qe.push(...[...Df].map((Gn)=>`plugin:${Gn}`));for(let Gn of to)try{await m.remove?.(Gn)}catch{qe.push(`plugin:${Gn}`)}if(qe.length>0)await Ul(r.conflictedRecord,{...Dt,step:"conflicted",status:"conflicted"}).catch(()=>{return});else await P_(r.preparingRecord).catch(()=>{return});if(ae instanceof wn)throw ae;if(ae instanceof N)throw ae;throw new N(ae instanceof Sr||ae instanceof Hl?"capability_denied":"install_failed",CI(ae),ae,qe.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function ms(e){let t=await Bn(e.activeRecord,xf);if(t===void 0)return;let n=mt(is,t);if(n!==void 0)return n;let r=mt(tI,t);if(r===void 0)throw new N("state_corrupt","The HolyCodex configuration is invalid.");if(!await LI(r))throw new N("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord});let o="profile"in r&&r.profile!==void 0?r.profile:("plan"in r)?r.plan:void 0;if(o===void 0)throw new N("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let i;try{i=qx(o)}catch(c){throw new N("state_corrupt",`The persisted profile ${o} was removed and requires an explicit replacement.`,c,{path:e.activeRecord,profile:o})}let s={..."plan"in r?Object.fromEntries(Object.entries(r).filter(([c])=>c!=="plan")):r,profile:i,digest:await If({owner:r.owner,install_id:r.install_id,version:r.version,profile:i,tier:r.tier,optional_selections:r.optional_selections,explicit_optional_selections:r.explicit_optional_selections,official_plugins:r.official_plugins??[],capability_state:r.capability_state??null,managed_artifacts:r.managed_artifacts,...r.managed_config===void 0?{}:{managed_config:r.managed_config},...r.plugin_config===void 0?{}:{plugin_config:r.plugin_config},...r.provider_config===void 0?{}:{provider_config:r.provider_config},...r.plugin_snapshot===void 0?{}:{plugin_snapshot:r.plugin_snapshot},...r.owned_plugins===void 0?{}:{owned_plugins:r.owned_plugins}})};return await Ko(e.activeRecord,Zt(s)),s}function MI(e){return{computer_use:e.computer_use,work:e.work,frontend:e.frontend,security:e.security}}function eo(e){if(e===void 0||e.trim().length===0)return{};try{let t=globalThis.Bun,n=t?.TOML?.parse?t.TOML.parse(e):mI(e),r=mt(pl,n);if(r===void 0)throw Error("TOML document contains unsupported values.");return r}catch(t){throw new N("state_corrupt","The Codex config.toml is not valid TOML.",t)}}function A_(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):hI(e)).trimEnd()}
42
- `}catch(t){throw new N("install_failed","The merged Codex configuration is not writable.",t)}}async function wI(e){return{preference:await jl(e,"plugins",PI),marketplace:await jl(e,"marketplaces",II)}}async function vI(e,t){return await Promise.all(t.map(async(n)=>{let r=await jl(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 O_(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",PI],["marketplace","marketplaces",II]]){let u=t.before[s],p=t.after[s],f=await jl(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=FI(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=NI(r,c,l,xj(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function R_(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 jl(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=FI(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=NI(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 jl(e,t,n){let r=gj(e,t,n),o=await Zr("holycodex-plugin-config",[Yr(Zt({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=yj(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function gj(e,t,n){let r=e[t];if(!hs(r))return;return r[n]}function yj(e,t){if(!hs(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!==bI)return;return{kind:"marketplace",source_type:"git",source:bI}}function xj(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function NI(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!hs(i))throw new N("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function FI(e,t,n){let r=e[t];if(!hs(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 hs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Pf(e,t,n=!1){let r=x_(e,t),o={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,model_verbosity:"low",developer_instructions:S_(n),suppress_unstable_features_warning:!0,"features.default_mode_request_user_input":!0,"features.multi_agent_v2":!0,"features.context_management":!0};for(let i of Za)o[`agents."${i}".config_file`]=`holycodex/agents/${i}.toml`;return o}async function Sj(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await es(e,n,a)).status==="drifted")o.push(a);continue}let c=Te(t,a),l=Te(e,a);if(c!==l)o.push(a)}if(o.length>0)throw new N("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function TI(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 Ui(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new N("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=Te(i,u);if(typeof p!=="string")continue;let f=p.replaceAll("\\","/").replace(/^\.\//u,"");if(f===`agents/${c}.toml`||f===`holycodex/agents/${c}.toml`)i=fl(i,u)}return{document:i,state:a}}async function EI(e,t){let o=t.managed["features.context_management.experimental_mode"];if(o===void 0)return{document:e,state:t};let i=Te(e,"features.context_management.experimental_mode"),a=Te(e,"features.context_management"),s=hs(a)?void 0:a;if(hs(a)&&Object.keys(a).some((p)=>p!=="experimental_mode"))throw new N("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 gr("features.context_management.experimental_mode",i);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new N("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 N("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 gr("features.context_management",s);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new N("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 N("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=fl(c,"features.context_management.experimental_mode"),s===void 0)c=dl(c,"features.context_management",i)}let l=Te(c,"features.context_management");if(l===void 0)throw new N("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 gr("features.context_management",l)},delete u["features.context_management.experimental_mode"],{document:c,state:{...t,managed:u}}}function _j(e,t){if(Te(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new N("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function bj(e,t){let n=await e.list();return t.map((r)=>{let o=$l(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function Ul(e,t){if(mt(ln,t)===void 0)throw new N("state_corrupt","The HolyCodex transaction state is invalid.");await Ko(e,Zt(t))}async function P_(e){await AI(e,{force:!1}).catch((t)=>{if(!ht(t,"ENOENT"))throw t})}async function wj(e,t){if(t===void 0){await AI(e,{force:!1}).catch((n)=>{if(!ht(n,"ENOENT"))throw n});return}await Qr(e,t)}async function vj(e,t,n,r,o,i=[]){let a=await Xt(e.configFile),s=eo(a),c=Pf(t,n,r);for(let[p,f]of Object.entries(c)){let h=Te(s,p);if(p==="developer_instructions"){if(typeof h!=="string"||await Tj(p,h)!==o.managed[p]?.lastManagedValue.value)throw new N("install_failed","The effective Root instructions did not converge.")}else if(h!==f)throw new N("install_failed",`The effective Codex setting ${p} did not converge.`)}let l=Ki(t,n);for(let p of l){let f=`agents."${p.name}".config_file`,h=Te(s,f);if(typeof h!=="string")throw new N("install_failed",`The ${p.name} registration is missing.`);let m=mj(e.roleRoot,`${p.name}.toml`),w=m.replaceAll("\\","/");if(hl(e.configFile,h).replaceAll("\\","/")!==w)throw new N("install_failed",`The ${p.name} registration is stale.`);let y=await Xt(m);if(y===void 0)throw new N("install_failed",`The ${p.name} role file is missing.`);if(i.includes(m))continue;let R=eo(y);if(R.name!==p.name||typeof R.description!=="string"||typeof R.model!=="string"||typeof R.model_reasoning_effort!=="string"||typeof R.service_tier!=="string"||typeof R.developer_instructions!=="string"||R.sandbox_mode!==(p.permissions.write?"workspace-write":"read-only")||R.approval_policy!=="never"||R.web_search!==(p.permissions.network?"live":"disabled")||R.tool_output_token_limit!==void 0||Te(R,"agents.enabled")!==!1||Te(R,"features.multi_agent_v2")!==!1||Te(R,"features.multi_agent")!==!1||Te(R,"features.computer_use")!==!1||Te(R,"features.browser_use")!==!1||Te(R,"features.in_app_browser")!==!1)throw new N("install_failed",`The ${p.name} role file is malformed.`)}let u=await Xt(`${e.codexHome}/agents/root.toml`);if(u!==void 0&&ps(u))throw new N("install_failed","A stale HolyCodex Root role remains installed.")}async function Tj(e,t){return await Zr("holycodex-managed-config-value",[Yr({keyPath:e,value:t})])}function Ej(e,t){let n={};for(let r of["computer_use","work","frontend","security"]){let o=t?.[r]??e?.[r];if(o!==void 0)n[r]=o}return n}function Oj(e){return["computer_use","work","frontend","security"].find((t)=>Xc[t].pluginIds.includes(e))}function OI(e){return(e?.official_plugins??[]).filter((t)=>{let n=Oj(t);return n===void 0||e?.optional_selections[n]!==!0})}async function Rj(e,t,n){for(let r of t){let o;try{o=$l(await e.list(),r)}catch(s){throw I_("list",s,r)}if(o?.installed&&!o.enabled)throw new Hl("uncertain",`${r} is disabled`);let i=!(o?.installed&&o.enabled);if(!(o?.installed&&o.enabled))try{await e.add(r)}catch(s){try{let c=$l(await e.list(),r);if(!RI(o,c))n?.(r,"uncertain")}catch{n?.(r,"uncertain")}throw I_("add",s,r)}let a;try{a=$l(await e.list(),r)}catch(s){if(i)n?.(r,"uncertain");throw I_("list",s,r)}if(!a?.installed){if(i&&!RI(o,a))n?.(r,"uncertain");throw new Hl("missing",`${r} is not installed after add`)}if(i&&a.enabled)n?.(r,"new");if(!a.enabled){if(i)n?.(r,"new");throw new Hl("uncertain",`${r} is disabled after add`)}}}function RI(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function I_(e,t,n){if(t instanceof Sr)return t;return new Sr(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 $l(e,t){let n=yr(e,t);if(n!==void 0)return n.entry;let r=Hn(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function kj(e,t){let n=e??t??"default";if(!fr(n).ok)throw new N("install_failed","Unknown profile.");return n}function Cj(e,t){let n=e??t??"standard";if(mt(Fi,n)===void 0)throw new N("install_failed","The tier is not supported.");return n}function Aj(e,t){let n=t?MI(t):ur,r=Nx(e,n);return{computer_use:r.computer_use,work:r.work,frontend:r.frontend,security:r.security,coding:!0}}function kI(e,t=new Map){return Object.fromEntries(["computer_use","work","frontend","security"].map((r)=>{let o=e[r],i={selected:o,status:o?t.get(r)??"healthy":"disabled",plugin_ids:[...Xc[r].pluginIds]};return[r,i]}))}async function If(e){let{profile:t,plan:n,...r}=e,o=n===void 0?{...r,profile:t}:{...r,plan:n};return await Zr("install-record",[Yr(Zt(o))])}async function Dl(e){return await LI(e)}async function LI(e){return await If({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.digest}function CI(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function zn(e,t){try{e.onProgress?.(t)}catch{}}var hj="davidbasilefilho/holycodex",br="holycodex@holycodex",bI="https://github.com/davidbasilefilho/holycodex.git",PI="holycodex@holycodex",II="holycodex",Hl,N;var ql=x(()=>{El();ut();Ol();Il();kf();Nl();Vi();as();cs();as();Hl=class Hl extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};N=class N 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 s1}from"readline/promises";ut();ut();ut();var rS=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:"work",kind:"boolean",usage:"--work / --no-work",description:"Work plugins (default: false)."},{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."}]),gP=new Set(["codex-home","profile","tier","add-plugin"]),sH=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","work","no-work","frontend","no-frontend","security","no-security"]);class ze extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Wd(e){if(e.length===0)throw new ze("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 Wd(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="upgrade"&&t!=="version")throw new ze("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 ze("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 ze("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!gP.has(u)&&!sH.has(u))throw new ze("invalid_argument","Unknown option.",{option:`--${c}`});if(gP.has(u)){let p=l??e[o+1];if(p===void 0||p.length===0||p.startsWith("-"))throw new ze("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 ze("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 ze("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new ze("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return cH(t,n,r),{command:t,positionals:n,options:r}}function cH(e,t,n){let r=uH(e);for(let s of Object.keys(n))if(!r.has(s))throw new ze("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 ze("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!fr(i).ok){let s=lH[i];if(s!==void 0)throw new ze("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 ze("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new ze("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 ze("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["work","no-work"],["frontend","no-frontend"],["security","no-security"]])if(n[s]!==void 0&&n[c]!==void 0)throw new ze("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove","upgrade"].includes(e)&&n.yes===!1)throw new ze("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","work","no-work","frontend","no-frontend","security","no-security","computer-use","no-computer-use","add-plugin"].includes(s)))throw new ze("invalid_argument",`Installation options are not valid for ${e}.`)}var lH={"plus-low":"low",plus:"default","plus-high":"high"};function uH(e){switch(e){case"install":return new Set([...rS.map((t)=>t.name),"no-work","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 pH=`HolyCodex
28
+ `)}`:`${o}: ${i}`}else o=n,i=bn(t,0),a=`${o}: ${i}`;if(r.length>0)a+=`
29
+ ${r.join(`
30
+ `)}`;super(i);this._tag=e,this.traces=r,this[nO]=aL,this.name=o,this.stack=a}pipe(){return E(this,arguments)}toString(){return this.stack}[re](){return this.stack}};aO=class aO extends Mg{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};sO=class sO extends Mg{constructor(e=[]){super("Interrupt","interrupted",e)}};oO=Symbol.for("effect/Micro/MicroFiber"),uL={_A:ce,_E:ce};cO=class cO{context;interruptible;[oO];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[oO]=uL}getRef(e){return Cw(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),ms;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(qg)}unsafePoll(){return this._exit}evaluate(e){if(this._exit)return;else if(this._yielded!==void 0){let n=this._yielded;this._yielded=void 0,n()}let t=this.runLoop(e);if(t===Lp)return;let r=iO.interruptChildren&&iO.interruptChildren(this);if(r!==void 0)return this.evaluate(Up(r,()=>t));this._exit=t;for(let n=0;n<this._observers.length;n++)this._observers[n](t);this._observers.length=0}runLoop(e){let t=!1,r=e;this.currentOpCount=0;try{while(!0){if(this.currentOpCount++,!t&&this.getRef($p).shouldYield(this)){t=!0;let n=r;r=Up(hL,()=>n)}if(r=r[Pg](this),r===Lp){let n=this._yielded;if(Dp in n)return this._yielded=void 0,n;return Lp}}}catch(n){if(!k(r,Pg))return Ig(`MicroFiber.runLoop: Not a valid effect: ${String(r)}`);return Ig(n)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let r=t[qp]&&t[qp](this);if(r)return{[e]:r};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Lp}children(){return this._children??=new Set}};iO=j("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),lO=Symbol.for("effect/Micro/identifier"),at=Symbol.for("effect/Micro/args"),Pg=Symbol.for("effect/Micro/evaluate"),Ma=Symbol.for("effect/Micro/successCont"),Ia=Symbol.for("effect/Micro/failureCont"),qp=Symbol.for("effect/Micro/ensureCont"),Lp=Symbol.for("effect/Micro/Yield"),pL={_A:ce,_E:ce,_R:ce},dL={...fv,_op:"Micro",[iL]:pL,pipe(){return E(this,arguments)},[Symbol.iterator](){return new Gi(new Sn(this))},toJSON(){return{_id:"Micro",op:this[lO],...at in this?{args:this[at]}:void 0}},toString(){return he(this)},[re](){return he(this)}};Fg=uO({op:"Success",prop:"value",eval(e){let t=e.getCont(Ma);return t?t[Ma](this[at],e):e.yieldWith(this)}}),pO=uO({op:"Failure",prop:"cause",eval(e){let t=e.getCont(Ia);while(lL(this[at])&&t&&e.interruptible)t=e.getCont(Ia);return t?t[Ia](this[at],e):e.yieldWith(this)}}),mL=Ng({op:"Yield",eval(e){let t=!1;return e.getRef($p).scheduleTask(()=>{if(t)return;e.evaluate(SL)},this[at]??0),e.yieldWith(()=>{t=!0})}}),hL=mL(0),gL=Fg(void 0),Lg=Ng({op:"WithMicroFiber",eval(e){return this[at](e)}}),Up=d(2,(e,t)=>{let r=Object.create(yL);return r[at]=e,r[Ma]=t,r}),yL=Hp({op:"OnSuccess",eval(e){return e._stack.push(this),this[at]}}),dO=Fg,Dg=pO,qg=Dg(cL()),SL=dO(void 0),bL="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);_L=d(2,(e,t)=>Lg((r)=>{let n=r.context;return r.context=t(n),EL(e,()=>(r.context=n,gL))})),fO=d(2,(e,t)=>_L(e,js(t)));mO=class mO extends Bs()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};$p=class $p extends Bs()("effect/Micro/currentScheduler",{defaultValue:()=>new Ug}){};wL=d(2,(e,t)=>{let r=Object.create(TL);return r[at]=e,r[Ma]=t.onSuccess,r[Ia]=t.onFailure,r}),TL=Hp({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[at]}}),EL=d(2,(e,t)=>OL((r)=>wL(r(e),{onFailure:(n)=>Up(t(Dg(n)),()=>pO(n)),onSuccess:(n)=>Up(t(dO(n)),()=>Fg(n))}))),hO=Ng({op:"SetInterruptible",ensure(e){if(e.interruptible=this[at],e._interrupted&&e.interruptible)return()=>qg}})});class jp{scheduleDrain;running=!1;tasks=new Hg;constructor(e){this.scheduleDrain=e}starveInternal=(e)=>{let t=this.tasks.buckets;this.tasks.buckets=[];for(let[r,n]of t)for(let o=0;o<n.length;o++)n[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 jp(e),r=new WeakMap;return(n)=>{if(n===void 0)return t;let o=r.get(n);if(o===void 0)o=new jp(e),r.set(n,o);return o}}}class Hg{buckets=[];scheduleTask(e,t){let r=this.buckets.length,n=void 0,o=0;for(;o<r;o++)if(this.buckets[o][0]<=t)n=this.buckets[o];else break;if(n&&n[0]===t)n[1].push(e);else if(o===r)this.buckets.push([t,[e]]);else this.buckets.splice(o,0,[t,[e]])}}class xO{maxNextTickBeforeTimer;getRunner=jp.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(rg)?e.getFiberRef(va):!1}scheduleTask(e,t,r){this.getRunner(r).scheduleTask(e,t)}}class bc{tasks=new Hg;deferred=!1;scheduleTask(e,t,r){if(this.deferred)SO.scheduleTask(e,t,r);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(rg)?e.getFiberRef(va):!1}flush(){while(this.tasks.buckets.length>0){let e=this.tasks.buckets;this.tasks.buckets=[];for(let[t,r]of e)for(let n=0;n<r.length;n++)r[n]()}this.deferred=!0}}var SO,Bp;var Vp=x(()=>{ot();SO=j(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new xO(2048));Bp=j(Symbol.for("effect/FiberRef/currentScheduler"),()=>_t(SO))});var zp;var $g=x(()=>{ot();zp=j(Symbol.for("effect/FiberRef/currentRequestMap"),()=>_t(new Map))});var jg=(e,t,r,n)=>{switch(e){case void 0:return t();case"unbounded":return r();case"inherit":return bi(dE,(o)=>o==="unbounded"?r():o>1?n(o):t());default:return e>1?n(e):t()}};var _O=x(()=>{ot()});var Bg=(e)=>e.replace(/[\s="]/g,"_"),wO=(e)=>(t)=>`${Bg(t.label)}=${e-t.startTime}ms`;var TO="effect/MetricLabel",Vg,EO,vO=(e,t)=>new EO(e,t),PL=(e)=>k(e,Vg);var OO=x(()=>{le();Me();_e();ge();Vg=Symbol.for(TO);EO=class EO{key;value;[Vg]=Vg;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=me(TO+this.key+this.value)}[M](){return this._hash}[I](e){return PL(e)&&this.key===e.key&&this.value===e.value}pipe(){return E(this,arguments)}}});var zg;var RO=x(()=>{fr();Ye();Op();zg=Or((e)=>Hs(e.context,lv)?e._tag==="Span"?zg(e.parent):C():N(e))});var kO;var CO=x(()=>{ot();kO=ig});var Kg="InterruptSignal",Wg="Stateful",Jg="Resume",Gg="YieldNow",Kp=(e)=>({_tag:"InterruptSignal",cause:e}),Na=(e)=>({_tag:"Stateful",onFiber:e}),Oi=(e)=>({_tag:"Resume",effect:e}),AO=()=>({_tag:"YieldNow"});var DL="effect/FiberScope",Wp,IO,MO,NO=(e)=>new MO(e.id(),e),_c;var Yg=x(()=>{ya();Wp=Symbol.for(DL);IO=class IO{[Wp]=Wp;fiberId=mr;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};MO=class MO{fiberId;parent;[Wp]=Wp;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(Na((r)=>{r.addChild(t),t.addObserver(()=>{r.removeChild(t)})}))}};_c=j(Symbol.for("effect/FiberScope/Global"),()=>new IO)});var HL="effect/Fiber",Zg,Xg,$L,jL="effect/Fiber",LO,Jp=(e)=>rp(oc(e.await),e.inheritAll),tW,Co="effect/FiberCurrent";var DO=x(()=>{ya();Ye();_e();ot();wn();Zg=Symbol.for(HL),Xg={_E:(e)=>e,_A:(e)=>e},$L={[Zg]:Xg,pipe(){return E(this,arguments)}},LO=Symbol.for(jL),tW={...oo,commit(){return Jp(this)},...$L,id:()=>mr,await:cc,children:pe([]),inheritAll:cc,poll:pe(C()),interruptAsFork:()=>cc}});var VL="effect/Logger",qO,UO,Gp=(e)=>({[qO]:UO,log:e,pipe(){return E(this,arguments)}}),oW,zL,KL=(e,t)=>({annotations:r,cause:n,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(zL)?m:e(m),u=(m,w)=>`${Bg(m)}=${l(w)}`,p=(m,w)=>" "+u(m,w),f=u("timestamp",o.toISOString());f+=p("level",a.label),f+=p("fiber",Cu(i));let h=um(s);for(let m=0;m<h.length;m++)f+=p("message",bn(h[m],t));if(!qm(n))f+=p("cause",Mr(n,{renderErrorCause:!0}));for(let m of c)f+=" "+wO(o.getTime())(m);for(let[m,w]of r)f+=p(m,bn(w,t));return f},WL=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,HO,Ri,iW,$O,aW,sW;var jO=x(()=>{Ve();H();Be();_e();ma();ah();qO=Symbol.for(VL),UO={_Message:(e)=>e,_Output:(e)=>e},oW={[qO]:UO,log:ms,pipe(){return E(this,arguments)}},zL=/^[^\s"=]*$/,HO=Gp(KL(WL)),Ri={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},iW={None:[],All:[],Trace:[Ri.gray],Debug:[Ri.blue],Info:[Ri.green],Warning:[Ri.yellow],Error:[Ri.red],Fatal:[Ri.bgBrightRed,Ri.black]},$O=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,aW=$O&&process.stdout.isTTY===!0,sW=$O||"Deno"in globalThis});var BO="effect/MetricBoundaries",Qg,VO,GL=(e)=>k(e,Qg),YL=(e)=>{let t=g(e,pm(rt(Number.POSITIVE_INFINITY)),xm);return new VO(t)},zO=(e)=>g(lm(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Ms,YL);var KO=x(()=>{Ve();Jr();le();H();Me();_e();ge();Qg=Symbol.for(BO);VO=class VO{values;[Qg]=Qg;constructor(e){this.values=e,this._hash=g(me(BO),J(Qt(this.values)))}_hash;[M](){return this._hash}[I](e){return GL(e)&&O(this.values,e.values)}pipe(){return E(this,arguments)}}});var XL="effect/MetricKeyType",WO,JO="effect/MetricKeyType/Counter",ey,QL="effect/MetricKeyType/Frequency",eD,tD="effect/MetricKeyType/Gauge",rD,GO="effect/MetricKeyType/Histogram",ty,nD="effect/MetricKeyType/Summary",oD,YO,ZO,XO,QO=(e)=>new ZO(e?.incremental??!1,e?.bigint??!1),eR=(e)=>new XO(e),ry=(e)=>k(e,ey),tR=(e)=>k(e,eD),rR=(e)=>k(e,rD),ny=(e)=>k(e,ty),nR=(e)=>k(e,oD);var oy=x(()=>{le();H();Me();_e();ge();WO=Symbol.for(XL),ey=Symbol.for(JO),eD=Symbol.for(QL),rD=Symbol.for(tD),ty=Symbol.for(GO),oD=Symbol.for(nD),YO={_In:(e)=>e,_Out:(e)=>e};ZO=class ZO{incremental;bigint;[WO]=YO;[ey]=ey;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=me(JO)}_hash;[M](){return this._hash}[I](e){return ry(e)}pipe(){return E(this,arguments)}};XO=class XO{boundaries;[WO]=YO;[ty]=ty;constructor(e){this.boundaries=e,this._hash=g(me(GO),J(v(this.boundaries)))}_hash;[M](){return this._hash}[I](e){return ny(e)&&O(this.boundaries,e.boundaries)}pipe(){return E(this,arguments)}}});var iD="effect/MetricKey",iR,aD,sD,Yp,cD=(e)=>k(e,iR),aR=(e,t)=>new Yp(e,QO(t),Tn(t?.description)),sR=(e,t,r)=>new Yp(e,eR(t),Tn(r)),cR;var lR=x(()=>{Ve();le();H();Me();Ye();_e();ge();oy();iR=Symbol.for(iD),aD={_Type:(e)=>e},sD=so(O);Yp=class Yp{name;keyType;description;tags;[iR]=aD;constructor(e,t,r,n=[]){this.name=e,this.keyType=t,this.description=r,this.tags=n,this._hash=g(me(this.name+this.description),J(v(this.keyType)),J(Qt(this.tags)))}_hash;[M](){return this._hash}[I](e){return cD(e)&&this.name===e.name&&O(this.keyType,e.keyType)&&O(this.description,e.description)&&sD(this.tags,e.tags)}pipe(){return E(this,arguments)}};cR=d(2,(e,t)=>t.length===0?e:new Yp(e.name,e.keyType,e.description,ao(e.tags,t)))});class pR{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 uR,uD,iy,dR=()=>{let e=Object.create(uD);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},Ao,pD=(e,t,r,n=!1)=>{for(let o=0,i=t.length;o<i;o++)if(r[I](t[o][0])){let a=t[o][1];if(n)t.splice(o,1),e.bucketsSize--;return N(a)}return C()},Fa,La,dD=(e,t,r)=>{for(let n=0,o=t.length;n<o;n++)if(r[I](t[n][0])){t.splice(n,1),e.bucketsSize--;return}};var fR=x(()=>{le();H();Me();Be();Ye();_e();uR=Symbol.for("effect/MutableHashMap"),uD={[uR]:uR,[Symbol.iterator](){return new iy(this)},toString(){return he(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(ue)}},[re](){return this.toJSON()},pipe(){return E(this,arguments)}};iy=class iy{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 pR(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new iy(this.self)}};Ao=d(2,(e,t)=>{if(ws(t)===!1)return e.referential.has(t)?N(e.referential.get(t)):C();let r=t[M](),n=e.buckets.get(r);if(n===void 0)return C();return pD(e,n,t)}),Fa=d(2,(e,t)=>Re(Ao(e,t))),La=d(3,(e,t,r)=>{if(ws(t)===!1)return e.referential.set(t,r),e;let n=t[M](),o=e.buckets.get(n);if(o===void 0)return e.buckets.set(n,[[t,r]]),e.bucketsSize++,e;return dD(e,o,t),o.push([t,r]),e.bucketsSize++,e})});var mD="effect/MetricState",wc,mR="effect/MetricState/Counter",ay,hR="effect/MetricState/Frequency",sy,gR="effect/MetricState/Gauge",cy,yR="effect/MetricState/Histogram",ly,xR="effect/MetricState/Summary",uy,Tc,SR,hD,bR,_R,wR,TR,ER=(e)=>new SR(e),vR=(e)=>new bR(e),OR=(e)=>new _R(e),RR=(e)=>new wR(e.buckets,e.count,e.min,e.max,e.sum),kR=(e)=>new TR(e.error,e.quantiles,e.count,e.min,e.max,e.sum),gD=(e)=>k(e,ay),yD=(e)=>k(e,sy),xD=(e)=>k(e,cy),SD=(e)=>k(e,ly),bD=(e)=>k(e,uy);var CR=x(()=>{Ve();le();H();Me();_e();ge();wc=Symbol.for(mD),ay=Symbol.for(mR),sy=Symbol.for(hR),cy=Symbol.for(gR),ly=Symbol.for(yR),uy=Symbol.for(xR),Tc={_A:(e)=>e};SR=class SR{count;[wc]=Tc;[ay]=ay;constructor(e){this.count=e}[M](){return g(v(mR),J(v(this.count)),oe(this))}[I](e){return gD(e)&&this.count===e.count}pipe(){return E(this,arguments)}};hD=so(O);bR=class bR{occurrences;[wc]=Tc;[sy]=sy;constructor(e){this.occurrences=e}_hash;[M](){return g(me(hR),J(Qt(ke(this.occurrences.entries()))),oe(this))}[I](e){return yD(e)&&hD(ke(this.occurrences.entries()),ke(e.occurrences.entries()))}pipe(){return E(this,arguments)}};_R=class _R{value;[wc]=Tc;[cy]=cy;constructor(e){this.value=e}[M](){return g(v(gR),J(v(this.value)),oe(this))}[I](e){return xD(e)&&this.value===e.value}pipe(){return E(this,arguments)}};wR=class wR{buckets;count;min;max;sum;[wc]=Tc;[ly]=ly;constructor(e,t,r,n,o){this.buckets=e,this.count=t,this.min=r,this.max=n,this.sum=o}[M](){return g(v(yR),J(v(this.buckets)),J(v(this.count)),J(v(this.min)),J(v(this.max)),J(v(this.sum)),oe(this))}[I](e){return SD(e)&&O(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return E(this,arguments)}};TR=class TR{error;quantiles;count;min;max;sum;[wc]=Tc;[uy]=uy;constructor(e,t,r,n,o,i){this.error=e,this.quantiles=t,this.count=r,this.min=n,this.max=o,this.sum=i}[M](){return g(v(xR),J(v(this.error)),J(v(this.quantiles)),J(v(this.count)),J(v(this.min)),J(v(this.max)),J(v(this.sum)),oe(this))}[I](e){return bD(e)&&this.error===e.error&&O(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return E(this,arguments)}}});var wD="effect/MetricHook",TD,ED,Ec=(e)=>({[TD]:ED,pipe(){return E(this,arguments)},...e}),AR,IR=(e)=>{let t=e.keyType.bigint?AR:0,r=e.keyType.incremental?e.keyType.bigint?(o)=>o>=AR:(o)=>o>=0:(o)=>!0,n=(o)=>{if(r(o))t=t+o};return Ec({get:()=>ER(t),update:n,modify:n})},MR=(e)=>{let t=new Map;for(let n of e.keyType.preregisteredWords)t.set(n,0);let r=(n)=>{let o=t.get(n)??0;t.set(n,o+1)};return Ec({get:()=>vR(t),update:r,modify:r})},NR=(e,t)=>{let r=t;return Ec({get:()=>OR(r),update:(n)=>{r=n},modify:(n)=>{r=r+n}})},FR=(e)=>{let t=e.keyType.boundaries.values,r=t.length,n=new Uint32Array(r+1),o=new Float64Array(r),i=0,a=0,{MAX_VALUE:s,MIN_VALUE:c}=Number;g(t,vn(en),kr((p,f)=>{o[f]=p}));let l=(p)=>{let f=0,h=r;while(f!==h){let m=Math.floor(f+(h-f)/2),w=o[m];if(p<=w)h=m;else f=m;if(h===f+1)if(p<=o[f])h=f;else f=h}if(n[f]=n[f]+1,i=i+1,a=a+p,p<s)s=p;if(p>c)c=p},u=()=>{let p=ri(r),f=0;for(let h=0;h<r;h++){let m=o[h],w=n[h];f=f+w,p[h]=[m,f]}return p};return Ec({get:()=>RR({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},LR=(e)=>{let{error:t,maxAge:r,maxSize:n,quantiles:o}=e.keyType,i=g(o,vn(en)),a=ri(n),s=0,c=0,l=0,u=0,p=0,f=(m)=>{let w=[],S=0;while(S!==n-1){let y=a[S];if(y!=null){let[R,P]=y,z=Tu(m-R);if(jw(z,Qm)&&$w(z,r))w.push(P)}S=S+1}return vD(t,i,vn(w,en))},h=(m,w)=>{if(n>0){s=s+1;let S=s%n;a[S]=[w,m]}u=c===0?m:Math.min(u,m),p=c===0?m:Math.max(p,m),c=c+1,l=l+m};return Ec({get:()=>kR({error:t,quantiles:f(Date.now()),count:c,min:u,max:p,sum:l}),update:([m,w])=>h(m,w),modify:([m,w])=>h(m,w)})},vD=(e,t,r)=>{let n=r.length;if(!we(t))return On();let o=t[0],i=t.slice(1),a=PR(e,n,C(),0,o,r),s=kt(a);return i.forEach((c)=>{s.push(PR(e,n,a.value,a.consumed,c,a.rest))}),kr(s,(c)=>[c.quantile,c.value])},PR=(e,t,r,n,o,i)=>{let a=e,s=t,c=r,l=n,u=o,p=i,f=e,h=t,m=r,w=n,S=o,y=i;while(!0){if(!we(p))return{quantile:u,value:C(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:N(mm(p)),consumed:l+p.length,rest:[]};let R=tt(p),P=O_(p,(F)=>F===R),z=u*s,Y=a/2*z,D=l+P[0].length,te=Math.abs(D-z);if(D<z-Y){f=a,h=s,m=En(p),w=D,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}if(D>z+Y){let F=Ne(c)?N(R):c;return{quantile:u,value:F,consumed:l,rest:p}}switch(c._tag){case"None":{f=a,h=s,m=En(p),w=D,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}case"Some":{let F=Math.abs(z-c.value);if(te<F){f=a,h=s,m=En(p),w=D,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}return{quantile:u,value:N(c.value),consumed:l,rest:p}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var DR=x(()=>{Ve();th();H();gc();Ye();_e();CR();TD=Symbol.for(wD),ED={_In:(e)=>e,_Out:(e)=>e},AR=BigInt(0)});var RD="effect/MetricPair",kD,CD,qR=(e,t)=>({[kD]:CD,metricKey:e,metricState:t,pipe(){return E(this,arguments)}});var UR=x(()=>{_e();kD=Symbol.for(RD),CD={_Type:(e)=>e}});var PD="effect/MetricRegistry",HR,$R,jR=()=>new $R;var BR=x(()=>{H();fR();Ye();DR();oy();UR();HR=Symbol.for(PD);$R=class $R{[HR]=HR;map=dR();snapshot(){let e=[];for(let[t,r]of this.map)e.push(qR(t,r.get()));return e}get(e){let t=g(this.map,Ao(e),Bt);if(t==null){if(ry(e.keyType))return this.getCounter(e);if(rR(e.keyType))return this.getGauge(e);if(tR(e.keyType))return this.getFrequency(e);if(ny(e.keyType))return this.getHistogram(e);if(nR(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=g(this.map,Ao(e),Bt);if(t==null){let r=IR(e);if(!g(this.map,Fa(e)))g(this.map,La(e,r));t=r}return t}getFrequency(e){let t=g(this.map,Ao(e),Bt);if(t==null){let r=MR(e);if(!g(this.map,Fa(e)))g(this.map,La(e,r));t=r}return t}getGauge(e){let t=g(this.map,Ao(e),Bt);if(t==null){let r=NR(e,e.keyType.bigint?BigInt(0):0);if(!g(this.map,Fa(e)))g(this.map,La(e,r));t=r}return t}getHistogram(e){let t=g(this.map,Ao(e),Bt);if(t==null){let r=FR(e);if(!g(this.map,Fa(e)))g(this.map,La(e,r));t=r}return t}getSummary(e){let t=g(this.map,Ao(e),Bt);if(t==null){let r=LR(e);if(!g(this.map,Fa(e)))g(this.map,La(e,r));t=r}return t}}});var MD="effect/Metric",ND,FD,VR,zR=function(e,t,r,n){let o=Object.assign((i)=>Qu(i,(a)=>DD(o,a)),{[ND]:FD,keyType:e,unsafeUpdate:t,unsafeValue:r,unsafeModify:n,register(){return this.unsafeValue([]),this},pipe(){return E(this,arguments)}});return o},vc=(e,t)=>KR(aR(e,t)),KR=(e)=>{let t,r=new WeakMap,n=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=VR.get(e),t}let i=r.get(o);if(i!==void 0)return i;return i=VR.get(cR(e,o)),r.set(o,i),i};return zR(e.keyType,(o,i)=>n(i).update(o),(o)=>n(o).get(),(o,i)=>n(i).modify(o))},WR=(e,t,r)=>KR(sR(e,t,r)),JR,LD,DD;var GR=x(()=>{Ve();H();_e();ot();lR();OO();BR();ND=Symbol.for(MD),FD={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},VR=j(Symbol.for("effect/Metric/globalMetricRegistry"),()=>jR()),JR=d(3,(e,t,r)=>LD(e,[vO(t,r)])),LD=d(2,(e,t)=>zR(e.keyType,(r,n)=>e.unsafeUpdate(r,ao(t,n)),(r)=>e.unsafeValue(ao(t,r)),(r,n)=>e.unsafeModify(r,ao(t,n)))),DD=d(2,(e,t)=>bi(uc,(r)=>L(()=>e.unsafeUpdate(t,r))))});var UD="effect/Request",HD,$D,qW,YR;var ZR=x(()=>{H();$g();ot();wn();HD=Symbol.for(UD),$D={_E:(e)=>e,_A:(e)=>e},qW={...ks,[HD]:$D},YR=d(2,(e,t)=>bi(zp,(r)=>L(()=>{if(r.has(e)){let n=r.get(e);if(!n.state.completed)n.state.completed=!0,pp(n.result,t)}})))});var jD="effect/Supervisor",Zp,py,Xp,Qp,dy=(e)=>k(e,Zp)&&bs(e,"Zip"),XR,BD=(e)=>new XR(e),ki;var ed=x(()=>{H();ge();ot();Zp=Symbol.for(jD),py={_T:(e)=>e};Xp=class Xp{underlying;value0;[Zp]=py;constructor(e,t){this.underlying=e,this.value0=t}get value(){return this.value0}onStart(e,t,r,n){this.underlying.onStart(e,t,r,n)}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 Xp(this,g(this.value,ze(e)))}zip(e){return new Qp(this,e)}};Qp=class Qp{left;right;_tag="Zip";[Zp]=py;constructor(e,t){this.left=e,this.right=t}get value(){return tp(this.left.value,this.right.value)}onStart(e,t,r,n){this.left.onStart(e,t,r,n),this.right.onStart(e,t,r,n)}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 Xp(this,g(this.value,ze(e)))}zip(e){return new Qp(this,e)}};XR=class XR{effect;[Zp]=py;constructor(e){this.effect=e}get value(){return this.effect}onStart(e,t,r,n){}onEnd(e,t){}onEffect(e,t){}onSuspend(e){}onResume(e){}map(e){return new Xp(this,g(this.value,ze(e)))}zip(e){return new Qp(this,e)}onRun(e,t){return e()}};ki=j("effect/Supervisor/none",()=>BD(nt))});var QR;var ek=x(()=>{qu();QR=So});var tk="Empty",rk="AddSupervisor",nk="RemoveSupervisor",ok="AndThen",Da,td=(e,t)=>({_tag:ok,first:e,second:t}),zD=(e,t)=>KD(t,rt(e)),KD=(e,t)=>{let r=e,n=t;while(Cr(n)){let o=Ar(n);switch(o._tag){case tk:{n=Pr(n);break}case rk:{r=r.zip(o.supervisor),n=Pr(n);break}case nk:{r=my(r,o.supervisor),n=Pr(n);break}case ok:{n=Ct(o.first)(Ct(o.second)(Pr(n)));break}}}return r},my=(e,t)=>{if(O(e,t))return ki;else if(dy(e))return my(e.left,t).zip(my(e.right,t));else return e},rd=(e)=>{if(O(e,ki))return Gr();else if(dy(e))return g(rd(e.left),Pn(rd(e.right)));else return ai(e)},WD=(e,t)=>{if(O(e,t))return Da;let r=rd(e),n=rd(t),o=g(n,Nm(r),ci(Da,(a,s)=>td(a,{_tag:rk,supervisor:s}))),i=g(r,Nm(n),ci(Da,(a,s)=>td(a,{_tag:nk,supervisor:s})));return td(o,i)},ik;var ak=x(()=>{Jr();ek();le();H();li();ed();Da={_tag:tk},ik=QR({empty:Da,patch:zD,combine:td,diff:WD})});var nq,sk,oq,iq,aq,Oc="Continue",sq="Done",ck="Yield",cq,nd=(e)=>{throw Error(`BUG: FiberRuntime - ${bn(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Hn,$n,Rc,lq,uq=(e)=>xi(IT(e),(t)=>Ci(NT(t),([r,n])=>{let o=new Map,i=[];for(let s of n){i.push(kn(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return vo(vq(r.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),zp,o)},!1,!1)),pq,od,dq,fq=(e)=>Gp((t)=>{let r=Ev(t.context,xc);Hs(r,Ep).unsafe.log(e.log(t))}),mq,hq,gq,pk,dk=(e,t,r)=>Ce(()=>{let n=ke(e),o=Array(n.length);return Eo(Ci(n,(a,s)=>B(t(a,s),(c)=>L(()=>o[s]=c)),r,!1),pe(o))}),Ci=(e,t,r,n,o)=>To((i)=>Zh((a)=>bt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return nt;let u=0,p=!1,f=o?Math.min(c.length,o):c.length,h=new Set,m=[],w=()=>h.forEach((F)=>{F.currentScheduler.scheduleTask(()=>{F.unsafeInterruptAsFork(s.id())},0,F)}),S=[],y=[],R=[],P=()=>{let F=m.filter(({exit:ie})=>ie._tag==="Failure").sort((ie,ae)=>ie.index<ae.index?-1:ie.index===ae.index?0:1).map(({exit:ie})=>ie);if(F.length===0)F.push(yr);return F},z=(F,ie=!1)=>{let ae=ep(a(F)),ee=xq(ae,s,s.currentRuntimeFlags,_c);return s.currentScheduler.scheduleTask(()=>{if(ie)ee.unsafeInterruptAsFork(s.id());ee.resume(ae)},0,ee),ee},Y=()=>{if(!n)l-=c.length,c=[];p=!0,w()},D=r?Yh:wo,te=z(_o((F)=>{let ie=(ee,Oe)=>{if(ee._op==="Blocked")R.push(ee);else if(m.push({index:Oe,exit:ee}),ee._op==="Failure"&&!p)Y()},ae=()=>{if(c.length>0){let ee=c.pop(),Oe=u++,yt=()=>{let We=c.pop();return Oe=u++,B(sc(),()=>B(D(i(t(We,Oe))),vt))},vt=(We)=>{if(c.length>0){if(ie(We,Oe),c.length>0)return yt()}return pe(We)},Ot=B(D(i(t(ee,Oe))),vt),$e=z(Ot);if(S.push($e),h.add($e),p)$e.currentScheduler.scheduleTask(()=>{$e.unsafeInterruptAsFork(s.id())},0,$e);$e.addObserver((We)=>{let je;if(We._op==="Failure")je=We;else je=We.effect_instruction_i0;if(y.push($e),h.delete($e),ie(je,Oe),m.length===l)F(pe(ve(Ei(P(),{parallel:!0}),()=>yr)));else if(R.length+m.length===l){let yn=P(),zi=R.map((lr)=>lr.effect_instruction_i0).reduce(qh);F(pe(Ju(zi,Ci([ve(Ei(yn,{parallel:!0}),()=>yr),...R.map((lr)=>lr.effect_instruction_i1)],(lr)=>lr,r,!0,o))))}else ae()})}};for(let ee=0;ee<f;ee++)ae()}));return qn(Ea(oc(i(Jp(te))),lp({onFailure:(F)=>{Y();let ie=R.length+1,ae=Math.min(typeof o==="number"?o:R.length,R.length),ee=Array.from(R);return _o((Oe)=>{let yt=[],vt=0,Ot=0,$e=(je,yn)=>(zi)=>{if(yt[je]=zi,vt++,vt===ie)Oe(Ie(Te(F)));if(ee.length>0&&yn)We()},We=()=>{z(ee.pop(),!0).addObserver($e(Ot,!0)),Ot++};te.addObserver($e(Ot,!1)),Ot++;for(let je=0;je<ae;je++)We()})},onSuccess:()=>gr(y,(F)=>F.inheritAll)})))}))),hy=(e,t,r,n)=>Ce(()=>{let o=ke(e),i=Array(o.length);return Eo(Ci(o,(s,c)=>ze(r(s,c),(l)=>i[c]=l),n,!1,t),pe(i))}),xy=(e)=>Sq(e,_c),yq=(e,t,r,n=null)=>{let o=fk(e,t,r,n);return o.resume(e),o},xq=(e,t,r,n=null)=>fk(e,t,r,n),fk=(e,t,r,n=null)=>{let o=Au(),i=t.getFiberRefs(),a=Og(i,o),s=new od(o,a,r),c=Ro(a,wi),l=s.currentSupervisor;return l.onStart(c,e,N(t),s),s.addObserver((p)=>l.onEnd(p,s)),(n!==null?n:g(t.getFiberRef(Wu),ve(()=>t.scope()))).add(r,s),s},Sq=(e,t)=>bt((r,n)=>pe(yq(e,r,n.runtimeFlags,t))),gy=(e)=>vi((t)=>Ge(yo(t,kc),{onNone:()=>e,onSome:(r)=>{switch(r.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return B(Oa(r,Cp),(n)=>Sy(e,n))}}})),lk=(e)=>(t)=>vi((r)=>Ge(yo(r,kc),{onNone:()=>t,onSome:(n)=>{if(n.strategy._tag==="ParallelN"&&n.strategy.parallelism===e)return t;return B(Oa(n,Ap(e)),(o)=>Sy(t,o))}})),qa=(e,t)=>(r)=>vi((n)=>Ge(yo(n,kc),{onNone:()=>r(ce),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?gy:e._tag==="Sequential"?yy:lk(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(r(gy));case"Sequential":return i(r(yy));case"ParallelN":return i(r(lk(o.strategy.parallelism)))}}else return r(ce)}})),yy=(e)=>vi((t)=>Ge(yo(t,kc),{onNone:()=>e,onSome:(r)=>{switch(r.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return B(Oa(r,kp),(n)=>Sy(e,n))}}})),kc,bq=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},_q,wq=(e=Aa)=>{let t=Object.create(_q);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},Sy,Tq=(e)=>_i(e,{differ:ik,fork:Da}),uk,Eq,mk,vq=(e,t,r)=>nc((n)=>mk(B(xy(Zu(e)),(o)=>_o((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"&&Ra(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&yu(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),r?.(),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(),L(()=>{c.forEach((l)=>l())})})),Ce(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return xi(o,(i)=>YR(i.request,sg(n)))})));var by=x(()=>{Ve();Jr();fr();Sg();Sv();ya();Cg();Uv();Qv();H();li();Be();rO();yO();Ye();_e();ge();Lh();Vp();ro();FT();ma();mg();$g();_O();RO();ot();uv();gg();Rp();DO();Pp();Yg();jO();GR();KO();ZR();ec();ec();ed();ak();Op();nq=vc("effect_fiber_started",{incremental:!0}),sk=vc("effect_fiber_active"),oq=vc("effect_fiber_successes",{incremental:!0}),iq=vc("effect_fiber_failures",{incremental:!0}),aq=JR(WR("effect_fiber_lifetimes",zO({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),cq={_E:(e)=>e,_A:(e)=>e},Hn=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),$n=j("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Rc={[Yi]:(e,t,r)=>St(()=>t.effect_instruction_i1(r)),["OnStep"]:(e,t,r)=>Ie(Ie(r)),[Zi]:(e,t,r)=>St(()=>t.effect_instruction_i2(r)),[Os]:(e,t,r)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),Ln(e.currentRuntimeFlags)&&e.isInterrupted())return Te(e.getInterruptedCause());else return Ie(r)},[Xi]:(e,t,r)=>{if(St(()=>t.effect_instruction_i2(r)),St(()=>t.effect_instruction_i0()))return e.pushStack(t),St(()=>t.effect_instruction_i1());else return nt},[Qi]:(e,t,r)=>{while(!0){let n=St(()=>t.effect_instruction_i0.next(r));if(n.done)return Ie(n.value);let o=zf(n.value);if(!Ra(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;r=o.value}}},lq={[Kg]:(e,t,r,n)=>(e.processNewInterruptSignal(n.cause),Ln(t)?Te(n.cause):r),[Jg]:(e,t,r,n)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[Wg]:(e,t,r,n)=>(n.onFiber(e,Ag(t)),r),[Gg]:(e,t,r,n)=>B(sc(),()=>r)},pq=Rs();od=class od extends xg{[Zg]=Xg;[LO]=cq;_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,r){super();if(this.currentRuntimeFlags=r,this._fiberId=e,this._fiberRefs=t,Ph(r)){let n=this.getFiberRef(uc);nq.unsafeUpdate(1,n),sk.unsafeUpdate(1,n)}this.refreshRefCache()}commit(){return Jp(this)}id(){return this._fiberId}resume(e){this.tell(Oi(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(Xv(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(pc)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return Ce(()=>{let t=xE(this._fiberId);return this.tell(Na((r,n)=>{pp(t,L(()=>e(r,n)))})),up(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return _o((e)=>{let t=(r)=>e(pe(r));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(Na((r,n)=>{if(r._exitValue!==null)t(this._exitValue);else r.addObserver(t)})),L(()=>this.tell(Na((r,n)=>{r.removeObserver(t)})))},this.id())}get inheritAll(){return bt((e,t)=>{let r=e.id(),n=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=vg(n,r,i);e.setFiberRefs(a);let s=e.getFiberRef(uk),c=g(Xs(o,s),Fh(Fn),Fh($u));return Xh(c)})}get poll(){return L(()=>Tn(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return L(()=>this.tell(Kp(Ir(e))))}unsafeInterruptAsFork(e){this.tell(Kp(Ir(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=Sc(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=Pa(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(xc),this.currentTracer=this.currentDefaultServices.unsafeMap.get(yc.key),this.currentSupervisor=this.getFiberRef(Eq),this.currentScheduler=this.getFiberRef(Bp),this.currentContext=this.getFiberRef(wi),this.currentSpan=this.currentContext.unsafeMap.get(vp.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 r of t)if(r._exitValue===null)e.add(this.currentRuntimeFlags,r)}}drainQueueOnCurrentThread(){let e=!0;while(e){let t=Oc,r=globalThis[Co];globalThis[Co]=this;try{while(t===Oc)t=this._queue.length===0?sq:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Co]=r}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(va),this)}drainQueueWhileRunning(e,t){let r=t;while(this._queue.length>0){let n=this._queue.splice(0,1)[0];r=lq[n._tag](this,e,r,n)}return r}isInterrupted(){return!gu(this.getFiberRef(pc))}addInterruptedCause(e){let t=this.getFiberRef(pc);this.setFiberRef(pc,At(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(Kp(Ir(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return ac({while:()=>!t,body:()=>{let n=e.next();if(!n.done)return qn(n.value.await);else return L(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(Ph(this.currentRuntimeFlags)){let t=this.getFiberRef(uc),r=this.id().startTimeMillis,n=Date.now();switch(aq.unsafeUpdate(n-r,t),sk.unsafeUpdate(-1,t),e._tag){case jt:{oq.unsafeUpdate(1,t);break}case $t:{iq.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(mE);if(!fa(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(gq)}log(e,t,r){let n=Re(r)?r.value:this.getFiberRef(ng),o=this.getFiberRef(dq);if(eO(o,n))return;let i=this.getFiberRef(uE),a=this.getFiberRef(lE),s=this.getLoggers(),c=this.getFiberRefs();if(Ls(s)>0){let l=Hs(this.getFiberRef(xc),hc),u=new Date(l.unsafeCurrentTimeMillis());Kb(c,()=>{for(let p of s)p.log({fiberId:this.id(),logLevel:n,message:e,cause:t,context:c,spans:i,annotations:a,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case Gg:return ck;case Kg:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Te(e.cause)),this._asyncInterruptor=null;return Oc}case Jg:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),Oc;case Wg:return e.onFiber(this,this._exitValue!==null?Yv:Zv(this.currentRuntimeFlags,this._asyncBlockingOn)),Oc;default:return nd(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=Ln(this.currentRuntimeFlags)&&this.isInterrupted()?Te(this.getInterruptedCause()):e;while(t!==null){let r=t,n=this.runLoop(r);if(n===Hn){let o=$n.currentOp;if($n.currentOp=null,o._op===ea)if(kT(this.currentRuntimeFlags))this.tell(AO()),this.tell(Oi(yr)),t=null;else t=yr;else if(o._op===Qo)t=null}else{this.currentRuntimeFlags=g(this.currentRuntimeFlags,kh($u));let o=this.interruptAllChildren();if(o!==null)t=B(o,()=>n);else{if(this._queue.length===0)this.setExitValue(n);else this.tell(Oi(n));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Co];globalThis[Co]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Co]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(Oi(e))}startFork(e){this.tell(Oi(e))}patchRuntimeFlags(e,t){let r=Qs(e,t);return globalThis[Co]=this,this.currentRuntimeFlags=r,r}initiateAsync(e,t){let r=!1,n=(o)=>{if(!r)r=!0,this.tell(Oi(o))};if(Ln(e))this._asyncInterruptor=n;try{t(n)}catch(o){n(Pt(rr(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!==vs)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==Yi&&e._op!==Xi&&e._op!==Qi)return e;e=this.popStack()}}[Jb](e){return L(()=>$s(this.currentContext,e))}["Left"](e){return ft(e.left)}["None"](e){return ft(new dc)}["Right"](e){return Ie(e.right)}["Some"](e){return Ie(e.value)}["Micro"](e){return tc((t)=>{let r=t,n=gO(fO(e,this.currentContext));return n.addObserver((o)=>{if(o._tag==="Success")return r(Ie(o.value));switch(o.cause._tag){case"Interrupt":return r(Te(Ir(mr)));case"Fail":return r(ft(o.cause.error));case"Die":return r(Yu(o.cause.defect))}}),tc((o)=>{r=(i)=>{o(nt)},n.unsafeInterrupt()})})}[zl](e){let t=St(()=>e.effect_instruction_i0()),r=this.getNextSuccessCont();if(r!==void 0){if(!(r._op in Rc))nd(r);return Rc[r._op](this,r,t)}else return $n.currentOp=Ie(t),Hn}[jt](e){let t=e,r=this.getNextSuccessCont();if(r!==void 0){if(!(r._op in Rc))nd(r);return Rc[r._op](this,r,t.effect_instruction_i0)}else return $n.currentOp=t,Hn}[$t](e){let t=e.effect_instruction_i0,r=this.getNextFailCont();if(r!==void 0)switch(r._op){case vs:case Zi:if(!(Ln(this.currentRuntimeFlags)&&this.isInterrupted()))return St(()=>r.effect_instruction_i1(t));else return Te(Su(t));case"OnStep":if(!(Ln(this.currentRuntimeFlags)&&this.isInterrupted()))return Ie(Te(t));else return Te(Su(t));case Os:if(this.patchRuntimeFlags(this.currentRuntimeFlags,r.patch),Ln(this.currentRuntimeFlags)&&this.isInterrupted())return Te(At(t,this.getInterruptedCause()));else return Te(t);default:nd(r)}else return $n.currentOp=Te(t),Hn}[Kl](e){return St(()=>e.effect_instruction_i0(this,Ag(this.currentRuntimeFlags)))}["Blocked"](e){let t=this.getFiberRefs(),r=this.currentRuntimeFlags;if(this._steps.length>0){let n=[],o=this._steps[this._steps.length-1],i=this.popStack();while(i&&i._op!=="OnStep")n.push(i),i=this.popStack();this.setFiberRefs(o.refs),this.currentRuntimeFlags=o.flags;let a=Dv(o.refs,t),s=Xs(o.flags,r);return Ie(Ju(e.effect_instruction_i0,bt((c)=>{while(n.length>0)c.pushStack(n.pop());return c.setFiberRefs(qv(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=Qs(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return To((n)=>B(xy(jh(e.effect_instruction_i0)),()=>n(e.effect_instruction_i1)))}["RunBlocked"](e){return uq(e.effect_instruction_i0)}[ti](e){let t=e.effect_instruction_i0,r=this.currentRuntimeFlags,n=Qs(r,t);if(Ln(n)&&this.isInterrupted())return Te(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Xs(n,r);return this.pushStack(new Bh(o,e)),St(()=>e.effect_instruction_i1(r))}else return yr}[Yi](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[vs](e){return this.pushStack(e),e.effect_instruction_i0}[Zi](e){return this.pushStack(e),e.effect_instruction_i0}[Qo](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),$n.currentOp=e,Hn}[ea](e){return this._isYielding=!1,$n.currentOp=e,Hn}[Xi](e){let{effect_instruction_i0:t,effect_instruction_i1:r}=e;if(t())return this.pushStack(e),r();else return yr}[Qi](e){return Rc[Qi](this,e,void 0)}[ei](e){return St(()=>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 r=this.currentScheduler.shouldYield(this);if(r!==!1){this._isYielding=!0,this.currentOpCount=0;let n=t;t=B(sc({priority:r}),()=>n)}}try{if(t=this.currentTracer.context(()=>{if(pq!==t[bo]._V){let r=this.getFiberRef(hE);if(r._tag==="Some"){let n=t[bo]._V;this.log(`Executing an Effect versioned ${n} with a Runtime of version ${Rs()}, 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`,In,r)}}return this[t._op](t)},this),t===Hn){let r=$n.currentOp;if(r._op===ea||r._op===Qo)return Hn;return $n.currentOp=null,r._op===jt||r._op===$t?r:Te(rr(r))}}catch(r){if(t!==Hn&&!k(t,"_op")||!(t._op in this))t=Wh(`Not a valid effect: ${bn(t)}`);else if(gE(r))t=Te(At(rr(r),Ir(mr)));else t=Yu(r)}}}run=()=>{this.drainQueueOnCurrentThread()}};dq=j("effect/FiberRef/currentMinimumLogLevel",()=>_t(tO("Info"))),mq=j(Symbol.for("effect/Logger/defaultLogger"),()=>fq(HO)),hq=j(Symbol.for("effect/Logger/tracerLogger"),()=>Gp(({annotations:e,cause:t,context:r,fiberId:n,logLevel:o,message:i})=>{let a=zg(yo(Ro(r,wi),vp));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=$s(Ro(r,xc),hc),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=Xw(n),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=Mr(t,{renderErrorCause:!0});a.value.event(bn(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),gq=j(Symbol.for("effect/FiberRef/currentLoggers"),()=>sE(ai(mq,hq))),pk=d((e)=>$f(e[0]),(e,t,r)=>bt((n)=>{let o=r?.batching===!0||r?.batching==="inherit"&&n.getFiberRef(fE);if(r?.discard)return jg(r.concurrency,()=>qa(kp,r?.concurrentFinalizers)((i)=>o?Ci(e,(a,s)=>i(t(a,s)),!0,!1,1):xi(e,(a,s)=>i(t(a,s)))),()=>qa(Cp,r?.concurrentFinalizers)((i)=>Ci(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>qa(Ap(i),r?.concurrentFinalizers)((a)=>Ci(e,(s,c)=>a(t(s,c)),o,!1,i)));return jg(r?.concurrency,()=>qa(kp,r?.concurrentFinalizers)((i)=>o?hy(e,1,(a,s)=>i(t(a,s)),!0):gr(e,(a,s)=>i(t(a,s)))),()=>qa(Cp,r?.concurrentFinalizers)((i)=>dk(e,(a,s)=>i(t(a,s)),o)),(i)=>qa(Ap(i),r?.concurrentFinalizers)((a)=>hy(e,i,(s,c)=>a(t(s,c)),o)))})),kc=Vt("effect/Scope"),_q={[ip]:ip,[ap]:ap,pipe(){return E(this,arguments)},fork(e){return L(()=>{let t=wq(e);if(this.state._tag==="Closed")return t.state=this.state,t;let r={},n=(o)=>t.close(o);return this.state.finalizers.set(r,n),bq(t,(o)=>L(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(r)})),t})},close(e){return Ce(()=>{if(this.state._tag==="Closed")return nt;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return nt;return bg(this.strategy)?g(gr(t,(r)=>wo(r(e))),B((r)=>g(Ei(r),vr(fc),ve(()=>yr)))):_g(this.strategy)?g(dk(t,(r)=>wo(r(e)),!1),B((r)=>g(Ei(r,{parallel:!0}),vr(fc),ve(()=>yr)))):g(hy(t,this.strategy.parallelism,(r)=>wo(r(e)),!1),B((r)=>g(Ei(r,{parallel:!0}),vr(fc),ve(()=>yr))))})},addFinalizer(e){return Ce(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),nt})}},Sy=d(2,(e,t)=>lg(e,js(Nw(kc,t)))),uk=cE(CT),Eq=Tq(ki),mk=d(2,(e,t)=>To((r)=>hr(r(e),{onFailure:(n)=>hr(t,{onFailure:(o)=>Pt(At(n,o)),onSuccess:()=>Pt(n)}),onSuccess:(n)=>Dn(t,n)})))});var gk,yk;var xk=x(()=>{ot();gk=og,yk=Oa});class wk{context;runtimeFlags;fiberRefs;constructor(e,t,r){this.context=e,this.runtimeFlags=t,this.fiberRefs=r}pipe(){return E(this,arguments)}}var wy=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(r,...n)=>e(t,r,...n)}return e.apply(this,arguments)},Sk,Cq,bk,Aq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let r=new bk(e);return Error.stackTraceLimit=t,r},_y,id,_k,Pq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let r=new _k(e);return Error.stackTraceLimit=t,r},Iq=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return mc(t.left);case"Right":return Ie(t.right);case"Some":return Ie(t.value);case"None":return mc(new dc)}},Mq,Nq=(e)=>new wk(e.context,e.runtimeFlags,e.fiberRefs),Fq,Tk,Ek,vk;var Ok=x(()=>{fr();le();ya();Cg();Be();Ye();_e();Vp();xk();ma();ot();Rp();by();Yg();ec();ed();Sk=wy((e,t,r)=>{let n=Au(),o=[[wi,[[n,e.context]]]];if(r?.scheduler)o.push([Bp,[[n,r.scheduler]]]);let i=vv(e.fiberRefs,{entries:o,forkAs:n});if(r?.updateRefs)i=r.updateRefs(i,n);let a=new od(n,i,e.runtimeFlags),s=t;if(r?.scope)s=B(yk(r.scope,Aa),(l)=>Eo(sp(l,nc((u)=>O(u,a.id())?nt:lc(a,u))),Ea(t,(u)=>gk(l,u))));let c=a.currentSupervisor;if(c!==ki)c.onStart(e.context,s,C(),a),a.addObserver((l)=>c.onEnd(l,a));if(_c.add(e.runtimeFlags,a),r?.immediate===!1)a.resume(s);else a.start(s);return a}),Cq=wy((e,t)=>{let r=Mq(e)(t);if(r._tag==="Failure")throw Pq(r.effect_instruction_i0);return r.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}};_y=Symbol.for("effect/Runtime/FiberFailure"),id=Symbol.for("effect/Runtime/FiberFailure/Cause");_k=class _k extends Error{[_y];[id];constructor(e){let t=Ds(e)[0];super(t?.message||"An error has occurred");if(this[_y]=_y,this[id]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[id].toJSON()}}toString(){return"(FiberFailure) "+Mr(this[id],{renderErrorCause:!0})}[re](){return this.toString()}};Mq=wy((e,t)=>{let r=Iq(t);if(r)return r;let n=new bc,o=Sk(e)(t,{scheduler:n});n.flush();let i=o.unsafePoll();if(i)return i;return ag(Gu(Aq(o),dp(o)))});Fq=Ah(Fn,Rh,Oh),Tk=Nq({context:go(),runtimeFlags:Fq,fiberRefs:Ov()}),Ek=Sk(Tk),vk=Cq(Tk)});var Rk,Cc,Ac,or,kk,ad,Ck,Ai,Fr,Ak,Pk;var Ik=x(()=>{ot();by();Ok();Rk=wa,Cc=pk,Ac=Ce,or=nt,kk=rc,ad=ze,Ck=Si,Ai=yi,Fr=B,Ak=Ek,Pk=vk});var Ty=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return Ty(e,t.from)}},Pc=(e)=>{let t=!1,r;return()=>{if(t)return r;return r=e(),t=!0,r}},Ey=(e)=>Array.isArray(e),Nk=(e)=>!Array.isArray(e),Mk=(e)=>`[${Es(e)}]`,sd=(e)=>Ey(e)?e.map(Mk).join(""):Mk(e);var Ic=x(()=>{Be()});var Po=(e,t,r,n)=>{let o=e;if(r&&we(r))o+=`
31
+ at path: ${sd(r)}`;if(t!==void 0)o+=`
32
+ details: ${t}`;if(n)o+=`
33
+ schema (${n._tag}): ${n}`;return o},Fk=(e)=>Po("Invalid Argument",e),Lk=(e)=>Po("Unsupported key schema",void 0,void 0,e),Dk=(e)=>Po("Unsupported literal",`literal value: ${Kr(e)}`),vy=(e)=>Po("Duplicate index signature",`${e} index signature`),qk,Uk,Oy=(e)=>Po("Duplicate property signature transformation",`Duplicate key ${Kr(e)}`),Ry=(e)=>Po("Duplicate property signature",`Duplicate key ${Kr(e)}`);var ky=x(()=>{Ve();Be();Ic();qk=Po("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=Po("Invalid element","A required element cannot follow an optional element. ts(1257)")});var $k,jk,Bk,Vk,zk,Kk,Wk;var Jk=x(()=>{$k=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 Ua{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(e,t,r,n={}){this.typeParameters=e,this.decodeUnknown=t,this.encodeUnknown=r,this.annotations=n}toString(){return ve(rn(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:Ue(this.annotations)}}}class Pi{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return ve(rn(this),()=>Kr(this.literal))}toJSON(){return{_tag:this._tag,literal:eo(this.literal)?String(this.literal):this.literal,annotations:Ue(this.annotations)}}}class fd{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return ve(rn(this),()=>Kr(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:Ue(this.annotations)}}}class sC{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class cC{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class lC{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class uC{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class pC{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class fC{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class hC{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class yC{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class SC{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class bC{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class wC{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return Lr(this)}toJSON(){return{_tag:this._tag,annotations:Ue(this.annotations)}}}class Ha{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:Ue(this.annotations)}}toString(){return String(this.type)}}class Fc{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(e,t,r,n={}){this.elements=e,this.rest=t,this.isReadonly=r,this.annotations=n;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 ve(rn(this),()=>Kq(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:Ue(this.annotations)}}}class $a{type;isReadonly;parameter;constructor(e,t,r){if(this.type=t,this.isReadonly=r,EC(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 nn{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(e,t,r={}){this.annotations=r;let n={};for(let i=0;i<e.length;i++){let a=e[i].name;if(Object.prototype.hasOwnProperty.call(n,a))throw Error(Ry(a));n[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=ax(t[i].parameter);if(gd(a)){if(o.string)throw Error(vy("string"));o.string=!0}else if(_C(a)){if(o.symbol)throw Error(vy("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return ve(rn(this),()=>Wq(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:Ue(this.annotations)}}}class qt{types;annotations;static make=(e,t)=>yd(e)?new qt(e,t):e.length===1?e[0]:hd;static unify=(e,t)=>qt.make(Yq(vC(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return ve(rn(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:Ue(this.annotations)}}}class xd{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=Pc(e)}toString(){return rn(this).pipe(Er(()=>Or(h_(this.f)(),(e)=>rn(e))),ve(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=Cy.get(e);if(t)return t;return Cy.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:Ue(this.annotations)},Cy.set(e,t),t}}class Lc{from;filter;annotations;_tag="Refinement";constructor(e,t,r={}){this.from=e,this.filter=t,this.annotations=r}toString(){return Mc(this).pipe(ve(()=>Ge(AC(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Dc(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:Ue(this.annotations)}}}class tx{from;to;transformation;annotations;_tag="Transformation";constructor(e,t,r,n={}){this.from=e,this.to=t,this.transformation=r,this.annotations=n}toString(){return ve(rn(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:Ue(this.annotations)}}}class rx{from;to;decode;encode;constructor(e,t,r,n){this.from=e,this.to=t,this.decode=r,this.encode=n}}class nx{propertySignatureTransformations;_tag="TypeLiteralTransformation";constructor(e){this.propertySignatureTransformations=e;let t={},r={};for(let n of e){let o=n.from;if(t[o])throw Error(Oy(o));t[o]=!0;let i=n.to;if(r[i])throw Error(Oy(i));r[i]=!0}}}function xr(e,t){let r=!1,n=ri(e.length);for(let o=0;o<e.length;o++){let i=e[o],a=t(i);if(a!==i)r=!0;n[o]=a}return r?n:e}function t2(e){return Ge(Ky(e),{onNone:()=>"",onSome:(t)=>t.map((r)=>` & Brand<${Kr(r)}>`).join("")})}var Yk,Py,Zk,Iy,ld,ud,zt,pd,jn,My,Ny,Fy,Ly,Dy,qy,Xk,Uy,Hy,$y,jy,By,Vy,zy,It,Ky,Qk,eC,Wy,Jy,Mc,Gy,tC,rC,nC,oC,iC,Yy,Uq,Zy=(e)=>x_(Uq(e),(t)=>t===!0),Xy,Hq,$q=(e)=>Er(Hq(e),()=>Mc(e)),Nc=(e)=>(t)=>t._tag===e,dd,aC,md,jq,hd,Qy,dC,mC,gd,gC,xC,Bq,Vq,_C,zq,Io,TC=(e)=>e.map((t)=>t.type),Kq=(e)=>{let t=e.elements.map(String).join(", ");return __(e.rest,{onEmpty:()=>`readonly [${t}]`,onNonEmpty:(r,n)=>{let o=String(r),i=o.includes(" | ")?`(${o})`:o;if(n.length>0){let a=n.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}>`}})},ct,EC=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return EC(e.from)}return!1},Gk=(e)=>e.map(String).join("; "),Wq=(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"{}"},Jq,Gq,vC=(e)=>Ps(e,(t)=>ex(t)?vC(t.types):[t]),Yq=(e)=>{let t=Jq(e),r=[],n={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[dC];case"UnknownKeyword":return[Qy];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!n[i._tag])n[i._tag]=i,r.push(i);break}case"Literal":{let a=typeof i.literal;switch(a){case"string":case"number":case"bigint":case"boolean":{let s=Gq[a];if(!n[s]&&!o.includes(i.literal))o.push(i.literal),r.push(i);break}case"object":{if(!o.includes(i.literal))o.push(i.literal),r.push(i);break}}break}case"UniqueSymbol":{if(!n.SymbolKeyword&&!o.includes(i.symbol))o.push(i.symbol),r.push(i);break}case"TupleType":{if(!n.ObjectKeyword)r.push(i);break}case"TypeLiteral":{if(i.propertySignatures.length===0&&i.indexSignatures.length===0){if(!n["{}"])n["{}"]=i,r.push(i)}else if(!n.ObjectKeyword)r.push(i);break}default:r.push(i)}return r},OC=(e,t)=>e.map(t),yd=(e)=>e.length>1,ex,Cy,Dc,Sd,qc=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={...e.annotations};delete n[ud];let o={...n,...t},i=Yy(e);if(Re(i))o[Vy]=qc(i.value,t);return r.annotations.value=o,Object.create(Object.getPrototypeOf(e),r)},Zq="[\\s\\S]*?",Xq="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",RC=(e,t)=>{switch(e._tag){case"Literal":return Ca(String(e.literal));case"StringKeyword":return Zq;case"NumberKeyword":return Xq;case"TemplateLiteral":return kC(e,t,!1);case"Union":return e.types.map((r)=>RC(r,t)).join("|")}},Qq=(e,t,r,n)=>{if(ex(e)){if(r&&!n)return`(?:${t})`}else if(!r||!n)return t;return`(${t})`},kC=(e,t,r)=>{let n="";if(e.head!==""){let o=Ca(e.head);n+=t&&r?`(${o})`:o}for(let o of e.spans){let i=RC(o.type,t);if(n+=Qq(o.type,i,t,r),o.literal!==""){let a=Ca(o.literal);n+=t&&r?`(${a})`:a}}return n},CC=(e)=>new RegExp(`^${kC(e,!1,!0)}$`),ox=(e,t)=>{let r=[],n=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":n.push(new $a(i,t,!0));break;case"Literal":if(xt(i.literal)||Xt(i.literal))r.push(new ct(i.literal,t,!1,!0));else throw Error(Dk(i.literal));break;case"Enums":{for(let[a,s]of i.enums)r.push(new ct(s,t,!1,!0));break}case"UniqueSymbol":r.push(new ct(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(Lk(i))}};return o(e),{propertySignatures:r,indexSignatures:n}},ix=(e)=>(t)=>{let r=void 0;for(let n of e)if(Object.prototype.hasOwnProperty.call(t.annotations,n)){if(r===void 0)r={};r[n]=t.annotations[n]}return r},e2,st=(e)=>{switch(e._tag){case"Declaration":{let t=xr(e.typeParameters,st);return t===e.typeParameters?e:new Ua(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=xr(e.elements,(o)=>{let i=st(o.type);return i===o.type?o:new Io(i,o.isOptional)}),r=TC(e.rest),n=xr(r,st);return t===e.elements&&n===r?e:new Fc(t,n.map((o)=>new Ha(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=xr(e.propertySignatures,(n)=>{let o=st(n.type);return o===n.type?n:new ct(n.name,o,n.isOptional,n.isReadonly)}),r=xr(e.indexSignatures,(n)=>{let o=st(n.type);return o===n.type?n:new $a(n.parameter,o,n.isReadonly)});return t===e.propertySignatures&&r===e.indexSignatures?e:new nn(t,r,e.annotations)}case"Union":{let t=xr(e.types,st);return t===e.types?e:qt.make(t,e.annotations)}case"Suspend":return new xd(()=>st(e.f()),e.annotations);case"Refinement":{let t=st(e.from);return t===e.from?e:new Lc(t,e.filter,e.annotations)}case"Transformation":{let t=e2(e);return st(t!==void 0?qc(e.to,t):e.to)}}return e},Ay=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return Ay(e.from);case"Suspend":return Ay(e.f())}},tn=(e,t)=>{switch(e._tag){case"Declaration":{let r=xr(e.typeParameters,(n)=>tn(n,t));return r===e.typeParameters?e:new Ua(r,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let r=xr(e.elements,(i)=>{let a=tn(i.type,t);return a===i.type?i:new Io(a,i.isOptional)}),n=TC(e.rest),o=xr(n,(i)=>tn(i,t));return r===e.elements&&o===n?e:new Fc(r,o.map((i)=>new Ha(i)),e.isReadonly)}case"TypeLiteral":{let r=xr(e.propertySignatures,(o)=>{let i=tn(o.type,t);return i===o.type?o:new ct(o.name,i,o.isOptional,o.isReadonly)}),n=xr(e.indexSignatures,(o)=>{let i=tn(o.type,t);return i===o.type?o:new $a(o.parameter,i,o.isReadonly)});return r===e.propertySignatures&&n===e.indexSignatures?e:new nn(r,n)}case"Union":{let r=xr(e.types,(n)=>tn(n,t));return r===e.types?e:qt.make(r)}case"Suspend":{let r=void 0,n=$q(e);if(Re(n)){let o=t?"Bound":"";r={[Xy]:`${n.value}Encoded${o}`}}return new xd(()=>tn(e.f(),t),r)}case"Refinement":{let r=tn(e.from,t);if(t){if(r===e.from)return e;if(Ay(e.from)===void 0&&Zy(e))return new Lc(r,e.filter,e.annotations);return r}else return r}case"Transformation":return tn(e.from,t)}return e},bd=(e)=>tn(e,!1),Ue=(e)=>{let t={};for(let r of Object.getOwnPropertySymbols(e))t[String(r)]=e[r];return t},ax=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return ax(e.from)}},Lr=(e)=>ve(rn(e),()=>e._tag),AC=(e)=>Wy(e).pipe(Er(()=>Gy(e)),Er(()=>Jy(e)),vr((t)=>t+t2(e))),rn=(e)=>Er(Mc(e),()=>AC(e));var sx=x(()=>{Ve();H();Be();ky();Ic();gc();Ye();Zl();ge();hg();Yk=Symbol.for("effect/annotation/TypeConstructor"),Py=Symbol.for("effect/annotation/Brand"),Zk=Symbol.for("effect/annotation/SchemaId"),Iy=Symbol.for("effect/annotation/Message"),ld=Symbol.for("effect/annotation/MissingMessage"),ud=Symbol.for("effect/annotation/Identifier"),zt=Symbol.for("effect/annotation/Title"),pd=Symbol.for("effect/annotation/AutoTitle"),jn=Symbol.for("effect/annotation/Description"),My=Symbol.for("effect/annotation/Examples"),Ny=Symbol.for("effect/annotation/Default"),Fy=Symbol.for("effect/annotation/JSONSchema"),Ly=Symbol.for("effect/annotation/Arbitrary"),Dy=Symbol.for("effect/annotation/Pretty"),qy=Symbol.for("effect/annotation/Equivalence"),Xk=Symbol.for("effect/annotation/Documentation"),Uy=Symbol.for("effect/annotation/Concurrency"),Hy=Symbol.for("effect/annotation/Batching"),$y=Symbol.for("effect/annotation/ParseIssueTitle"),jy=Symbol.for("effect/annotation/ParseOptions"),By=Symbol.for("effect/annotation/DecodingFallback"),Vy=Symbol.for("effect/annotation/Surrogate"),zy=Symbol.for("effect/annotation/StableFilter"),It=d(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?N(e.annotations[t]):C()),Ky=It(Py),Qk=It(Iy),eC=It(ld),Wy=It(zt),Jy=It(pd),Mc=It(ud),Gy=It(jn),tC=It(Uy),rC=It(Hy),nC=It($y),oC=It(jy),iC=It(By),Yy=It(Vy),Uq=It(zy),Xy=Symbol.for("effect/annotation/JSONIdentifier"),Hq=It(Xy);dd=Nc("Literal"),aC=new Pi(null);md=new sC({[zt]:"undefined"});jq=new cC({[zt]:"void"});hd=new lC({[zt]:"never"});Qy=new uC({[zt]:"unknown"});dC=new pC({[zt]:"any"});mC=new fC({[zt]:"string",[jn]:"a string"}),gd=Nc("StringKeyword");gC=new hC({[zt]:"number",[jn]:"a number"});xC=new yC({[zt]:"boolean",[jn]:"a boolean"});Bq=new SC({[zt]:"bigint",[jn]:"a bigint"});Vq=new bC({[zt]:"symbol",[jn]:"a symbol"}),_C=Nc("SymbolKeyword");zq=new wC({[zt]:"object",[jn]:"an object in the TypeScript meaning, i.e. the `object` type"});Io=class Io extends Ha{isOptional;constructor(e,t,r={}){super(e,r);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:Ue(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};ct=class ct extends Io{name;isReadonly;constructor(e,t,r,n,o){super(t,r,o);this.name=e,this.isReadonly=n}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:Ue(this.annotations)}}};Jq=vn(Yl(en,(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})),Gq={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};ex=Nc("Union"),Cy=j(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Dc=Nc("Refinement"),Sd={};e2=ix([My,Ny,Fy,Ly,Dy,qy])});class lt{path;actual;issue;_tag="Pointer";constructor(e,t,r){this.path=e,this.actual=t,this.issue=r}}class ux{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class ja{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class He{ast;actual;issues;output;_tag="Composite";constructor(e,t,r,n){this.ast=e,this.actual=t,this.issues=r,this.output=n}}class wd{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,r,n){this.ast=e,this.actual=t,this.kind=r,this.issue=n}}class Td{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,r,n){this.ast=e,this.actual=t,this.kind=r,this.issue=n}}class Sr{ast;actual;message;_tag="Type";constructor(e,t,r){this.ast=e,this.actual=t,this.message=r}}class px{ast;actual;message;_tag="Forbidden";constructor(e,t,r){this.ast=e,this.actual=t,this.message=r}}function Dr(e){return e.sort(a2).map((t)=>t[1])}function d2(e){return Gy(e).pipe(Er(()=>Wy(e)),Er(()=>Jy(e)),Er(()=>Mc(e)),ve(()=>`{ ${e.from} | filter }`))}function f2(e){if(e.message!==void 0)return e.message;return`Expected ${Dc(e.ast)?d2(e.ast):String(e.ast)}, actual ${Kr(e.actual)}`}var IC,FC,fx=(e)=>new FC({issue:e}),LC,DC,Wt,Bn,qr,Ed,qC,UC=(e,t)=>{if(t===void 0||Xt(t))return e;if(e===void 0)return t;return{...e,...t}},HC=(e,t,r)=>{let n=Mt(e,t);return(o,i)=>n(o,UC(r,i))},r2=(e,t,r)=>{let n=HC(e,t,r);return(o,i)=>im(n(o,i),fx)},$C=(e,t)=>HC(e.ast,!0,t),vd=(e,t)=>r2(st(e.ast),!0,t),n2,o2,Mt=(e,t)=>{let r=t?n2:o2,n=r.get(e);if(n)return n;let o=i2(e,t),i=oC(e),a=Re(i)?(l,u)=>o(l,UC(u,i.value)):o,s=iC(e),c=t&&Re(s)?(l,u)=>Hc(qC(a(l,u),s.value),e,l,u):a;return r.set(e,c),c},cx=(e)=>Bt(tC(e)),lx=(e)=>Bt(rC(e)),i2=(e,t)=>{switch(e._tag){case"Refinement":if(t){let r=Mt(e.from,!0);return(n,o)=>{o=o??Sd;let i=o?.errors==="all",a=Bn(qC(r(n,o),(s)=>{let c=new wd(e,n,"From",s);if(i&&Zy(e)&&KC(s))return Ge(e.filter(n,o,e),{onNone:()=>K(c),onSome:(l)=>K(new He(e,n,[c,new wd(e,n,"Predicate",l)]))});return K(c)}),(s)=>Ge(e.filter(s,o,e),{onNone:()=>Z(s),onSome:(c)=>K(new wd(e,n,"Predicate",c))}));return Hc(a,e,n,o)}}else{let r=Mt(st(e),!0),n=Mt(BC(e.from),!1);return(o,i)=>Hc(Bn(r(o,i),(a)=>n(a,i)),e,o,i)}case"Transformation":{let r=s2(e.transformation,t),n=t?Mt(e.from,!0):Mt(e.to,!1),o=t?Mt(e.to,!0):Mt(e.from,!1);return(i,a)=>Hc(Bn(Ed(n(i,a),(s)=>new Td(e,i,t?"Encoded":"Type",s)),(s)=>Bn(Ed(r(s,a??Sd,e,i),(c)=>new Td(e,i,"Transformation",c)),(c)=>Ed(o(c,a),(l)=>new Td(e,i,t?"Type":"Encoded",l)))),e,i,a)}case"Declaration":{let r=t?e.decodeUnknown(...e.typeParameters):e.encodeUnknown(...e.typeParameters);return(n,o)=>Hc(r(n,o??Sd,e),e,n,o)}case"Literal":return Kt(e,(r)=>r===e.literal);case"UniqueSymbol":return Kt(e,(r)=>r===e.symbol);case"UndefinedKeyword":return Kt(e,Ub);case"NeverKeyword":return Kt(e,Hb);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return Z;case"StringKeyword":return Kt(e,xt);case"NumberKeyword":return Kt(e,Xt);case"BooleanKeyword":return Kt(e,Wo);case"BigIntKeyword":return Kt(e,eo);case"SymbolKeyword":return Kt(e,Jo);case"ObjectKeyword":return Kt(e,Dt);case"Enums":return Kt(e,(r)=>e.enums.some(([n,o])=>o===r));case"TemplateLiteral":{if(e.spans.every((n)=>gd(n.type)))return Kt(e,(n)=>{if(!xt(n)||!n.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=n.indexOf(s,o);if(c===-1)return!1;o=c+s.length}let i=e.spans[e.spans.length-1].literal;return n.endsWith(i)&&n.length-i.length>=o});let r=CC(e);return Kt(e,(n)=>xt(n)&&r.test(n))}case"TupleType":{let r=e.elements.map((l)=>Mt(l.type,t)),n=e.rest.map((l)=>Mt(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=cx(e),c=lx(e);return(l,u)=>{if(!dm(l))return K(new Sr(e,l));let p=u?.errors==="all",f=[],h=0,m=[],w=l.length;for(let P=w;P<=i-1;P++){let z=new lt(P,l,new ja(o[P-w]));if(p){f.push([h++,z]);continue}else return K(new He(e,l,z,m))}if(e.rest.length===0)for(let P=e.elements.length;P<=w-1;P++){let z=new lt(P,l,new ux(l[P],`is unexpected, expected: ${a}`));if(p){f.push([h++,z]);continue}else return K(new He(e,l,z,m))}let S=0,y=void 0;for(;S<r.length;S++)if(w<S+1){if(e.elements[S].isOptional)continue}else{let P=r[S],z=P(l[S],u);if(Wt(z)){if(Ee(z)){let Y=new lt(S,l,z.left);if(p){f.push([h++,Y]);continue}else return K(new He(e,l,Y,Dr(m)))}m.push([h++,z.right])}else{let Y=h++,D=S;if(!y)y=[];y.push(({es:te,output:F})=>Fr(Ai(z),(ie)=>{if(Ee(ie)){let ae=new lt(D,l,ie.left);if(p)return te.push([Y,ae]),or;else return K(new He(e,l,ae,Dr(F)))}return F.push([Y,ie.right]),or}))}}if(we(n)){let[P,...z]=n;for(;S<w-z.length;S++){let Y=P(l[S],u);if(Wt(Y))if(Ee(Y)){let D=new lt(S,l,Y.left);if(p){f.push([h++,D]);continue}else return K(new He(e,l,D,Dr(m)))}else m.push([h++,Y.right]);else{let D=h++,te=S;if(!y)y=[];y.push(({es:F,output:ie})=>Fr(Ai(Y),(ae)=>{if(Ee(ae)){let ee=new lt(te,l,ae.left);if(p)return F.push([D,ee]),or;else return K(new He(e,l,ee,Dr(ie)))}else return ie.push([D,ae.right]),or}))}}for(let Y=0;Y<z.length;Y++){let D=S+Y;if(w<D+1)continue;else{let te=z[Y](l[D],u);if(Wt(te)){if(Ee(te)){let F=new lt(D,l,te.left);if(p){f.push([h++,F]);continue}else return K(new He(e,l,F,Dr(m)))}m.push([h++,te.right])}else{let F=h++;if(!y)y=[];y.push(({es:ie,output:ae})=>Fr(Ai(te),(ee)=>{if(Ee(ee)){let Oe=new lt(D,l,ee.left);if(p)return ie.push([F,Oe]),or;else return K(new He(e,l,Oe,Dr(ae)))}return ae.push([F,ee.right]),or}))}}}}let R=({es:P,output:z})=>io(P)?K(new He(e,l,Dr(P),Dr(z))):Z(Dr(z));if(y&&y.length>0){let P=y;return Ac(()=>{let z={es:ra(f),output:ra(m)};return Fr(Cc(P,(Y)=>Y(z),{concurrency:s,batching:c,discard:!0}),()=>R(z))})}return R({output:m,es:f})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Kt(e,$b);let r=[],n={},o=[];for(let u of e.propertySignatures)r.push([Mt(u.type,t),u]),n[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Mt(u.parameter,t),Mt(u.type,t),u.parameter]),a=qt.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>Jo(u)?new fd(u):new Pi(u)))),s=Mt(a,t),c=cx(e),l=lx(e);return(u,p)=>{if(!jf(u))return K(new Sr(e,u));let f=p?.errors==="all",h=[],m=0,w=p?.onExcessProperty==="error",S=p?.onExcessProperty==="preserve",y={},R;if(w||S){R=Reflect.ownKeys(u);for(let D of R){let te=s(D,p);if(Wt(te)&&Ee(te))if(w){let F=new lt(D,u,new ux(u[D],`is unexpected, expected: ${String(a)}`));if(f){h.push([m++,F]);continue}else return K(new He(e,u,F,y))}else y[D]=u[D]}}let P=void 0,z=p?.exact===!0;for(let D=0;D<r.length;D++){let te=r[D][1],F=te.name,ie=Object.prototype.hasOwnProperty.call(u,F);if(!ie){if(te.isOptional)continue;else if(z){let Oe=new lt(F,u,new ja(te));if(f){h.push([m++,Oe]);continue}else return K(new He(e,u,Oe,y))}}let ae=r[D][0],ee=ae(u[F],p);if(Wt(ee)){if(Ee(ee)){let Oe=new lt(F,u,ie?ee.left:new ja(te));if(f){h.push([m++,Oe]);continue}else return K(new He(e,u,Oe,y))}y[F]=ee.right}else{let Oe=m++,yt=F;if(!P)P=[];P.push(({es:vt,output:Ot})=>Fr(Ai(ee),($e)=>{if(Ee($e)){let We=new lt(yt,u,ie?$e.left:new ja(te));if(f)return vt.push([Oe,We]),or;else return K(new He(e,u,We,Ot))}return Ot[yt]=$e.right,or}))}}for(let D=0;D<i.length;D++){let te=i[D],F=te[0],ie=te[1],ae=Ty(u,te[2]);for(let ee of ae){let Oe=F(ee,p);if(Wt(Oe)&&Rt(Oe)){let yt=ie(u[ee],p);if(Wt(yt)){if(Ee(yt)){let vt=new lt(ee,u,yt.left);if(f){h.push([m++,vt]);continue}else return K(new He(e,u,vt,y))}else if(!Object.prototype.hasOwnProperty.call(n,ee))y[ee]=yt.right}else{let vt=m++,Ot=ee;if(!P)P=[];P.push(({es:$e,output:We})=>Fr(Ai(yt),(je)=>{if(Ee(je)){let yn=new lt(Ot,u,je.left);if(f)return $e.push([vt,yn]),or;else return K(new He(e,u,yn,We))}else{if(!Object.prototype.hasOwnProperty.call(n,ee))We[ee]=je.right;return or}}))}}}}let Y=({es:D,output:te})=>{if(io(D))return K(new He(e,u,Dr(D),te));if(p?.propertyOrder==="original"){let F=R||Reflect.ownKeys(u);for(let ae of o)if(F.indexOf(ae)===-1)F.push(ae);let ie={};for(let ae of F)if(Object.prototype.hasOwnProperty.call(te,ae))ie[ae]=te[ae];return Z(ie)}return Z(te)};if(P&&P.length>0){let D=P;return Ac(()=>{let te={es:ra(h),output:Object.assign({},y)};return Fr(Cc(D,(F)=>F(te),{concurrency:c,batching:l,discard:!0}),()=>Y(te))})}return Y({es:h,output:y})}}case"Union":{let r=jC(e.types,t),n=Reflect.ownKeys(r.keys),o=n.length,i=e.types.length,a=new Map;for(let l=0;l<i;l++)a.set(e.types[l],Mt(e.types[l],t));let s=cx(e)??1,c=lx(e);return(l,u)=>{let p=[],f=0,h=[];if(o>0)if(Ss(l))for(let S=0;S<o;S++){let y=n[S],R=r.keys[y].buckets;if(Object.prototype.hasOwnProperty.call(l,y)){let P=String(l[y]);if(Object.prototype.hasOwnProperty.call(R,P))h=h.concat(R[P]);else{let{candidates:z,literals:Y}=r.keys[y],D=qt.make(Y),te=z.length===i?new nn([new ct(y,D,!1,!0)],[]):qt.make(z);p.push([f++,new He(te,l,new lt(y,l,new Sr(D,l[y])))])}}else{let{candidates:P,literals:z}=r.keys[y],Y=new ct(y,qt.make(z),!1,!0),D=P.length===i?new nn([Y],[]):qt.make(P);p.push([f++,new He(D,l,new lt(y,l,new ja(Y)))])}}else{let S=r.candidates.length===i?e:qt.make(r.candidates);p.push([f++,new Sr(S,l)])}if(r.otherwise.length>0)h=h.concat(r.otherwise);let m=void 0;for(let S=0;S<h.length;S++){let y=h[S],R=a.get(y)(l,u);if(Wt(R)&&(!m||m.length===0))if(Rt(R))return R;else p.push([f++,R.left]);else{let P=f++;if(!m)m=[];m.push((z)=>Ac(()=>{if("finalResult"in z)return or;else return Fr(Ai(R),(Y)=>{if(Rt(Y))z.finalResult=Y;else z.es.push([P,Y.left]);return or})}))}}let w=(S)=>io(S)?S.length===1&&S[0][1]._tag==="Type"?K(S[0][1]):K(new He(e,l,Dr(S))):K(new Sr(e,l));if(m&&m.length>0){let S=m;return Ac(()=>{let y={es:ra(p)};return Fr(Cc(S,(R)=>R(y),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in y)return y.finalResult;return w(y.es)})})}return w(p)}}case"Suspend":{let r=Pc(()=>Mt(e.f(),t));return(n,o)=>r()(n,o)}}},Kt=(e,t)=>(r)=>t(r)?Z(r):K(new Sr(e,r)),Uc=(e,t)=>{switch(e._tag){case"Declaration":{let r=Yy(e);if(Re(r))return Uc(r.value,t);break}case"TypeLiteral":{let r=[];for(let n=0;n<e.propertySignatures.length;n++){let o=e.propertySignatures[n],i=t?bd(o.type):st(o.type);if(dd(i)&&!o.isOptional)r.push([o.name,i])}return r}case"TupleType":{let r=[];for(let n=0;n<e.elements.length;n++){let o=e.elements[n],i=t?bd(o.type):st(o.type);if(dd(i)&&!o.isOptional)r.push([n,i])}return r}case"Refinement":return Uc(e.from,t);case"Suspend":return Uc(e.f(),t);case"Transformation":return Uc(t?e.from:e.to,t)}return[]},jC=(e,t)=>{let r={},n=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=Uc(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);r[l]=r[l]||{buckets:{},literals:[],candidates:[]};let f=r[l].buckets;if(Object.prototype.hasOwnProperty.call(f,p)){if(c<s.length-1)continue;f[p].push(a),r[l].literals.push(u),r[l].candidates.push(a)}else{f[p]=[a],r[l].literals.push(u),r[l].candidates.push(a);break}}}else n.push(a)}return{keys:r,otherwise:n,candidates:o}},BC=(e)=>Dc(e)?BC(e.from):e,Hc=(e,t,r,n)=>{if(n?.isEffectAllowed===!0)return e;if(Wt(e))return e;let o=new bc,i=Ak(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(kO(a))return Z(a.value);let s=a.cause;if(bE(s))return K(s.error);return K(new px(t,r,_E(s)))}return K(new px(t,r,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},a2=([e],[t])=>e>t?1:e<t?-1:0,s2=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return Z;case"TypeLiteralTransformation":return(r)=>{let n=Z(r);for(let o of e.propertySignatureTransformations){let[i,a]=t?[o.from,o.to]:[o.to,o.from],s=t?o.decode:o.encode;n=qr(n,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?N(l[i]):C());if(delete l[i],Re(u))l[a]=u.value;return l})}return n}}},Ut=(e,t=[])=>({value:e,forest:t}),$c,c2=(e)=>e.value+VC(`
34
+ `,e.forest),VC=(e,t)=>{let r="",n=t.length,o;for(let i=0;i<n;i++){o=t[i];let a=i===n-1;r+=e+(a?"\u2514":"\u251C")+"\u2500 "+o.value,r+=VC(e+(n>1&&!a?"\u2502 ":" "),o.forest)}return r},l2=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},u2=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},zC=(e)=>("ast"in e)?N(e.ast):C(),dx,p2=(e)=>zC(e).pipe(Or(Qk),Ge({onNone:()=>dx,onSome:(t)=>{let r=t(e);if(xt(r))return Z({message:r,override:!1});if(Rk(r))return ad(r,(n)=>({message:n,override:!1}));if(xt(r.message))return Z({message:r.message,override:r.override});return ad(r.message,(n)=>({message:n,override:r.override}))}})),mx=(e)=>(t)=>t._tag===e,KC,MC,NC,jc=(e)=>Bn(p2(e),(t)=>{if(t!==void 0)return!t.override&&(KC(e)||MC(e)&&e.kind==="From"||NC(e)&&e.kind!=="Transformation")?NC(e)||MC(e)?jc(e.issue):dx:Z(t.message);return dx}),WC=(e)=>zC(e).pipe(Or(nC),g_((t)=>t(e)),Bt),m2=(e)=>qr(jc(e),(t)=>t??WC(e)??f2(e)),_d=(e)=>WC(e)??String(e.ast),h2=(e)=>e.message??"is forbidden",g2=(e)=>e.message??"is unexpected",y2=(e)=>{let t=eC(e.ast);if(Re(t)){let r=t.value();return xt(r)?Z(r):r}return Z(e.message??"is missing")},Ba=(e)=>{switch(e._tag){case"Type":return qr(m2(e),Ut);case"Forbidden":return Z(Ut(_d(e),[Ut(h2(e))]));case"Unexpected":return Z(Ut(g2(e)));case"Missing":return qr(y2(e),Ut);case"Transformation":return Bn(jc(e),(t)=>{if(t!==void 0)return Z(Ut(t));return qr(Ba(e.issue),(r)=>Ut(_d(e),[Ut(l2(e.kind),[r])]))});case"Refinement":return Bn(jc(e),(t)=>{if(t!==void 0)return Z(Ut(t));return qr(Ba(e.issue),(r)=>Ut(_d(e),[Ut(u2(e.kind),[r])]))});case"Pointer":return qr(Ba(e.issue),(t)=>Ut(sd(e.path),[t]));case"Composite":return Bn(jc(e),(t)=>{if(t!==void 0)return Z(Ut(t));let r=_d(e);return Ey(e.issues)?qr(Cc(e.issues,Ba),(n)=>Ut(r,n)):qr(Ba(e.issues),(n)=>Ut(r,[n]))})}};var JC=x(()=>{Ve();wE();dv();Ik();er();CO();H();Be();Ic();Ye();ge();Vp();sx();IC=Symbol.for("effect/Schema/ParseErrorTypeId");FC=class FC extends pv("ParseError"){[IC]=IC;get message(){return this.toString()}toString(){return $c.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[re](){return this.toJSON()}};LC=Z,DC=K,Wt=om,Bn=d(2,(e,t)=>Wt(e)?As(e,{onLeft:K,onRight:t}):Fr(e,t)),qr=d(2,(e,t)=>Wt(e)?l_(e,t):ad(e,t)),Ed=d(2,(e,t)=>Wt(e)?Gl(e,t):Ck(e,t)),qC=d(2,(e,t)=>Wt(e)?As(e,{onLeft:t,onRight:Z}):kk(e,t)),n2=j(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),o2=j(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);$c={formatIssue:(e)=>qr(Ba(e),c2),formatIssueSync:(e)=>{let t=$c.formatIssue(e);return Wt(t)?p_(t):Pk(t)},formatError:(e)=>$c.formatIssue(e.issue),formatErrorSync:(e)=>$c.formatIssueSync(e.issue)},dx=Z(void 0),KC=mx("Composite"),MC=mx("Refinement"),NC=mx("Transformation")});var GC,YC;var ZC=x(()=>{H();ge();GC=d((e)=>Dt(e[0]),(e,...t)=>{let r={};for(let n of t)if(n in e)r[n]=e[n];return r}),YC=d((e)=>Dt(e[0]),(e,...t)=>{let r={...e};for(let n of t)delete r[n];return r})});function wt(e){return class{[Bc]=XC;static ast=e;static annotations(r){return wt(on(this.ast,r))}static pipe(){return E(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Bc]=XC}}function b2(e){return yd(e)?qt.make(OC(e,(t)=>new Pi(t))):new Pi(e[0])}function aA(e,t=b2(e)){return class extends wt(t){static annotations(n){return aA(this.literals,on(this.ast,n))}static literals=[...e]}}function T(...e){return we(e)?aA(e):yx}function gx(e,t){return class extends wt(t){static annotations(n){return gx(this.typeParameters,on(this.ast,n))}static typeParameters=[...e]}}function cA(e,t=T2(e)){return class extends wt(t){static annotations(n){return cA(this.members,on(this.ast,n))}static members=[...e]}}function ye(...e){return yd(e)?cA(e):we(e)?e[0]:yx}function Od(e,t,r=v2(e,t)){return class extends wt(r){static annotations(o){return Od(this.elements,this.rest,on(this.ast,o))}static elements=[...e];static rest=[...t]}}function lA(...e){return Array.isArray(e[0])?Od(e[0],e.slice(1)):Od(e,[])}function uA(e,t){return class extends Od([],[e],t){static annotations(n){return uA(this.value,on(this.ast,n))}static value=e}}class dA{from;to;decode;encode;_tag="PropertySignatureTransformation";constructor(e,t,r,n){this.from=e,this.to=t,this.decode=r,this.encode=n}toString(){return`PropertySignature<${hx(this.to.isOptional)}, ${this.to.type}, ${O2(this.from.fromKey)}, ${hx(this.from.isOptional)}, ${this.from.type}>`}}function wx(e,t,r=k2(e,t)){return class extends wt(r){static annotations(o){return wx(this.fields,this.records,on(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=C2(e,{...o});return Ox(i)?a:vd(this)(a)};static pick(...o){return b(GC(e,...o))}static omit(...o){return b(YC(e,...o))}}}function b(e,...t){return wx(e,t)}function gA(e,t,r){return class extends wx({},[{key:e,value:t}],r){static annotations(o){return gA(e,t,on(this.ast,o))}static key=e;static value=t}}function yA(e,t){return class extends wt(t){static annotations(n){return yA(this.from,on(this.ast,n))}static make=(n,o)=>Ox(o)?n:vd(this)(n);static from=e}}function xA(e,t,r){return class extends wt(r){static annotations(o){return xA(this.from,this.filter,on(this.ast,o))}static[A2]=e;static from=e;static filter=t;static make=(o,i)=>Ox(i)?o:vd(this)(o)}}function Xe(e,t){return(r)=>{function n(i,a,s){return P2(e(i,a,s),s,i)}let o=new Lc(r.ast,n,Ii(t));return xA(r,n,o)}}function Ox(e){return Wo(e)?e:e?.disableValidation??!1}var Bc,XC,QC,Ii=(e)=>{if(!e)return{};let t={...e};for(let r in QC)if(r in e){let n=QC[r];t[n]=e[r],delete t[r]}return t},on=(e,t)=>qc(e,Ii(t)),iA=(e,t)=>{let r=$C(e,t);return(n,o)=>Gl(r(n,o),fx)},eA=(e)=>k(e,Bc)&&Dt(e[Bc]),_2=(e,t,r)=>gx(e,new Ua(e.map((n)=>n.ast),(...n)=>t.decode(...n.map(wt)),(...n)=>t.encode(...n.map(wt)),Ii(r))),w2=(e,t)=>{let r=()=>(o,i,a)=>e(o)?LC(o):DC(new Sr(a,o));return gx([],new Ua([],r,r,Ii(t)))},q=function(){if(Array.isArray(arguments[0])){let r=arguments[0],n=arguments[1],o=arguments[2];return _2(r,n,o)}let e=arguments[0],t=arguments[1];return w2(e,t)},sA,ut,yx,xx,A,Jt,W,T2=(e)=>qt.make(e.map((t)=>t.ast)),E2=(e)=>ye(e,sA),v2=(e,t)=>new Fc(e.map((r)=>eA(r)?new Io(r.ast,!1):r.ast),t.map((r)=>eA(r)?new Ha(r.ast):r.ast),!0),U=(e)=>uA(e),hx=(e)=>e?'"?:"':'":"',Sx,pA,O2=(e)=>{if(e===void 0)return"never";if(xt(e))return JSON.stringify(e);return String(e)},fA=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new Sx(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new dA(e.from,new pA(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},mA,hA=(e)=>k(e,mA),bx,_x,_=(e)=>{let t=e.ast===md||e.ast===hd?md:E2(e).ast;return new _x(new Sx(t,!0,!0,{},void 0),e)},R2,k2=(e,t)=>{let r=Reflect.ownKeys(e),n=[];if(r.length>0){let i=[],a=[],s=[];for(let c=0;c<r.length;c++){let l=r[c],u=e[l];if(hA(u)){let p=u.ast;switch(p._tag){case"PropertySignatureDeclaration":{let{type:f,isOptional:h,annotations:m}=p;i.push(new ct(l,f,h,!0,R2(p))),a.push(new ct(l,st(f),h,!0,m)),n.push(new ct(l,f,h,!0,m));break}case"PropertySignatureTransformation":{let f=p.from.fromKey??l;i.push(new ct(f,p.from.type,p.from.isOptional,!0,p.from.annotations)),a.push(new ct(l,p.to.type,p.to.isOptional,!0,p.to.annotations)),s.push(new rx(f,l,p.decode,p.encode));break}}}else i.push(new ct(l,u.ast,!1,!0)),a.push(new ct(l,st(u.ast),!1,!0)),n.push(new ct(l,u.ast,!1,!0))}if(we(s)){let c=[],l=[];for(let u of t){let{indexSignatures:p,propertySignatures:f}=ox(u.key.ast,u.value.ast);f.forEach((h)=>{i.push(h),a.push(new ct(h.name,st(h.type),h.isOptional,h.isReadonly,h.annotations))}),p.forEach((h)=>{c.push(h),l.push(new $a(h.parameter,st(h.type),h.isReadonly))})}return new tx(new nn(i,c,{[pd]:"Struct (Encoded side)"}),new nn(a,l,{[pd]:"Struct (Type side)"}),new nx(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=ox(i.key.ast,i.value.ast);s.forEach((c)=>n.push(c)),a.forEach((c)=>o.push(c))}return new nn(n,o)},C2=(e,t)=>{let r=Reflect.ownKeys(e);for(let n of r){let o=e[n];if(t[n]===void 0&&hA(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[n]=a()}}return t},Rd=(e)=>gA(e.key,e.value),Vc=(e,t)=>(r)=>{let n=Ge(Ky(r.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=qc(r.ast,Ii({[Py]:n,...t}));return yA(r,o)},A2,tA=(e,t,r)=>{if(Wo(e))return e?C():N(new Sr(t,r));if(xt(e))return N(new Sr(t,r,e));if(e!==void 0){if("_tag"in e)return N(e);let n=new Sr(t,r,e.message);return N(we(e.path)?new lt(e.path,r,n):n)}return C()},P2=(e,t,r)=>{if(Nk(e))return tA(e,t,r);if(we(e)){let n=Ql(e,(o)=>tA(o,t,r));if(we(n))return N(n.length===1?n[0]:new He(t,r,n))}return C()},I2,Tx=(e,t)=>(r)=>r.pipe(Xe((n)=>n.length<=e,{schemaId:I2,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),M2,Va=(e,t)=>(r)=>r.pipe(Xe((n)=>n.length>=e,{schemaId:M2,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),rA,de=(e,t)=>(r)=>{let n=e.source;return r.pipe(Xe((o)=>(e.lastIndex=0,e.test(o)),{schemaId:rA,[rA]:{regex:e},description:`a string matching the pattern ${n}`,jsonSchema:{pattern:n},...t}))},N2,nA,F2,L2,Ex=(e,t)=>(r)=>r.pipe(Xe((n)=>n>e,{schemaId:L2,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),D2,SA=(e,t)=>(r)=>r.pipe(Xe((n)=>n>=e,{schemaId:D2,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),q2,kd=(e)=>(t)=>t.pipe(Xe((r)=>Number.isSafeInteger(r),{schemaId:q2,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),vx=(e)=>Ex(0,{title:"positive",...e}),Cd,U2,Ad=(e,t)=>(r)=>{let n=Math.floor(e);if(n<1)throw Error(Fk(`Expected an integer greater than or equal to 1, actual ${e}`));return r.pipe(Xe((o)=>o.length>=n,{schemaId:U2,title:`minItems(${n})`,description:`an array of at least ${n} item(s)`,jsonSchema:{minItems:n},[zy]:!0,...t}))},oA,H2;var Tt=x(()=>{Ve();er();ys();ky();Jk();Ic();Ye();JC();_e();ge();sx();ZC();Bc=Symbol.for("effect/Schema");XC={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},QC={typeConstructor:Yk,schemaId:Zk,message:Iy,missingMessage:ld,identifier:ud,title:zt,description:jn,examples:My,default:Ny,documentation:Xk,jsonSchema:Fy,arbitrary:Ly,pretty:Dy,equivalence:qy,concurrency:Uy,batching:Hy,parseIssueTitle:$y,parseOptions:jy,decodingFallback:By};sA=class sA extends wt(md){};ut=class ut extends wt(aC){};yx=class yx extends wt(hd){};xx=class xx extends wt(Qy){};A=class A extends wt(mC){};Jt=class Jt extends wt(gC){};W=class W extends wt(xC){};Sx=class Sx extends Io{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,r,n,o){super(e,t,n);this.isReadonly=r,this.defaultValue=o}toString(){let e=hx(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};pA=class pA extends Io{isReadonly;defaultValue;constructor(e,t,r,n,o){super(e,t,n);this.isReadonly=r,this.defaultValue=o}};mA=Symbol.for("effect/PropertySignature");bx=class bx{ast;[Bc];[mA]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return E(this,arguments)}annotations(e){return new bx(fA(this.ast,Ii(e)))}toString(){return String(this.ast)}};_x=class _x extends bx{from;constructor(e,t){super(e);this.from=t}annotations(e){return new _x(fA(this.ast,Ii(e)),this.from)}};R2=ix([ld]);A2=Symbol.for("effect/SchemaId/Refine");I2=Kk,M2=zk,rA=Symbol.for("effect/SchemaId/Pattern"),N2=Symbol.for("effect/SchemaId/UUID"),nA=/^[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;F2=class F2 extends A.pipe(de(nA,{schemaId:N2,identifier:"UUID",jsonSchema:{format:"uuid",pattern:nA.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};L2=jk,D2=Bk,q2=Vk;Cd=class Cd extends Jt.pipe(kd({identifier:"Int"})){};U2=Wk,oA=$k;H2=class H2 extends q(Ul,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:oA,[oA]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>Db}){}});function br(e,t){return iA(e,$2)(t)}var $2;var za=x(()=>{Tt();$2={onExcessProperty:"error"}});function kx(e,t){if(typeof t!=="string")return;let r=e.lastIndexOf("@");if(r<=0)return;let n=e.slice(0,r),o=e.slice(r+1);if(!wA(n)||!_A(o)||t!==o)return;return{pluginName:n,marketplaceName:o,canonicalPluginId:`${n}@openai-curated`}}function Ur(e){let t=e.lastIndexOf("@");if(t<=0)return;let r=e.slice(0,t),n=e.slice(t+1);return wA(r)&&_A(n)?`${r}@openai-curated`:void 0}function _A(e){return bA.includes(e)}function wA(e){return Pd.includes(e)}function Cx(e,t){let r=t??an;return{computer_use:e?.computer_use??r.computer_use,work:e?.work??r.work,frontend:e?.frontend??r.frontend,security:e?.security??r.security}}function Kc(e,t=[]){let r=[],n=new Set;for(let o of TA){if(!e[o])continue;for(let i of zc[o].pluginIds)if(!n.has(i))n.add(i),r.push(i)}for(let o of t)if(!n.has(o))n.add(o),r.push(o);return r}var Rx,j2,B2,V2,bA,Pd,Vn,z2,zc,TA,an;var Ax=x(()=>{Tt();Rx=T("computer_use","work","frontend","security"),j2=T("computer_use","work","frontend","security"),B2=T("installed","disabled","missing","uncertain"),V2=T("healthy","missing","disabled","uncertain"),bA=Object.freeze(["openai-curated","openai-curated-remote"]),Pd=Object.freeze(["build-web-apps","codex-security"]);Vn=Object.freeze({coding:!0,computer_use:!1,work:!1,frontend:!0,security:!0}),z2={work:{name:"work",pluginIds:["documents@openai-primary-runtime","pdf@openai-primary-runtime","presentations@openai-primary-runtime","spreadsheets@openai-primary-runtime","template-creator@openai-primary-runtime"],defaultSelected:Vn.work,migrationKey:"work",semanticSkillIds:["documents:documents","pdf:pdf","presentations:Presentations","spreadsheets:Spreadsheets","template-creator:template-creator"],ownership:"shared-preserve"},frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Vn.frontend,migrationKey:"frontend",semanticSkillIds:["build-web-apps:frontend-app-builder","build-web-apps:frontend-testing-debugging","build-web-apps:react-best-practices"],ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Vn.security,migrationKey:"security",semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Vn.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],ownership:"shared-preserve"}},zc=Object.freeze(z2),TA=Object.freeze(["computer_use","work","frontend","security"]),an=Object.freeze({computer_use:Vn.computer_use,work:Vn.work,frontend:Vn.frontend,security:Vn.security})});function sn(e){return b({identifier:T(e),label:A,requiresRootApproval:W})}function EA(e){let t=e.map((n)=>n.label),r=t.at(-1);if(r===void 0)return"";if(t.length===1)return r;return`${t.slice(0,-1).join(", ")}, and ${r}`}function vA(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var OA,K2,W2,Px,J2,RA,G2,Y2,Z2;var kA=x(()=>{Tt();OA=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"),K2=b({identifier:OA,label:A,requiresRootApproval:W});W2=b({localRepositoryEdit:sn("local.repository.edit"),localRepositoryCheck:sn("local.repository.check"),localRepositoryLint:sn("local.repository.lint"),localRepositoryFormat:sn("local.repository.format"),localRepositoryCommit:sn("local.repository.commit"),externalRead:sn("external.read"),specialistDispatch:sn("specialist.dispatch"),versionControlServerMutation:sn("vcs.server.mutation"),versionControlServerCiTrigger:sn("vcs.server.ci-trigger"),unknownEffect:sn("unknown.effect")}),Px={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}};zr(Px);J2=T("never","root"),RA=Object.values(Px);G2=RA.filter((e)=>!e.requiresRootApproval),Y2=RA.filter((e)=>e.requiresRootApproval),Z2=Object.freeze({noRootApproval:`${vA(EA(G2))} actions do not require Root approval.`,rootApproval:`${vA(EA(Y2))} require Root approval.`})});function Id(e){let t=br(X2,e);if(Ee(t))return Ko(ps("sha256 digest",t.left));return Ki(t.right)}var Hr,Ix,M6,N6,F6,X2,Q2,eU,tU,rU;var Md=x(()=>{er();Tt();Wi();za();Hr=A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Ix=A.pipe(de(/^[0-9a-f]{64}$/u)),M6=Hr.pipe(Vc("RunId")),N6=Hr.pipe(Vc("ProjectId")),F6=Hr.pipe(Vc("TrustId")),X2=Ix.pipe(Vc("Sha256Digest"));Q2=b({run_id:Hr,objective_lineage:Hr,parent_run_id:_(ye(Hr,ut))}),eU=b({project_id:Hr,trust_id:Hr,trust_digest:Ix}),tU=b({project_id:Hr,project_digest:Ix}),rU=A.pipe(de(/^state-[0-9]+\.[0-9]+$/u))});function Mx(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 IA(e){return typeof e==="string"&&oU.has(e)}function aU(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:r}=e;if(!IA(t)||typeof r!=="string")return!1;return Wc.get(t)?.tasks.some((n)=>n.name===r)===!0}function Fd(e,t){return typeof t==="string"&&Wc.get(e)?.tasks.some((r)=>r.name===t)===!0}function MA(e){return typeof e==="string"&&iU.has(e)}function Dx(e){let t=`${e.role}.${e.task}`;if(!Fx.has(t))throw Error("Unknown native specialist agent type.");return t}function qx(e){let t=Wc.get(e.role)?.tasks.find((r)=>r.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.instruction}function Ux(e){let t=Wc.get(e.role)?.tasks.find((r)=>r.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function FA(e){let t=Wc.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function Hx(e){let t=FA(e.role),r=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":t.permissions.network?"current_sources":"disabled";return Object.freeze({network:r!=="disabled",write:t.permissions.write,networkScope:r})}var Mo,CA,Nd,Mi,nU,AA="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.",$r,Wc,oU,Nx,iU,PA,Fx,Lx,sU,cU,lU,uU,Jc,Ni,NA,Ka,pU,LA,dU,No;var Gc=x(()=>{Tt();Mo=T("low","default","high"),CA=T("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),Nd=ye(Mo,CA);Mi=T("standard","fast","fast-all"),nU=T("low","medium","high","xhigh","max"),$r=[{role:"Explorer",tasks:[{name:"lookup",description:"Use when Root needs one exact repository fact; locate it and return the exact path, symbol, or value.",instruction:"Locate the exact requested repository fact."},{name:"trace",description:"Use when Root needs a complete in-scope execution or reference path; trace every relevant caller and constraint, then return the path and evidence.",instruction:"Trace the complete in-scope execution or reference path."}],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,write:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Use when Root needs one exact current external fact; locate it in the assigned authoritative source and return the citation.",instruction:"Locate the exact requested authoritative external fact."},{name:"research",description:"Use when Root needs a sourced current synthesis; combine the assigned authoritative sources with citations and return the evidence and uncertainty.",instruction:"Synthesize the assigned current sources with citations."}],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:!0,write:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Use when Root has decided deterministic edits; apply only those edits, verify the result, and return changed paths and evidence.",instruction:"Apply only deterministic, already-decided edits."},{name:"implementation",description:"Use when Root has decided a bounded behavior seam; implement and verify that seam, then return changed paths and evidence.",instruction:"Implement and verify the bounded behavior seam."},{name:"integration",description:"Use when Root has decided seams that must be combined; integrate and verify them together, then return the result and residual risk.",instruction:"Integrate the decided seams and verify them together."},{name:"operations",description:"Use after Root approves an exact ref or SHA; observe required CI and release state to terminal evidence and return it, never treating pending as success.",instruction:"After Root approves an exact ref or SHA, observe required CI and release state through terminal evidence; pending or running state is never success."}],capability:"bounded-write",authority:"Change only the delegated Assignment seam; 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,write:!0}},{role:"Reviewer",tasks:[{name:"plan",description:"Use when Root needs a complete plan adversarially checked; review it to a fixed point and return findings, proof, and residual risk.",instruction:"Review the complete plan to a fixed point."},{name:"code",description:"Use when Root needs implemented code adversarially checked; review and repair it to a fixed point, returning findings, proof, and residual risk.",instruction:"Review and repair the implemented code to a fixed point."},{name:"artifact",description:"Use when Root needs a produced artifact inspected; review and repair it to a fixed point, returning findings, proof, and residual risk.",instruction:"Review and repair the produced artifact to a fixed point."}],capability:"bounded-review",authority:"Inspect and repair only reviewer-owned defects within the delegated Assignment; 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,write:!0}}];zr($r);Wc=new Map($r.map((e)=>[e.role,e])),oU=new Set($r.map((e)=>e.role)),Nx=$r.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),iU=new Set(Nx),PA=Nx.map((e)=>e.replace(":",".")),Fx=new Set(PA);Lx=q(IA),sU=q((e)=>Fd("Explorer",e)),cU=q((e)=>Fd("Librarian",e)),lU=q((e)=>Fd("Worker",e)),uU=q((e)=>Fd("Reviewer",e)),Jc=q(aU),Ni=Object.freeze(Nx.filter((e)=>MA(e))),NA=q(MA),Ka=Object.freeze(PA.filter((e)=>Fx.has(e))),pU=q((e)=>typeof e==="string"&&Fx.has(e));LA=b({profile:Mo,service_tier:_(Mi)}),dU=T("git_vcs","computer_use"),No=Object.freeze({requiresDelegation:!0,trivialWorkRequiresDelegation:!0,directExecutionExceptions:Object.freeze(["git_vcs","computer_use"]),requestUserInputGates:Object.freeze(["plan_approval","installation_profile_approval","remote_origin_server_vcs_mutation","public_publication_or_release","ambiguity_or_missing_material_input"]),surgicalMutationRule:AA,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Ft(e,t){return new Je("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function $x(e,t,r){if(e===null)return"null";switch(typeof e){case"string":{let n=JSON.stringify(e);if(n===void 0)throw Ft(t,"invalid string");return n}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw Ft(t,"non-finite number");let n=JSON.stringify(e);if(n===void 0)throw Ft(t,"invalid number");return n}case"undefined":throw Ft(t,"undefined is not JSON");case"bigint":throw Ft(t,"bigint is not JSON");case"function":throw Ft(t,"function is not JSON");case"symbol":throw Ft(t,"symbol is not JSON");case"object":break}if(r.has(e))throw Ft(t,"cyclic value");r.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw Ft(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 Ft(`${t}[${s}]`,"sparse or accessor array item");a.push($x(c.value,`${t}[${s}]`,r))}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 Ft(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw Ft(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw Ft(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw Ft(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 Ft(`${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 Ft(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${$x(a.value,`${t}.${i}`,r)}`)}return`{${o.join(",")}}`}finally{r.delete(e)}}function cn(e){return $x(e,"$",new Set)}function zn(e){return new TextEncoder().encode(cn(e))}function DA(e,t){if(e.length===0||e.includes("\x00"))throw new Je("invalid_digest_domain","Digest domains must be non-empty and NUL-free.",{field:"domain"});let r=new TextEncoder().encode("holycodex-sha256\x00"),n=new TextEncoder().encode(e),o=r.byteLength+8+n.byteLength;for(let c of t){if(c.byteLength>4294967295||o>4294967291-c.byteLength)throw new Je("invalid_digest_domain","Digest input is too large.");o+=4+c.byteLength}let i=new Uint8Array(o),a=new DataView(i.buffer);i.set(r,0);let s=r.byteLength;a.setUint32(s,n.byteLength,!1),s+=4,i.set(n,s),s+=n.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 mU(e){let t="";for(let r of e)t+=r.toString(16).padStart(2,"0");return t}async function Kn(e,t){let r=globalThis.crypto?.subtle;if(!r)throw new Je("crypto_unavailable","The standards-based crypto API is unavailable.");let n=await r.digest("SHA-256",hU(DA(e,t)));return mU(new Uint8Array(n))}function hU(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var jx=x(()=>{Wi();Md()});function HA(e){try{return cn(e)!==void 0}catch{return!1}}function Dd(e){let t=br(WA,e);if(Ee(t))return Ko(ps("CLI envelope",t.left));return Ki(t.right)}var qA,UA,$A,gU,yU,Bx="holycodex-specialist-outcome-2",Gt,Yc,xU,SU,bU,_U,wU,TU,Ld,EU,vU,OU,RU,kU,jA,BA,VA,CU,zA,KA,WA;var JA=x(()=>{er();Tt();jx();Ax();Wi();Md();Gc();za();qA=T("blocked","completed","failed","partial"),UA=ye(T("high","max","xhigh"),ut);$A=q((e)=>HA(e)),gU=q((e)=>qf(e)&&!Array.isArray(e)&&HA(e)),yU=b({blocked:W,changed_files:U(A),confidence:Jt,context_owner:ye(A,ut),material_findings:U(A),needs_more_context:W,needs_root_decision:W,needs_verification:W,relevant_files:U(A),remaining_risk:U(A),reuse_recommended:W,status:qA,suggested_followup:ye(A,ut),suggested_luna_effort:UA,suggested_specialist:ye(Lx,ut),verification:U(A),verification_passed:W}),Gt=A.pipe(Va(1)),Yc={protocol_version:T(Bx),route:Jc,evidence:U(Gt)},xU=b(Yc),SU=b({...Yc,status:T("completed"),summary:Gt}),bU=b({...Yc,status:T("blocked"),reason:Gt,needs_root_decision:W}),_U=b({...Yc,status:T("partial"),summary:Gt,completed:U(Gt),remaining:U(Gt),needs_root_decision:W}),wU=b({...Yc,status:T("failed"),error:Gt}),TU=ye(SU,bU,_U,wU),Ld={protocol_version:T(Bx),capability:Rx,route:ye(Jc,ut),evidence:U(Gt),data:$A},EU=b({...Ld,status:T("completed"),summary:Gt}),vU=b({...Ld,status:T("blocked"),reason:Gt,needs_root_decision:W}),OU=b({...Ld,status:T("partial"),summary:Gt,completed:U(Gt),remaining:U(Gt),needs_root_decision:W}),RU=b({...Ld,status:T("failed"),error:Gt}),kU=ye(EU,vU,OU,RU),jA=U(A),BA=A.pipe(de(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),VA=T(xn),CU=b({code:Hr,message:A,details:gU}),zA=b({schema_version:VA,ok:T(!0),command:BA,data:$A,warnings:jA}),KA=b({schema_version:VA,ok:T(!1),command:BA,error:CU,warnings:jA}),WA=ye(zA,KA)});function AU(e,t,r){return{key:`${e}:${t}`,role:e,task:t,model:YA,effort:r}}function MU(e){let t=IU.get(e);if(t===void 0)throw new Je("catalog_invalid","A profile has no route effort policy.",{profile:e});return $r.flatMap((r)=>r.tasks.map((n)=>{let o=`${r.role}:${n.name}`,i=t.efforts[o];if(i===void 0)throw new Je("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return AU(r.role,n.name,i)}))}function Vx(e){return{name:e.name,root:{model:"gpt-6-astra",effort:e.effort},specialistModel:"gpt-5.6-luna",defaultServiceTier:"standard",routes:MU(e.name)}}function NU(e){let t=["low","default","high"];if(e.length!==t.length)throw new Je("catalog_invalid","The profile catalog has an invalid size.");for(let r=0;r<t.length;r+=1){let n=e[r],o=t[r];if(!n||n.name!==o)throw new Je("catalog_invalid","The profile catalog order is invalid.",{index:r});let i=o==="low"?"low":o==="default"?"medium":"high";if(n.root.model!=="gpt-6-astra"||n.root.effort!==i||n.specialistModel!=="gpt-5.6-luna")throw new Je("catalog_invalid","A profile has an invalid model route.",{profile:n.name});if(n.routes.length!==Ni.length)throw new Je("catalog_invalid","A profile is incomplete.",{profile:n.name});let a=new Set;for(let s of n.routes){if(a.has(s.key)||!PU.has(s.key)||s.model!=="gpt-5.6-luna"||`${s.role}:${s.task}`!==s.key)throw new Je("catalog_invalid","A profile contains an invalid route.",{profile:n.name});a.add(s.key)}if(a.size!==Ni.length)throw new Je("catalog_invalid","A profile is missing a specialist route.",{profile:n.name})}for(let r=0;r<Ni.length;r+=1){let n=-1;for(let o of e){let i=o.routes[r];if(!i||GA[i.effort]<n)throw new Je("catalog_invalid","Profile route effort is not monotonic.",{route:Ni[r]??"unknown"});n=GA[i.effort]}}}function ln(e){let t=br(Mo,e);if(Ee(t))return Ko(new Je("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let r=XA.get(t.right);if(!r)return Ko(new Je("invalid_profile","Unknown profile selection.",{profile:t.right}));return Ki(r)}var YA="gpt-5.6-luna",PU,GA,zx,IU,Kx,ZA,XA,FU;var QA=x(()=>{er();Wi();Gc();za();PU=new Set(Ni),GA={low:0,medium:1,high:2,xhigh:3,max:4},zx=[{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","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","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","Reviewer:plan":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];zr(zx);IU=new Map(zx.map((e)=>[e.profile,e]));Kx=[Vx({name:"low",effort:"low"}),Vx({name:"default",effort:"medium"}),Vx({name:"high",effort:"high"})];NU(Kx);zr(Kx);ZA=Kx,XA=new Map,FU=new Map;for(let e of ZA){XA.set(e.name,e);let t=new Map;for(let r of e.routes)t.set(r.key,r);FU.set(e.name,t)}});import{execFile as LU}from"child_process";import{promisify as DU}from"util";var tP="holycodex-intent-1",rP="holycodex-plan-1",nP="holycodex-assignment-1",qd="toon-4",Q,Fo,Wx,Zc,un,Qe,iY,Jx,Fi,Gx,Yx,qU,eP,UU,HU,Zx,oP,iP,$U,aY,jU,BU,VU,zU,KU,sY;var aP=x(()=>{Tt();Gc();za();Q=A.pipe(Xe((e)=>e.trim().length>0)),Fo=A.pipe(de(/^[a-z0-9][a-z0-9-]{0,95}$/u)),Wx=A.pipe(de(/^[a-f0-9]{64}$/u)),Zc=Cd.pipe(SA(1)),un=A.pipe(Xe((e)=>!Number.isNaN(Date.parse(e)))),Qe=U(Q),iY=b({pid:Cd.pipe(Ex(0)),token:Q}),Jx=b({role:T("Explorer","Librarian","Worker","Reviewer"),task:Q}).pipe(Xe((e)=>$r.some((t)=>t.role===e.role&&t.tasks.some((r)=>r.name===e.task)))),Fi=b({kind:T("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:Q,result:_(T("passed","failed","observed","unknown"))}),Gx=b({root:Q,git_common_dir:Q,initial_head:Q,expected_head:Q,expected_changes:Qe,expected_status_digest:Wx,updated_at:un}),Yx=T("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),qU=T("scoping","ready","executing","verifying","reviewing"),eP=b({required:W,status:T("not_required","missing","passed","failed","accepted","rejected"),evidence:U(Fi)}),UU=b({schema_version:T(tP),toon_compatibility:T(qd),id:Fo,slug:Fo,title:Q,goal:Q,acceptance_criteria:Qe,state:Yx,revision:Zc,plan_required:W,active_plan_revision:_(Zc),active_plan_digest:_(Wx),blockers:Qe,resume_state:_(qU),verification:eP,review:eP,acceptance_met:W,root_readiness:W,evidence:U(Fi),baseline:Gx,created_at:un,updated_at:un}),HU=b({schema_version:T(rP),toon_compatibility:T(qd),intent_id:Fo,revision:Zc,predecessor_digest:_(Wx),approach:Q,scope:Qe,exclusions:Qe,assignments:Qe,dependencies:Qe,architecture:Qe,risks:Qe,assumptions:Qe,open_questions:Qe,verification:Qe,recovery:Qe,updated_at:un}),Zx=T("completed","blocked","needs_root_input","failed"),oP=T("pending","executing","completed","blocked","needs_root_input","failed"),iP=b({id:Fo,outcome:Zx,started_at:un,finished_at:un,summary:Q,evidence:U(Fi),blocker:_(Q),remaining_risk:Qe}),$U=b({schema_version:T(nP),toon_compatibility:T(qd),intent_id:Fo,id:Fo,objective:Q,owner:Jx,scope:Qe,constraints:Qe,exclusions:Qe,dependencies:Qe,acceptance_criteria:Qe,status:oP,revision:Zc,invocations:U(iP),evidence:U(Fi),blocker:_(Q),remaining_risk:Qe,created_at:un,updated_at:un}),aY=b({schema_version:T("holycodex-intent-0"),id:Fo,slug:Fo,title:Q,goal:Q,acceptance_criteria:Qe,state:Yx,revision:Zc,baseline:Gx,created_at:un,updated_at:un}),jU=b({title:Q,goal:Q,acceptanceCriteria:U(Q).pipe(Ad(1)),planRequired:_(W),verificationRequired:_(W),reviewRequired:_(W)}),BU=b({approach:Q,scope:_(U(Q)),exclusions:_(U(Q)),assignments:_(U(Q)),dependencies:_(U(Q)),architecture:_(U(Q)),risks:_(U(Q)),assumptions:_(U(Q)),openQuestions:_(U(Q)),verification:_(U(Q)),recovery:_(U(Q))}),VU=b({id:_(Q),objective:Q,owner:Jx,scope:U(Q).pipe(Ad(1)),constraints:_(U(Q)),exclusions:_(U(Q)),dependencies:_(U(Q)),acceptanceCriteria:U(Q).pipe(Ad(1))}),zU=b({invocationId:_(Q),outcome:Zx,startedAt:_(Q),summary:Q,evidence:_(U(Fi)),blocker:_(Q),remainingRisk:_(U(Q))}),KU=b({evidence:_(U(Fi)),verification:_(T("passed","failed")),review:_(T("accepted","rejected")),acceptanceMet:_(W),rootReadiness:_(W),clearBlockers:_(W)}),sY=DU(LU)});var pt=x(()=>{Lb();Wi();za();Ax();kA();Md();Gc();JA();QA();jx();aP()});function ne(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Fe(e){try{return cn(e),!0}catch{return!1}}function oH(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 lP(e){return{ok:!1,error:e}}function uP(e){return{ok:!0,value:e}}function ir(e,t=512){let r="";for(let n of e){let o=n.codePointAt(0)??0;r+=o<=8||o===11||o===12||o>=14&&o<=31||o===127?" ":n}return r.replace(/\s+/gu," ").trim().slice(0,t)}function Li(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return ir(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((r)=>Li(r,t+1));if(ne(e)){let r={};for(let[n,o]of Object.entries(e).slice(0,32)){let i=ir(n,96);if(i.length>0)r[i]=Li(o,t+1)}return r}return"[redacted]"}function pP(e){let t=Li(e);return ne(t)?t:{value:t}}function Le(e,t,r){return new V("invalid_external_data",`Invalid ${e}.`,{field:e,received:Li(t)},r===void 0?void 0:{cause:r})}function Ae(e,t,r){let n=br(e,t);if(Ee(n))throw Le(r,t,String(n.left));return n.right}function dP(e,t){try{return Ae(e,t,"value"),!0}catch{return!1}}var eS,tl=1048576,tS=65536,ar,Lo,n5,Wn,nH,V;var pn=x(()=>{pt();er();Tt();eS=xn;ar=q((e)=>Fe(e)),Lo=q((e)=>ne(e)&&Fe(e)),n5=A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Wn=A.pipe(Xe((e)=>e.length>0&&e.length<=4096)),nH=Jt.pipe(Xe((e)=>Number.isFinite(e)&&e>=0));V=class V extends Error{code;kind;details;retryable;constructor(e,t,r={},n){super(t,n?.cause===void 0?void 0:{cause:n.cause});this.name="CodexError",this.code=e,this.kind=oH(e),this.details=r,this.retryable=n?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var rS,rl,nl,nS,oS,iS,aS="turn/completed";var jd=x(()=>{rS=["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"],rl=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],nl=["item/permissions/requestApproval"],nS=["mcpServer/elicitation/request"],oS=["item/tool/call"],iS={method:"initialized"}});function Ja(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((r)=>Ja(r,t));return ne(e)&&Object.values(e).every((r)=>Ja(r,t))}finally{t.delete(e)}}function dn(e){return ne(e)&&Ja(e)}function sS(e){let t=[],r=0,n=!1,o=!1;for(let i=0;i<=e.length;i+=1){let a=e[i];if(i===e.length||a==="."&&!n){let s=e.slice(r,i),c=s.startsWith('"')?aH(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Ka.includes(c))throw Le("TOML key path",e);t.push(c),r=i+1;continue}if(n){if(o)o=!1;else if(a==="\\")o=!0;else if(a==='"')n=!1}else if(a==='"')n=!0}if(n||o||t.length===0)throw Le("TOML key path",e);if(t.some((i)=>i==="__proto__"||i==="constructor"||i==="prototype"))throw Le("TOML key path",e);return t}function aH(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Le("TOML quoted key",e)}function Pe(e,t){if(!dn(e))throw Le("TOML document",e);let r=e;for(let n of sS(t)){if(!dn(r)||!Object.prototype.hasOwnProperty.call(r,n))return;r=r[n]}return r}function Bd(e){if(Array.isArray(e))return e.map(Bd);if(ne(e))return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Bd(r)]));return e}function Vd(e){return Bd(e)}function cS(e,t,r){if(!dn(e)||!Ja(r))throw Le("TOML write",{keyPath:t});let n=sS(t),o={...Vd(e)},i=o;for(let a of n.slice(0,-1)){let s=i[a];if(s!==void 0&&!dn(s))throw Le("TOML table path",t);let c=s===void 0?{}:{...s};i[a]=c,i=c}return i[n.at(-1)]=Bd(r),o}function zd(e,t){if(!dn(e))throw Le("TOML document",e);let r=sS(t),n={...Vd(e)},o=[],i=n;for(let s of r.slice(0,-1)){let c=i[s];if(!dn(c))return n;let l={...c};o.push({table:i,key:s}),i[s]=l,i=l}let a=r.at(-1);if(!Object.prototype.hasOwnProperty.call(i,a))return n;delete i[a];for(let s=o.length-1;s>=0;s-=1){let c=o[s],l=c.table[c.key];if(dn(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return n}function il(e){if(typeof e!=="string")return!1;if(mP.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Ka.some((t)=>e===`agents."${t}".config_file`)}function Kd(e){return il(e)}function Do(e){return typeof e==="string"&&cH.test(e)}function lS(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 lH(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function uS(e,t){let r=new Set(t);return Object.keys(e).every((n)=>r.has(n))}function pS(e){if(!ne(e)||!uS(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return lS(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&Gd(e.value);case"digest":return lH(e.value);default:return!1}}function fP(e,t){switch(fS(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 xP(e){return ne(e)&&e.kind==="absent"?Object.keys(e).length===1:pS(e)}function SP(e){return ne(e)&&uS(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Do(e.schema)&&Do(e.installId)&&Kd(e.keyPath)&&xP(e.originalValue)&&pS(e.lastManagedValue)&&fP(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||fP(e.keyPath,e.originalValue))}function Ga(e){if(!ne(e)||!uS(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Do(e.schema)||!Do(e.installId)||!ne(e.managed))return!1;return Object.entries(e.managed).every(([t,r])=>Kd(t)&&SP(r)&&r.keyPath===t)}function Jd(e){if(!Do(e.schema)||!Do(e.installId))throw Le("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Gd(e){if(e.length===0||e.includes("\x00")||/^[\\/]|^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/").split("/");return t.some((r)=>r!==".")&&t.every((r)=>r.length>0&&r!=="..")}function dS(e){if(!Gd(e))throw Le("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function al(e,t){let r=dS(t),n=e.replaceAll("\\","/").split("/");n.pop();let o=[...n,...r.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 fS(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_v2"||e==="features.context_management.experimental_mode")return"boolean";return"enum"}function uH(e,t){let r=fS(e);if(r==="boolean")return typeof t==="boolean";if(r==="relative_path")return typeof t==="string"&&Gd(t);if(r==="digest")return typeof t==="string";return typeof t==="string"&&lS(t)}async function Wa(e,t){if(!Kd(e)||!Ja(t))throw Le("managed config value",{keyPath:e});let r=fS(e);if(r==="boolean"&&typeof t==="boolean")return{kind:r,value:t};if(r==="relative_path"&&typeof t==="string"&&Gd(t))return{kind:r,value:dS(t)};if(r==="enum"&&typeof t==="string"&&lS(t))return{kind:r,value:t};return{kind:"digest",value:await Kn("holycodex-managed-config-value",[zn({keyPath:e,value:t})])}}function pH(e){if(e.kind==="enum"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function sl(e,t,r,n){if(!dn(e)||!Ga(t)||!Do(n.schema)||!Do(n.installId))throw Le("managed runtime config",{});let o={...t.managed},i=Vd(e),a=[];for(let[c,l]of Object.entries(r)){if(!il(c)||typeof l!=="string"&&typeof l!=="boolean")throw Le("managed config key",c);let u=c,p=t.managed[u],f=Pe(i,u);if(p&&(p.schema!==n.schema||p.installId!==n.installId)){a.push(u);continue}if(p&&p.owner==="holycodex"){let m=f===void 0?void 0:await Wa(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 Wa(u,f));if(!uH(u,l))throw Le("managed config value",{keyPath:u});i=cS(i,u,l),o[u]={owner:"holycodex",schema:n.schema,installId:n.installId,keyPath:u,originalValue:h,lastManagedValue:await Wa(u,l)}}let s={owner:"holycodex",schema:n.schema,installId:n.installId,managed:o};if(!Ga(s))throw Le("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Di(e,t,r){if(!dn(e)||!Ga(t))throw Le("managed runtime config",{});let n=Vd(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!Kd(c))throw Le("managed config key",c);let u=c;if(l.owner!=="holycodex"||l.schema!==r.schema||l.installId!==r.installId){if(l.schema!==r.schema||l.installId!==r.installId)s.push(u);continue}let p=Pe(n,u);if(!(p!==void 0&&JSON.stringify(await Wa(u,p))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")n=zd(n,u),i.push(u),delete o[u];else{let h=pH(l.originalValue);if(h===void 0){s.push(u),a.push(u);continue}n=cS(n,u,h),i.push(u),delete o[u]}}return{document:n,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function Ya(e,t,r){if(!il(r)||!Ga(t))throw Le("managed config key",r);let n=t.managed[r],o=Pe(e,r),i=o===void 0?void 0:await Wa(r,o);if(!n)return i===void 0?{keyPath:r,status:"unmanaged"}:{keyPath:r,status:"unmanaged",current:i};return{keyPath:r,status:i!==void 0&&JSON.stringify(i)===JSON.stringify(n.lastManagedValue)?"unchanged":"drifted",expected:n.lastManagedValue,...i===void 0?{}:{current:i}}}var iH,ol,mP,sH,hP,gP,yP,Wd,cH;var Yd=x(()=>{pt();pt();Tt();pn();iH=q((e)=>Ja(e)),ol=q((e)=>dn(e));mP=["model","model_reasoning_effort","service_tier","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.default_mode_request_user_input","features.multi_agent_v2","features.context_management.experimental_mode"],sH=q((e)=>il(e));hP=q((e)=>pS(e)),gP=q((e)=>xP(e)),yP=q((e)=>SP(e)),Wd=q((e)=>Ga(e)),cH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function fH(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function bP(e,t,r){let n=new Set([...t,r]),o=Object.keys(e);if(Object.keys(e).some((i)=>!n.has(i)))return!1;return o.length>0&&o.every((i)=>fH(e[i]))}function TP(e){if(!ne(e)||!Fe(e))return!1;return bP(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||bP(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function Zd(e){return ne(e)&&Fe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function EP(e){return ne(e)&&Fe(e)&&Zd(e.thread)}function gH(e){return ne(e)&&Fe(e)&&typeof e.id==="string"}function qo(e){return ne(e)&&Fe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function vP(e){return ne(e)&&Fe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||TP(e.usage))}function yH(e){return ne(e)&&Fe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>ne(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>ne(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 OP(e){if(nl.some((t)=>t===e))return"permissions";if(rl.some((t)=>t===e))return"approval";if(nS.some((t)=>t===e))return"elicitation";if(oS.some((t)=>t===e))return"dynamic_tool";return"other"}var _P,cl,wP,ll,dH,mS,ul,mH,Xd,hS,gS,hH,pl,yS,xS,SS,bS,_S,wS,TS,ES,vS,OS,RS,kS,CS,AS,PS,IS,MS,NS,FS,LS,DS,qS,US,HS,$S,jS,BS,VS,f5,xH,m5;var zS=x(()=>{Tt();pn();jd();Yd();_P=A.pipe(de(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),cl=ye(A.pipe(Va(1)),Jt.pipe(Xe((e)=>Number.isSafeInteger(e)))),wP=b({code:Jt.pipe(Xe((e)=>Number.isSafeInteger(e))),message:A,data:_(ar)}),ll=ye(b({id:cl,result:ar}),b({id:cl,error:wP})),dH=b({id:cl,error:wP}),mS=b({method:_P,params:_(ar)}),ul=b({id:cl,method:_P,params:_(ar),trace:_(ar)});mH=q(TP),Xd=b({clientInfo:b({name:Wn,version:Wn,title:ye(Wn,ut)}),capabilities:ye(b({experimentalApi:W,requestAttestation:W,mcpServerOpenaiFormElicitation:_(W),optOutNotificationMethods:_(ye(U(A),ut)),extensions:_(Lo)}),ut)}),hS=q((e)=>ne(e)&&Fe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),gS=b({method:T("initialized")});hH=q(Zd);pl=q((e)=>EP(e)||gH(e)),yS=pl,xS=pl,SS=q(qo),bS=q((e)=>ne(e)&&Fe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),_S=q((e)=>EP(e)),wS=q((e)=>{if(!ne(e)||!Fe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((n)=>Zd(n)),r=Array.isArray(e.threads)&&e.threads.every((n)=>Zd(n));return t&&e.threads===void 0||r&&e.data===void 0}),TS=q((e)=>ne(e)&&Fe(e));ES=q(qo),vS=q(qo),OS=q(qo),RS=q((e)=>ne(e)&&Fe(e));kS=q((e)=>qo(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Fe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),CS=q((e)=>qo(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Fe(t))),AS=q((e)=>ne(e)&&Fe(e)&&(e.turn!==void 0&&vP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),PS=q((e)=>ne(e)&&Fe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),IS=q((e)=>qo(e)&&typeof e.turnId==="string"&&e.turnId.length>0),MS=q((e)=>ne(e)&&Fe(e)),NS=q((e)=>qo(e)&&(e.turn!==void 0&&vP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),FS=q((e)=>ne(e)&&Fe(e));LS=q((e)=>ne(e)&&Fe(e)&&Array.isArray(e.data)&&e.data.every((t)=>yH(t))),DS=Lo,qS=Lo,US=b({includeLayers:_(W),cwd:_(ye(A,ut))}),HS=b({config:ol,origins:Lo,layers:ye(U(Lo),ut)}),$S=Lo,jS=Lo,BS=q((e)=>ne(e)&&Fe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&ne(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),VS=ar,f5=q((e)=>ne(e)&&Fe(e)&&typeof e.kind==="string"&&typeof e.method==="string");xH=ye(T("stable","experimental","disabled"),W),m5=Rd({key:A,value:xH})});class Qd{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??tl,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new V("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new V("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=SH){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new V("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Ae(Xd,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",TS,e,pl)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",ES,t,yS)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",vS,t,_S)}async listThreads(e={}){return this.action("thread/list",RS,e,wS)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",OS,t,xS)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",SS,t,bS)}async startTurn(e){return this.action("turn/start",kS,e,AS)}async steerTurn(e){return this.action("turn/steer",CS,e,PS)}async interruptTurn(e,t){let r=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",IS,r,MS)}async listModels(e={}){return this.action("model/list",FS,e,LS)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",DS,e,qS)}async readConfig(e={}){return this.action("config/read",US,e,HS)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",$S,e,jS)}async call(e,t={}){if(e==="initialize"){let n=await this.initialize(Ae(Xd,t,"initialize parameters"));return Ae(ar,n,"initialize result")}let r=Ae(ul,{id:1,method:e,params:t},"App Server method");if(!bH.has(r.method))throw new V("method_unsupported",`Unsupported App Server method: ${e}.`,{method:e});return this.request(r.method,r.params===void 0?{}:r.params)}async close(){await this.closeWithError(new V("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Ae(ar,e,"initialize parameters")),r=Ae(hS,t,"initialize result"),n=Ae(gS,iS,"initialized notification");return await this.transport.writeLine(JSON.stringify(n)),this.initialized=!0,r}catch(t){let r=t instanceof V?t:new V("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(r),r}}async action(e,t,r,n){let o=Ae(t,r,`${e} parameters`),i=Ae(ar,o,`${e} parameters`),a=await this.request(e,i);return Ae(n,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new V("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let r=this.nextRequestId;this.nextRequestId+=1;let n=Ae(ul,{id:r,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(r),s!==void 0)clearTimeout(s);c?.(),i(p)};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new V("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let p=()=>l(new V("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(r,u),this.transport.writeLine(JSON.stringify(n)).catch((p)=>{l(p instanceof V?p:new V("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 V("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new V("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof V?e:new V("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 V("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let r=this.tryDecode(ll,t);if(r!==void 0){this.handleResponse(r);return}let n=this.tryDecode(ul,t);if(n!==void 0){this.handleServerRequest(n);return}let o=this.tryDecode(mS,t);if(o!==void 0){this.handleNotification(o);return}throw Le("JSON-RPC message",t)}tryDecode(e,t){try{return Ae(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new V("unexpected_response","The App Server returned an unknown request id.",{id:e.id});if(this.pending.delete(e.id),"error"in e){let r=e.error.code===-32001,n=wH(t.method);t.reject(new V(n,`The App Server rejected ${t.method}: ${ir(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:r,...e.error.data===void 0?{}:{data:Li(e.error.data)}},{retryable:r}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},r=Ae(BS,{...e,params:t,category:OP(e.method)},"server request");this.emitNotification({kind:"server_request",method:e.method,params:t});let n=[...this.serverRequestHandlers];if(n.length===0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let o=n[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(r)}catch(s){this.completeServerRequest(i,()=>this.writeServerError(e.id,-32000,ir(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,ir(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let r=Ae(VS,t,"server response");return this.writeServerResult(e,r)}catch(r){return this.writeServerError(e,-32000,ir(String(r)))}}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 r=Ae(ll,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(r))}async writeServerError(e,t,r){let n=Ae(ll,{id:e,error:{code:t,message:_H(r)}},"server error response");await this.transport.writeLine(JSON.stringify(n))}handleNotification(e){let t=e.params;if(e.method===aS){let r=Ae(NS,t,"turn/completed notification");this.emitNotification({kind:"turn_completed",method:e.method,params:r});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:pP({params:Li(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 V("closed","The App Server client is closed.")}}function _H(e){let t=ir(e);return t.length>0?t:"server request failed"}function wH(e){if(nl.some((t)=>t===e))return"permission_denied";if(rl.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var SH,bH;var KS=x(()=>{pn();jd();zS();SH={clientInfo:{name:"holycodex",title:null,version:eS},capabilities:null},bH=new Set(rS)});import{isAbsolute as TH}from"path";function Uo(e=process.env){let t=["PATH","HOME","USER","CODEX_HOME","TMPDIR","TEMP","TMP","LANG","LC_ALL"],r={};for(let n of t){let o=e[n];if(o!==void 0&&o.length>0)r[n]=o}return r}function WS(e=process.env){return Object.freeze(Uo(e))}async function ef(e,t){let r=e.getReader(),n=[],o=0;try{while(!0){let s=await r.read();if(s.done)break;if(o+=s.value.byteLength,o>t)throw new V("invalid_transport_line","A subprocess stream exceeded its limit.");n.push(s.value)}}finally{r.releaseLock()}let i=new Uint8Array(o),a=0;for(let s of n)i.set(s,a),a+=s.byteLength;return i}function tf(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(r){throw new V("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:r})}}function Za(e){return ir(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}class rf{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!TH(e.executablePath))throw new V("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??tl,this.maxDiagnosticBytes=e.maxDiagnosticBytes??tS,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new V("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:Uo(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new V("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new V("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 V("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 V("invalid_transport_line","The App Server emitted an overlong line.");let r=await e.read();if(r.done){if(this.stdoutBuffer.byteLength===0)return null;if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new V("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 n=new Uint8Array(this.stdoutBuffer.byteLength+r.value.byteLength);n.set(this.stdoutBuffer,0),n.set(r.value,this.stdoutBuffer.byteLength),this.stdoutBuffer=n}}catch(t){if(t instanceof V)throw t;throw new V("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new V("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new V("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 V("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 ef(this.stderrStream,this.maxDiagnosticBytes),t=tf(e,"Codex stderr");for(let r of t.split(/\r?\n/u).slice(0,128)){let n=Za(r);if(n.length>0)this.stderrDiagnostics.push(n)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var nf=x(()=>{pn()});import{lstat as E5,mkdir as v5,readFile as EH,readdir as O5,realpath as vH,stat as OH}from"fs/promises";import{delimiter as RH,isAbsolute as k5,join as C5,relative as A5,resolve as RP}from"path";async function CH(e){let t=[];if(e.executablePath!==void 0)t.push(RP(e.cwd??process.cwd(),e.executablePath));else{let r=e.pathValue??e.environment?.PATH??process.env.PATH??"",n=process.platform==="win32"?["codex.exe","codex.cmd","codex"]:["codex"];for(let o of r.split(RH).filter((i)=>i.length>0))for(let i of n)t.push(RP(o,i))}for(let r of t)try{let n=await OH(r);if(!n.isFile())continue;if(process.platform!=="win32"&&(n.mode&73)===0)continue;return await vH(r)}catch{if(e.executablePath!==void 0)throw new V("discovery_failed","The explicit Codex executable was not found.",{path:r})}throw new V("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function AH(e,t){let r=Bun.spawn([e,"--version"],{env:t,stdin:"ignore",stdout:"pipe",stderr:"pipe"});if(!(r.stdout instanceof ReadableStream)||!(r.stderr instanceof ReadableStream))throw new V("discovery_failed","The Codex version command did not expose output pipes.");try{let[n,o,i]=await IH(Promise.all([ef(r.stdout,16384),ef(r.stderr,16384),r.exited]),()=>r.kill(),"The Codex version command timed out."),a=ir(tf(n,"Codex version output"));if(i!==0||a.length===0){let s=Za(tf(o,"Codex version diagnostics"));throw new V("discovery_failed","The Codex executable did not provide a version.",{exitCode:i,diagnostics:s})}return a}catch(n){try{r.kill()}catch{}if(n instanceof V)throw n;throw new V("discovery_failed","The Codex version command failed.",{},{cause:n})}}async function PH(e){let t=await EH(e),r=await crypto.subtle.digest("SHA-256",t),n=[...new Uint8Array(r)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=Id(n);if(!o.ok)throw new V("discovery_failed","The Codex executable digest was invalid.");return o.value}async function JS(e={}){let t=await CH(e),r=Uo(e.environment),n=e.versionRunner?ir(await e.versionRunner(t,r)):await AH(t,r);if(n.length===0)throw new V("discovery_failed","The Codex version output was empty.");return{path:t,version:n,sha256:await PH(t)}}async function IH(e,t,r){let n;try{return await Promise.race([e,new Promise((o,i)=>{n=setTimeout(()=>{try{t()}catch{}i(new V("timeout",r))},kH)})])}finally{if(n!==void 0)clearTimeout(n)}}var kH=30000,N5;var kP=x(()=>{pt();Tt();pn();nf();N5=b({exitCode:Jt.pipe(Xe((e)=>Number.isSafeInteger(e))),stdout:A.pipe(Tx(1048576)),stderr:A.pipe(Tx(1048576))})});var MH="packages/codex/generated",NH,FH,GS,q5,U5;var CP=x(()=>{pt();Tt();pn();NH=/^codex-cli \d+\.\d+\.\d+$/u,FH=/^codex-app-server-\d+\.\d+\.\d+$/u,GS=A.pipe(de(/^[a-f0-9]{64}$/u)),q5=b({schema_version:T("holycodex-generated-v2"),artifact_root:T(MH),codex_cli_version:A.pipe(de(NH)),codex_cli_digest:GS,protocol_epoch:A.pipe(de(FH)),generator:b({command:lA(T("app-server"),T("generate-ts")),supported_surface:T("codex app-server generators")}),typescript_root:T("typescript"),files:b({count:Jt.pipe(kd(),vx()),digest:GS})}),U5=b({path:A.pipe(Va(1)),size:Jt.pipe(kd(),vx()),sha256:GS})});var LH;var AP=x(()=>{Tt();Yd();LH=b({owner:T("holycodex"),schema:A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});import{spawn as DH}from"child_process";import{lstat as $o,mkdir as qH,mkdtemp as UH,readFile as HH,readdir as $H,realpath as YS,rename as jH,rm as BH,stat as z5}from"fs/promises";import{dirname as IP,isAbsolute as tb,join as Ho,relative as MP,resolve as af,sep as NP}from"path";async function LP(e){let t=ib(e.selectedPluginIds);if(t.length===0)return;if(HP(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new xe("cancelled","Official Codex marketplace bootstrap was cancelled.");let r=e.readSnapshot??((s)=>ob(s,e.selectedPluginIds)),n=await r(e.codexHome);if(n!==void 0&&cf(n,t))return n;let o=e.initializeRuntime??(()=>e$(e)),i,a;try{i=await o()}catch(s){a=G("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??nb,c=e.pollIntervalMs??VH,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new xe("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await r(e.codexHome);if(u!==void 0&&cf(u,t))return u;let p=s-(Date.now()-l);if(p<=0)break;await(e.sleep??r$)(Math.min(c,p))}a=G("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 xe&&s.code==="cancelled")throw s;a=s instanceof xe?s:G("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await DP({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 xe)throw s;throw G("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??G("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function DP(e){let t=ib(e.selectedPluginIds);if(t.length===0)throw G("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(HP(e.timeoutMs,void 0),!tb(e.codexHome))throw G("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new xe("cancelled","Official Codex marketplace fallback was cancelled.");let r=Uo(e.environment),n=e.gitRunner??BP("git",{environment:r,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??nb,i;try{i=await WH(n,o,e.signal)}catch(u){if(u instanceof xe)throw u;throw G("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Ho(e.codexHome,"plugins"),s=Ho(a,rb[1]);if(await GH(a,e.codexHome),await $o(s).catch((u)=>{if(hl(u))return;throw G("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw G("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await UH(Ho(a,".openai-plugins-stage-"));try{if(await XS(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(qi,l)}catch(m){if(t$(m))throw G("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",m);throw m}else{let m=await n.run(["clone","--depth=1","--no-tags",qi,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw G("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await sf(l);let u=await qP(l,e.codexHome,t);if(u===void 0||!cf(u,t))throw G("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await JH(n,l,o,e.signal)!==i)throw G("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await $o(s).catch((m)=>{if(hl(m))return;throw G("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw G("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await jH(l,s);let h=await ob(e.codexHome,e.selectedPluginIds);if(h===void 0||!cf(h,t))throw G("marketplace_invalid","The published official marketplace failed validation.");return h}catch(u){if(u instanceof xe)throw u;throw G("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await BH(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function WH(e,t,r){let n=await e.run(["ls-remote",qi,"HEAD"],{...r===void 0?{}:{signal:r},timeoutMs:t});if(n.exitCode!==0)throw G("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",n.stderr);let o=n.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 G("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function JH(e,t,r,n){let o=await e.run(["rev-parse","HEAD"],{timeoutMs:r,cwd:t,...n===void 0?{}:{signal:n}}),i=o.stdout.trim().toLowerCase();if(o.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(i))throw G("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function GH(e,t){await ZS(t,e),await qH(e,{recursive:!0}),await ZS(t,e)}async function ZS(e,t){let r=af(e),n=af(t);while(!0){if((await $o(n).catch((a)=>{if(hl(a))return;throw a}))?.isSymbolicLink())throw G("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(n===r)return;let i=IP(n);if(i===n||i!==r&&!YH(r,i))throw G("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");n=i}}function YH(e,t){let r=MP(e,t);return r.length>0&&r!==".."&&!r.startsWith(`..${NP}`)&&!tb(r)}async function sf(e){let t=await $o(e);if(t.isSymbolicLink())throw G("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw G("marketplace_invalid","The official marketplace snapshot is not a directory.");let r=await $H(e,{withFileTypes:!0});for(let n of r){let o=Ho(e,n.name),i=await $o(o);if(i.isSymbolicLink())throw G("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await sf(o)}}async function ob(e,t=[]){return await qP(Ho(e,...rb),e,ib(t))}async function qP(e,t,r=[]){if(t!==void 0)await ZS(t,e);let n=await $o(e).catch((l)=>{if(hl(l))return;throw G("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",l)});if(n===void 0)return;if(n.isSymbolicLink()||!n.isDirectory())throw G("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await XS(t,e);else await sf(e);if(t!==void 0)await sf(e);let o=await YS(e),i=[Ho(o,".agents","plugins","marketplace.json"),Ho(o,".codex-plugin","marketplace.json"),Ho(o,"marketplace.json")],a,s;for(let l of i){let u=await $o(l).catch((p)=>{if(hl(p))return;throw G("marketplace_invalid","The official marketplace manifest could not be read safely.",p)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw G("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await XS(o,l),a!==void 0)throw G("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await HH(l))}catch(p){throw G("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 G("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return UP(c,o,a,r)}function UP(e,t=`${rb.join("/")}`,r=`${t}/marketplace.json`,n=[]){if(!ne(e)||e.name!==ml)throw G("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");ZH(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw G("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!ne(s)||typeof s.name!=="string"){if(n.length>0)continue;throw G("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(n.length>0)continue;throw G("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(n.length>0&&!n.includes(c))continue;throw G("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),n.length>0&&!n.includes(c))continue;let l=XH(s);if(!QH(l))throw G("marketplace_invalid",`The official marketplace source for ${c} is unsafe.`);i.push({name:c,source:l})}if(n.some((s)=>!i.some((c)=>c.name===s)))throw G("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:ml,source:qi,rootPath:t,manifestPath:r,plugins:i}}function ZH(e){for(let t of["source","repository","repo","url"]){let r=e[t];if(r===void 0)continue;if((typeof r==="string"?r:ne(r)&&typeof r.url==="string"?r.url:void 0)!==qi)throw G("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function XH(e){let t=e.source;if(typeof t==="string")return t;if(ne(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function QH(e){if(e===void 0||e.length===0||tb(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((r)=>r.length===0||r==="."||r!=="..")}function ib(e){let t=[],r=new Set;for(let n of e){let o=n.lastIndexOf("@");if(o<1)continue;let i=n.slice(o+1);if(i!==ml&&i!=="openai-curated-remote")continue;let a=n.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw G("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!$P(a))continue;if(!r.has(a))r.add(a),t.push(a)}return t}function cf(e,t){return t.every((r)=>{let n=e.plugins.find((i)=>i.name===r);if(n===void 0)return!1;return n.source.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)===r})}async function e$(e){let t=Uo(e.environment),r;try{r=new rf({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let n=new Qd(r,{requestTimeoutMs:Math.min(e.timeoutMs??nb,1e4),...e.signal===void 0?{}:{signal:e.signal}});return await n.initialize(),async()=>{await n.close()}}catch(n){throw await r?.close().catch(()=>{return}),n}}function HP(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw G("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw G("marketplace_invalid","The official marketplace poll interval is invalid.")}async function XS(e,t){let r=await YS(e),n=await YS(t),o=MP(r,n);if(o===""||o===".."||o.startsWith(`..${NP}`))throw G("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=af(e),a=af(t);while(!0){if((await $o(a)).isSymbolicLink())throw G("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=IP(a);if(c===a)throw G("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function hl(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function t$(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function r$(e){await new Promise((t)=>setTimeout(t,e))}function G(e,t,r){return new xe(e,t,r instanceof Error?{cause:Za(r.message)}:{})}function fn(e,t){let r=Ur(t);if(r===void 0||r!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=kx(i.pluginId,i.marketplaceName);return a?.canonicalPluginId===r?[{identity:a,entry:i}]:[]});return o.find((i)=>i.entry.pluginId===r&&i.entry.installed)??o.find((i)=>i.entry.installed)??o.find((i)=>i.entry.pluginId===r)??o[0]}function $P(e){return Pd.includes(e)}function jP(e){if(!dP(eb,e))return lP(Le("live official plugin list",e));return uP(Ae(eb,e,"live official plugin list"))}function lf(e){let t=e.runner??BP(e.executable,{environment:e.environment??Uo(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),r=async()=>{let n=await t.run(["plugin","list","--json"]);if(n.exitCode!==0)throw of("list",n);let o;try{o=JSON.parse(n.stdout)}catch{throw new xe("command_failed","Codex returned invalid plugin data.")}let i=jP(o);if(!i.ok)throw new xe("command_failed","Codex returned an invalid official plugin list.");return i.value};return{list:r,ensureOfficialMarketplace:async(n)=>{if(e.codexHome===void 0)throw new xe("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await LP({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:n,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(n,o)=>{let i=Ae(fl,n,"plugin marketplace source");if(i===ml||i===qi)throw new xe("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 of("marketplace add",a,i)},add:async(n,o)=>{let i=Ae(fl,n,"official plugin id"),a=await t.run(["plugin","add",i,"--json"],o===void 0?void 0:{signal:o});if(a.exitCode!==0)throw of("add",a,i);let s=await r(),c=fn(s,i),l=Ur(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 xe("readback_mismatch",`Codex did not report ${i} after installation.`,{plugin_id:i});if(!p.installed)throw new xe("plugin_missing",`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!p.enabled)throw new xe("plugin_disabled",`Codex installed ${i} but it is disabled; enable it in Codex and retry.`,{plugin_id:i})},remove:async(n,o)=>{let i=Ae(fl,n,"official plugin id"),a=i;if(Ur(i)===i){let u=await r(),p=fn(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 of("remove",s,a);let c=await r(),l=[...c.installed,...c.available].find((u)=>u.pluginId===a);if(l?.installed)throw new xe("readback_mismatch",`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:l.pluginId})}}}function of(e,t,r){let n=Za(t.stderr).trim().slice(0,512),o=n.length>0?`: ${n}`:"";return new xe("command_failed",`Codex plugin ${e} failed${r===void 0?"":` for ${r}`}${o}`,{exit_code:t.exitCode})}function BP(e,t){let r=t.timeoutMs??30000,n=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>o$(e,i,{...t.environment===void 0?{}:{environment:t.environment},timeoutMs:a?.timeoutMs??r,stdoutLimit:n,stderrLimit:o,...a?.cwd===void 0?{}:{cwd:a.cwd},...a?.signal===void 0?{}:{signal:a.signal}})}}async function o$(e,t,r){if(r.signal?.aborted)throw new xe("cancelled","The Codex plugin command was cancelled.");let n=DH(e,[...t],{env:r.environment===void 0?void 0:{...r.environment},...r.cwd===void 0?{}:{cwd:r.cwd},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=PP(n.stdout,r.stdoutLimit),i=PP(n.stderr,r.stderrLimit),a=new Promise((p,f)=>{n.once("error",f),n.once("close",(h)=>p(h??-1))}),s,c,l=new Promise((p,f)=>{c=()=>{try{n.kill()}catch{}f(new xe("cancelled","The Codex plugin command was cancelled."))},r.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((p,f)=>{s=setTimeout(()=>{try{n.kill()}catch{}f(new xe("timeout","The Codex plugin command timed out."))},r.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{n.kill()}catch{}if(p instanceof xe)throw p;throw new xe("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)r.signal?.removeEventListener("abort",c)}}function PP(e,t){if(e===null)return Promise.reject(new xe("command_failed","Codex plugin command output is unavailable."));return new Promise((r,n)=>{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){n(new xe("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){n(new xe("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{r(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(c){n(c)}}),e.once("error",(a)=>n(a))})}var ml="openai-curated",qi="https://github.com/openai/plugins.git",rb,nb=30000,VH=100,FP,zH,dl,fl,KH,n$,QS,eb,xe;var ab=x(()=>{pt();Tt();KS();pn();nf();rb=["plugins","openai-plugins"],FP=A.pipe(de(/^[a-z][a-z0-9._-]{1,63}$/u)),zH=A.pipe(de(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),dl=U(A),fl=A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),KH=b({name:FP,version:zH,description:Wn,author:_(ar),license:_(Wn),homepage:_(Wn),repository:_(Wn),keywords:_(dl),skills:_(dl),commands:_(dl),hooks:_(dl),assets:_(dl),official:_(W)});n$=b({id:FP,selected:T(!0)}),QS=b({pluginId:fl,installed:W,enabled:W,name:_(ye(A,ut)),marketplaceName:_(ye(A,ut)),version:_(ye(A,ut))},Rd({key:A,value:xx})),eb=b({installed:U(QS),available:U(QS)});xe=class xe extends Error{code;details;constructor(e,t,r={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=r}}});var gl=x(()=>{pn();pn();jd();zS();KS();nf();kP();CP();AP();Yd();ab();ab()});function sr(e){if(!Xa(e))throw Error("The value is not JSON serializable.");return cn(e),e}function Xa(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((r)=>Xa(r,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((r)=>Xa(r,t))}finally{t.delete(e)}}var yl=x(()=>{pt()});function ht(e,t){let r=br(e,t);return Rt(r)?r.right:void 0}function WP(e){return ht(pf,e)!==void 0}var pf,L4,sb,df,i$,es,a$,s$,c$,zP,xl,ff,Qa,cb,uf,l$,VP,u$,lb,ts,p$,KP,d$,f$,jr;var rs=x(()=>{gl();pt();er();Tt();yl();pf=q((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&Xa(e)),L4=q(Xa),sb=A.pipe(de(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)),df=A.pipe(de(/^[0-9a-f]{64}$/u)),i$=A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),es=A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),a$=A.pipe(Xe((e)=>!Number.isNaN(Date.parse(e)))),s$=b({path:A.pipe(de(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:df}),c$=b({computer_use:W,work:W,frontend:W,security:W,coding:T(!0)}),zP=b({computer_use:_(W),work:_(W),frontend:_(W),security:_(W)}),xl=b({profile:_(Mo),tier:_(Mi),optional:_(zP),officialPlugins:_(U(es))}),ff=xl,Qa=b({selected:W,status:T("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:U(es),reason:_(A)}),cb=b({computer_use:Qa,work:Qa,frontend:Qa,security:Qa}),uf=b({presence:T("absent","present"),digest:df,safe_value:_(ye(b({kind:T("boolean"),value:W}),b({kind:T("marketplace"),source_type:T("git"),source:T("https://github.com/davidbasilefilho/holycodex.git")})))}),l$=b({plugin_id:T("holycodex@holycodex"),before:b({preference:uf,marketplace:uf}),after:b({preference:uf,marketplace:uf})}),VP=b({presence:T("absent","present"),digest:df,safe_value:_(b({kind:T("boolean"),value:W}))}),u$=b({plugin_id:es,before:VP,after:VP}),lb={owner:T("holycodex"),schema_epoch:T(Tr),install_id:i$,version:sb,digest:df,profile:Mo,tier:Mi,optional_selections:c$,explicit_optional_selections:zP,official_plugins:_(U(es)),capability_state:_(cb),managed_artifacts:U(s$),installed_at:a$,status:_(T("active")),step:_(T("active")),managed_config:_(Wd),plugin_snapshot:_(U(b({plugin_id:es,status:T("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:_(l$),provider_config:_(U(u$)),owned_plugins:_(U(es))},ts=b(lb),p$=(({profile:e,...t})=>t)(lb),KP=ye(b({...lb,profile:Nd}),b({...p$,plan:Nd})),d$=T("preparing","conflicted"),f$=T("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),jr=b({...ts.fields,status:d$,step:f$})});import{lstat as m$,mkdir as h$}from"fs/promises";import{homedir as g$}from"os";import{dirname as y$,join as Ui,posix as JP,resolve as x$,sep as GP,win32 as YP}from"path";function ns(e={},t=process.env){let r=g$(),n=e.paths?.codexHome??t.CODEX_HOME??Ui(r,".codex"),o=pb(n,"CODEX_HOME"),i=Ui(o,S$);return{codexHome:o,stateRoot:i,activeRecord:Ui(i,b$),preparingRecord:Ui(i,_$),conflictedRecord:Ui(i,w$),roleRoot:Ui(i,"agents"),configFile:Ui(o,"config.toml")}}function pb(e,t,r=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||E$(e))throw new _r("invalid_path",`${t} contains invalid characters.`);let n=r==="win32"?YP:JP,o=ub(e,r);if(typeof o!=="string"||o.length===0||!n.isAbsolute(o))throw new _r("invalid_path",`${t} must be an absolute path.`);let i=n.normalize(o);if(i.split(r==="win32"?"\\":GP).filter((s)=>s.length>0).length===0||i===n.dirname(i))throw new _r("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new _r("invalid_path",`${t} cannot contain traversal.`);return n.resolve(i)}function E$(e){for(let t of e){let r=t.codePointAt(0)??0;if(r<=31||r===127)return!0}return!1}async function Sl(e){pb(e,"owned path"),await mn(e),await h$(e,{recursive:!0}),await mn(e)}async function mn(e){let r=x$(e);while(!0){try{if((await m$(r)).isSymbolicLink())throw new _r("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof _r)throw o;if(!gt(o,"ENOENT"))throw o}let n=y$(r);if(n===r)break;r=n}}async function bl(e){await mn(e)}function os(e,t,r=process.platform==="win32"?"win32":"posix"){let n=r==="win32"?YP:JP,o=n.resolve(ub(e,r)),i=n.resolve(ub(t,r)),a=n.relative(o,i);return a.length>0&&!a.startsWith(`..${r==="win32"?"\\":GP}`)&&a!==".."&&!n.isAbsolute(a)}function ub(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function gt(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var S$="holycodex",b$="active.json",_$="preparing.json",w$="conflicted.json",T$,_r;var Hi=x(()=>{pt();T$=Tr;_r=class _r extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as ZP,open as v$,readFile as XP,rename as O$,unlink as R$,writeFile as k$}from"fs/promises";import{dirname as C$}from"path";async function QP(e){let t;try{t=await v$(e,"r"),await t.sync()}catch(r){if(!eI(r))throw r}finally{await t?.close().catch(()=>{return})}}async function P$(e){await QP(e).catch((t)=>{if(!eI(t))throw t})}async function jo(e,t){await Jn(e,`${cn(t)}
36
+ `)}async function Jn(e,t){let r=C$(e);await Sl(r),await mn(e);let n=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await k$(n,t,{encoding:"utf8",mode:384}),await QP(n),await O$(n,e),await P$(r)}catch(o){throw await R$(n).catch(()=>{return}),o}}async function I$(e,t){let r=await ZP(e);if(!r.isFile()||r.isSymbolicLink())throw new $i("state_corrupt","A persisted file is not a regular file.");let n;try{n=JSON.parse(await XP(e,"utf8"))}catch(i){throw new $i("state_corrupt","A persisted file is not valid JSON.",i)}let o=ht(t,n);if(o===void 0)throw new $i("state_corrupt","A persisted file failed schema validation.");return o}async function Yt(e){try{let t=await ZP(e);if(!t.isFile()||t.isSymbolicLink())throw new $i("state_corrupt","A persisted file is not a regular file.");return await XP(e,"utf8")}catch(t){if(gt(t,"ENOENT"))return;throw t}}async function Gn(e,t){try{return await I$(e,t)}catch(r){if(gt(r,"ENOENT"))return;throw r}}function eI(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return A$.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var A$,$i;var is=x(()=>{pt();Hi();rs();A$=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);$i=class $i extends Error{code;causeValue;constructor(e,t,r){super(t);this.name="StorageError",this.code=e,this.causeValue=r}}});import{readFile as M$}from"fs/promises";import{dirname as N$,resolve as F$}from"path";import{fileURLToPath as L$}from"url";async function tI(e=_l){let t=JSON.parse(await M$(e,"utf8")),r=ht(q$,t);if(r===void 0)throw new wl("manifest_invalid","The public package manifest is invalid.");return r}async function mf(e=_l){return(await tI(e)).version}async function hf(e=_l){return(await mf(e)).split("-",1)[0]??""}async function db(e,t,r=_l){let n=await tI(r),o=await hf(r),i=U$(e,o);if(!t)await jo(r,{...n,version:i});return{previous:o,next:i}}function U$(e,t){if(e!=="patch"&&e!=="minor"){if(ht(sb,e)===void 0)throw new wl("version_invalid","The version target is invalid.");return e}let r=t.split("."),n=Number(r[1]),o=Number(r[2]);return e==="minor"?`0.${n+1}.0`:`0.${n}.${o+1}`}var D$,q$,_l,wl;var gf=x(()=>{Tt();rs();is();D$=A.pipe(de(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*\.[1-9]\d*)?$/u)),q$=q((e)=>WP(e)&&e.name==="holycodex"&&ht(D$,e.version)!==void 0),_l=F$(N$(L$(import.meta.url)),"../package.json");wl=class wl extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{lstat as yf,readFile as xf,rm as Sf}from"fs/promises";import{join as cr,relative as rI}from"path";function nI(){return`Surgical mutation rule: ${No.surgicalMutationRule} ${$$}`}function ji(e,t="standard"){let r=ln(e);if(!r.ok)return[];return r.value.routes.map((n)=>{let o={role:n.role,task:n.task};return{name:Dx(o),rolePolicy:$r.find((i)=>i.role===n.role),description:Ux(o),taskInstruction:qx(o),permissions:Hx(o),model:"gpt-5.6-luna",effort:n.effort,serviceTier:t==="standard"?"default":"fast"}})}function mb(e,t="standard"){let r=ln(e);if(!r.ok)throw Error("Unknown profile.");return{name:"root",description:"Root-directed HolyCodex control agent.",model:r.value.root.model,effort:r.value.root.effort,serviceTier:t==="fast-all"?"fast":"default"}}function hb(e=!1){if(!No.requiresDelegation||!No.trivialWorkRequiresDelegation||!No.codeReviewRequiredForImplementation||!No.codeReviewRequiredBeforeVcs||!No.externalVerificationMustBeTerminal)throw Error("The Root orchestration policy is incomplete.");let t=["You are the HolyCodex Root orchestrator and final integration owner. Treat these generated Root instructions as the authoritative global behavior contract, AGENTS.md as repository rules, and installed skills as branch procedures.","MUST orchestrate and delegate every task, including trivial work, through a bounded Assignment to the native Explorer, Librarian, Worker, or Reviewer agents; do not implement, debug, research, test, review, or operate CI for the underlying work directly. Git/VCS is always Root-only and may be performed directly; Computer Use is a direct exception only when this installation selected --computer-use.",nI(),"Own the persistent Intent, user goal and acceptance criteria, architecture and material product or policy choices, lifecycle transitions, assignment integration, contradictory-evidence resolution, external effects, and final readiness. Use holycodex-agent semantic operations for Intent, Plan, and Assignment state; never manually edit TOON or create handoff, Decision, or standalone blocker files. Keep model_verbosity = low.","Bias toward action. Before request_user_input, finish all authorized read-only, reversible, preparatory, and independent work that can reduce uncertainty. Request input only for a material choice or explicit approval boundary: before plan approval, before installation profile approval, before remote/origin/server VCS mutation, before public publication or release, or when ambiguity/missing material input blocks safe progress. Persist the resulting needs_root_input state.","Load writing-for-agents fully before the first dispatch and apply it before every dispatch. Reuse that contract while the current context contains a complete usable load; reload only when it no longer does. Dispatch independent, non-overlapping Assignments concurrently when that improves latency or evidence coverage, preserve dependency order, and never run parallel writes against the same mutable seam. Leaves return compact structured outcomes and evidence; they cannot delegate, message peers, mutate global Intent lifecycle, perform Git/VCS, or decide material product or architecture choices.","Run proportional proof: start with the smallest relevant check, then broaden only for a new change, failure, or unresolved evidence gap. A review fixed point means no actionable finding remains within scope; do not repeat broader testing without a reason. Inspect every specialist outcome and evidence before integration. Reviewer.code fixed-point review is mandatory after implementation or any major codebase change and must pass before completion or any VCS operation.","After integration, follow the repository's discovered workflow: commit the finished change as Root, push when its topology requires a remote, and delegate Worker.operations to observe CI for the exact ref/SHA to terminal evidence; pending or running is never success. If the development gate is terminal green and release is requested and approved, perform that release action as Root and delegate terminal release observation. If any gate fails, delegate a bounded fix and repeat implementation, fixed-point review, VCS, and exact-ref observation until green. Discover the repository's actual gate and provider topology; never assume a branch or server separation."];if(e)t.push("Interactive GUI, browser, and Computer Use execution is Root-only and must not be delegated.");else t.push("Computer Use is not selected for this installation; delegate GUI, browser, and Computer Use execution to an appropriate bounded specialist.");return t.join(`
37
+ `)}async function gb(e,t,r=[],n="standard"){let o=cr(e,"holycodex","agents"),i=[],a=[],s=ji(t,n).map((p)=>({path:cr(o,`${p.name}.toml`),contents:wf(p)})),c=new Map(r.map((p)=>[cr(e,p.path),p])),l=new Map;for(let p of s){let f=await fb(p.path);l.set(p.path,f);let h=c.get(p.path);if(f!==void 0&&h===void 0&&f!==p.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${p.path}`)}let u=[];try{for(let m of s){let w=l.get(m.path),S=c.get(m.path);if(w!==void 0&&S!==void 0){if(await as(w)!==S.digest&&w!==m.contents){i.push(m.path),u.push({path:rI(e,m.path).replaceAll("\\","/"),digest:S.digest});continue}}if(w===void 0||w!==m.contents)await Jn(m.path,m.contents),a.push({path:m.path,previous:w,installedDigest:await as(m.contents)});u.push({path:rI(e,m.path).replaceAll("\\","/"),digest:await as(m.contents)})}let p=cr(e,"agents","root.toml"),f=await fb(p),h=await oI(p);if(h==="preserved")i.push(p);if(h==="removed"&&f!==void 0)a.push({path:p,previous:f,installedDigest:void 0});for(let m of r){let w=cr(e,m.path);if(!s.some((S)=>S.path===w)){if(!V$(e,w,m.path)){i.push(w);continue}let S=await z$(w,m.digest);if(S.status==="preserved")i.push(w);else if(S.previous!==void 0)a.push({path:w,previous:S.previous,installedDigest:void 0})}}for(let m of r){let w=cr(e,m.path);if(i.includes(w)&&!u.some((S)=>cr(e,S.path)===w))u.push(m)}return{managed_artifacts:u,preserved:i,rollback:a}}catch(p){throw await bf(a).catch(()=>{return}),p}}async function bf(e){let t=[],r=[];for(let n of[...e].reverse()){let o=await fb(n.path);if(!(n.installedDigest===void 0?o===void 0:o!==void 0&&await as(o)===n.installedDigest)){r.push(n.path);continue}if(n.previous===void 0)await Sf(n.path,{force:!1}).catch((a)=>{if(!gt(a,"ENOENT"))throw a}),t.push(n.path);else await Jn(n.path,n.previous)}return{removed:t,preserved:r}}async function _f(e,t){let r=[],n=[],o=cr(e,"agents"),i=cr(e,"holycodex","agents");for(let c of t){let l=cr(e,c.path);if(!os(e,l)||!os(o,l)&&!os(i,l)&&l!==cr(e,"config.toml")){n.push(l);continue}try{await mn(l);let u=await yf(l);if(u.isSymbolicLink()||!u.isFile()){n.push(l);continue}let p=await xf(l);if(await as(p)!==c.digest){n.push(l);continue}await Sf(l,{force:!1}),r.push(l)}catch(u){if(gt(u,"ENOENT"))r.push(l);else n.push(l)}}let a=cr(e,"agents","root.toml"),s=await oI(a);if(s==="removed")r.push(a);if(s==="preserved")n.push(a);return{removed:r,preserved:n}}function wf(e){let t=e.rolePolicy,r=[nI(),H$,`${t.role} shared policy: ${t.authority}`,t.evidence,t.completion,e.taskInstruction].join(`
38
+ `);return[`name = ${JSON.stringify(e.name)}`,`description = ${JSON.stringify(e.description)}`,`model = ${JSON.stringify(e.model)}`,`model_reasoning_effort = ${JSON.stringify(e.effort)}`,`service_tier = ${JSON.stringify(e.serviceTier)}`,'model_reasoning_summary = "none"','model_verbosity = "low"',`sandbox_mode = ${JSON.stringify(e.permissions.write?"workspace-write":"read-only")}`,'approval_policy = "never"',`web_search = ${JSON.stringify(e.permissions.network?"live":"disabled")}`,`developer_instructions = ${JSON.stringify(r)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent_v2 = false","multi_agent = false","computer_use = false","browser_use = false","in_app_browser = false",""].join(`
39
+ `)}function j$(e,t,r){return['name = "root"','description = "Root-directed HolyCodex control agent."',`model = ${JSON.stringify(e)}`,`model_reasoning_effort = ${JSON.stringify(t)}`,`service_tier = ${JSON.stringify(r)}`,'model_verbosity = "low"',""].join(`
40
+ `)}function ss(e){return B$.has(e)}function V$(e,t,r){if(r==="agents/root.toml")return!0;if(/^holycodex\/agents\/(?:explorer|librarian|worker|reviewer)\.toml$/u.test(r))return!0;return os(cr(e,"agents"),t)&&/^(?:Explorer|Librarian|Worker|Reviewer)\.(?:lookup|trace|research|mechanical|implementation|integration|operations|plan|code|artifact)\.toml$/u.test(r.slice(7))}async function oI(e){try{await mn(e);let t=await yf(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let r=await xf(e,"utf8");if(!ss(r))return"preserved";return await Sf(e,{force:!1}),"removed"}catch(t){if(gt(t,"ENOENT"))return"absent";throw t}}async function fb(e){try{await mn(e);let t=await yf(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await xf(e))}catch(t){if(gt(t,"ENOENT"))return;throw t}}async function z$(e,t){try{await mn(e);let r=await yf(e);if(r.isSymbolicLink()||!r.isFile())return{status:"preserved"};let n=new TextDecoder("utf-8",{fatal:!0}).decode(await xf(e));if(await as(n)===t)return await Sf(e,{force:!1}),{status:"removed",previous:n};return{status:"preserved"}}catch(r){if(gt(r,"ENOENT"))return{status:"removed"};throw r}}async function as(e){let t=typeof e==="string"?new TextEncoder().encode(e):e,r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),(n)=>n.toString(16).padStart(2,"0")).join("")}var H$="Do not delegate, message peers, mutate global Intent lifecycle, make material decisions, or perform Git/VCS. Return exactly one compact structured outcome (`completed`, `blocked`, `needs_root_input`, or `failed`) with observable evidence, changed paths and checks, local blockers, and remaining risk.",$$="Every Assignment must state its exact boundary, exclusions, acceptance criteria, and evidence.",B$;var Tf=x(()=>{pt();Hi();is();B$=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((r)=>j$(e,t,r))))});class Bo{adapter;observedIdentities={};constructor(e){if("run"in e){let t=lf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await JS({environment:e}),r=lf({executable:t.path,environment:WS(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new Bo(r)}async list(){try{return await this.adapter.list()}catch(e){throw Tl("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw Tl("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw Tl("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw Tl("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw Tl("add",t,e)}}async status(e){let t=await this.list(),r={},n=new Map;for(let i of[...t.installed,...t.available])if(!n.has(i.pluginId)||i.installed)n.set(i.pluginId,i);let o=Object.fromEntries(e.map((i)=>{let a=fn(t,i),s=Ur(i),c=n.get(i),l=a?.entry??(s===void 0||c?.marketplaceName==null?c:void 0),u=a;if(l!==void 0)r[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(r),o}getObservedIdentities(){return this.observedIdentities}}function Tl(e,t,r){if(t instanceof hn)return t;let o=(t instanceof xe?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 ${r??"the selected official plugin"}.`:e==="bootstrap"?"Codex could not initialize the official marketplace.":`Codex could not add ${r??"the selected official plugin"}.`;return new hn(i,a,t,r===void 0?{}:{plugin_id:r})}var hn;var El=x(()=>{gl();pt();hn=class hn extends Error{code;causeValue;details;constructor(e,t,r,n={}){super(t);this.name="OfficialPluginManagerError",this.code=e,this.causeValue=r,this.details=n}}});function aI(e){let t={},r=[];for(let n of e.split(/\r?\n/u)){let o=W$(n).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("]")){r=yb(o.slice(1,-1).trim()),K$(t,r);continue}let i=uI(o);if(i<1)throw Error("TOML assignment is invalid.");let a=yb(o.slice(0,i).trim()),s=Ef(o.slice(i+1).trim());lI(t,[...r,...a],s)}return t}function sI(e){let t=[];return cI(e,[],t),t.join(`
41
+ `)}function cI(e,t,r){let n=[],o=[];for(let[i,a]of Object.entries(e))if(Sb(a))o.push([i,a]);else n.push([i,a]);if(t.length>0){if(r.length>0)r.push("");r.push(`[${t.map(iI).join(".")}]`)}for(let[i,a]of n)r.push(`${iI(i)} = ${pI(a)}`);for(let[i,a]of o)cI(a,[...t,i],r)}function Ef(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?[]:xb(t,",").map(Ef)}if(e.startsWith("{")){if(!e.endsWith("}"))throw Error("TOML inline table is invalid.");let t=e.slice(1,-1).trim(),r={};if(t.length===0)return r;for(let n of xb(t,",")){let o=uI(n);if(o<1)throw Error("TOML inline table entry is invalid.");lI(r,yb(n.slice(0,o).trim()),Ef(n.slice(o+1).trim()))}return r}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 yb(e){let t=xb(e,".").map((r)=>r.trim());if(t.length===0||t.some((r)=>!/^(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(r)||r==="__proto__"||r==="constructor"||r==="prototype"))throw Error("TOML key is invalid.");return t.map((r)=>r.startsWith('"')||r.startsWith("'")?Ef(r):r)}function lI(e,t,r){if(t.length===0)throw Error("TOML key is missing.");let n=e;for(let i of t.slice(0,-1)){let a=n[i];if(a===void 0){let s={};n[i]=s,n=s}else if(Sb(a))n=a;else throw Error("TOML key conflicts with a scalar.")}let o=t.at(-1);if(Object.prototype.hasOwnProperty.call(n,o))throw Error("TOML key is duplicated.");n[o]=r}function K$(e,t){let r=e;for(let n of t){let o=r[n];if(o===void 0){let i={};r[n]=i,r=i}else if(Sb(o))r=o;else throw Error("TOML table conflicts with a scalar.")}}function xb(e,t){let r=[],n=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)r.push(e.slice(n,s)),n=s+1}if(i!==void 0||o!==0)throw Error("TOML value is unbalanced.");return r.push(e.slice(n)),r}function uI(e){let t,r=!1,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];if(t!==void 0){if(t==='"'&&r)r=!1;else if(t==='"'&&i==="\\")r=!0;else if(i===t)t=void 0}else if(i==='"'||i==="'")t=i;else if(i==="["||i==="{")n+=1;else if(i==="]"||i==="}")n-=1;else if(i==="="&&n===0)return o}return-1}function W$(e){let t,r=!1;for(let n=0;n<e.length;n+=1){let o=e[n];if(t!==void 0){if(t==='"'&&r)r=!1;else if(t==='"'&&o==="\\")r=!0;else if(o===t)t=void 0}else if(o==='"'||o==="'")t=o;else if(o==="#")return e.slice(0,n)}return e}function Sb(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function iI(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function pI(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(pI).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{rm as bb,rmdir as dI}from"fs/promises";async function Tb(e={},t=process.env){let r=ns(e,t),n={};try{await bl(r.codexHome),await bl(r.stateRoot),n.paths=vl({state_root:r.stateRoot})}catch(l){n.paths=Et(["path_symlink"],{error:Yn(l)})}let[o,i,a]=await Promise.all([Rl(r).catch((l)=>{n.configuration=Et(["state_corrupt"],{error:Yn(l)});return}),Gn(r.preparingRecord,jr).catch((l)=>{n.transaction=Et(["state_corrupt"],{path:r.preparingRecord,error:Yn(l)});return}),Gn(r.conflictedRecord,jr).catch((l)=>{n.transaction=Et(["state_corrupt"],{path:r.conflictedRecord,error:Yn(l)});return})]);if(i!==void 0&&n.transaction?.status!=="failed")n.transaction=Et(["incomplete_install_state"]);if(a!==void 0&&n.transaction?.status!=="failed")n.transaction=Et(["conflicted_state"]);if(!n.configuration)if(!o)n.configuration=Et(["configuration_missing"]);else if(await Rf(o))n.configuration=vl({profile:o.profile,tier:o.tier,install_id:o.install_id});else n.configuration=Et(["configuration_changed"],{path:r.activeRecord});if(o){n.runtime_config=await J$(r,o),n.native_roles=await G$(r,o.profile,o.tier);let l=Object.entries(o.capability_state??{}).find(([,u])=>u.selected&&u.status!=="healthy");if(l)n.capabilities=Et(["selected_capability_not_healthy"],{capability:l[0],status:l[1].status})}try{let l=await Yt(`${r.codexHome}/agents/root.toml`);if(l!==void 0&&ss(l)){let u=n.native_roles;n.native_roles={status:"failed",reasons:[...u?.reasons??[],"stale_legacy_root"],details:{...u?.details,path:`${r.codexHome}/agents/root.toml`}}}}catch(l){n.native_roles=Et(["native_role_invalid"],{error:Yn(l)})}let s=e.officialPluginManager??await Bo.discover({...t,CODEX_HOME:r.codexHome}).catch(()=>{return});if(o&&s?.status){let l=[...new Set([Vr,...Kc({computer_use:o.optional_selections.computer_use,work:o.optional_selections.work,frontend:o.optional_selections.frontend,security:o.optional_selections.security},o.official_plugins),...o.owned_plugins??[]])];try{let u=await s.status(l),p=Object.entries(u).filter(([,h])=>h!=="installed").map(([h])=>h),f=s.getObservedIdentities?.()??{};n.native_plugins=p.length===0?vl({status:u,observed_identities:f}):Et(["native_plugin_disagreement"],{missing:p,status:u,observed_identities:f})}catch(u){n.native_plugins=Et(["native_plugin_status_failed"],{error:Yn(u)})}}else n.native_plugins={status:"unsupported",reasons:["native_plugin_manager_unavailable"],details:{}};let c=Object.values(n).flatMap((l)=>l.reasons);return{healthy:Object.values(n).every((l)=>l.status!=="failed"),checks:n,reasons:[...new Set(c)]}}async function Ol(e={},t=process.env){let r=ns(e,t);await bl(r.codexHome),await bl(r.stateRoot);let n=await Rl(r),[o,i]=await Promise.all([Gn(r.preparingRecord,jr),Gn(r.conflictedRecord,jr)]),a=i??o??n,s=new Set(Y$(a)),c=[],l=[],u=[];if(n&&!await Rf(n))return l.push(r.activeRecord),u.push("configuration_changed"),{removed:c,preserved:l,reasons:u};let p=await Yt(r.configFile),f=Zn(p),h=a?.managed_config;if(h){let y=await Di(f,h,{schema:h.schema,installId:h.installId});if(y.preservedKeys.length>0||y.unresolvedKeys.length>0)return l.push(r.configFile),u.push("managed_config_changed"),await Br(r,a??cs()),{removed:c,preserved:l,reasons:u}}if(a?.plugin_config){if((await _b(f,a.plugin_config)).preserved.length>0)return l.push(r.configFile),u.push("plugin_config_changed"),await Br(r,a),{removed:c,preserved:l,reasons:u}}if(a?.provider_config){if((await wb(f,a.provider_config,s)).preserved.length>0)return l.push(r.configFile),u.push("provider_config_changed"),await Br(r,a),{removed:c,preserved:l,reasons:u}}let m;try{m=e.officialPluginManager??await Bo.discover({...t,CODEX_HOME:r.codexHome})}catch(y){throw new X("capability_denied","Native Codex plugin removal is unavailable.",y,{recovery:"Install or expose Codex, then retry."})}if(m===void 0||!m.remove||!m.list)throw new X("capability_denied","Native Codex plugin removal and readback are unavailable.");let w=await _f(r.codexHome,a?.managed_artifacts??[]);if(c.push(...w.removed),l.push(...w.preserved),w.preserved.length>0)u.push("managed_artifact_changed");for(let y of s)try{let R=await m.list(),P=fn(R,y),z=P?.entry.installed?P.entry.pluginId:y;await m.remove(z);let Y=await m.list();if(fn(Y,y)?.entry?.installed===!0||[...Y.installed,...Y.available].some((F)=>F.pluginId===y&&F.installed))throw new X("capability_denied",`Codex still reports ${y} after removal.`);c.push(y)}catch(R){throw u.push("native_plugin_remove_failed"),await Br(r,a??cs()),new X("capability_denied",`Codex native plugin removal did not converge for ${y}: ${Yn(R)}`,R)}if(w.preserved.length>0)return await Br(r,a??cs()),{removed:c,preserved:l,reasons:u};let S;try{let y=f,R=h;if(R){let P=await Di(y,R,{schema:R.schema,installId:R.installId});if(P.preservedKeys.length>0||P.unresolvedKeys.length>0)return l.push(r.configFile),u.push("managed_config_changed"),await Br(r,a??cs()),{removed:c,preserved:l,reasons:u};y=P.document,R=P.state}if(a?.plugin_config){let P=await _b(y,a.plugin_config,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(r.configFile),u.push("plugin_config_changed"),await Br(r,a),{removed:c,preserved:l,reasons:u};y=P.document}if(a?.provider_config){let P=await wb(y,a.provider_config,s,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(r.configFile),u.push("provider_config_changed"),await Br(r,a),{removed:c,preserved:l,reasons:u};y=P.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)S=R===void 0?{document:y}:{document:y,state:R};if(S!==void 0)if(Object.keys(S.document).length===0&&p===void 0)await bb(r.configFile,{force:!1});else await Jn(r.configFile,Eb(S.document))}catch(y){if(y instanceof X)throw await Br(r,a??cs()),y;return l.push(r.configFile),u.push("managed_config_write_failed"),await Br(r,a??cs()),{removed:c,preserved:l,reasons:u}}if(n)try{await bb(r.activeRecord,{force:!1}),c.push(r.activeRecord)}catch(y){if(gt(y,"ENOENT"))c.push(r.activeRecord);else return l.push(r.activeRecord),u.push("state_remove_failed"),await Br(r,a??n),{removed:c,preserved:l,reasons:u}}if(l.length===0)for(let[y,R]of[[r.preparingRecord,o!==void 0],[r.conflictedRecord,i!==void 0]]){if(!R)continue;try{await Z$(y),c.push(y)}catch{l.push(y),u.push("state_remove_failed")}}if(l.length===0)try{await dI(r.roleRoot),c.push(r.roleRoot)}catch(y){if(!gt(y,"ENOENT"))l.push(r.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await dI(r.stateRoot),c.push(r.stateRoot)}catch(y){if(gt(y,"ENOENT"))c.push(r.stateRoot);else l.push(r.stateRoot),u.push("state_directory_not_empty")}return{removed:c,preserved:l,reasons:u}}async function J$(e,t){if(!t.managed_config)return Et(["incomplete_install_state"]);try{let r=Zn(await Yt(e.configFile)),n=Of(t.profile,t.tier,t.optional_selections.computer_use),o=[];for(let[i,a]of Object.entries(n))if((await Ya(r,t.managed_config,i)).status!=="unchanged"||i!=="developer_instructions"&&Pe(r,i)!==a)o.push(i);return o.length===0?vl({managed_keys:Object.keys(n).length}):Et(["changed_holycodex_config"],{keys:o})}catch(r){return Et(["config_unreadable"],{error:Yn(r)})}}async function G$(e,t,r){try{let n=Zn(await Yt(e.configFile)),o=[];for(let a of ji(t,r)){let s=Pe(n,`agents."${a.name}".config_file`),c=`${e.roleRoot}/${a.name}.toml`.replaceAll("\\","/");if(typeof s!=="string"||al(e.configFile,s).replaceAll("\\","/")!==c){o.push(`${a.name}:registration`);continue}let l=await Yt(`${e.roleRoot}/${a.name}.toml`);if(l===void 0){o.push(`${a.name}:missing`);continue}if(l!==wf(a)){o.push(`${a.name}:changed`);continue}let u=Zn(l);if(u.name!==a.name||typeof u.description!=="string"||typeof u.developer_instructions!=="string"||u.model!=="gpt-5.6-luna"||u.model_reasoning_summary!=="none"||u.model_verbosity!=="low"||u.tool_output_token_limit!==void 0||u.service_tier!==(r==="standard"?"default":"fast")||u.sandbox_mode!==(a.permissions.write?"workspace-write":"read-only")||u.approval_policy!=="never"||u.web_search!==(a.permissions.network?"live":"disabled")||Pe(u,"agents.enabled")!==!1||Pe(u,"features.multi_agent_v2")!==!1||Pe(u,"features.multi_agent")!==!1||Pe(u,"features.computer_use")!==!1||Pe(u,"features.browser_use")!==!1||Pe(u,"features.in_app_browser")!==!1)o.push(`${a.name}:malformed`)}let i=await Yt(`${e.codexHome}/agents/root.toml`);if(i!==void 0&&ss(i))o.push("root:stale");return o.length===0?vl({role_root:e.roleRoot,agent_types:ji(t,r).map((a)=>a.name)}):Et(["native_role_disagreement"],{roles:o})}catch(n){return Et(["native_role_invalid"],{error:Yn(n)})}}async function Br(e,t){let r={...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(ht(jr,r)!==void 0)await jo(e.conflictedRecord,sr(r))}function cs(){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,work:!1,frontend:!1,security:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function Y$(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)];let t=(e?.plugin_snapshot??[]).filter((r)=>r.plugin_id!==Vr&&r.status!=="installed").map((r)=>r.plugin_id);return[...new Set([Vr,...t])]}function vl(e){return{status:"healthy",reasons:[],details:e}}function Et(e,t={}){return{status:"failed",reasons:e,details:t}}async function Z$(e){await bb(e,{force:!1}).catch((t)=>{if(!gt(t,"ENOENT"))throw t})}function Yn(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}var vf=x(()=>{gl();pt();kl();yl();Tf();El();Hi();rs();is()});import{rm as bI}from"fs/promises";import{join as X$}from"path";function Xn(e){let t=ht(ff,e);if(t===void 0)throw new X("install_failed","The installation options are invalid.");return t}async function kf(e={},t={},r=process.env){if(ht(xl,e)===void 0)throw new X("install_failed","The installation options are invalid.");let n=ns(t,r);await Sl(n.stateRoot);let o=await Gn(n.preparingRecord,jr),a=await Gn(n.conflictedRecord,jr)??o;if(a!==void 0){await Promise.resolve().then(() => vf());let De=await Ol(t,r);if(De.preserved.length>0||De.reasons.length>0)throw new X("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:De.preserved.join(","),reasons:De.reasons.join(",")});return await kf({profile:e.profile??a.profile,tier:e.tier??a.tier,optional:{computer_use:e.optional?.computer_use??a.optional_selections.computer_use,work:e.optional?.work??a.optional_selections.work,frontend:e.optional?.frontend??a.optional_selections.frontend,security:e.optional?.security??a.optional_selections.security},officialPlugins:e.officialPlugins??gI(a)},t,r)}let s=await Rl(n);if(s!==void 0&&!await Rf(s))throw new X("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:n.activeRecord});let c=fj(e.profile,s?.profile),l=mj(e.tier,s?.tier),u=hj(e.optional,s?.optional_selections),p=uj(s?.explicit_optional_selections,e.optional),f=e.officialPlugins??gI(s),h=[...new Set(Kc(TI(u),f).map((se)=>Ur(se)??se))],m;try{m=t.officialPluginManager??await Bo.discover({...r,CODEX_HOME:n.codexHome})}catch(se){throw new X("capability_denied","Native Codex plugin installation is unavailable.",se,{recovery:"Install or expose Codex, then retry."})}if(!m.addMarketplace||!m.add||!m.list)throw new X("install_failed","Native Codex plugin installation and verification are unavailable.");let w;try{w=await m.list()}catch(se){throw new X("capability_denied","Native Codex plugin state could not be read safely.",se)}let S=h.filter((se)=>{if(Ur(se)!==se)return!1;let De=Pl(w,se);return!(De?.installed&&De.enabled)});if(m.ensureOfficialMarketplace!==void 0&&S.length>0)try{await m.ensureOfficialMarketplace(S)}catch(se){throw new X("capability_denied",`The selected official Codex provider marketplace is unavailable: ${SI(se)}`,se,{recovery:"Check Codex network and marketplace policy, then retry."})}let y=s?.install_id??crypto.randomUUID().replaceAll("-",""),R=await hf(),P=(t.now?.()??new Date).toISOString(),z=await Yt(n.configFile),Y=Zn(z),D=s?.plugin_config?.before??await mI(Y),te=[...new Set([...h,...(s?.provider_config??[]).map((se)=>se.plugin_id),...s?.owned_plugins??[]])].filter((se)=>se!==Vr),ie=(await hI(Y,te)).map((se)=>{let De=s?.provider_config?.find((Zt)=>Zt.plugin_id===se.plugin_id);return De===void 0?se:{plugin_id:se.plugin_id,before:De.before,after:De.before}}),ae=s?.managed_config??Jd({schema:Tr,installId:y}),ee=await oj(Y,ae,s),{document:Oe,state:yt}=ee;ij(Oe,yt);let vt=Of(c,l,u.computer_use),Ot=await sl(Oe,yt,vt,{schema:Tr,installId:y});if(Ot.driftedKeys.length>0)throw new X("state_corrupt","HolyCodex-owned Codex settings changed and cannot be replaced safely.",void 0,{keys:Ot.driftedKeys.join(",")});let $e;try{$e=await aj({list:()=>m.list()},[...new Set([Vr,...h,...s?.owned_plugins??[]])])}catch(se){throw new X("capability_denied","Native Codex plugin state could not be read safely.",se)}let We={owner:"holycodex",schema_epoch:Tr,install_id:y,version:R,digest:s?.digest??"0".repeat(64),profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:xI(u),managed_artifacts:s?.managed_artifacts??[],installed_at:P,status:"preparing",step:"validated",managed_config:Ot.state,plugin_snapshot:$e,plugin_config:{plugin_id:Vr,before:D,after:D},provider_config:ie,owned_plugins:[...new Set(s?.owned_plugins??[])]};await Cl(n.preparingRecord,We);let je,yn=!1,zi=new Set,lr=new Set(s?.owned_plugins??[]),If=new Set,Lt=We,Mb=!1,Nb=!1,Mf=z,us=Ot.state;try{await Sl(n.roleRoot),je=await gb(n.codexHome,c,s?.managed_artifacts,l),Lt={...We,step:"roles_prepared",managed_artifacts:je.managed_artifacts},await Cl(n.preparingRecord,Lt),Mb=!0,await m.addMarketplace(Q$),await dj({list:()=>m.list(),add:(wr)=>m.add(wr)},[Vr,...h],(wr,Df)=>{if(Df==="new")zi.add(wr),lr.add(wr),Lt={...Lt,owned_plugins:[...lr]};else If.add(wr),lr.add(wr),Lt={...Lt,owned_plugins:[...lr]}}),Lt={...Lt,step:"plugins_installed"},await Cl(n.preparingRecord,Lt);let De=await Yt(n.configFile);Mf=De;let Zt=Zn(De),Nf=await mI(Zt),Ff=(await hI(Zt,te)).map((wr)=>({plugin_id:wr.plugin_id,before:ie.find((Df)=>Df.plugin_id===wr.plugin_id)?.before??wr.before,after:wr.before}));await nj(Zt,Oe,yt,vt);let Ll=await sl(Zt,yt,vt,{schema:Tr,installId:y});if(Ll.driftedKeys.length>0)throw new X("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Ll.driftedKeys.join(",")});Nb=!0,us=Ll.state,Lt={...Lt,managed_config:us,plugin_config:{plugin_id:Vr,before:D,after:Nf},provider_config:Ff},await Jn(n.configFile,Eb(Ll.document)),yn=!0,Lt={...Lt,step:"config_published"},await Cl(n.preparingRecord,Lt),await cj(n,c,l,u.computer_use,us,je.preserved);let Fb=xI(u),UI=await Af({owner:"holycodex",install_id:y,version:R,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:Fb,managed_artifacts:je.managed_artifacts,managed_config:us,plugin_config:{plugin_id:Vr,before:D,after:Nf},provider_config:Ff,plugin_snapshot:$e,owned_plugins:[...lr]}),Lf={owner:"holycodex",schema_epoch:Tr,install_id:y,version:R,digest:UI,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:Fb,managed_artifacts:je.managed_artifacts,installed_at:P,status:"active",step:"active",managed_config:us,plugin_snapshot:$e,plugin_config:{plugin_id:Vr,before:D,after:Nf},provider_config:Ff,owned_plugins:[...lr]};if(ht(ts,Lf)===void 0)throw new X("state_corrupt","The HolyCodex configuration is invalid.");return await jo(n.activeRecord,sr(Lf)),await vb(n.preparingRecord),await vb(n.conflictedRecord),{record:Lf,optional_plugins:h,preserved:je.preserved,warnings:je.preserved.length===0?[]:["modified managed files were preserved"]}}catch(se){let De=[];if(yn)try{await sj(n.configFile,Mf)}catch{De.push("config")}if(Mb&&!Nb){if(await Yt(n.configFile).catch(()=>{return})!==Mf)De.push("config")}if(je!==void 0)try{if((await bf(je.rollback)).preserved.length>0)De.push("roles")}catch{De.push("roles")}if(If.size>0)De.push(...[...If].map((Zt)=>`plugin:${Zt}`));for(let Zt of zi)try{await m.remove?.(Zt)}catch{De.push(`plugin:${Zt}`)}if(De.length>0)await Cl(n.conflictedRecord,{...Lt,step:"conflicted",status:"conflicted"}).catch(()=>{return});else await vb(n.preparingRecord).catch(()=>{return});if(se instanceof _r)throw se;if(se instanceof X)throw se;throw new X(se instanceof hn||se instanceof Al?"capability_denied":"install_failed",SI(se),se,De.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function Rl(e){let t=await Gn(e.activeRecord,pf);if(t===void 0)return;let r=ht(ts,t);if(r!==void 0)return r;let n=ht(KP,t);if(n===void 0)throw new X("state_corrupt","The HolyCodex configuration is invalid.");if(!await OI(n))throw new X("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord});let o="profile"in n&&n.profile!==void 0?n.profile:("plan"in n)?n.plan:void 0;if(o===void 0)throw new X("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let i;try{i=Mx(o)}catch(c){throw new X("state_corrupt",`The persisted profile ${o} was removed and requires an explicit replacement.`,c,{path:e.activeRecord,profile:o})}let s={..."plan"in n?Object.fromEntries(Object.entries(n).filter(([c])=>c!=="plan")):n,profile:i,digest:await Af({owner:n.owner,install_id:n.install_id,version:n.version,profile:i,tier:n.tier,optional_selections:n.optional_selections,explicit_optional_selections:n.explicit_optional_selections,official_plugins:n.official_plugins??[],capability_state:n.capability_state??null,managed_artifacts:n.managed_artifacts,...n.managed_config===void 0?{}:{managed_config:n.managed_config},...n.plugin_config===void 0?{}:{plugin_config:n.plugin_config},...n.provider_config===void 0?{}:{provider_config:n.provider_config},...n.plugin_snapshot===void 0?{}:{plugin_snapshot:n.plugin_snapshot},...n.owned_plugins===void 0?{}:{owned_plugins:n.owned_plugins}})};return await jo(e.activeRecord,sr(s)),s}function TI(e){return{computer_use:e.computer_use,work:e.work,frontend:e.frontend,security:e.security}}function Zn(e){if(e===void 0||e.trim().length===0)return{};try{let t=globalThis.Bun,r=t?.TOML?.parse?t.TOML.parse(e):aI(e),n=ht(ol,r);if(n===void 0)throw Error("TOML document contains unsupported values.");return n}catch(t){throw new X("state_corrupt","The Codex config.toml is not valid TOML.",t)}}function Eb(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):sI(e)).trimEnd()}
42
+ `}catch(t){throw new X("install_failed","The merged Codex configuration is not writable.",t)}}async function mI(e){return{preference:await Il(e,"plugins",_I),marketplace:await Il(e,"marketplaces",wI)}}async function hI(e,t){return await Promise.all(t.map(async(r)=>{let n=await Il(e,"plugins",r),o={presence:n.presence,digest:n.digest,...n.safe_value?.kind==="boolean"?{safe_value:n.safe_value}:{}};return{plugin_id:r,before:o,after:o}}))}async function _b(e,t,r={}){let n=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",_I],["marketplace","marketplaces",wI]]){let u=t.before[s],p=t.after[s],f=await Il(e,c,l);if(r.allowBeforeState===!0&&f.digest===u.digest)continue;if(f.digest!==p.digest){a.push(s);continue}if(u.presence==="absent"){if(f.presence==="present")n=vI(n,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}n=EI(n,c,l,rj(u.safe_value)),o.push(s)}return{document:n,restored:o,removed:i,preserved:a}}async function wb(e,t,r,n={}){let o=e,i=[],a=[],s=[];for(let c of t){if(!r.has(c.plugin_id))continue;let{before:l,after:u}=c,p=await Il(e,"plugins",c.plugin_id);if(n.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=vI(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=EI(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 Il(e,t,r){let n=ej(e,t,r),o=await Kn("holycodex-plugin-config",[zn(sr({key:`${t}.${r}`,value:n===void 0?{presence:"absent"}:n}))]),i=tj(t,n);return{presence:n===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function ej(e,t,r){let n=e[t];if(!Cf(n))return;return n[r]}function tj(e,t){if(!Cf(t))return;let r=Object.keys(t);if(e==="plugins"){if(r.length!==1||r[0]!=="enabled"||typeof t.enabled!=="boolean")return;return{kind:"boolean",value:t.enabled}}if(r.length!==2||!r.includes("source_type")||!r.includes("source")||t.source_type!=="git"||t.source!==fI)return;return{kind:"marketplace",source_type:"git",source:fI}}function rj(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function EI(e,t,r,n){let o={...e},i=o[t];if(i!==void 0&&!Cf(i))throw new X("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[r]:n},o}function vI(e,t,r){let n=e[t];if(!Cf(n)||!Object.prototype.hasOwnProperty.call(n,r))return e;let o={...e},i={...n};if(delete i[r],Object.keys(i).length===0)delete o[t];else o[t]=i;return o}function Cf(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Of(e,t,r=!1){let n=mb(e,t),o={model:n.model,model_reasoning_effort:n.effort,service_tier:n.serviceTier,model_verbosity:"low",developer_instructions:hb(r),suppress_unstable_features_warning:!0,"features.default_mode_request_user_input":!0,"features.multi_agent_v2":!0,"features.context_management.experimental_mode":!0};for(let i of Ka)o[`agents."${i}".config_file`]=`holycodex/agents/${i}.toml`;return o}async function nj(e,t,r,n){let o=[];for(let i of Object.keys(n)){let a=i;if(r.managed[a]!==void 0){if((await Ya(e,r,a)).status==="drifted")o.push(a);continue}let c=Pe(t,a),l=Pe(e,a);if(c!==l)o.push(a)}if(o.length>0)throw new X("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function oj(e,t,r){let n=["agents.explorer.config_file","agents.librarian.config_file","agents.worker.config_file","agents.reviewer.config_file"],o=Object.fromEntries(n.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 Di(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new X("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])=>!n.includes(l)))}}if(!r)return{document:i,state:a};let s=r.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=Pe(i,u);if(typeof p!=="string")continue;let f=p.replaceAll("\\","/").replace(/^\.\//u,"");if(f===`agents/${c}.toml`||f===`holycodex/agents/${c}.toml`)i=zd(i,u)}return{document:i,state:a}}function ij(e,t){if(Pe(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new X("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function aj(e,t){let r=await e.list();return t.map((n)=>{let o=Pl(r,n),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:n,status:i}})}async function Cl(e,t){if(ht(jr,t)===void 0)throw new X("state_corrupt","The HolyCodex transaction state is invalid.");await jo(e,sr(t))}async function vb(e){await bI(e,{force:!1}).catch((t)=>{if(!gt(t,"ENOENT"))throw t})}async function sj(e,t){if(t===void 0){await bI(e,{force:!1}).catch((r)=>{if(!gt(r,"ENOENT"))throw r});return}await Jn(e,t)}async function cj(e,t,r,n,o,i=[]){let a=await Yt(e.configFile),s=Zn(a),c=Of(t,r,n);for(let[p,f]of Object.entries(c)){let h=Pe(s,p);if(p==="developer_instructions"){if(typeof h!=="string"||await lj(p,h)!==o.managed[p]?.lastManagedValue.value)throw new X("install_failed","The effective Root instructions did not converge.")}else if(h!==f)throw new X("install_failed",`The effective Codex setting ${p} did not converge.`)}let l=ji(t,r);for(let p of l){let f=`agents."${p.name}".config_file`,h=Pe(s,f);if(typeof h!=="string")throw new X("install_failed",`The ${p.name} registration is missing.`);let m=X$(e.roleRoot,`${p.name}.toml`),w=m.replaceAll("\\","/");if(al(e.configFile,h).replaceAll("\\","/")!==w)throw new X("install_failed",`The ${p.name} registration is stale.`);let y=await Yt(m);if(y===void 0)throw new X("install_failed",`The ${p.name} role file is missing.`);if(i.includes(m))continue;let R=Zn(y);if(R.name!==p.name||typeof R.description!=="string"||typeof R.model!=="string"||typeof R.model_reasoning_effort!=="string"||typeof R.service_tier!=="string"||typeof R.developer_instructions!=="string"||R.sandbox_mode!==(p.permissions.write?"workspace-write":"read-only")||R.approval_policy!=="never"||R.web_search!==(p.permissions.network?"live":"disabled")||R.tool_output_token_limit!==void 0||Pe(R,"agents.enabled")!==!1||Pe(R,"features.multi_agent_v2")!==!1||Pe(R,"features.multi_agent")!==!1||Pe(R,"features.computer_use")!==!1||Pe(R,"features.browser_use")!==!1||Pe(R,"features.in_app_browser")!==!1)throw new X("install_failed",`The ${p.name} role file is malformed.`)}let u=await Yt(`${e.codexHome}/agents/root.toml`);if(u!==void 0&&ss(u))throw new X("install_failed","A stale HolyCodex Root role remains installed.")}async function lj(e,t){return await Kn("holycodex-managed-config-value",[zn({keyPath:e,value:t})])}function uj(e,t){let r={};for(let n of["computer_use","work","frontend","security"]){let o=t?.[n]??e?.[n];if(o!==void 0)r[n]=o}return r}function pj(e){return["computer_use","work","frontend","security"].find((t)=>zc[t].pluginIds.includes(e))}function gI(e){return(e?.official_plugins??[]).filter((t)=>{let r=pj(t);return r===void 0||e?.optional_selections[r]!==!0})}async function dj(e,t,r){for(let n of t){let o;try{o=Pl(await e.list(),n)}catch(s){throw Ob("list",s,n)}if(o?.installed&&!o.enabled)throw new Al("uncertain",`${n} is disabled`);let i=!(o?.installed&&o.enabled);if(!(o?.installed&&o.enabled))try{await e.add(n)}catch(s){try{let c=Pl(await e.list(),n);if(!yI(o,c))r?.(n,"uncertain")}catch{r?.(n,"uncertain")}throw Ob("add",s,n)}let a;try{a=Pl(await e.list(),n)}catch(s){if(i)r?.(n,"uncertain");throw Ob("list",s,n)}if(!a?.installed){if(i&&!yI(o,a))r?.(n,"uncertain");throw new Al("missing",`${n} is not installed after add`)}if(i&&a.enabled)r?.(n,"new");if(!a.enabled){if(i)r?.(n,"new");throw new Al("uncertain",`${n} is disabled after add`)}}}function yI(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function Ob(e,t,r){if(t instanceof hn)return t;return new hn(e==="list"?"list_failed":"add_failed",e==="list"?`Codex could not read the status of ${r}.`:`Codex could not add ${r}.`,t,{plugin_id:r})}function Pl(e,t){let r=fn(e,t);if(r!==void 0)return r.entry;let n=Ur(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(n===void 0||o.marketplaceName==null))}function fj(e,t){let r=e??t??"default";if(!ln(r).ok)throw new X("install_failed","Unknown profile.");return r}function mj(e,t){let r=e??t??"standard";if(ht(Mi,r)===void 0)throw new X("install_failed","The tier is not supported.");return r}function hj(e,t){let r=t?TI(t):an,n=Cx(e,r);return{computer_use:n.computer_use,work:n.work,frontend:n.frontend,security:n.security,coding:!0}}function xI(e,t=new Map){return Object.fromEntries(["computer_use","work","frontend","security"].map((n)=>{let o=e[n],i={selected:o,status:o?t.get(n)??"healthy":"disabled",plugin_ids:[...zc[n].pluginIds]};return[n,i]}))}async function Af(e){let{profile:t,plan:r,...n}=e,o=r===void 0?{...n,profile:t}:{...n,plan:r};return await Kn("install-record",[zn(sr(o))])}async function Rf(e){return await OI(e)}async function OI(e){return await Af({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.digest}function SI(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}var Q$="davidbasilefilho/holycodex",Vr="holycodex@holycodex",fI="https://github.com/davidbasilefilho/holycodex.git",_I="holycodex@holycodex",wI="holycodex",Al,X;var kl=x(()=>{gl();pt();yl();gf();Tf();El();Hi();rs();is();rs();Al=class Al extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};X=class X extends Error{code;causeValue;details;constructor(e,t,r,n={}){super(t);this.name="InstallerError",this.code=e,this.causeValue=r,this.details=n}}});import{createInterface as Vj}from"readline/promises";pt();pt();pt();var Xx=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:"work",kind:"boolean",usage:"--work / --no-work",description:"Work plugins (default: false)."},{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."}]),sP=new Set(["codex-home","profile","tier","add-plugin"]),WU=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","work","no-work","frontend","no-frontend","security","no-security"]);class Ke extends Error{code;details;constructor(e,t,r={}){super(t);this.name="ArgumentError",this.code=e,this.details=r}}function Ud(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 Ud(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new Ke("unknown_command","Unknown command.",{command:t??""});let r=[],n={};for(let o=1;o<e.length;o+=1){let i=e[o];if(i===void 0)continue;if(i==="-"||!i.startsWith("-")){r.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(!sP.has(u)&&!WU.has(u))throw new Ke("invalid_argument","Unknown option.",{option:`--${c}`});if(sP.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=n[u];n[u]=Array.isArray(f)?[...f,p]:[p]}else{if(n[u]!==void 0)throw new Ke("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});n[u]=p}continue}if(l!==void 0&&l!=="true"&&l!=="false")throw new Ke("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(n[u]!==void 0)throw new Ke("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});n[u]=l==="false"?!1:!0}return JU(t,r,n),{command:t,positionals:r,options:n}}function JU(e,t,r){let n=YU(e);for(let s of Object.keys(r))if(!n.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=r.profile;if(typeof i==="string"&&!ln(i).ok){let s=GU[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=r.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"],["work","no-work"],["frontend","no-frontend"],["security","no-security"]])if(r[s]!==void 0&&r[c]!==void 0)throw new Ke("invalid_argument",`Conflicting --${s} and --${c} options.`);if(e==="install"&&r.yes===!1)throw new Ke("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(r).some((s)=>["profile","tier","work","no-work","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 GU={"plus-low":"low",plus:"default","plus-high":"high"};function YU(e){switch(e){case"install":return new Set([...Xx.map((t)=>t.name),"no-work","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"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var ZU=`HolyCodex
43
43
 
44
44
  Usage:
45
45
  holycodex install [options]
46
46
  holycodex remove [options]
47
- holycodex upgrade [options]
48
47
  holycodex doctor [options]
49
48
  holycodex version [<0.x.y|patch|minor>] [options]
50
49
 
@@ -54,7 +53,7 @@ Options:
54
53
  --json Emit one validated JSON envelope.
55
54
 
56
55
  Use --json for scripts. Install and remove use native Codex plugin management.
57
- `,dH=`Install HolyCodex through Codex native plugin management.
56
+ `,XU=`Install HolyCodex through Codex native plugin management.
58
57
 
59
58
  Usage:
60
59
  holycodex install [options]
@@ -71,7 +70,7 @@ Tier is independent service handling (CLI values are lowercase only):
71
70
  fast-all Fast service handling for Root and leaves.
72
71
 
73
72
  Options:
74
- ${rS.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
73
+ ${Xx.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
75
74
  `)}
76
75
  --no-work / --no-frontend / --no-security /
77
76
  --no-computer-use Disable the corresponding plugin.
@@ -81,58 +80,43 @@ Capability defaults: Work false, Frontend true (mapped to build-web-apps),
81
80
  Security true, and Computer Use false. --add-plugin may be repeated.
82
81
  On an interactive TTY, install opens one wizard and final review with Install,
83
82
  Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
84
- Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
85
- remains repeatable on the command line.
86
- `,fH=`Remove HolyCodex-owned state through Codex native plugin management.
83
+ `,QU=`Remove HolyCodex-owned state through Codex native plugin management.
87
84
 
88
85
  Usage:
89
86
  holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
90
87
 
91
88
  Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
92
89
  configuration are preserved; changed owned files are preserved for review.
93
- `,mH=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
90
+ `,eH=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
94
91
 
95
92
  Usage:
96
93
  holycodex doctor [--json] [--codex-home <absolute-path>]
97
- `,hH=`Migrate an existing HolyCodex installation in place.
98
-
99
- Usage:
100
- holycodex upgrade [--dry-run] [--yes] [--json] [--codex-home <absolute-path>]
101
-
102
- Upgrade preserves your selected profile, service tier, capabilities, additional
103
- plugins, and unrelated Codex configuration while applying the running version.
104
- Use --dry-run to preview changes. It does not download or install a new binary.
105
- `,gH=`Read or update the canonical public package version.
94
+ `,tH=`Read or update the canonical public package version.
106
95
 
107
96
  Usage:
108
97
  holycodex version [<0.x.y|patch|minor>] [--dry-run] [--json]
109
98
  holycodex --version
110
99
  holycodex -v
111
- `;function il(e){switch(e){case"install":return dH;case"remove":return fH;case"doctor":return mH;case"upgrade":return hH;case"version":return gH;default:return pH}}function oS(e,t={}){let n=Gd({...t,stream:"stdout"});return il(e).split(`
112
- `).map((r)=>{if(r==="HolyCodex")return Jd(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return Jd(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>Jd(o,"option",n)).replace(/<[^>]+>/gu,(o)=>Jd(o,"argument",n))}).join(`
113
- `)}function al(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function sl(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 Gd(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 Jd(e,t,n){if(!n)return e;return`\x1B[${{heading:"1",option:"36",argument:"2"}[t]}m${e}\x1B[0m`}ut();ql();var Pj=["low","default","high"],Ij=["standard","fast","fast-all"],Wn=["work","frontend","security","computer_use"];async function M_(e={}){let t=wr(e),n=await import("@opentui/core"),r=$I(t),o=await n.createCliRenderer({exitOnCtrlC:!0,clearOnShutdown:!0}),i=new n.TextRenderable(o,{content:UI(r,0)});return o.root.add(i),await new Promise((a,s)=>{let c=0,l=!1,u=0,p=!1,f=(S)=>{if(p)return;p=!0,o.keyInput.off("keypress",w),o.destroy(),a(S)},h=(S)=>{if(p)return;p=!0,o.keyInput.off("keypress",w),o.destroy(),s(S)},m=()=>{i.content=l?BI(r,u):UI(r,c),o.requestRender()},w=(S)=>{try{let y=S.name.toLowerCase();if(y==="escape"||S.ctrl===!0&&y==="c"){f({action:"cancel"});return}if(l){if(y==="up"||y==="k")u=(u+2)%3;else if(y==="down"||y==="j")u=(u+1)%3;else if(y==="return"||y==="enter"||y==="linefeed"){if(u===0)f({action:"install",request:HI(r)});else if(u===1)l=!1,c=0;else f({action:"cancel"});return}m();return}if(c===Wn.length+2){if(y==="backspace")r.pluginInput=r.pluginInput.slice(0,-1);else if(y==="space")r.pluginInput+=" ";else if(y==="return"||y==="enter"||y==="linefeed")r.plugins=VI(r.pluginInput),l=!0,u=0;else if(!S.ctrl&&!S.meta&&S.name.length===1&&!Lj(S.name))r.pluginInput+=S.name;m();return}if(y==="up"||y==="k")c=Math.max(0,c-1);else if(y==="down"||y==="j")c=Math.min(Wn.length+2,c+1);else if(y==="space"&&c>=2)jI(r,c-2);else if(y==="left"||y==="h")DI(r,c,-1);else if(y==="right"||y==="l")DI(r,c,1);else if(y==="return"||y==="enter"||y==="linefeed"){if(c<Wn.length+2)c+=1}if(c===Wn.length+2)r.pluginInput=r.plugins.join(" ");m()}catch(y){h(y)}};o.keyInput.on("keypress",w);try{o.start()}catch(S){h(S)}})}function HI(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 wr(t)}function Mj(e,t="install"){let n=$I(wr(e));return BI(n,t==="install"?0:t==="change"?1:2)}function $I(e){let t={...ur,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{computer_use:t.computer_use??ur.computer_use,work:t.work??ur.work,frontend:t.frontend??ur.frontend,security:t.security??ur.security},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" ")}}function DI(e,t,n){if(t===0)e.profile=qI(Pj,e.profile,n);else if(t===1)e.tier=qI(Ij,e.tier,n);else if(t>=2&&t<Wn.length+2)jI(e,t-2)}function jI(e,t){let n=Wn[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function qI(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function VI(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return wr({officialPlugins:t}),t}function UI(e,t){let n=t<2?t===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":t<Wn.length+2?Nj(Wn[t-2]):"Optional plugin IDs separated by spaces. Enter continues to review.";return`${["HolyCodex \xB7 install","\u2191/\u2193 move \u2190/\u2192 change Space toggle Enter review Esc cancel","","PROFILE",`${t===0?"\u276F":" "} Profile ${e.profile}`,`${t===1?"\u276F":" "} Service tier ${e.tier}`,"","OPTIONAL CAPABILITIES",...Wn.map((o,i)=>`${t===i+2?"\u276F":" "} ${zI(o).padEnd(14)} ${e.optional[o]?"[x] enabled":"[ ] disabled"}`),"","ADDITIONAL PLUGINS",...KI(`${t===Wn.length+2?"\u276F":" "} ${e.pluginInput||"(none)"}`),"",n].join(`
100
+ `;function Xc(e){switch(e){case"install":return XU;case"remove":return QU;case"doctor":return eH;case"version":return tH;default:return ZU}}function Qx(e,t={}){let r=$d({...t,stream:"stdout"});return Xc(e).split(`
101
+ `).map((n)=>{if(n==="HolyCodex")return Hd(n,"heading",r);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(n))return Hd(n,"heading",r);return n.replace(/--[a-z][a-z0-9-]*/gu,(o)=>Hd(o,"option",r)).replace(/<[^>]+>/gu,(o)=>Hd(o,"argument",r))}).join(`
102
+ `)}function Qc(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function el(e){let t=e.filter((r)=>!r.startsWith("-"));if(t[0]==="help")return t[1];if(t[0]==="--version"||t[0]==="version"||t[0]==="-v")return"version";return t[0]}function $d(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 Hd(e,t,r){if(!r)return e;return`\x1B[${{heading:"1",option:"36",argument:"2"}[t]}m${e}\x1B[0m`}pt();kl();var gj=["low","default","high"],yj=["standard","fast","fast-all"],Vo=["work","frontend","security","computer_use"];async function Rb(e={}){let t=Xn(e),r=await import("@opentui/core"),n=PI(t),o=await r.createCliRenderer({exitOnCtrlC:!0,clearOnShutdown:!0}),i=new r.TextRenderable(o,{content:CI(n,0)});return o.root.add(i),await new Promise((a,s)=>{let c=0,l=!1,u=0,p=!1,f=(S)=>{if(p)return;p=!0,o.keyInput.off("keypress",w),o.destroy(),a(S)},h=(S)=>{if(p)return;p=!0,o.keyInput.off("keypress",w),o.destroy(),s(S)},m=()=>{i.content=l?MI(n,u):CI(n,c),o.requestRender()},w=(S)=>{try{let y=S.name.toLowerCase();if(y==="escape"||S.ctrl===!0&&y==="c"){f({action:"cancel"});return}if(l){if(y==="up"||y==="k")u=(u+2)%3;else if(y==="down"||y==="j")u=(u+1)%3;else if(y==="return"||y==="enter"||y==="linefeed"){if(u===0)f({action:"install",request:AI(n)});else if(u===1)l=!1,c=0;else f({action:"cancel"});return}m();return}if(c===Vo.length+2){if(y==="backspace")n.pluginInput=n.pluginInput.slice(0,-1);else if(y==="return"||y==="enter"||y==="linefeed")n.plugins=Sj(n.pluginInput),l=!0,u=0;else if(!S.ctrl&&!S.meta&&S.name.length===1&&!_j(S.name))n.pluginInput+=S.name;m();return}if(y==="up"||y==="k")c=Math.max(0,c-1);else if(y==="down"||y==="j")c=Math.min(Vo.length+2,c+1);else if(y==="space"&&c>=2)II(n,c-2);else if(y==="left"||y==="h")RI(n,c,-1);else if(y==="right"||y==="l")RI(n,c,1);else if(y==="return"||y==="enter"||y==="linefeed"){if(c<Vo.length+2)c+=1}if(c===Vo.length+2)n.pluginInput=n.plugins.join(", ");m()}catch(y){h(y)}};o.keyInput.on("keypress",w);try{o.start()}catch(S){h(S)}})}function AI(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 Xn(t)}function xj(e,t="install"){let r=PI(Xn(e));return MI(r,t==="install"?0:t==="change"?1:2)}function PI(e){let t={...an,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{computer_use:t.computer_use??an.computer_use,work:t.work??an.work,frontend:t.frontend??an.frontend,security:t.security??an.security},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(", ")}}function RI(e,t,r){if(t===0)e.profile=kI(gj,e.profile,r);else if(t===1)e.tier=kI(yj,e.tier,r);else if(t>=2&&t<Vo.length+2)II(e,t-2)}function II(e,t){let r=Vo[t];if(r!==void 0)e.optional[r]=!e.optional[r]}function kI(e,t,r){let n=e.indexOf(t);return e[(n+r+e.length)%e.length]??e[0]}function Sj(e){return[...new Set(e.split(",").map((t)=>t.trim()).filter(Boolean))]}function CI(e,t){return`${["HolyCodex install wizard","Use \u2191/\u2193 (or j/k) to move, \u2190/\u2192 to change, Enter to continue, Esc to cancel.","",...[["Profile",e.profile],["Service tier",e.tier],...Vo.map((n)=>[bj(n),Ml(e.optional[n])])].map(([n,o],i)=>`${i===t?"\u203A":" "} ${n}: ${o}`),`${t===Vo.length+2?"\u203A":" "} Additional plugins (comma-separated, optional): ${e.pluginInput||"none"}`].join(`
114
103
  `)}
115
- `}function BI(e,t){let n=["Install","Change options / Redo","Cancel"];return`${["HolyCodex \xB7 review","Review configuration","\u2191/\u2193 choose Enter confirm Esc cancel","",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"","CAPABILITIES",...Wn.map((o)=>` ${zI(o)}: ${Fj(e.optional[o])}`),...KI(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...n.map((o,i)=>`${i===t?"\u203A":" "} ${o}`)].join(`
104
+ `}function MI(e,t){let r=["Install","Change options / Redo","Cancel"];return`${["Review configuration","",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,`Work: ${Ml(e.optional.work)}`,`Frontend: ${Ml(e.optional.frontend)}`,`Security: ${Ml(e.optional.security)}`,`Computer Use: ${Ml(e.optional.computer_use)}`,`Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(", ")}`,"",...r.map((o,i)=>`${i===t?"\u203A":" "} ${o}`),"","Enter selects the highlighted action. Esc cancels."].join(`
116
105
  `)}
117
- `}function Nj(e){switch(e){case"work":return"Work plugins for documents, spreadsheets, and presentations.";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 KI(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 zI(e){return e==="computer_use"?"Computer Use":`${e[0].toUpperCase()}${e.slice(1)}`}function Fj(e){return e?"enabled":"disabled"}function Lj(e){let t=e.codePointAt(0)??0;return t<=31||t===127}ql();Ol();Af();Il();Nl();Vi();cs();async function F_(e,t={}){if(al(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:sl(e);return{envelope:WI(r===void 0?"help":`${r} help`,{help:il(r)}),exitCode:0}}let n;try{n=Wd(e);let r=await JI(n,t);return{envelope:WI(n.command,r),exitCode:Gj(n.command,r)}}catch(r){return Jj(n?.command??Zj(e),r)}}async function JI(e,t){switch(e.command){case"install":return Zt(await Dj(e,t));case"doctor":return Zt(await k_(Mf(e,t),t.env));case"remove":return Zt(await Hj(e,t));case"upgrade":return Zt(await $j(e,t));case"version":return Zt(await jj(e,t));case"help":return{help:il(e.positionals[0])};default:throw new Ji("invalid_argument","Unknown command.")}}async function Dj(e,t){let n=Uj(e),r=await qj(e,t,n);if("cancelled"in r)return r;return await fs(r,Mf(e,t),t.env)}async function qj(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??M_)(n);if(i.action==="cancel")return{cancelled:!0};return wr(i.request)}let o=await L_(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new Ji("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return wr(n)}function Uj(e){let t=Kj(e),n=zj(e),r=Bj(e),o=Wj(e,"add-plugin");return wr({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o.length===0?{}:{officialPlugins:o}})}async function Hj(e,t){let n=await L_(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable")throw new Ji("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.");return await Ll(Mf(e,t),t.env)}async function $j(e,t){let n=e.options["dry-run"]===!0;if(!n){let r=await L_(e,t,"Upgrade the existing HolyCodex installation in place?");if(r==="cancelled")return{cancelled:!0,status:"cancelled",changes:[]};if(r==="unavailable")throw new Ji("non_tty_confirmation_required","Upgrade requires --yes in non-interactive mode.")}return await C_(Mf(e,t),t.env,{dryRun:n})}async function jj(e,t){let n=e.positionals[0];if(!n)return{version:await bf()};return await g_(n,e.options["dry-run"]===!0)}async function L_(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 Vj(t,n)}async function Vj(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 Bj(e){let t={};for(let n of["computer_use","work","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 Kj(e){let t=e.options.profile;if(typeof t!=="string")return;let n=fr(t);return n.ok?n.value.name:void 0}function zj(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function Wj(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Mf(e,t){let n=t.installer??{},r=e.options.json===!0,o=(a)=>{n.onProgress?.(a),t.onProgress?.(a),Xj(t,r,a.message)},i=e.options["codex-home"];if(typeof i!=="string")return{...n,onProgress:o,...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:i},onProgress:o,...t.now?{now:t.now}:{}}}function WI(e,t){let n=Kd({schema_version:vr,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new Ji("internal_error","The success envelope failed validation.");return n.value}function Jj(e,t){let n=Yj(t),r=Kd({schema_version:vr,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:vr,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 Gj(e,t){return e==="doctor"&&Jn(t)&&t.healthy===!1?4:0}function Yj(e){if(e instanceof ze)return{code:e.code,message:zi(e.message),details:e.details,exitCode:1};if(e instanceof Ji)return{code:e.code,message:zi(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof wn)return{code:"trust_boundary_failed",message:zi(e.message),details:{},exitCode:4};if(e instanceof N){let t=e.code==="capability_denied"?2:e.code==="state_corrupt"?4:3;return{code:e.code,message:zi(e.message),details:e.details,exitCode:t}}if(e instanceof Sr){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:zi(e.message),details:e.details,exitCode:t?4:n?2:3}}if(e instanceof Bi)return{code:e.code,message:zi(e.message),details:{},exitCode:4};if(e instanceof Pl)return{code:e.code,message:zi(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 Zj(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function zi(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 Jn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Xj(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${GI(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
118
- `)}function Nf(e,t={}){let n=Gd(t);if(e.envelope.ok){if(e.envelope.command==="version")return Qj(e.envelope.data);if(e.envelope.command==="install")return e1(e.envelope.data,n);if(e.envelope.command==="remove")return t1(e.envelope.data,n);if(e.envelope.command==="upgrade")return n1(e.envelope.data,n);if(e.envelope.command==="doctor")return r1(e.envelope.data,n);return`${oe("\u2714","green",n)} ${oe(e.envelope.command,"heading",n)}
119
- ${o1(e.envelope.data,n)}`}let r=e.envelope.error,o=a1(r.code,e.envelope.command);return[`${oe("\u2716","red",n)} ${oe(e.envelope.command,"heading",n)}`,` ${oe(r.code,"red",n)}: ${r.message}`,...i1(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
120
- `)}function GI(e,t={}){return`${oe("\u2022","cyan",Gd({...t,stream:"stderr"}))} ${e}`}function Qj(e){if(Jn(e)&&typeof e.version==="string")return`holycodex ${e.version}
121
- `;if(Jn(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
106
+ `}function bj(e){return e==="computer_use"?"Computer Use":`${e[0].toUpperCase()}${e.slice(1)}`}function Ml(e){return e?"enabled":"disabled"}function _j(e){let t=e.codePointAt(0)??0;return t<=31||t===127}kl();yl();vf();gf();El();Hi();is();async function Cb(e,t={}){if(Qc(e)||e[0]==="help"){let n=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:el(e);return{envelope:NI(n===void 0?"help":`${n} help`,{help:Xc(n)}),exitCode:0}}let r;try{r=Ud(e);let n=await FI(r,t);return{envelope:NI(r.command,n),exitCode:Mj(r.command,n)}}catch(n){return Ij(r?.command??Fj(e),n)}}async function FI(e,t){switch(e.command){case"install":return sr(await wj(e,t));case"doctor":return sr(await Tb(Ab(e,t),t.env));case"remove":return sr(await vj(e,t));case"version":return sr(await Oj(e,t));case"help":return{help:Xc(e.positionals[0])};default:throw new Vi("invalid_argument","Unknown command.")}}async function wj(e,t){let r=e.options.json===!0,n=Ej(e),o=await Tj(e,t,n);gn(t,r,"Validating Codex target"),gn(t,r,"Installing HolyCodex"),gn(t,r,"Installing selected capabilities"),gn(t,r,"Configuring Root"),gn(t,r,"Installing subagent roles");let i=await kf(o,Ab(e,t),t.env);return gn(t,r,"Verifying installation"),gn(t,r,"HolyCodex installation complete"),i}async function Tj(e,t,r){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let o=await(t.io?.installWizard??Rb)(r);if(o.action==="cancel")throw new Vi("install_cancelled","Installation cancelled.");return Xn(o.request)}if(!await LI(e,t,"Install HolyCodex into the selected Codex home?"))throw new Vi("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return Xn(r)}function Ej(e){let t=Cj(e),r=Aj(e),n=kj(e),o=Pj(e,"add-plugin");return Xn({...t===void 0?{}:{profile:t},...r===void 0?{}:{tier:r},...n===void 0?{}:{optional:n},...o.length===0?{}:{officialPlugins:o}})}async function vj(e,t){let r=e.options.json===!0;if(!await LI(e,t,"Remove HolyCodex-owned Codex state?"))throw new Vi("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.");gn(t,r,"Validating HolyCodex ownership");let n=await Ol(Ab(e,t),t.env);return gn(t,r,"Removing HolyCodex-owned state"),gn(t,r,"HolyCodex removal complete"),n}async function Oj(e,t){let r=e.positionals[0];if(!r)return{version:await mf()};return await db(r,e.options["dry-run"]===!0)}async function LI(e,t,r){if(e.options.yes===!0)return!0;if(e.options.json===!0||t.io?.stdoutIsTTY!==!0)return!1;return await Rj(t,r)}async function Rj(e,t){return e.io?.confirm?await e.io.confirm(t):!1}function kj(e){let t={};for(let r of["computer_use","work","frontend","security"]){let n=r.replaceAll("_","-");if(e.options[n]===!0)t[r]=!0;else if(e.options[n]===!1)t[r]=!1;else if(e.options[`no-${n}`]===!0)t[r]=!1}return Object.keys(t).length===0?void 0:t}function Cj(e){let t=e.options.profile;if(typeof t!=="string")return;let r=ln(t);return r.ok?r.value.name:void 0}function Aj(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function Pj(e,t){let r=e.options[t];return Array.isArray(r)?r.filter((n)=>typeof n==="string"):[]}function Ab(e,t){let r=t.installer??{},n=e.options["codex-home"];if(typeof n!=="string")return{...r,...t.now?{now:t.now}:{}};return{...r,paths:{...r.paths,codexHome:n},...t.now?{now:t.now}:{}}}function NI(e,t){let r=Dd({schema_version:xn,ok:!0,command:e,data:t,warnings:[]});if(!r.ok)throw new Vi("internal_error","The success envelope failed validation.");return r.value}function Ij(e,t){let r=Nj(t),n=Dd({schema_version:xn,ok:!1,command:e,error:{code:r.code,message:r.message,details:r.details},warnings:[]});if(!n.ok)return{envelope:{schema_version:xn,ok:!1,command:"internal-error",error:{code:"internal_error",message:"The CLI failure envelope was invalid.",details:{}},warnings:[]},exitCode:5};return{envelope:n.value,exitCode:r.exitCode}}function Mj(e,t){return e==="doctor"&&zo(t)&&t.healthy===!1?4:0}function Nj(e){if(e instanceof Ke)return{code:e.code,message:Bi(e.message),details:e.details,exitCode:1};if(e instanceof Vi)return{code:e.code,message:Bi(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof _r)return{code:"trust_boundary_failed",message:Bi(e.message),details:{},exitCode:4};if(e instanceof X){let t=e.code==="capability_denied"?2:e.code==="state_corrupt"?4:3;return{code:e.code,message:Bi(e.message),details:e.details,exitCode:t}}if(e instanceof hn){let t=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),r=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:t?"effect_uncertain":r?"capability_denied":"install_failed",message:Bi(e.message),details:e.details,exitCode:t?4:r?2:3}}if(e instanceof $i)return{code:e.code,message:Bi(e.message),details:{},exitCode:4};if(e instanceof wl)return{code:e.code,message:Bi(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 Fj(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function Bi(e){return Array.from(e).map((t)=>{let r=t.codePointAt(0)??0;return r<=31||r===127?" ":t}).join("").replace(/\s+/gu," ").trim().slice(0,512)}function zo(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function gn(e,t,r){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${DI(r,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
107
+ `)}function Pf(e,t={}){let r=$d(t);if(e.envelope.ok){if(e.envelope.command==="version")return Lj(e.envelope.data);if(e.envelope.command==="install")return Dj(e.envelope.data,r);if(e.envelope.command==="remove")return qj(e.envelope.data,r);if(e.envelope.command==="doctor")return Uj(e.envelope.data,r);return`${Se("\u2714","green",r)} ${Se(e.envelope.command,"heading",r)}
108
+ ${$j(e.envelope.data,r)}`}let n=e.envelope.error,o=Bj(n.code,e.envelope.command);return[`${Se("\u2716","red",r)} ${Se(e.envelope.command,"heading",r)}`,` ${Se(n.code,"red",r)}: ${n.message}`,...jj(n.details,r),...o===void 0?[]:[` hint: ${o}`],""].join(`
109
+ `)}function DI(e,t={}){return`${Se("\u2022","cyan",$d({...t,stream:"stderr"}))} ${e}`}function Lj(e){if(zo(e)&&typeof e.version==="string")return`holycodex ${e.version}
110
+ `;if(zo(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
122
111
  `}return`holycodex version completed
123
- `}function e1(e,t){if(Ff(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("install","heading",t)} cancelled
124
- `;let n=Vl(e,"record"),r=Wo(n,"version")??"unknown",o=Wo(n,"profile")??"unknown",i=Wo(n,"tier")??"unknown",a=Vl(n,"optional_selections"),s=Vl(n,"capability_state"),c=["frontend","security","work","computer_use"].filter((m)=>a?.[m]===!0).map((m)=>{let w=Wo(Vl(s,m),"status");return w===void 0||w==="healthy"?m:`${m} (${w})`}),l=Wi(e,"preserved"),u=Wi(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`${[`${oe("\u2714","green",t)} ${oe("install","heading",t)}`,` ${oe("version","option",t)}: ${r}`,` ${oe("profile","option",t)}: ${o}`,` ${oe("tier","option",t)}: ${i}`,` ${oe("capabilities","option",t)}: ${p}`,` ${oe("preserved","option",t)}: ${f}`,...u.map((m)=>` ${oe("warning","red",t)}: ${Lf(m)}`)].join(`
125
- `)}
126
- `}function t1(e,t){if(Ff(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("remove","heading",t)} cancelled
127
- `;let n=Wi(e,"removed"),r=Wi(e,"preserved"),o=Wi(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`;return`${[`${oe("\u2714","green",t)} ${oe("remove","heading",t)}`,` ${oe("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${oe("preserved","option",t)}: ${i}`,...o.map((s)=>` ${oe("reason","option",t)}: ${Lf(s)}`)].join(`
112
+ `}function Dj(e,t){let r=Nl(e,"record"),n=Fl(r,"version")??"unknown",o=Fl(r,"profile")??"unknown",i=Fl(r,"tier")??"unknown",a=Nl(r,"optional_selections"),s=Nl(r,"capability_state"),c=["frontend","security","work","computer_use"].filter((m)=>a?.[m]===!0).map((m)=>{let w=Fl(Nl(s,m),"status");return w===void 0||w==="healthy"?m:`${m} (${w})`}),l=ls(e,"preserved"),u=ls(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)}: ${n}`,` ${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)}: ${Pb(m)}`)].join(`
128
113
  `)}
129
- `}function n1(e,t){if(Ff(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("upgrade","heading",t)} cancelled
130
- `;let n=Wo(Jn(e)?e:void 0,"status")??"completed",r=Wo(Jn(e)?e:void 0,"from_version"),o=Wo(Jn(e)?e:void 0,"to_version"),i=Wi(e,"changes"),a=r!==void 0&&o!==void 0?` (${r} \u2192 ${o})`:"";return`${[`${oe("\u2714","green",t)} ${oe("upgrade","heading",t)}${a}`,` ${oe("status","option",t)}: ${n}`,` ${oe("changes","option",t)}: ${i.length===0?"none":i.map(Lf).join(", ")}`].join(`
114
+ `}function qj(e,t){let r=ls(e,"removed"),n=ls(e,"preserved"),o=ls(e,"reasons"),i=n.length===0?"none":`${n.length} item${n.length===1?"":"s"} (review before retrying)`;return`${[`${Se("\u2714","green",t)} ${Se("remove","heading",t)}`,` ${Se("removed","option",t)}: ${r.length} owned item${r.length===1?"":"s"}`,` ${Se("preserved","option",t)}: ${i}`,...o.map((s)=>` ${Se("reason","option",t)}: ${Pb(s)}`)].join(`
131
115
  `)}
132
- `}function r1(e,t){let n=Ff(e,"healthy")===!0,r=Vl(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=Jn(l)?l:void 0,p=Wo(u,"status");if(p===void 0||p==="healthy")return[];let f=Wi(u,"reasons");return[` ${oe(c,"option",t)}: ${f.length===0?p:f.map(Lf).join(", ")}`]});return`${[`${n?oe("\u2714","green",t):oe("\u2716","red",t)} ${oe("doctor","heading",t)}`,` ${oe("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${oe("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${oe("issues","option",t)}:`,...i]].join(`
116
+ `}function Uj(e,t){let r=Hj(e,"healthy")===!0,n=Nl(e,"checks"),o=n===void 0?[]:Object.entries(n),i=o.flatMap(([c,l])=>{let u=zo(l)?l:void 0,p=Fl(u,"status");if(p===void 0||p==="healthy")return[];let f=ls(u,"reasons");return[` ${Se(c,"option",t)}: ${f.length===0?p:f.map(Pb).join(", ")}`]});return`${[`${r?Se("\u2714","green",t):Se("\u2716","red",t)} ${Se("doctor","heading",t)}`,` ${Se("status","option",t)}: ${r?"healthy":"needs attention"}`,` ${Se("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${Se("issues","option",t)}:`,...i]].join(`
133
117
  `)}
134
- `}function Vl(e,t){if(!Jn(e))return;return Jn(e[t])?e[t]:void 0}function Ff(e,t){return Jn(e)?e[t]:void 0}function Wo(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function Wi(e,t){if(!Jn(e)||!Array.isArray(e[t]))return[];return e[t]}function Lf(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function o1(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${oe(N_(e),"dim",t)}
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])=>` ${oe(o.padEnd(r),"option",t)}: ${N_(i)}`).join(`
118
+ `}function Nl(e,t){if(!zo(e))return;return zo(e[t])?e[t]:void 0}function Hj(e,t){return zo(e)?e[t]:void 0}function Fl(e,t){let r=e?.[t];return typeof r==="string"?r:void 0}function ls(e,t){if(!zo(e)||!Array.isArray(e[t]))return[];return e[t]}function Pb(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function $j(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${Se(kb(e),"dim",t)}
119
+ `;let r=Object.entries(e);if(r.length===0)return"";let n=Math.max(...r.map(([o])=>o.length));return`${r.map(([o,i])=>` ${Se(o.padEnd(n),"option",t)}: ${kb(i)}`).join(`
136
120
  `)}
137
- `}function i1(e,t){return Object.entries(e).map(([n,r])=>` ${oe(n,"option",t)}: ${oe(N_(r),"dim",t)}`)}function N_(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function a1(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 oe(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 Ji extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function D_(e=Bun.argv.slice(2),t=c1()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??l1(),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 F_(e,n);if((al(e)||e[0]==="help")&&!YI(e))n.io?.writeStdout?.(oS(sl(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(YI(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
138
- `);else if(r.envelope.ok)n.io?.writeStdout?.(Nf(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(Nf(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function c1(){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=s1({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 YI(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*l1(){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}ql();Af();Il();Vi();Nl();kf();var bZ="holycodex";if(import.meta.main)process.exitCode=await D_();export{ze as ArgumentError,rs as CapabilityInstallStateSchema,d_ as CapabilityStateRecordSchema,zo as CodexOfficialPluginManager,_f as InstallOptionsSchema,is as InstallRecordSchema,Rl as InstallRequestSchema,N as InstallerError,Sr as OfficialPluginManagerError,wn as PathBoundaryError,q$ as STATE_SCHEMA,h_ as assertRootText,k_ as doctorHolyCodex,JI as executeCommand,al as helpRequested,il as helpText,sl as helpTopic,fs as installHolyCodex,__ as installNativeAgents,If as installRecordDigest,bZ as packageName,Wd as parseArgv,VI as parsePluginInput,ss as pathWithin,Ki as projectNativeAgents,x_ as projectRootAgent,Al as publicManifestPath,ms as readActiveInstallRecord,ls as readCanonicalBaseVersion,bf as readCanonicalVersion,Ll as removeHolyCodex,Of as removeManagedNativeAgents,oS as renderHelp,Nf as renderHuman,Mj as renderInstallWizardReview,Rf as renderNativeAgent,GI as renderProgress,ji as resolveInstallerPaths,Ef as rollbackNativeAgentInstall,S_ as rootDeveloperInstructions,D_ as runBinary,F_ as runCli,M_ as runOpenTuiInstallWizard,HI as toInstallOptions,g_ as updateCanonicalVersion,C_ as upgradeHolyCodex,wr as validateInstallOptions};
121
+ `}function jj(e,t){return Object.entries(e).map(([r,n])=>` ${Se(r,"option",t)}: ${Se(kb(n),"dim",t)}`)}function kb(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function Bj(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,r){if(!r)return e;return`\x1B[${{red:"31",green:"32",cyan:"36",dim:"2",heading:"1",option:"36"}[t]}m${e}\x1B[0m`}class Vi extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function Ib(e=Bun.argv.slice(2),t=zj()){let r={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??Kj(),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}},n=await Cb(e,r);if((Qc(e)||e[0]==="help")&&!qI(e))r.io?.writeStdout?.(Qx(el(e),{stdoutIsTTY:r.io?.stdoutIsTTY,stderrIsTTY:r.io?.stderrIsTTY,env:r.env,stream:"stdout"}));else if(qI(e))r.io?.writeStdout?.(`${JSON.stringify(n.envelope)}
122
+ `);else if(n.envelope.ok)r.io?.writeStdout?.(Pf(n,{stdoutIsTTY:r.io?.stdoutIsTTY,stderrIsTTY:r.io?.stderrIsTTY,env:r.env,stream:"stdout"}));else r.io?.writeStderr?.(Pf(n,{stdoutIsTTY:r.io?.stderrIsTTY,stderrIsTTY:r.io?.stderrIsTTY,env:r.env,stream:"stderr"}));return n.exitCode}function zj(){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=Vj({input:process.stdin,output:process.stderr});try{let r=await t.question(`${e} [y/N] `);return/^(?:y|yes)$/iu.test(r.trim())}finally{t.close()}}}}function qI(e){let t=!1;for(let r of e)if(r==="--json"||r==="--json=true")t=!0;else if(r==="--json=false")t=!1;return t}async function*Kj(){let e=new TextDecoder;for await(let r of process.stdin)if(typeof r==="string")yield r;else yield e.decode(r,{stream:!0});let t=e.decode();if(t.length>0)yield t}kl();vf();gf();Hi();El();Tf();var nZ="holycodex";if(import.meta.main)process.exitCode=await Ib();export{Ke as ArgumentError,Qa as CapabilityInstallStateSchema,cb as CapabilityStateRecordSchema,Bo as CodexOfficialPluginManager,ff as InstallOptionsSchema,ts as InstallRecordSchema,xl as InstallRequestSchema,X as InstallerError,hn as OfficialPluginManagerError,_r as PathBoundaryError,T$ as STATE_SCHEMA,pb as assertRootText,Tb as doctorHolyCodex,FI as executeCommand,Qc as helpRequested,Xc as helpText,el as helpTopic,kf as installHolyCodex,gb as installNativeAgents,Af as installRecordDigest,nZ as packageName,Ud as parseArgv,os as pathWithin,ji as projectNativeAgents,mb as projectRootAgent,_l as publicManifestPath,Rl as readActiveInstallRecord,hf as readCanonicalBaseVersion,mf as readCanonicalVersion,Ol as removeHolyCodex,_f as removeManagedNativeAgents,Qx as renderHelp,Pf as renderHuman,xj as renderInstallWizardReview,wf as renderNativeAgent,DI as renderProgress,ns as resolveInstallerPaths,bf as rollbackNativeAgentInstall,hb as rootDeveloperInstructions,Ib as runBinary,Cb as runCli,Rb as runOpenTuiInstallWizard,AI as toInstallOptions,db as updateCanonicalVersion,Xn as validateInstallOptions};