holycodex 0.16.4 → 0.16.5-dev.79.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +5 -0
  2. package/dist/agent.js +54 -38
  3. package/dist/assets/plugin/plugin.json +2 -2
  4. package/dist/assets/plugin/skills/code-review/SKILL.md +10 -23
  5. package/dist/assets/plugin/skills/code-review/agents/openai.yaml +2 -2
  6. package/dist/assets/plugin/skills/commit/SKILL.md +6 -12
  7. package/dist/assets/plugin/skills/commit/agents/openai.yaml +1 -1
  8. package/dist/assets/plugin/skills/compress/SKILL.md +4 -15
  9. package/dist/assets/plugin/skills/compress/agents/openai.yaml +1 -1
  10. package/dist/assets/plugin/skills/context7-cli/SKILL.md +7 -9
  11. package/dist/assets/plugin/skills/context7-cli/agents/openai.yaml +2 -2
  12. package/dist/assets/plugin/skills/debugging/SKILL.md +7 -22
  13. package/dist/assets/plugin/skills/debugging/agents/openai.yaml +2 -2
  14. package/dist/assets/plugin/skills/grill-me/SKILL.md +21 -0
  15. package/dist/assets/plugin/skills/grill-me/agents/openai.yaml +6 -0
  16. package/dist/assets/plugin/skills/handoff/SKILL.md +4 -13
  17. package/dist/assets/plugin/skills/handoff/agents/openai.yaml +1 -1
  18. package/dist/assets/plugin/skills/operations/SKILL.md +11 -26
  19. package/dist/assets/plugin/skills/operations/agents/openai.yaml +1 -1
  20. package/dist/assets/plugin/skills/plan/SKILL.md +9 -20
  21. package/dist/assets/plugin/skills/plan/agents/openai.yaml +2 -2
  22. package/dist/assets/plugin/skills/plan-review/SKILL.md +7 -18
  23. package/dist/assets/plugin/skills/plan-review/agents/openai.yaml +2 -2
  24. package/dist/assets/plugin/skills/programming/SKILL.md +7 -17
  25. package/dist/assets/plugin/skills/programming/agents/openai.yaml +2 -2
  26. package/dist/assets/plugin/skills/refactor/SKILL.md +4 -18
  27. package/dist/assets/plugin/skills/refactor/agents/openai.yaml +1 -1
  28. package/dist/assets/plugin/skills/rules/SKILL.md +7 -14
  29. package/dist/assets/plugin/skills/rules/agents/openai.yaml +2 -2
  30. package/dist/assets/plugin/skills/stop-slop/SKILL.md +5 -42
  31. package/dist/assets/plugin/skills/stop-slop/agents/openai.yaml +1 -1
  32. package/dist/assets/plugin/skills/testing-quality.md +13 -24
  33. package/dist/assets/plugin/skills/writing-for-agents/SKILL-MECHANICS.md +6 -16
  34. package/dist/assets/plugin/skills/writing-for-agents/SKILL.md +29 -55
  35. package/dist/assets/plugin/skills/writing-for-agents/agents/openai.yaml +1 -1
  36. package/dist/index.js +69 -53
  37. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,49 +1,50 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
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(`,
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&&zf(r.value))Yn(r.value,t)}Object.freeze(e)}function zf(e){return typeof e==="object"&&e!==null}var vr="0.15",En="state-0.16";var W_=()=>{};function Qi(e){return{ok:!0,value:e}}function Go(e){return{ok:!1,error:e}}function xs(e,t){return new We("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var We;var ea=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 Wf=(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,Ss=(e)=>()=>e,_s,no,Jl,bs;var j=x(()=>{_s=Ss(!0),no=Ss(!1),Jl=Ss(void 0),bs=Jl});var vs=(e)=>(t,n)=>t===n||e(t,n),eM=(e,t)=>e===t,tM=()=>eM,nM,Jf,J_,G_=(e)=>vs((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 Ts=x(()=>{j();nM=tM(),Jf=d(2,(e,t)=>vs((n,r)=>e(t(n),t(r)))),J_=Jf(nM,(e)=>e.getTime())});var Es,V=(e,t)=>{if(!Es)globalThis["effect/GlobalValue"]??=new Map,Es=globalThis["effect/GlobalValue"];if(!Es.has(e))Es.set(e,t());return Es.get(e)};var gt=(e)=>typeof e==="string",Qt=(e)=>typeof e==="number",Yo=(e)=>typeof e==="boolean",ro=(e)=>typeof e==="bigint",Zo=(e)=>typeof e==="symbol",oo,Y_=(e)=>e===void 0,Z_=(e)=>!1,Os=(e)=>typeof e==="object"&&e!==null,qt=(e)=>Os(e)||oo(e),C,Rs,Xo=(e)=>e===null||e===void 0,X_=(e)=>e!==null&&e!==void 0,Yl=(e)=>e instanceof Date,Gf=(e)=>typeof e==="string"||C(e,Symbol.iterator),Yf=(e)=>Os(e)&&!Array.isArray(e),Q_=(e)=>C(e,"then")&&oo(e.then);var xe=x(()=>{j();oo=Wf,C=d(2,(e,t)=>qt(e)&&(t in e)),Rs=d(2,(e,t)=>C(e,"_tag")&&e._tag===t)});var Qo=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Xf{_state;constructor(e,t,n,r){if(Xo(t)&&Xo(e))t=Math.random()*4294967295>>>0,e=0;else if(Xo(t))t=e,e=0;if(Xo(r)&&Xo(n))r=this._state?this._state[3]:oM,n=this._state?this._state[2]:rM;else if(Xo(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),eb(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*cM+t)/sM}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;lM(this._state,e,t,iM,aM),eb(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 lM(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 eb(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 Qf(e){if(typeof e==="object"&&e!==null&&Zf in e)return e[Zf]();throw Error(Qo("yieldWrapGet"))}var na,rM=335903614,oM=4150755663,iM=1481765933,aM=1284865837,sM=9007199254740992,cM=134217728,Zf,Tr,$t,tb,uM,pM,yt,R1;var io=x(()=>{xe();na=class na{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 na(this.self)}};Zf=Symbol.for("effect/Utils/YieldWrap");Tr=class Tr{#e;constructor(e){this.#e=e}[Zf](){return this.#e}};$t=V("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),tb={effect_internal_function:(e)=>e()},uM={effect_internal_function:(e)=>{try{return e()}finally{}}},pM=tb.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,yt=pM?tb.effect_internal_function:uM.effect_internal_function,R1=function*(){}.constructor});var em,M,O=(e)=>{if($t.enabled===!0)return 0;switch(typeof e){case"number":return Xl(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 O(e.toISOString())}else if(e instanceof URL)return O(e.href);else if(fM(e))return e[M]();else return ks(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},ks=(e)=>{if(!em.has(e))em.set(e,Xl(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return em.get(e)},G=(e)=>(t)=>t*53^e,Zl=(e)=>e&3221225471|e>>>1&1073741824,fM=(e)=>C(e,M),Xl=(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 Zl(t)},he=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Zl(t)},mM=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=g(he(t[r]),G(O(e[t[r]])));return Zl(n)},Ql=(e)=>mM(e,Object.keys(e)),en=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=g(t,G(O(e[n])));return Zl(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();xe();io();em=V(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),M=Symbol.for("effect/Hash")});function R(){if(arguments.length===1)return(e)=>eu(e,arguments[0]);return eu(arguments[0],arguments[1])}function eu(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(Cs(e)&&Cs(t))if(O(e)===O(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)=>eu(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)&&eu(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,Cs=(e)=>C(e,I),As=()=>R;var pe=x(()=>{Me();xe();io();I=Symbol.for("effect/Equal")});function hM(e){try{return e.toISOString()}catch{return"Invalid Date"}}function gM(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function Ps(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 tm;if(r.add(l),!o||l.length<=1)return`[${l.map((f)=>c(f,u)).join(",")}]`;let p=l.map((f)=>c(f,u+1)).join(`,
4
4
  `+i(u+1));return`[
5
5
  ${i(u+1)}${p}
6
- ${i(u)}]`}if(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(`,
6
+ ${i(u)}]`}if(Yl(l))return hM(l);if(!t?.ignoreToString&&C(l,"toString")&&oo(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let p=gM(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||Yo(l)||Zo(l))return String(l);if(ro(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return tm;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(qt(l)){if(r.has(l))return tm;r.add(l);let p=s(l);if(!o||p.length<=1){let h=`{${p.map((m)=>`${Ps(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,h)}let f=`{
7
+ ${p.map((h)=>`${i(u+1)}${Ps(h)}: ${c(l[h],u+1)}`).join(`,
8
8
  `)}
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," ")}
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 ob(e)},tm="[Circular]",ge=(e)=>JSON.stringify(e,null,2),F1,Er=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?tu(e,t):String(e)}catch{return String(e)}},tu=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(ei.fiberRefs!==void 0&&nb(i)?i[nm](ei.fiberRefs):i):i,t);return n=void 0,r},nm,nb=(e)=>typeof e==="object"&&e!==null&&(nm in e),ei,rb=(e,t)=>{let n=ei.fiberRefs;ei.fiberRefs=e;try{return t()}finally{ei.fiberRefs=n}},ob=(e)=>{if(nb(e)&&ei.fiberRefs!==void 0)return e[nm](ei.fiberRefs);return e};var Ve=x(()=>{xe();ne=Symbol.for("nodejs.util.inspect.custom");F1={toJSON(){return de(this)},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},nm=Symbol.for("effect/Inspectable/Redactable"),ei=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 we=()=>{};var ni="Async",ri="Commit",jt="Failure",Is="OnFailure",ra="OnSuccess",oa="OnSuccessAndFailure",Vt="Success",nu="Sync",ib="Tag",oi="UpdateRuntimeFlags",ia="While",aa="Iterator",ru="WithRuntime",sa="Yield",Ms="RevertFlags";var yM="3.22.1",Ns=()=>yM;var sb,cb,lb,ub,ao,xM,SM,Or,Fs,so,om,pb;var Rr=x(()=>{pe();Me();we();io();sb=Symbol.for("effect/Effect"),cb=Symbol.for("effect/Stream"),lb=Symbol.for("effect/Sink"),ub=Symbol.for("effect/Channel"),ao={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Ns()},xM={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},SM={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},Or={[sb]:ao,[cb]:ao,[lb]:xM,[ub]:SM,[I](e){return this===e},[M](){return ie(this,ks(this))},[Symbol.iterator](){return new na(new Tr(this))},pipe(){return T(this,arguments)}},Fs={[M](){return ie(this,Ql(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)&&R(this[r],e[r])))return!1;return!0}},so={...Or,_op:ri},om={...so,...Fs},pb=function(){function e(){}return e.prototype=so,e}()});var fb,mb,_M,bM,wM,im=(e)=>C(e,fb),am=(e)=>e._tag==="None",sm=(e)=>e._tag==="Some",ou,Ls=(e)=>{let t=Object.create(_M);return t.value=e,t};var cm=x(()=>{pe();Me();Ve();xe();Rr();fb=Symbol.for("effect/Option"),mb={...Or,[fb]:{_A:(e)=>e},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},_M=Object.assign(Object.create(mb),{_tag:"Some",_op:"Some",[I](e){return im(e)&&sm(e)&&R(this.value,e.value)},[M](){return ie(this,G(O(this._tag))(O(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:de(this.value)}}}),bM=O("None"),wM=Object.assign(Object.create(mb),{_tag:"None",_op:"None",[I](e){return im(e)&&am(e)},[M](){return bM},toJSON(){return{_id:"Option",_tag:this._tag}}}),ou=Object.create(wM)});var lm,gb,vM,TM,iu=(e)=>C(e,lm),um=(e)=>e._tag==="Left",pm=(e)=>e._tag==="Right",yb=(e)=>{let t=Object.create(TM);return t.left=e,t},xb=(e)=>{let t=Object.create(vM);return t.right=e,t};var Sb=x(()=>{pe();Me();Ve();xe();Rr();lm=Symbol.for("effect/Either"),gb={...Or,[lm]:{_R:(e)=>e},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},vM=Object.assign(Object.create(gb),{_tag:"Right",_op:"Right",[I](e){return iu(e)&&pm(e)&&R(this.right,e.right)},[M](){return G(O(this._tag))(O(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:de(this.right)}}}),TM=Object.assign(Object.create(gb),{_tag:"Left",_op:"Left",[I](e){return iu(e)&&um(e)&&R(this.left,e.left)},[M](){return G(O(this._tag))(O(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:de(this.left)}}})});var Q,W,dm,Ee,Ot,au,_b,Ds,bb,fm,wb;var tn=x(()=>{j();Sb();Q=xb,W=yb,dm=iu,Ee=um,Ot=pm,au=d(2,(e,t)=>Ee(e)?W(t(e.left)):Q(e.right)),_b=d(2,(e,t)=>Ot(e)?Q(t(e.right)):W(e.left)),Ds=d(2,(e,{onLeft:t,onRight:n})=>Ee(e)?t(e.left):n(e.right)),bb=Ds({onLeft:ue,onRight:ue}),fm=d(2,(e,t)=>{if(Ot(e))return e.right;throw t(e.left)}),wb=fm(()=>Error("getOrThrow called on a Left"))});var mm=(e)=>e.length>0;var vb=(e)=>(t,n)=>t===n?0:e(t,n),Tb,su,hm=(e)=>d(2,(t,n)=>e(t,n)===1);var cu=x(()=>{j();Tb=vb((e,t)=>e<t?-1:1),su=d(2,(e,t)=>vb((n,r)=>e(t(n),t(r))))});var A=()=>ou,F,Ne,Re,Je,Oe,On,Eb,kr=(e)=>e==null?A():F(e),Bt,Ob=(e)=>(...t)=>{try{return F(e(...t))}catch{return A()}},Rn,kn,Rb,kM=(e)=>d(2,(t,n)=>Ne(t)?!1:e(t.value,n)),CM,kb,Cb;var Ge=x(()=>{pe();j();cm();F=Ls,Ne=am,Re=sm,Je=d(2,(e,{onNone:t,onSome:n})=>Ne(e)?t():n(e.value)),Oe=d(2,(e,t)=>Ne(e)?t():e.value),On=d(2,(e,t)=>Ne(e)?t():e),Eb=d(2,(e,t)=>Ne(e)?F(t()):e),Bt=Oe(Jl),Rn=d(2,(e,t)=>Ne(e)?A():F(t(e.value))),kn=d(2,(e,t)=>Ne(e)?A():t(e.value)),Rb=d(2,(e,t)=>Ne(e)?A():kr(t(e.value))),CM=As(),kb=kM(CM),Cb=d(2,(e,t)=>Ne(e)?!1:t(e.value))});var Ab=(...e)=>e;var Pb=()=>{};var ii=(e)=>Array(e),ym,ke=(e)=>Array.isArray(e)?e:Array.from(e),xm=(e)=>Array.isArray(e)?e:[e],Ib,ca,Mb,Sm,_m,PM=(e)=>e.length===0,Nb,co,ve,Fb=(e,t)=>e<0||e>=t.length,IM=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),MM,bm,Cr,et,Lb=(e)=>ve(e)?F(wm(e)):A(),wm=(e)=>e[e.length-1],Cn=(e)=>e.slice(1),NM=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},Db,qb,vm=(e)=>Array.from(e).reverse(),Ar,Tm,Ub,FM,LM,DM,la=(e)=>e.slice(),qM,lo,Pr=()=>[],Rt=(e)=>[e],An,qs,lu,uu,ua,Em=(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,Hb,Om=(e)=>Hb(e,As()),Ir;var Be=x(()=>{pe();Ts();j();Ge();Pb();ym=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}),Ib=d(2,(e,{onEmpty:t,onNonEmpty:n})=>ve(e)?n(et(e),Cn(e)):t()),ca=d(2,(e,t)=>[t,...e]),Mb=d(2,(e,t)=>[...e,t]),Sm=d(2,(e,t)=>ke(e).concat(ke(t))),_m=Array.isArray,Nb=PM,co=mm,ve=mm,MM=d(2,(e,t)=>{let n=Math.floor(t);return Fb(n,e)?A():F(e[n])}),bm=d(2,(e,t)=>{let n=Math.floor(t);if(Fb(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),Cr=MM(0),et=bm(0),Db=d(2,(e,t)=>LM(e,NM(e,t))),qb=d(2,(e,t)=>{let n=ke(e);return n.slice(IM(t,n),n.length)}),Ar=d(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),Tm=d(2,(e,t)=>Ub(e,t,Ab)),Ub=d(3,(e,t,n)=>{let r=ke(e),o=ke(t);if(ve(r)&&ve(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[]}),FM=As(),LM=d(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(ve(n)){if(r>=1)return DM(n,r);return[[],n]}return[n,[]]}),DM=d(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[la(e),[]]:[ca(e.slice(1,n),et(e)),e.slice(n)]}),qM=d(3,(e,t,n)=>{let r=ke(e),o=ke(t);if(ve(r)){if(ve(o))return Hb(n)(Sm(r,o));return r}return o}),lo=d(2,(e,t)=>qM(e,t,FM)),An=d(2,(e,t)=>e.map(t)),qs=d(2,(e,t)=>{if(Nb(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}),lu=qs(ue),uu=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}),ua=d(3,(e,t,n)=>ke(e).reduce((r,o,i)=>n(r,o,i),t)),uo=G_,Hb=d(2,(e,t)=>{let n=ke(e);if(ve(n)){let r=[et(n)],o=Cn(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 jM(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 jb,Vb,VM=(e)=>vs((t,n)=>t.length===n.length&&Mr(t).every((r,o)=>e(r,pa(n,o)))),BM,KM,ot=(e)=>{let t=Object.create(KM);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},Bb=(e)=>C(e,jb),Xn,dn=()=>Xn,Us=(...e)=>JM(e),tt=(e)=>ot({_tag:"ISingleton",a:e}),pu=(e)=>Bb(e)?e:Hs(ke(e)),Rm=(e,t,n)=>{switch(e.backing._tag){case"IArray":{jM(e.backing.array,0,t,n,e.length);break}case"IConcat":{Rm(e.left,t,n),Rm(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]=pa(e,r),r+=1,o+=1;break}}},zM=(e)=>{switch(e.backing._tag){case"IEmpty":return Vb;case"IArray":return e.backing.array;default:{let t=Array(e.length);return Rm(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Xn,e.right=Xn,e.depth=0,t}}},Mr,WM=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return ot({_tag:"IArray",array:vm(e.backing.array)});case"IConcat":return ot({_tag:"IConcat",left:po(e.backing.right),right:po(e.backing.left)});case"ISlice":return Hs(vm(Mr(e)))}},po,Hs=(e)=>e.length===0?dn():e.length===1?tt(e[0]):ot({_tag:"IArray",array:e}),JM=(e)=>Hs(e),pa,Kb,kt,km,nn,zb=(e)=>e.length===0,Pn=(e)=>e.length>0,Cm=(e)=>pa(e,0),In,Mn=(e)=>km(e,1);var Qn=x(()=>{Be();pe();Ts();j();Me();Ve();we();xe();jb=Symbol.for("effect/Chunk");Vb=[],BM=VM(R),KM={[jb]:{_A:(e)=>e},toString(){return ge(this.toJSON())},toJSON(){return{_id:"Chunk",values:Mr(this).map(de)}},[ne](){return this.toJSON()},[I](e){return Bb(e)&&BM(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 Vb[Symbol.iterator]();default:return Mr(this)[Symbol.iterator]()}},pipe(){return T(this,arguments)}},Xn=ot({_tag:"IEmpty"}),Mr=zM,po=WM,pa=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?pa(e.left,t):pa(e.right,t-e.left.length);case"ISlice":return pa(e.backing.chunk,t+e.backing.offset)}}),Kb=d(2,(e,t)=>nn(e,tt(t))),kt=d(2,(e,t)=>nn(tt(t),e)),km=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 km(e.right,t-e.left.length);return ot({_tag:"IConcat",left:km(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})}}}),In=Cm});var fo=5,Am,Wb,Jb,Gb;var du=x(()=>{Am=Math.pow(2,5),Wb=Am-1,Jb=Am/2,Gb=Am/4});function GM(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&Wb}function ho(e){return 1<<e}function fu(e,t){return GM(e&t-1)}var Pm=x(()=>{du()});var Yb=(e,t)=>({value:e,previous:t});function ai(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 Im(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 Zb(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 si(e,r,o,a)}}function fn(e){return Rs(e,"EmptyNode")}function ZM(e){return fn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function mu(e,t){return fn(e)?!1:t===e.edit}class si{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(R(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Ne(s))return--i.value,new Fr;if(mu(this,e))return this.value=s,this;return new si(e,r,o,s)}let a=n(A());if(Ne(a))return this;return++i.value,Xb(e,t,this.hash,this,r,new si(e,r,o,a))}}class Mm{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=mu(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 Mm(e,this.hash,c):c[0]}let a=n(A());if(Ne(a))return this;return++i.value,Xb(e,t,this.hash,this,r,new si(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&&R(i,u.key)){let p=u.value,f=o(p);if(f===p)return r;if(Ne(f))return--a.value,Im(e,l,r);return ai(e,l,new si(t,n,i,f),r)}}let c=o(A());if(Ne(c))return r;return++a.value,ai(e,s,new si(t,n,i,c),r)}}class da{edit;mask;children;_tag="IndexedNode";constructor(e,t,n){this.edit=e,this.mask=t,this.children=n}modify(e,t,n,r,o,i){let a=this.mask,s=this.children,c=mo(t,r),l=ho(c),u=fu(a,l),p=a&l,f=mu(this,e);if(!p){let y=new Fr().modify(e,t+fo,n,r,o,i);if(!y)return this;return s.length>=Jb?QM(e,c,y,a,s):new da(e,a|l,Zb(f,u,y,s))}let h=s[u],m=h.modify(e,t+fo,n,r,o,i);if(h===m)return this;let v=a,S;if(fn(m)){if(v&=~l,!v)return new Fr;if(s.length<=2&&ZM(s[u^1]))return s[u^1];S=Im(f,u,s)}else S=ai(f,u,m,s);if(f)return this.mask=v,this.children=S,this;return new da(e,v,S)}}class Nm{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=mu(this,e),f;if(fn(l)&&!fn(u))++a,f=ai(p,c,u,s);else if(!fn(l)&&fn(u)){if(--a,a<=Gb)return XM(e,a,c,s);f=ai(p,c,new Fr,s)}else f=ai(p,c,u,s);if(p)return this.size=a,this.children=f,this;return new Nm(e,a,f)}}function XM(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 da(e,a,o)}function QM(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 Nm(e,s+1,i)}function eN(e,t,n,r,o,i){if(n===o)return new Mm(e,n,[i,r]);let a=mo(t,n),s=mo(t,o);if(a===s)return(c)=>new da(e,ho(a)|ho(s),[c]);else{let c=a<s?[r,i]:[i,r];return new da(e,ho(a)|ho(s),c)}}function Xb(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=eN(e,s,n,r,o,i);if(typeof c==="function")a=Yb(c,a),s=s+fo;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var Qb=x(()=>{pe();Ge();xe();Pm();du()});var ew="effect/HashMap",hu,nN,Fm=(e,t,n,r)=>{let o=Object.create(nN);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},yu,gu=(e)=>e?nw(e[0],e[1],e[2],e[3],e[4]):A(),tw=(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 gu(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return nw(r.length,r,0,t,n)}default:return gu(n)}},nw=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!fn(i))return tw(i,r,[e,t,n,r,o])}return gu(o)},rN,fa=()=>rN,rw=(e)=>{let t=_u(fa());for(let n of e)ci(t,n[0],n[1]);return sw(t)},ow=(e)=>C(e,hu),iw=(e)=>e&&fn(e._root),aw,xu,Lm,ci,oN,Su=(e)=>new yu(e,(t)=>t),$s=(e)=>e._size,_u=(e)=>Fm(!0,e._edit+1,e._root,e._size),sw=(e)=>(e._editable=!1,e),bu,cw,wu,lw,Dm,ma;var qm=x(()=>{pe();j();j();Me();Ve();Ge();we();xe();Pm();du();Qb();hu=Symbol.for(ew),nN={[hu]:hu,[Symbol.iterator](){return new yu(this,(e,t)=>[e,t])},[M](){let e=O(ew);for(let t of this)e^=g(O(t[0]),G(O(t[1])));return ie(this,e)},[I](e){if(ow(e)){if(e._size!==this._size)return!1;for(let t of this){let n=g(e,xu(t[0],O(t[0])));if(Ne(n))return!1;else if(!R(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)}};yu=class yu{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=tw(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=gu(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new yu(this.map,this.f)}};rN=Fm(!1,0,new Fr,0),aw=d(2,(e,t)=>xu(e,t,O(t))),xu=d(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return R(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&&R(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[fu(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()}}),Lm=d(2,(e,t)=>Re(xu(e,t,O(t)))),ci=d(3,(e,t,n)=>bu(e,t,()=>F(n))),oN=d(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:Fm(e._editable,e._edit,t,n)}),bu=d(3,(e,t,n)=>cw(e,t,O(t),n)),cw=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,oN(i,o.value))}),wu=d(2,(e,t)=>bu(e,t,A)),lw=d(2,(e,t)=>ma(e,fa(),(n,r,o)=>ci(n,o,t(r,o)))),Dm=d(2,(e,t)=>ma(e,void 0,(n,r,o)=>t(r,o))),ma=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 pw="effect/HashSet",vu,iN,Tu=(e)=>{let t=Object.create(iN);return t._keyMap=e,t},dw=(e)=>C(e,vu),aN,js=()=>aN,fw=(e)=>{let t=Eu(js());for(let n of e)ha(t,n);return Ou(t)},mw=(...e)=>{let t=Eu(js());for(let n of e)ha(t,n);return Ou(t)},hw,gw=(e)=>$s(e._keyMap),Eu=(e)=>Tu(_u(e._keyMap)),Ou=(e)=>(e._keyMap._editable=!1,e),Um,ha,Hm,yw,xw,Sw,_w;var bw=x(()=>{pe();j();Me();Ve();we();xe();qm();vu=Symbol.for(pw),iN={[vu]:vu,[Symbol.iterator](){return Su(this._keyMap)},[M](){return ie(this,G(O(this._keyMap))(O(pw)))},[I](e){if(dw(e))return $s(this._keyMap)===$s(e._keyMap)&&R(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)}},aN=Tu(fa()),hw=d(2,(e,t)=>Lm(e._keyMap,t)),Um=d(2,(e,t)=>{let n=Eu(e);return t(n),Ou(n)}),ha=d(2,(e,t)=>e._keyMap._editable?(ci(t,!0)(e._keyMap),e):Tu(ci(t,!0)(e._keyMap))),Hm=d(2,(e,t)=>e._keyMap._editable?(wu(t)(e._keyMap),e):Tu(wu(t)(e._keyMap))),yw=d(2,(e,t)=>Um(e,(n)=>{for(let r of t)Hm(n,r)})),xw=d(2,(e,t)=>Um(js(),(n)=>{Sw(e,(r)=>ha(n,r));for(let r of t)ha(n,r)})),Sw=d(2,(e,t)=>Dm(e._keyMap,(n,r)=>t(r))),_w=d(3,(e,t,n)=>ma(e._keyMap,t,(r,o,i)=>n(r,i)))});var er,ww,li,vw,Vs,ui,$m,jm,Lr,pi;var di=x(()=>{bw();er=js,ww=fw,li=mw,vw=hw,Vs=gw,ui=ha,$m=Hm,jm=yw,Lr=xw,pi=_w});var ya="Die",go="Empty",yo="Fail",fi="Interrupt",mi="Parallel",hi="Sequential";var Ow="effect/Cause",Km,lN,xa,Dr,Sa=(e)=>{let t=Object.create(xa);return t._tag=yo,t.error=e,t},rn=(e)=>{let t=Object.create(xa);return t._tag=ya,t.defect=e,t},Nn=(e)=>{let t=Object.create(xa);return t._tag=fi,t.fiberId=e,t},xi=(e,t)=>{let n=Object.create(xa);return n._tag=mi,n.left=e,n.right=t,n},Ct=(e,t)=>{let n=Object.create(xa);return n._tag=hi,n.left=e,n.right=t,n},Rw=(e)=>C(e,Km),zm=(e)=>e._tag===go,kw=(e)=>e._tag===yo,Ru=(e)=>{if(e._tag===go)return!0;return gi(e,!0,(t,n)=>{switch(n._tag){case go:return F(t);case ya:case yo:case fi:return F(!1);default:return A()}})},ku=(e)=>Re(Cw(e)),_a=(e)=>Pu(void 0,fN)(e),Wm=(e)=>po(gi(e,dn(),(t,n)=>n._tag===yo?F(g(t,kt(n.error))):A())),Jm=(e)=>po(gi(e,dn(),(t,n)=>n._tag===ya?F(g(t,kt(n.defect))):A())),Gm=(e)=>gi(e,er(),(t,n)=>n._tag===fi?F(g(t,ui(n.fiberId))):A()),Ym=(e)=>Zm(e,(t)=>t._tag===yo?F(t.error):A()),Cu=(e)=>{let t=Ym(e);switch(t._tag){case"None":return Q(e);case"Some":return W(t.value)}},Cw=(e)=>Zm(e,(t)=>t._tag===fi?F(t.fiberId):A()),Au=(e)=>Xm(e,{onEmpty:Dr,onFail:()=>Dr,onDie:rn,onInterrupt:Nn,onSequential:Ct,onParallel:xi}),Aw=(e)=>Xm(e,{onEmpty:Dr,onFail:rn,onDie:rn,onInterrupt:Nn,onSequential:Ct,onParallel:xi}),uN=(e,t)=>{let n=tt(e),r=tt(t);while(Pn(n)&&Pn(r)){let[o,i]=g(In(n),gi([er(),dn()],([c,l],u)=>{let[p,f]=Vm(u);return F([g(c,Lr(p)),g(l,nn(f))])})),[a,s]=g(In(r),gi([er(),dn()],([c,l],u)=>{let[p,f]=Vm(u);return F([g(c,Lr(p)),g(l,nn(f))])}));if(!R(o,a))return!1;n=i,r=s}return!0},pN=(e)=>dN(tt(e),dn()),dN=(e,t)=>{while(!0){let[n,r]=g(e,ua([er(),dn()],([i,a],s)=>{let[c,l]=Vm(s);return[g(i,Lr(c)),g(a,nn(l))]})),o=Vs(n)>0?g(t,kt(n)):t;if(zb(r))return po(o);e=r,t=o}throw Error(Qo("Cause.flattenCauseLoop"))},Zm,Vm=(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=ui(r,Us(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case ya:{if(r=ui(r,Us(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case fi:{if(r=ui(r,Us(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case hi:{switch(t.left._tag){case go:{t=t.right;break}case hi:{t=Ct(t.left.left,Ct(t.left.right,t.right));break}case mi:{t=xi(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 mi:{n.push(t.right),t=t.left;break}}throw Error(Qo("Cause.evaluateCauseLoop"))},fN,Tw="SequentialCase",Ew="ParallelCase",Xm,gi,Pu,Fn=(e,t)=>{if(_a(e))return"All fibers interrupted without errors.";return Bs(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
+ ${Pw(n.cause," ")}
11
11
  }`}).join(`
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(`
12
+ `)},Pw=(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
+ ${Pw(e.cause,`${t} `)}
16
+ ${t}}`;return r},Bm=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(mN(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:Bm(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(yi in e)r.span=e[yi];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=yN(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},mN=(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 tu(e)},hN,gN,yN=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
17
17
  `):t.split(`
18
- `);for(let i=1;i<o.length;i++){if(o[i].includes(" at new BaseEffectError")||o[i].includes(" at new YieldableError")){i++;continue}if(o[i].includes("Generator.next"))break;if(o[i].includes("effect_internal_function"))break;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()}
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=gN.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(hN),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
+ `)},yi,Bs=(e)=>Pu(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[Bm(n)],failCase:(t,n)=>[Bm(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var ba=x(()=>{Be();Qn();tn();pe();j();Me();di();Ve();Ge();we();xe();Km=Symbol.for(Ow),lN={_E:(e)=>e},xa={[Km]:lN,[M](){return g(O(Ow),G(O(pN(this))),ie(this))},[I](e){return Rw(e)&&uN(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 Fn(this)},[ne](){return this.toJSON()}},Dr=(()=>{let e=Object.create(xa);return e._tag=go,e})(),Zm=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 hi:case mi:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return A()}),fN={emptyCase:_s,failCase:no,dieCase:no,interruptCase:_s,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},Xm=d(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>Pu(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)})),gi=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 hi:{i.push(o.right),o=o.left;break}case mi:{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}),Pu=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 ya:{o.push(Q(n.dieCase(t,a.defect)));break}case fi:{o.push(Q(n.interruptCase(t,a.fiberId)));break}case hi:{r.push(a.right),r.push(a.left),o.push(W({_tag:Tw}));break}case mi:{r.push(a.right),r.push(a.left),o.push(W({_tag:Ew}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case Tw:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case Ew:{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()}),hN=/\((.*)\)/g,gN=V("effect/Tracer/spanToTrace",()=>new WeakMap),yi=Symbol.for("effect/SpanAnnotation")});var Iw,zs,xN="effect/STM",SN,Mw,_N,Nw=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(Mw);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},Fw=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,_N),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},eh,bN,xo=(e)=>{let t=Object.create(bN);return t.unsafeMap=e,t},wN=(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},Lw=(e)=>C(e,eh),Dw=(e)=>C(e,zs),vN,qw=()=>vN,th=(e,t)=>xo(new Map([[e.key,t]])),Uw,Qm,nh=(e)=>{if(Qm.has(e.key))return Qm.get(e.key);let t=e.defaultValue();return Qm.set(e.key,t),t},Hw=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):nh(t),rh,$w,jw,Vw;var Iu=x(()=>{pe();j();Me();Ve();we();xe();Rr();cm();Iw=Symbol.for("effect/Context/Tag"),zs=Symbol.for("effect/Context/Reference"),SN=Symbol.for(xN),Mw={...Or,_op:"Tag",[SN]:ao,[Iw]:{_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 th(this,e)}},_N={...Mw,[zs]:zs},eh=Symbol.for("effect/Context"),bN={[eh]:{_Services:(e)=>e},[I](e){if(Lw(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!R(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[M](){return ie(this,Xl(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()}},vN=xo(new Map),Uw=d(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),xo(r)}),Qm=V("effect/Context/defaultValueCache",()=>new Map),rh=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(zs in t)return nh(t);throw wN(t)}return e.unsafeMap.get(t.key)}),$w=rh,jw=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return Dw(t)?Ls(nh(t)):ou;return Ls(e.unsafeMap.get(t.key))}),Vw=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,Kw,tr,Ws,Js,_o,Gs,Ys;var mn=x(()=>{Iu();Kt=Nw,So=qw,Kw=th,tr=Uw,Ws=$w,Js=rh,_o=jw,Gs=Vw,Ys=Fw});var ih,Yw,zw,Mu,ah,Ww,Jw,TN,qr=(e)=>{if(Zw(e))return e;else if(Qt(e))return Nu(e);else if(ro(e))return oh(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 sh;if(e[0]===1/0||e[1]===1/0)return kN;return oh(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(gt(e)){let t=TN.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return oh(BigInt(r));case"micro":case"micros":return CN(BigInt(r));case"milli":case"millis":return Nu(i);case"second":case"seconds":return AN(i);case"minute":case"minutes":return PN(i);case"hour":case"hours":return IN(i);case"day":case"days":return MN(i);case"week":case"weeks":return NN(i)}}}throw Error("Invalid DurationInput")},Gw,EN,ON,nr=(e)=>{let t=Object.create(ON);if(Qt(e))if(isNaN(e)||e<=0)t.value=Gw;else if(!Number.isFinite(e))t.value=EN;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<=Yw)t.value=Gw;else t.value={_tag:"Nanos",nanos:e};return t},Zw=(e)=>C(e,ih),RN=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Yw;case"Infinity":return!1}},sh,kN,oh=(e)=>nr(e),CN=(e)=>nr(e*ah),Nu=(e)=>nr(e),AN=(e)=>nr(e*1000),PN=(e)=>nr(e*60000),IN=(e)=>nr(e*3600000),MN=(e)=>nr(e*86400000),NN=(e)=>nr(e*604800000),Fu=(e)=>DN(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),FN=(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))}},LN=(e)=>{let t=qr(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/Jw),Number(t.value.nanos%Jw)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},DN,ch,qN=(e,t)=>ch(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),Xw,Qw,UN,HN=(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=FN(t),r=n/Ww,o=r/ah,i=o/Mu,a=i/Mu,s=a/zw;return{days:Number(s),hours:Number(a%zw),minutes:Number(i%Mu),seconds:Number(o%Mu),millis:Number(r%ah),nanos:Number(n%Ww)}},$N=(e)=>{let t=qr(e);if(t.value._tag==="Infinity")return"Infinity";if(RN(t))return"0";let n=HN(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 lh=x(()=>{pe();j();Me();Ve();we();xe();ih=Symbol.for("effect/Duration"),Yw=BigInt(0),zw=BigInt(24),Mu=BigInt(60),ah=BigInt(1000),Ww=BigInt(1e6),Jw=BigInt(1e9),TN=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,Gw={_tag:"Millis",millis:0},EN={_tag:"Infinity"},ON={[ih]:ih,[M](){return ie(this,Ql(this.value))},[I](e){return Zw(e)&&UN(this,e)},toString(){return`Duration(${$N(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:LN(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},sh=nr(0),kN=nr(1/0),DN=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)}}),ch=d(3,(e,t,n)=>{let r=qr(e),o=qr(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(Fu(r),Fu(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)}),Xw=d(2,(e,t)=>ch(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),Qw=d(2,(e,t)=>ch(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),UN=d(2,(e,t)=>qN(qr(e),qr(t)))});var tv,jN,Lu=(e)=>{let t=Object.create(jN);return t.current=e,t},wa=(e)=>e.current,Du;var uh=x(()=>{j();Ve();we();tv=Symbol.for("effect/MutableRef"),jN={[tv]:tv,toString(){return ge(this.toJSON())},toJSON(){return{_id:"MutableRef",current:de(this.current)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},Du=d(2,(e,t)=>(e.current=t,e))});var dh="effect/FiberId",va,qu="None",ph="Runtime",VN="Composite",BN,ov,iv,av,fh=(e)=>C(e,va),Uu=(e)=>{switch(e._tag){case qu:return er();case ph:return li(e.id);case VN:return g(Uu(e.left),Lr(Uu(e.right)))}},rv,Hu=(e)=>Array.from(Uu(e)).map((n)=>`#${n}`).join(","),sv=()=>{let e=wa(rv);return g(rv,Du(e+1)),new iv(e,Date.now())};var mh=x(()=>{pe();j();Me();di();Ve();uh();xe();va=Symbol.for(dh),BN=he(`${dh}-${qu}`);ov=class ov{[va]=va;_tag=qu;id=-1;startTimeMillis=-1;[M](){return BN}[I](e){return fh(e)&&e._tag===qu}toString(){return ge(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[ne](){return this.toJSON()}};iv=class iv{id;startTimeMillis;[va]=va;_tag=ph;constructor(e,t){this.id=e,this.startTimeMillis=t}[M](){return ie(this,he(`${dh}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[I](e){return fh(e)&&e._tag===ph&&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()}};av=new ov,rv=V(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Lu(0))});var hn,lv,$u;var Ta=x(()=>{mh();hn=av,lv=Hu,$u=sv});var Ea,uv,pv,hh,gh,yh,dv,fv,xh;var ju=x(()=>{qm();Ea=fa,uv=rw,pv=iw,hh=aw,gh=ci,yh=Su,dv=bu,fv=lw,xh=ma});var Xs,_h=(e)=>ke(e),KN=(e)=>Jf(uo(e),_h),zN,WN,Vu=(e,t)=>{let n=Object.create(WN);return n.head=e,n.tail=t,n},JN,GN,mv,hv=(e)=>C(e,Xs),rr=(e)=>e._tag==="Nil",bh=(e)=>e._tag==="Cons",YN=()=>mv,Ur=(e,t)=>Vu(e,t),bo,Qs=(e)=>Vu(e,mv),gv,ZN,XN,yv,xv=(e)=>{let t=bo(),n=e;while(!rr(n))t=ZN(t,n.head),n=n.tail;return t};var Bu=x(()=>{Be();pe();Ts();j();Me();Ve();we();xe();Xs=Symbol.for("effect/List"),zN=KN(R),WN={[Xs]:Xs,_tag:"Cons",toString(){return ge(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:_h(this).map(de)}},[ne](){return this.toJSON()},[I](e){return hv(e)&&this._tag===e._tag&&zN(this,e)},[M](){return ie(this,en(_h(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)}},JN=he("Nil"),GN={[Xs]:Xs,_tag:"Nil",toString(){return ge(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[ne](){return this.toJSON()},[M](){return JN},[I](e){return hv(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return T(this,arguments)}},mv=Object.create(GN),bo=YN,gv=d(2,(e,t)=>XN(t,e)),ZN=d(2,(e,t)=>Ur(t,e)),XN=d(2,(e,t)=>{if(rr(e))return t;else if(rr(t))return e;else{let n=Vu(t.head,e),r=n,o=t.tail;while(!rr(o)){let i=Vu(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),yv=d(3,(e,t,n)=>{let r=t,o=e;while(!rr(o))r=n(r,o.head),o=o.tail;return r})});var sK,Oa;var Ku=x(()=>{pe();Me();Rr();sK=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)=>R(t,e[n]));else return!1}}),Oa=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=Fs,e}()});function Sv(e){return e}var e0,tc,t0,n0,vh=()=>n0,r0,o0=(e,t)=>{let n=Object.create(r0);return n.first=e,n.second=t,n},i0,a0=(e,t)=>{let n=Object.create(i0);return n.key=e,n.service=t,n},s0,c0=(e)=>{let t=Object.create(s0);return t.key=e,t},l0,u0=(e,t)=>{let n=Object.create(l0);return n.key=e,n.update=t,n},_v=(e,t)=>{let n=new Map(e.unsafeMap),r=vh();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!R(a,i))r=ec(u0(o,()=>i))(r)}else n.delete(o),r=ec(a0(o,i))(r);for(let[o]of n.entries())r=ec(c0(o))(r);return r},ec,bv;var wv=x(()=>{Qn();pe();j();Iu();Ku();e0=Symbol.for("effect/DifferContextPatch");tc={...Oa.prototype,[e0]:{_Value:Sv,_Patch:Sv}},t0=Object.assign(Object.create(tc),{_tag:"Empty"}),n0=Object.create(t0),r0=Object.assign(Object.create(tc),{_tag:"AndThen"}),i0=Object.assign(Object.create(tc),{_tag:"AddService"}),s0=Object.assign(Object.create(tc),{_tag:"RemoveService"}),l0=Object.assign(Object.create(tc),{_tag:"UpdateService"}),ec=d(2,(e,t)=>o0(e,t)),bv=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=tt(e),o=new Map(t.unsafeMap);while(Pn(r)){let a=In(r),s=Mn(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 Th(e){return e}var d0,Wu,f0,m0,Eh=()=>m0,h0,g0=(e,t)=>{let n=Object.create(h0);return n.first=e,n.second=t,n},y0,x0=(e)=>{let t=Object.create(y0);return t.value=e,t},S0,_0=(e)=>{let t=Object.create(S0);return t.value=e,t},vv=(e,t)=>{let[n,r]=pi([e,Eh()],([o,i],a)=>{if(vw(a)(o))return[$m(a)(o),i];return[o,zu(x0(a))(i)]})(t);return pi(r,(o,i)=>zu(_0(i))(o))(n)},zu,Tv;var Ev=x(()=>{Qn();j();di();Ku();d0=Symbol.for("effect/DifferHashSetPatch");Wu={...Oa.prototype,[d0]:{_Value:Th,_Key:Th,_Patch:Th}},f0=Object.assign(Object.create(Wu),{_tag:"Empty"}),m0=Object.create(f0),h0=Object.assign(Object.create(Wu),{_tag:"AndThen"}),y0=Object.assign(Object.create(Wu),{_tag:"Add"}),S0=Object.assign(Object.create(Wu),{_tag:"Remove"}),zu=d(2,(e,t)=>g0(e,t)),Tv=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=tt(e);while(Pn(r)){let o=In(r),i=Mn(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=kt(o.first)(kt(o.second)(i));break}case"Add":{n=ui(o.value)(n),r=i;break}case"Remove":n=$m(o.value)(n),r=i}}return n})});function Ov(e){return e}var w0,rc,v0,T0,Oh=()=>T0,E0,O0=(e,t)=>{let n=Object.create(E0);return n.first=e,n.second=t,n},R0,k0=(e)=>{let t=Object.create(R0);return t.values=e,t},C0,A0=(e,t)=>{let n=Object.create(C0);return n.from=e,n.until=t,n},P0,I0=(e,t)=>{let n=Object.create(P0);return n.index=e,n.patch=t,n},Rv=(e)=>{let t=0,n=Oh();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(!R(i,e.differ.empty))n=nc(n,I0(t,i));t=t+1}if(t<e.oldValue.length)n=nc(n,A0(0,t));if(t<e.newValue.length)n=nc(n,k0(qb(t)(e.newValue)));return n},nc,kv;var Cv=x(()=>{Be();pe();j();Ku();w0=Symbol.for("effect/DifferReadonlyArrayPatch");rc={...Oa.prototype,[w0]:{_Value:Ov,_Patch:Ov}},v0=Object.assign(Object.create(rc),{_tag:"Empty"}),T0=Object.create(v0),E0=Object.assign(Object.create(rc),{_tag:"AndThen"}),R0=Object.assign(Object.create(rc),{_tag:"Append"}),C0=Object.assign(Object.create(rc),{_tag:"Slice"}),P0=Object.assign(Object.create(rc),{_tag:"Update"}),nc=d(2,(e,t)=>O0(e,t)),kv=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=Cn(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 Av,N0,wo=(e)=>{let t=Object.create(N0);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},Rh=()=>wo({empty:vh(),combine:(e,t)=>ec(t)(e),diff:(e,t)=>_v(e,t),patch:(e,t)=>bv(t)(e)}),kh=()=>wo({empty:Eh(),combine:(e,t)=>zu(t)(e),diff:(e,t)=>vv(e,t),patch:(e,t)=>Tv(t)(e)}),Ch=(e)=>wo({empty:Oh(),combine:(t,n)=>nc(t,n),diff:(t,n)=>Rv({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>kv(t,n,e)}),Ju=()=>Pv((e,t)=>t),Pv=(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(R(t,n))return ue;return Ss(n)},patch:(t,n)=>e(n,t(n))});var Gu=x(()=>{pe();j();we();wv();Ev();Cv();Av=Symbol.for("effect/Differ"),N0={[Av]:{_P:ue,_V:ue},pipe(){return T(this,arguments)}}});var oc=255,Iv=8,Yu=(e)=>e&oc,Zu=(e)=>e>>Iv&oc,Si=(e,t)=>(e&oc)+((t&e&oc)<<Iv),Ph,Mv=(e)=>Si(e,e),Nv=(e)=>Si(e,0),Fv,Ih,Lv=(e)=>~e>>>0&oc;var Mh=x(()=>{j();Ph=Si(0,0),Fv=d(2,(e,t)=>Si(Yu(e)&~t,Zu(e))),Ih=d(2,(e,t)=>e|t)});var F0=0,Hr=1,qv=2,Nh=4,Xu=16,Fh=32,Uv=(e)=>Qu(e,Fh),Lh,$r=(e)=>Dh(e)&&!L0(e),Dh=(e)=>Qu(e,Hr),Qu,qh=(...e)=>e.reduce((t,n)=>t|n,0),Hv,Uh=(e)=>Qu(e,Nh),L0=(e)=>Qu(e,Xu),ic,ac,Hh;var sc=x(()=>{j();Gu();Mh();Lh=d(2,(e,t)=>e|t),Qu=d(2,(e,t)=>(e&t)!==0),Hv=qh(F0),ic=d(2,(e,t)=>Si(e^t,t)),ac=d(2,(e,t)=>e&(Lv(Yu(t))|Zu(t))|Yu(t)&Zu(t)),Hh=wo({empty:Ph,diff:(e,t)=>ic(e,t),combine:(e,t)=>Ih(t)(e),patch:(e,t)=>ac(t,e)})});var $v,jh,Vh;var Bh=x(()=>{Mh();$v=Mv,jh=Nv,Vh=Fv});var zh=(e,t)=>({_tag:"Par",left:e,right:t}),ep=(e,t)=>({_tag:"Seq",left:e,right:t}),Vv=(e)=>{let t=Qs(e),n=bo();while(!0){let[r,o]=yv(t,[Bv(),bo()],([i,a],s)=>{let[c,l]=D0(s);return[j0(i,c),gv(a,l)]});if(n=q0(n,r),rr(o))return xv(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},D0=(e)=>{let t=e,n=Bv(),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=zh(ep(s,a),ep(c,a));break}case"Seq":{let{left:s,right:c}=i;t=ep(s,ep(c,a));break}case"Single":{t=i,o=Ur(a,o);break}}break}case"Single":{if(n=$0(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")},q0=(e,t)=>{if(rr(e))return Qs(Kh(t));if(V0(t))return e;let n=G0(e.head),r=B0(t);if(n.length===1&&r.length===1&&R(n[0],r[0]))return Ur(J0(e.head,Kh(t)),e.tail);return Ur(Kh(t),e)},U0,H0,tp,Bv=()=>new tp(Ea()),$0=(e,t)=>new tp(dv(e.map,t.dataSource,(n)=>Eb(Rn(n,Kb(t.blockedRequest)),()=>tt(t.blockedRequest)))),j0=(e,t)=>new tp(xh(e.map,t.map,(n,r,o)=>gh(n,o,Je(hh(n,o),{onNone:()=>r,onSome:(i)=>nn(r,i)})))),V0=(e)=>pv(e.map),B0=(e)=>Array.from(yh(e.map)),Kh=(e)=>W0(fv(e.map,(t)=>tt(t))),K0,z0,Wh,W0=(e)=>new Wh(e),J0=(e,t)=>new Wh(xh(t.map,e.map,(n,r,o)=>gh(n,o,Je(hh(n,o),{onNone:()=>dn(),onSome:(i)=>nn(i,r)})))),G0=(e)=>Array.from(yh(e.map)),Kv=(e)=>Array.from(e.map);var zv=x(()=>{Qn();pe();ju();Bu();Ge();U0=Symbol.for("effect/RequestBlock/RequestBlockParallel"),H0={_R:(e)=>e};tp=class tp{map;[U0]=H0;constructor(e){this.map=e}};K0=Symbol.for("effect/RequestBlock/RequestBlockSequential"),z0={_R:(e)=>e};Wh=class Wh{map;[K0]=z0;constructor(e){this.map=e}}});var Ra="Pending",np="Done";var Z0="effect/Deferred",Jv,Gv,Yv=(e)=>({_tag:Ra,joiners:e}),Zv=(e)=>({_tag:np,effect:e});var Xv=x(()=>{Jv=Symbol.for(Z0),Gv={_E:(e)=>e,_A:(e)=>e}});var ka;var Qv=x(()=>{ka=class ka{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 ka(this.self)}}});class Zh{patch;op;_op=Ms;constructor(e,t){this.patch=e,this.op=t}}var ip=(e,t)=>{let n=new pt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},Yh=(e)=>{let t=new pt("RunBlocked");return t.effect_instruction_i0=e,t},vo,pt,Xh,Qh,Ca=(e)=>C(e,vo),xt=(e)=>{let t=new pt(ru);return t.effect_instruction_i0=e,t},cT,jr,Vr=(e)=>jr(e,void 0),eg=function(){let e=new pt(ri);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(Qo("you're not supposed to end up here"))}return e},cc=(e,t=hn)=>{let n=new pt(ni),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,dc(n,(o)=>Ca(r)?r:nt)},lT=(e,t=hn)=>Ce(()=>cc(e,t)),To=(e,t=hn)=>eg(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(ni);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?dc(i,(c)=>{if(s)s.abort();return a??nt}):i}),lc,eT,ap=(e,t)=>{if(Re(t))return new Proxy(e,{has(n,r){return r===yi||r===eT||r in n},get(n,r){if(r===yi)return t.value;if(r===eT)return e;return n[r]}});return e},sp=(e)=>qt(e)&&!(yi in e)?xt((t)=>At(rn(ap(e,vp(t))))):At(rn(e)),tg=(e)=>uT(()=>rn(new aF(e))),_i=(e)=>Aa(e,{onFailure:(t)=>fe(W(t)),onSuccess:(t)=>fe(Q(t))}),Eo=(e)=>pT(e,{onFailure:Te,onSuccess:Ie}),dt=(e)=>qt(e)&&!(yi in e)?xt((t)=>At(Sa(ap(e,vp(t))))):At(Sa(e)),ng=(e)=>B(D(e),dt),At=(e)=>{let t=new Xh(jt);return t.effect_instruction_i0=e,t},uT=(e)=>B(D(e),At),rg,uc=(e)=>xt((t)=>e(t.id())),B,og=(e)=>{let t=new pt("OnStep");return t.effect_instruction_i0=e,t},pc=(e)=>B(e,ue),pT,gn,Aa,yn,bi,cp=(e)=>{let t=new pt(oi);return t.effect_instruction_i0=$v(Hr),t.effect_instruction_i1=()=>e,t},Ke,lp,wi,Pa,dc,fe=(e)=>{let t=new Qh(Vt);return t.effect_instruction_i0=e,t},Ce=(e)=>{let t=new pt(ri);return t.commit=e,t},D=(e)=>{let t=new pt(nu);return t.effect_instruction_i0=e,t},up,ig=(e)=>xt((t)=>{let n=t.getFiberRef(op),r=g(n,Oe(()=>t.scope()));return e(ko(op,F(r)))}),pp=(e)=>{let t=new pt(oi);return t.effect_instruction_i0=jh(Hr),t.effect_instruction_i1=()=>e,t},Oo=(e)=>eg(e,function(){let t=new pt(oi);return t.effect_instruction_i0=jh(Hr),t.effect_instruction_i1=(n)=>Dh(n)?yt(()=>this.effect_instruction_i0(cp)):yt(()=>this.effect_instruction_i0(pp)),t}),nt,ag=(e)=>{let t=new pt(oi);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},fc=(e)=>{let t=new pt(ia);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},mc=(e)=>{let t=new pt(sa);return typeof e?.priority<"u"?wT(t,e.priority):t},dp,fp,Ro,hc,dT=(e)=>B(rg,(t)=>g(e,gc(t))),gc,fT,mT,hT,sg,cg,lg,gT,yT,tF="effect/FiberRef",nF,rF,mp=(e)=>xt((t)=>Ie(t.getFiberRef(e))),vi,Jh,oF,ko,St=(e,t)=>Ti(e,{differ:Ju(),fork:t?.fork??ue,join:t?.join}),xT=(e)=>{let t=kh();return Ti(e,{differ:t,fork:t.empty})},iF=(e)=>{let t=Ch(Ju());return Ti(e,{differ:t,fork:t.empty})},hp=(e)=>{let t=Rh();return Ti(e,{differ:t,fork:t.empty})},Ti=(e,t)=>({...so,[nF]:rF,initial:e,commit(){return mp(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)}),ST=(e)=>Ti(e,{differ:Hh,fork:Hh.empty}),Ei,Ia,ug,_T,pg,bT,wT,vT,TT,ET,OT,yc,op,xc,gp,yp,xp=(e,t)=>e.addFinalizer(()=>Vr(t)),dg=(e,t)=>e.close(t),Ma=(e,t)=>e.fork(t),Sp,Oi=(e,t)=>{class n extends Sp{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},tT,aF,Gh,qK,RT=(e)=>C(e,Gh),nT,sF,rT,Sc,oT,UK,iT,HK,aT,$K,sT,cF,Na=(e)=>Ca(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),fg=(e)=>e._tag==="Success",kT,_c=(e)=>kT(e,void 0),Ri=(e,t)=>lF(e,t?.parallel?xi:Ct),mg=(e)=>Te(rn(e)),bc=(e)=>Te(Sa(e)),Te=(e)=>{let t=new Xh(jt);return t.effect_instruction_i0=e,t},hg=(e)=>Te(Nn(e)),rp,_p,Ie=(e)=>{let t=new Qh(Vt);return t.effect_instruction_i0=e,t},xn,gg,lF=(e,t)=>{let n=pu(e);if(!Pn(n))return A();return g(Mn(n),ua(g(In(n),rp(tt)),(r,o)=>g(r,gg(o,{onSuccess:(i,a)=>g(i,kt(a)),onFailure:t}))),rp(po),rp((r)=>Mr(r)),F)},CT=(e)=>({...so,[Jv]:Gv,state:Lu(Yv([])),commit(){return bp(this)},blockingOn:e}),bp=(e)=>lT((t)=>{let n=wa(e.state);switch(n._tag){case np:return t(n.effect);case Ra:return n.joiners.push(t),uF(e,t)}},e.blockingOn),wp=(e,t)=>{let n=wa(e.state);if(n._tag===Ra){Du(e.state,Zv(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},uF=(e,t)=>D(()=>{let n=wa(e.state);if(n._tag===Ra){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),pF,AT=()=>pF,ki=(e)=>B(AT(),e),dF,yg,vp=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?F(t):A()};var rt=x(()=>{Be();Qn();mn();tn();pe();Ta();j();Me();ju();Ve();Bu();uh();Ge();we();xe();Bh();io();ba();Xv();Gu();Rr();sc();Qv();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,ks(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 ka(new Tr(this))}};Xh=class Xh{_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 Na(e)&&e._op==="Failure"&&R(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(he(this._tag),G(O(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 ka(new Tr(this))}};Qh=class Qh{_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 Na(e)&&e._op==="Success"&&R(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(he(this._tag),G(O(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 ka(new Tr(this))}};cT=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))),lc=d(2,(e,t)=>Aa(e,{onFailure:t,onSuccess:fe})),eT=Symbol.for("effect/OriginalAnnotation"),rg=xt((e)=>fe(e.id())),B=d(2,(e,t)=>{let n=new pt(ra);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),pT=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(oa);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),Aa=d(2,(e,t)=>gn(e,{onFailure:(n)=>{if(Jm(n).length>0)return At(Aw(n));let o=Wm(n);if(o.length>0)return t.onFailure(Cm(o));return At(n)},onSuccess:t.onSuccess})),yn=d(2,(e,t)=>Ce(()=>{let n=ke(e),r=ii(n.length),o=0;return jr(fc({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),bi=d(2,(e,t)=>Ce(()=>{let n=ke(e),r=0;return fc({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),Ke=d(2,(e,t)=>B(e,(n)=>D(()=>t(n)))),lp=d(2,(e,t)=>Aa(e,{onFailure:(n)=>ng(()=>t.onFailure(n)),onSuccess:(n)=>D(()=>t.onSuccess(n))})),wi=d(2,(e,t)=>gn(e,{onFailure:(n)=>{let r=Cu(n);switch(r._tag){case"Left":return ng(()=>t(r.left));case"Right":return At(r.right)}},onSuccess:fe})),Pa=d(2,(e,t)=>Oo((n)=>gn(n(e),{onFailure:(r)=>{let o=Te(r);return gn(t(o),{onFailure:(i)=>Te(Ct(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=Ie(r);return Ro(t(o),o)}}))),dc=d(2,(e,t)=>Pa(e,_p({onFailure:(n)=>_a(n)?Vr(t(Gm(n))):nt,onSuccess:()=>nt}))),up=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(Ca(r))return jr(r,n);else if(Q_(r))return cc((o)=>{r.then((i)=>o(fe(n)),(i)=>o(dt(new cF(i,"An unknown error occurred in Effect.tap"))))});return fe(n)})),nt=fe(void 0),dp=d(2,(e,t)=>B(e,(n)=>Ke(t,(r)=>[n,r]))),fp=d(2,(e,t)=>B(e,(n)=>jr(t,n))),Ro=d(2,(e,t)=>B(e,()=>t)),hc=lT(()=>{let e=setInterval(()=>{},2147483647);return D(()=>clearInterval(e))}),gc=d(2,(e,t)=>B(e.interruptAsFork(t),()=>e.await)),fT={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return T(this,arguments)}},mT={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return T(this,arguments)}},hT={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return T(this,arguments)}},sg={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return T(this,arguments)}},cg={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return T(this,arguments)}},lg={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return T(this,arguments)}},gT={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return T(this,arguments)}},yT={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return T(this,arguments)}},nF=Symbol.for(tF),rF={_A:(e)=>e},vi=d(2,(e,t)=>B(mp(e),t)),Jh=d(2,(e,t)=>oF(e,()=>[void 0,t])),oF=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)=>cT(fp(mp(t),Jh(t,n)),()=>e,(r)=>Jh(t,r))),Ei=V(Symbol.for("effect/FiberRef/currentContext"),()=>hp(So())),Ia=V(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>St(0)),ug=V(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>St(2048)),_T=V(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>St(Ea())),pg=V(Symbol.for("effect/FiberRef/currentLogLevel"),()=>St(cg)),bT=V(Symbol.for("effect/FiberRef/currentLogSpan"),()=>St(bo())),wT=d(2,(e,t)=>ko(e,Ia,t)),vT=V(Symbol.for("effect/FiberRef/currentConcurrency"),()=>St("unbounded")),TT=V(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>St(!0)),ET=V(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>St(F(lg))),OT=V(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>St(F(sg))),yc=V(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>iF(Pr())),op=V(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>St(A(),{fork:()=>A(),join:(e,t)=>e})),xc=V(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>St(Dr,{fork:()=>Dr,join:(e,t)=>e})),gp=Symbol.for("effect/Scope"),yp=Symbol.for("effect/CloseableScope"),Sp=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()}
23
23
  ${this.stack.split(`
24
24
  `).slice(1).join(`
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(`
25
+ `)}`:this.toString();else if("Bun"in globalThis)return Fn(Sa(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,om),e}(),tT=Symbol.for("effect/Cause/errors/RuntimeException"),aF=Oi({[tT]:tT},"RuntimeException"),Gh=Symbol.for("effect/Cause/errors/InterruptedException"),qK=Oi({[Gh]:Gh},"InterruptedException"),nT=Symbol.for("effect/Cause/errors/IllegalArgument"),sF=Oi({[nT]:nT},"IllegalArgumentException"),rT=Symbol.for("effect/Cause/errors/NoSuchElement"),Sc=Oi({[rT]:rT},"NoSuchElementException"),oT=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),UK=Oi({[oT]:oT},"InvalidPubSubCapacityException"),iT=Symbol.for("effect/Cause/errors/ExceededCapacityException"),HK=Oi({[iT]:iT},"ExceededCapacityException"),aT=Symbol.for("effect/Cause/errors/Timeout"),$K=Oi({[aT]:aT},"TimeoutException"),sT=Symbol.for("effect/Cause/errors/UnknownException"),cF=function(){class e extends Sp{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[sT]:sT,name:"UnknownException"}),e}(),kT=d(2,(e,t)=>{switch(e._tag){case jt:return Te(e.effect_instruction_i0);case Vt:return Ie(t)}}),rp=d(2,(e,t)=>{switch(e._tag){case jt:return Te(e.effect_instruction_i0);case Vt:return Ie(t(e.effect_instruction_i0))}}),_p=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),gg=d(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case jt:switch(t._tag){case Vt:return Te(e.effect_instruction_i0);case jt:return Te(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 Te(t.effect_instruction_i0)}}}),pF=xt((e)=>Ie(e.currentContext)),dF=d(2,(e,t)=>ko(Ei,t)(e)),yg=d(2,(e,t)=>ki((n)=>dF(e,t(n))))});var PT,IT;var MT=x(()=>{ba();PT=kw,IT=Fn});var Tp="And",Ep="Or",Op="InvalidData",Rp="MissingData",kp="SourceUnavailable",Cp="Unsupported";var hF="effect/ConfigError",NT,Fa,Ap=(e,t)=>{let n=Object.create(Fa);return n._op=Tp,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},Pp=(e,t)=>{let n=Object.create(Fa);return n._op=Ep,n.left=e,n.right=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(n,"message",{enumerable:!1,get(){return this.toString()}}),n},xg=(e,t,n={pathDelim:"."})=>{let r=Object.create(Fa);return r._op=Op,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(Fa);return r._op=Rp,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},Sg=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(Fa);return o._op=kp,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},_g=(e,t,n={pathDelim:"."})=>{let r=Object.create(Fa);return r._op=Cp,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,FT;var bg=x(()=>{Be();tn();j();NT=Symbol.for(hF),Fa={_tag:"ConfigError",[NT]:NT},Co=d(2,(e,t)=>{switch(e._op){case Tp:return Ap(Co(e.left,t),Co(e.right,t));case Ep:return Pp(Co(e.left,t),Co(e.right,t));case Op:return xg([...t,...e.path],e.message);case Rp:return or([...t,...e.path],e.message);case kp:return Sg([...t,...e.path],e.message,e.cause);case Cp:return _g([...t,...e.path],e.message)}}),FT=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case Tp:{r.push(a.right),r.push(a.left),o.push(W({_op:"AndCase"}));break}case Ep:{r.push(a.right),r.push(a.left),o.push(W({_op:"OrCase"}));break}case Op:{o.push(Q(n.invalidDataCase(t,a.path,a.message)));break}case Rp:{o.push(Q(n.missingDataCase(t,a.path,a.message)));break}case kp:{o.push(Q(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case Cp:{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 gF="effect/Clock",DT,wc,yF=2147483647,qT,UT,xF,HT,$T=()=>new HT;var wg=x(()=>{mn();lh();j();rt();DT=Symbol.for(gF),wc=Kt("effect/Clock"),qT={unsafeSchedule(e,t){let n=Fu(t);if(n>yF)return no;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},UT=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))}}(),xF=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return UT;let t=UT()-e.bigint();return()=>t+e.bigint()}();HT=class HT{[DT]=DT;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return xF()}currentTimeMillis=D(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=D(()=>this.unsafeCurrentTimeNanos());scheduler(){return fe(qT)}sleep(e){return To((t)=>{let n=qT.unsafeSchedule(()=>t(nt),e);return Vr(D(n))})}}});var ir;var vc=x(()=>{cu();ir=Tb});var La=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var vg=()=>{};var BT,Mp;var KT=x(()=>{Be();tn();j();Bu();Ge();bg();BT={_tag:"Empty"},Mp=d(2,(e,t)=>{let n=Qs(t),r=e;while(bh(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=An(r,o.f),n=n.tail;break}case"Nested":{r=ca(r,o.name),n=n.tail;break}case"Unnested":{if(g(Cr(r),kb(o.name)))r=Cn(r),n=n.tail;else return W(or(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return Q(r)})});var zT="Constant",WT="Fail",JT="Fallback",GT="Described",YT="Lazy",ZT="MapOrFail",XT="Nested",QT="Primitive",eE="Redacted",tE="Sequence",nE="HashMap",rE="ZipWith";var Np=(e,t)=>[...e,...t],EF="effect/ConfigProvider",oE,aE,OF="effect/ConfigProviderFlat",iE,RF=(e)=>({[oE]:oE,pipe(){return T(this,arguments)},...e}),kF=(e)=>({[iE]:iE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),CF=(e)=>RF({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}),sE=(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 CF(kF({load:(c,l,u=!0)=>{let p=r(c),f=i(),h=p in f?F(f[p]):A();return g(h,wi(()=>or(c,`Expected ${p} to exist in the process context`)),B((m)=>LF(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 v=g(c,bm(m)),S=h[m];if(S===void 0||v!==S)return!1}return!0}).flatMap((h)=>h.slice(c.length,c.length+1));return ww(f)}),patch:BT}))},AF=(e,t,n,r)=>{let o=Em(n.length,(c)=>c>=r.length?A():F([e(c),c+1])),i=Em(r.length,(c)=>c>=n.length?A():F([t(c),c+1])),a=Np(n,o),s=Np(r,i);return[a,s]},PF=(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},IF,MF=(e)=>FT(e,void 0,IF),on=(e,t,n,r)=>{let o=n;switch(o._tag){case zT:return fe(Rt(o.value));case GT:return Ce(()=>on(e,t,o.config,r));case WT:return dt(or(t,o.message));case JT:return g(Ce(()=>on(e,t,o.first,r)),lc((i)=>{if(o.condition(i))return g(on(e,t,o.second,r),lc((a)=>dt(Pp(i,a))));return dt(i)}));case YT:return Ce(()=>on(e,t,o.config(),r));case ZT:return Ce(()=>g(on(e,t,o.original,r),B(yn((i)=>g(o.mapOrFail(i),wi(Co(PF(t,o.original))))))));case XT:return Ce(()=>on(e,Np(t,Rt(o.name)),o.config,r));case QT:return g(Mp(t,e.patch),B((i)=>g(e.load(i,o,r),B((a)=>{if(a.length===0){let s=g(Lb(i),Oe(()=>"<n/a>"));return dt(or([],`Expected ${o.description} with name ${s}`))}return fe(a)}))));case eE:return Ce(()=>g(on(e,t,o.original,r),wi(MF),Ke(An(o.redact))));case tE:return g(Mp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B(qF),B((a)=>{if(a.length===0)return Ce(()=>Ke(on(e,t,o.config,!0),Rt));return g(yn(a,(s)=>on(e,Mb(t,`[${s}]`),o.config,!0)),Ke((s)=>{let c=lu(s);if(c.length===0)return Rt(Pr());return Rt(c)}))}))));case nE:return Ce(()=>g(Mp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B((a)=>g(a,yn((s)=>on(e,Np(i,Rt(s)),o.valueConfig,r)),Ke((s)=>{if(s.length===0)return Rt(Ea());return g(DF(s),An((c)=>uv(Tm(ke(a),c))))})))))));case rE:return Ce(()=>g(on(e,t,o.left,r),_i,B((i)=>g(on(e,t,o.right,r),_i,B((a)=>{if(Ee(i)&&Ee(a))return dt(Ap(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=NF(t,s),[l,u]=AF(c,c,g(i.right,An(Q)),g(a.right,An(Q)));return g(l,Tm(u),yn(([p,f])=>g(dp(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")})))))}},NF=(e,t)=>(n)=>W(or(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),FF=(e,t)=>e.split(new RegExp(`\\s*${La(t)}\\s*`)),LF=(e,t,n,r,o)=>{if(!o)return g(n.parse(e),lp({onFailure:Co(t),onSuccess:Rt}));return g(FF(e,r),yn((i)=>n.parse(i.trim())),wi(Co(t)))},DF=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),qF=(e)=>g(yn(e,HF),lp({onFailure:()=>Pr(),onSuccess:Ar(ir)}),_i,Ke(bb)),UF,HF=(e)=>{let t=e.match(UF);if(t!==null){let n=t[2];return g(n!==void 0&&n.length>0?F(n):A(),kn($F))}return A()},$F=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?A():F(t)};var cE=x(()=>{Be();mn();tn();j();ju();di();vc();Ge();we();vg();bg();KT();rt();oE=Symbol.for(EF),aE=Kt("effect/ConfigProvider"),iE=Symbol.for(OF),IF={andCase:(e,t,n)=>Ap(t,n),orCase:(e,t,n)=>Pp(t,n),invalidDataCase:(e,t)=>xg(t,"<redacted>"),missingDataCase:(e,t)=>or(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>Sg(t,"<redacted>",r),unsupportedCase:(e,t)=>_g(t,"<redacted>")},UF=/^(\[(\d+)\])$/});var lE,Fp,uE;var Tg=x(()=>{mn();rt();lE=Symbol.for("effect/Console"),Fp=Kt("effect/Console"),uE={[lE]:lE,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 BF="effect/Random",pE,dE,fE,KF=(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,bi((o)=>g(t(o),Ke((i)=>zF(n,o-1,i)))),jr(pu(n)))}))),zF=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},mE=(e)=>new fE(O(e));var hE=x(()=>{Qn();mn();j();Me();io();rt();pE=Symbol.for(BF),dE=Kt("effect/Random");fE=class fE{seed;[pE]=pE;PRNG;constructor(e){this.seed=e,this.PRNG=new Xf(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 KF(e,(t)=>this.nextIntBetween(0,t))}}});class xE{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:yE(32),this.spanId=yE(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 gE,JF=(e)=>({[gE]:gE,...e}),Tc,Lp,yE,SE,_E;var Dp=x(()=>{mn();j();gE=Symbol.for("effect/Tracer"),Tc=Kt("effect/Tracer"),Lp=Kt("effect/ParentSpan"),yE=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();SE=JF({span:(e,t,n,r,o,i)=>new xE(e,t,n,r,o,i),context:(e)=>e()}),_E=Ys()("effect/Tracer/DisablePropagation",{defaultValue:no})});var ZF,Ec;var bE=x(()=>{mn();j();wg();cE();rt();Tg();hE();Dp();ZF=g(So(),tr(wc,$T()),tr(Fp,uE),tr(dE,mE(Math.random())),tr(aE,sE()),tr(Tc,SE)),Ec=V(Symbol.for("effect/DefaultServices/currentServices"),()=>hp(ZF))});var QF,wE=(e)=>{let t={BaseEffectError:class extends QF{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var vE=x(()=>{rt();QF=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends Sp{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 TE,eL,Og;var Rg=x(()=>{Rr();TE=Or,eL=pb;Og=class Og extends eL{}});var OE="Sequential",RE="Parallel",tL="ParallelN",Da,kE,CE=(e)=>({_tag:tL,parallelism:e}),kg=(e)=>e._tag===OE,Cg=(e)=>e._tag===RE;var qp=x(()=>{Da={_tag:OE},kE={_tag:RE}});var Up,Hp,$p;var AE=x(()=>{qp();Up=Da,Hp=kE,$p=CE});function PE(e){return new Br(e)}function IE(){return PE(new Map)}var Pg,Br,rL=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(ve(i)&&ve(a)){let l=et(i)[0],u=Cn(i),p=et(a)[0],f=et(a)[1],h=Cn(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},Mg,Ng,ME=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(R(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},Oc,Fg,Ao,qa,Ig=(e,t,n,r)=>{let o=e.get(n)??[],i;if(ve(o)){let[a,s]=et(o);if(a[I](t))if(R(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},NE;var jp=x(()=>{Be();pe();j();Ge();we();Pg=Symbol.for("effect/FiberRefs");Br=class Br{locals;[Pg]=Pg;constructor(e){this.locals=e}pipe(){return T(this,arguments)}};Mg=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(R(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=rL(i,s,o);if(l){let u=i.diff(c,a),p=s[0][1],f=i.join(p,i.patch(u)(p));if(!R(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)}),Ng=d(2,(e,t)=>{let n=new Map;return ME(e,n,t),new Br(n)}),Oc=d(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new Br(n)}),Fg=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(Fg(e,t),Oe(()=>t.initial))),qa=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 Ig(o,t,n,r),new Br(o)}),NE=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)ME(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)Ig(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{Ig(r,a,o,s)})}),new Br(r)})});var FE,LE,DE;var Dg=x(()=>{jp();FE=Ao,LE=NE,DE=IE});var UE="Empty",HE="Add",$E="Remove",jE="Update",VE="AndThen",BE,KE=(e,t)=>{let n=new Map(e.locals),r=BE;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(!R(c,a))r=Vp({_tag:jE,fiberRef:o,patch:o.diff(c,a)})(r)}else r=Vp({_tag:HE,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=Vp({_tag:$E,fiberRef:o})(r);return r},Vp,zE;var WE=x(()=>{Be();pe();j();jp();BE={_tag:UE},Vp=d(2,(e,t)=>({_tag:VE,first:e,second:t})),zE=d(3,(e,t,n)=>{let r=n,o=Rt(e);while(ve(o)){let i=et(o),a=Cn(o);switch(i._tag){case UE:{o=a;break}case HE:{r=qa(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case $E:{r=Oc(r,i.fiberRef),o=a;break}case jE:{let s=Ao(r,i.fiberRef);r=qa(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case VE:{o=ca(i.first)(ca(i.second)(a));break}}}return r})});var JE,GE;var YE=x(()=>{WE();JE=KE,GE=zE});var Kp="effect/FiberStatus",Po,Bp="Done",ZE="Running",XE="Suspended",aL,QE,eO,tO,nO,rO=(e)=>new eO(e),oO=(e,t)=>new tO(e,t),zp=(e)=>C(e,Po),iO=(e)=>e._tag===Bp;var aO=x(()=>{pe();j();Me();xe();Po=Symbol.for(Kp),aL=he(`${Kp}-${Bp}`);QE=class QE{[Po]=Po;_tag=Bp;[M](){return aL}[I](e){return zp(e)&&e._tag===Bp}};eO=class eO{runtimeFlags;[Po]=Po;_tag=ZE;constructor(e){this.runtimeFlags=e}[M](){return g(O(Kp),G(O(this._tag)),G(O(this.runtimeFlags)),ie(this))}[I](e){return zp(e)&&e._tag===ZE&&this.runtimeFlags===e.runtimeFlags}};tO=class tO{runtimeFlags;blockingOn;[Po]=Po;_tag=XE;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[M](){return g(O(Kp),G(O(this._tag)),G(O(this.runtimeFlags)),G(O(this.blockingOn)),ie(this))}[I](e){return zp(e)&&e._tag===XE&&this.runtimeFlags===e.runtimeFlags&&R(this.blockingOn,e.blockingOn)}};nO=new QE});var sO,qg,cO,lO;var uO=x(()=>{aO();sO=nO,qg=rO,cO=oO,lO=iO});var lL,uL,pL,dL,fL,mL,hL,gL,yL,pO,dO=(e)=>{switch(e){case"All":return lL;case"Debug":return mL;case"Error":return pL;case"Fatal":return uL;case"Info":return fL;case"Trace":return hL;case"None":return gL;case"Warning":return dL}};var fO=x(()=>{j();rt();vc();cu();lL=fT,uL=mT,pL=hT,dL=sg,fL=cg,mL=lg,hL=gT,gL=yT,yL=g(ir,su((e)=>e.ordinal)),pO=hm(yL)});function RL(e){return Hg("Micro.evaluate: Not implemented")}class Wg{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,NL(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(EO)}flush(){while(this.tasks.length>0)this.runTasks()}}var SL,Jp,mO,_L,$g,yO,bL=(e,t=[])=>new yO(e,t),xO,wL=(e=[])=>new xO(e),vL=(e)=>e._tag==="Interrupt",hO,TL,SO,gO,_O,it,Ug,Ha,Ua,Gp,Wp,EL,OL,Zp=(e)=>({...OL,[_O]:e.op,[Ug]:e.eval??RL,[Ha]:e.contA,[Ua]:e.contE,[Gp]:e.ensure}),jg=(e)=>{let t=Zp(e);return function(){let n=Object.create(t);return n[it]=e.single===!1?arguments:arguments[0],n}},bO=(e)=>{let t={...Zp(e),[Jp]:Jp,_tag:e.op,get[e.prop](){return this[it]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[it]}},[I](n){return IL(n)&&n._tag===e.op&&R(this[it],n[it])},[M](){return ie(this,G(he(e.op))(O(this[it])))}};return function(n){let r=Object.create(t);return r[it]=n,r[Ha]=void 0,r[Ua]=void 0,r[Gp]=void 0,r}},Vg,wO,kL,CL,AL,Bg,Yp,PL,IL=(e)=>C(e,Jp),vO,Kg,zg,Hg=(e)=>Kg(bL(e)),ML,NL,FL,TO,EO,Xp,LL,DL,qL,OO,UL=(e)=>Bg((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(OO(!1)),t._interrupted)return zg;return e}),HL=(e)=>Bg((t)=>{if(!t.interruptible)return e(ue);return t.interruptible=!1,t._stack.push(OO(!0)),e(UL)}),RO=(e,t)=>{let n=new SO(Xp.context(t?.scheduler??new Wg));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 kO=x(()=>{mn();Rg();pe();j();Me();Ve();Iu();we();xe();io();SL=Symbol.for("effect/Micro"),Jp=Symbol.for("effect/Micro/MicroExit"),mO=Symbol.for("effect/Micro/MicroCause"),_L={_E:ue};$g=class $g extends globalThis.Error{_tag;traces;[mO];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(`
27
27
  `).slice(0,s+3).join(`
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
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[mO]=_L,this.name=o,this.stack=a}pipe(){return T(this,arguments)}toString(){return this.stack}[ne](){return this.stack}};yO=class yO extends $g{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};xO=class xO extends $g{constructor(e=[]){super("Interrupt","interrupted",e)}};hO=Symbol.for("effect/Micro/MicroFiber"),TL={_A:ue,_E:ue};SO=class SO{context;interruptible;[hO];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[hO]=TL}getRef(e){return Hw(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),bs;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(zg)}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===Wp)return;let n=gO.interruptChildren&&gO.interruptChildren(this);if(n!==void 0)return this.evaluate(Yp(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(Xp).shouldYield(this)){t=!0;let r=n;n=Yp(CL,()=>r)}if(n=n[Ug](this),n===Wp){let r=this._yielded;if(Jp in r)return this._yielded=void 0,r;return Wp}}}catch(r){if(!C(n,Ug))return Hg(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return Hg(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[Gp]&&t[Gp](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Wp}children(){return this._children??=new Set}};gO=V("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),_O=Symbol.for("effect/Micro/identifier"),it=Symbol.for("effect/Micro/args"),Ug=Symbol.for("effect/Micro/evaluate"),Ha=Symbol.for("effect/Micro/successCont"),Ua=Symbol.for("effect/Micro/failureCont"),Gp=Symbol.for("effect/Micro/ensureCont"),Wp=Symbol.for("effect/Micro/Yield"),EL={_A:ue,_E:ue,_R:ue},OL={...TE,_op:"Micro",[SL]:EL,pipe(){return T(this,arguments)},[Symbol.iterator](){return new na(new Tr(this))},toJSON(){return{_id:"Micro",op:this[_O],...it in this?{args:this[it]}:void 0}},toString(){return ge(this)},[ne](){return ge(this)}};Vg=bO({op:"Success",prop:"value",eval(e){let t=e.getCont(Ha);return t?t[Ha](this[it],e):e.yieldWith(this)}}),wO=bO({op:"Failure",prop:"cause",eval(e){let t=e.getCont(Ua);while(vL(this[it])&&t&&e.interruptible)t=e.getCont(Ua);return t?t[Ua](this[it],e):e.yieldWith(this)}}),kL=jg({op:"Yield",eval(e){let t=!1;return e.getRef(Xp).scheduleTask(()=>{if(t)return;e.evaluate(ML)},this[it]??0),e.yieldWith(()=>{t=!0})}}),CL=kL(0),AL=Vg(void 0),Bg=jg({op:"WithMicroFiber",eval(e){return this[it](e)}}),Yp=d(2,(e,t)=>{let n=Object.create(PL);return n[it]=e,n[Ha]=t,n}),PL=Zp({op:"OnSuccess",eval(e){return e._stack.push(this),this[it]}}),vO=Vg,Kg=wO,zg=Kg(wL()),ML=vO(void 0),NL="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);FL=d(2,(e,t)=>Bg((n)=>{let r=n.context;return n.context=t(r),qL(e,()=>(n.context=r,AL))})),TO=d(2,(e,t)=>FL(e,Gs(t)));EO=class EO extends Ys()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};Xp=class Xp extends Ys()("effect/Micro/currentScheduler",{defaultValue:()=>new Wg}){};LL=d(2,(e,t)=>{let n=Object.create(DL);return n[it]=e,n[Ha]=t.onSuccess,n[Ua]=t.onFailure,n}),DL=Zp({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[it]}}),qL=d(2,(e,t)=>HL((n)=>LL(n(e),{onFailure:(r)=>Yp(t(Kg(r)),()=>wO(r)),onSuccess:(r)=>Yp(t(vO(r)),()=>Vg(r))}))),OO=jg({op:"SetInterruptible",ensure(e){if(e.interruptible=this[it],e._interrupted&&e.interruptible)return()=>zg}})});class Qp{scheduleDrain;running=!1;tasks=new Jg;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 Qp(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new Qp(e),n.set(r,o);return o}}}class Jg{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 CO{maxNextTickBeforeTimer;getRunner=Qp.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(ug)?e.getFiberRef(Ia):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class Rc{tasks=new Jg;deferred=!1;scheduleTask(e,t,n){if(this.deferred)AO.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(ug)?e.getFiberRef(Ia):!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 AO,ed;var td=x(()=>{rt();AO=V(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new CO(2048));ed=V(Symbol.for("effect/FiberRef/currentScheduler"),()=>St(AO))});var nd;var Gg=x(()=>{rt();nd=V(Symbol.for("effect/FiberRef/currentRequestMap"),()=>St(new Map))});var Yg=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return vi(vT,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var IO=x(()=>{rt()});var Zg=(e)=>e.replace(/[\s="]/g,"_"),MO=(e)=>(t)=>`${Zg(t.label)}=${e-t.startTime}ms`;var NO="effect/MetricLabel",Xg,FO,LO=(e,t)=>new FO(e,t),KL=(e)=>C(e,Xg);var DO=x(()=>{pe();Me();we();xe();Xg=Symbol.for(NO);FO=class FO{key;value;[Xg]=Xg;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=he(NO+this.key+this.value)}[M](){return this._hash}[I](e){return KL(e)&&this.key===e.key&&this.value===e.value}pipe(){return T(this,arguments)}}});var Qg;var qO=x(()=>{mn();Ge();Dp();Qg=kn((e)=>Ws(e.context,_E)?e._tag==="Span"?Qg(e.parent):A():F(e))});var UO;var HO=x(()=>{rt();UO=fg});var ey="InterruptSignal",ty="Stateful",ny="Resume",ry="YieldNow",rd=(e)=>({_tag:"InterruptSignal",cause:e}),$a=(e)=>({_tag:"Stateful",onFiber:e}),Ci=(e)=>({_tag:"Resume",effect:e}),$O=()=>({_tag:"YieldNow"});var ZL="effect/FiberScope",od,VO,BO,KO=(e)=>new BO(e.id(),e),kc;var oy=x(()=>{Ta();od=Symbol.for(ZL);VO=class VO{[od]=od;fiberId=hn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};BO=class BO{fiberId;parent;[od]=od;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell($a((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};kc=V(Symbol.for("effect/FiberScope/Global"),()=>new VO)});var eD="effect/Fiber",iy,ay,tD,nD="effect/Fiber",WO,id=(e)=>fp(pc(e.await),e.inheritAll),wW,Io="effect/FiberCurrent";var JO=x(()=>{Ta();Ge();we();rt();Rr();iy=Symbol.for(eD),ay={_E:(e)=>e,_A:(e)=>e},tD={[iy]:ay,pipe(){return T(this,arguments)}},WO=Symbol.for(nD),wW={...so,commit(){return id(this)},...tD,id:()=>hn,await:hc,children:fe([]),inheritAll:hc,poll:fe(A()),interruptAsFork:()=>hc}});var oD="effect/Logger",GO,YO,ad=(e)=>({[GO]:YO,log:e,pipe(){return T(this,arguments)}}),EW,iD,aD=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(iD)?m:e(m),u=(m,v)=>`${Zg(m)}=${l(v)}`,p=(m,v)=>" "+u(m,v),f=u("timestamp",o.toISOString());f+=p("level",a.label),f+=p("fiber",Hu(i));let h=xm(s);for(let m=0;m<h.length;m++)f+=p("message",Er(h[m],t));if(!zm(r))f+=p("cause",Fn(r,{renderErrorCause:!0}));for(let m of c)f+=" "+MO(o.getTime())(m);for(let[m,v]of n)f+=p(m,Er(v,t));return f},sD=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,ZO,Ai,OW,XO,RW,kW;var QO=x(()=>{Be();j();Ve();we();ba();mh();GO=Symbol.for(oD),YO={_Message:(e)=>e,_Output:(e)=>e},EW={[GO]:YO,log:bs,pipe(){return T(this,arguments)}},iD=/^[^\s"=]*$/,ZO=ad(aD(sD)),Ai={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},OW={None:[],All:[],Trace:[Ai.gray],Debug:[Ai.blue],Info:[Ai.green],Warning:[Ai.yellow],Error:[Ai.red],Fatal:[Ai.bgBrightRed,Ai.black]},XO=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,RW=XO&&process.stdout.isTTY===!0,kW=XO||"Deno"in globalThis});var eR="effect/MetricBoundaries",sy,tR,lD=(e)=>C(e,sy),uD=(e)=>{let t=g(e,Sm(tt(Number.POSITIVE_INFINITY)),Om);return new tR(t)},nR=(e)=>g(ym(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Hs,uD);var rR=x(()=>{Be();Qn();pe();j();Me();we();xe();sy=Symbol.for(eR);tR=class tR{values;[sy]=sy;constructor(e){this.values=e,this._hash=g(he(eR),G(en(this.values)))}_hash;[M](){return this._hash}[I](e){return lD(e)&&R(this.values,e.values)}pipe(){return T(this,arguments)}}});var dD="effect/MetricKeyType",oR,iR="effect/MetricKeyType/Counter",cy,fD="effect/MetricKeyType/Frequency",mD,hD="effect/MetricKeyType/Gauge",gD,aR="effect/MetricKeyType/Histogram",ly,yD="effect/MetricKeyType/Summary",xD,sR,cR,lR,uR=(e)=>new cR(e?.incremental??!1,e?.bigint??!1),pR=(e)=>new lR(e),uy=(e)=>C(e,cy),dR=(e)=>C(e,mD),fR=(e)=>C(e,gD),py=(e)=>C(e,ly),mR=(e)=>C(e,xD);var dy=x(()=>{pe();j();Me();we();xe();oR=Symbol.for(dD),cy=Symbol.for(iR),mD=Symbol.for(fD),gD=Symbol.for(hD),ly=Symbol.for(aR),xD=Symbol.for(yD),sR={_In:(e)=>e,_Out:(e)=>e};cR=class cR{incremental;bigint;[oR]=sR;[cy]=cy;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=he(iR)}_hash;[M](){return this._hash}[I](e){return uy(e)}pipe(){return T(this,arguments)}};lR=class lR{boundaries;[oR]=sR;[ly]=ly;constructor(e){this.boundaries=e,this._hash=g(he(aR),G(O(this.boundaries)))}_hash;[M](){return this._hash}[I](e){return py(e)&&R(this.boundaries,e.boundaries)}pipe(){return T(this,arguments)}}});var SD="effect/MetricKey",gR,_D,bD,sd,wD=(e)=>C(e,gR),yR=(e,t)=>new sd(e,uR(t),kr(t?.description)),xR=(e,t,n)=>new sd(e,pR(t),kr(n)),SR;var _R=x(()=>{Be();pe();j();Me();Ge();we();xe();dy();gR=Symbol.for(SD),_D={_Type:(e)=>e},bD=uo(R);sd=class sd{name;keyType;description;tags;[gR]=_D;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(O(this.keyType)),G(en(this.tags)))}_hash;[M](){return this._hash}[I](e){return wD(e)&&this.name===e.name&&R(this.keyType,e.keyType)&&R(this.description,e.description)&&bD(this.tags,e.tags)}pipe(){return T(this,arguments)}};SR=d(2,(e,t)=>t.length===0?e:new sd(e.name,e.keyType,e.description,lo(e.tags,t)))});class wR{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 bR,TD,fy,vR=()=>{let e=Object.create(TD);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},Mo,ED=(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()},ja,Va,OD=(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 TR=x(()=>{pe();j();Me();Ve();Ge();we();bR=Symbol.for("effect/MutableHashMap"),TD={[bR]:bR,[Symbol.iterator](){return new fy(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)}};fy=class fy{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 wR(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new fy(this.self)}};Mo=d(2,(e,t)=>{if(Cs(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 ED(e,r,t)}),ja=d(2,(e,t)=>Re(Mo(e,t))),Va=d(3,(e,t,n)=>{if(Cs(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 OD(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var kD="effect/MetricState",Cc,ER="effect/MetricState/Counter",my,OR="effect/MetricState/Frequency",hy,RR="effect/MetricState/Gauge",gy,kR="effect/MetricState/Histogram",yy,CR="effect/MetricState/Summary",xy,Ac,AR,CD,PR,IR,MR,NR,FR=(e)=>new AR(e),LR=(e)=>new PR(e),DR=(e)=>new IR(e),qR=(e)=>new MR(e.buckets,e.count,e.min,e.max,e.sum),UR=(e)=>new NR(e.error,e.quantiles,e.count,e.min,e.max,e.sum),AD=(e)=>C(e,my),PD=(e)=>C(e,hy),ID=(e)=>C(e,gy),MD=(e)=>C(e,yy),ND=(e)=>C(e,xy);var HR=x(()=>{Be();pe();j();Me();we();xe();Cc=Symbol.for(kD),my=Symbol.for(ER),hy=Symbol.for(OR),gy=Symbol.for(RR),yy=Symbol.for(kR),xy=Symbol.for(CR),Ac={_A:(e)=>e};AR=class AR{count;[Cc]=Ac;[my]=my;constructor(e){this.count=e}[M](){return g(O(ER),G(O(this.count)),ie(this))}[I](e){return AD(e)&&this.count===e.count}pipe(){return T(this,arguments)}};CD=uo(R);PR=class PR{occurrences;[Cc]=Ac;[hy]=hy;constructor(e){this.occurrences=e}_hash;[M](){return g(he(OR),G(en(ke(this.occurrences.entries()))),ie(this))}[I](e){return PD(e)&&CD(ke(this.occurrences.entries()),ke(e.occurrences.entries()))}pipe(){return T(this,arguments)}};IR=class IR{value;[Cc]=Ac;[gy]=gy;constructor(e){this.value=e}[M](){return g(O(RR),G(O(this.value)),ie(this))}[I](e){return ID(e)&&this.value===e.value}pipe(){return T(this,arguments)}};MR=class MR{buckets;count;min;max;sum;[Cc]=Ac;[yy]=yy;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[M](){return g(O(kR),G(O(this.buckets)),G(O(this.count)),G(O(this.min)),G(O(this.max)),G(O(this.sum)),ie(this))}[I](e){return MD(e)&&R(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)}};NR=class NR{error;quantiles;count;min;max;sum;[Cc]=Ac;[xy]=xy;constructor(e,t,n,r,o,i){this.error=e,this.quantiles=t,this.count=n,this.min=r,this.max=o,this.sum=i}[M](){return g(O(CR),G(O(this.error)),G(O(this.quantiles)),G(O(this.count)),G(O(this.min)),G(O(this.max)),G(O(this.sum)),ie(this))}[I](e){return ND(e)&&this.error===e.error&&R(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 LD="effect/MetricHook",DD,qD,Pc=(e)=>({[DD]:qD,pipe(){return T(this,arguments)},...e}),$R,VR=(e)=>{let t=e.keyType.bigint?$R:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=$R:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return Pc({get:()=>FR(t),update:r,modify:r})},BR=(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 Pc({get:()=>LR(t),update:n,modify:n})},KR=(e,t)=>{let n=t;return Pc({get:()=>DR(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},zR=(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),An((p,f)=>{o[f]=p}));let l=(p)=>{let f=0,h=n;while(f!==h){let m=Math.floor(f+(h-f)/2),v=o[m];if(p<=v)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=ii(n),f=0;for(let h=0;h<n;h++){let m=o[h],v=r[h];f=f+v,p[h]=[m,f]}return p};return Pc({get:()=>qR({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},WR=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=g(o,Ar(ir)),a=ii(r),s=0,c=0,l=0,u=0,p=0,f=(m)=>{let v=[],S=0;while(S!==r-1){let y=a[S];if(y!=null){let[E,P]=y,z=Nu(m-E);if(Qw(z,sh)&&Xw(z,n))v.push(P)}S=S+1}return UD(t,i,Ar(v,ir))},h=(m,v)=>{if(r>0){s=s+1;let S=s%r;a[S]=[v,m]}u=c===0?m:Math.min(u,m),p=c===0?m:Math.max(p,m),c=c+1,l=l+m};return Pc({get:()=>UR({error:t,quantiles:f(Date.now()),count:c,min:u,max:p,sum:l}),update:([m,v])=>h(m,v),modify:([m,v])=>h(m,v)})},UD=(e,t,n)=>{let r=n.length;if(!ve(t))return Pr();let o=t[0],i=t.slice(1),a=jR(e,r,A(),0,o,n),s=Rt(a);return i.forEach((c)=>{s.push(jR(e,r,a.value,a.consumed,c,a.rest))}),An(s,(c)=>[c.quantile,c.value])},jR=(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,v=r,S=o,y=i;while(!0){if(!ve(p))return{quantile:u,value:A(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:F(wm(p)),consumed:l+p.length,rest:[]};let E=et(p),P=Db(p,(L)=>L===E),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),v=U,S=u,y=P[1],a=f,s=h,c=m,l=v,u=S,p=y;continue}if(U>z+X){let L=Ne(c)?F(E):c;return{quantile:u,value:L,consumed:l,rest:p}}switch(c._tag){case"None":{f=a,h=s,m=Cr(p),v=U,S=u,y=P[1],a=f,s=h,c=m,l=v,u=S,p=y;continue}case"Some":{let L=Math.abs(z-c.value);if(te<L){f=a,h=s,m=Cr(p),v=U,S=u,y=P[1],a=f,s=h,c=m,l=v,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 JR=x(()=>{Be();lh();j();vc();Ge();we();HR();DD=Symbol.for(LD),qD={_In:(e)=>e,_Out:(e)=>e},$R=BigInt(0)});var $D="effect/MetricPair",jD,VD,GR=(e,t)=>({[jD]:VD,metricKey:e,metricState:t,pipe(){return T(this,arguments)}});var YR=x(()=>{we();jD=Symbol.for($D),VD={_Type:(e)=>e}});var KD="effect/MetricRegistry",ZR,XR,QR=()=>new XR;var ek=x(()=>{j();TR();Ge();JR();dy();YR();ZR=Symbol.for(KD);XR=class XR{[ZR]=ZR;map=vR();snapshot(){let e=[];for(let[t,n]of this.map)e.push(GR(t,n.get()));return e}get(e){let t=g(this.map,Mo(e),Bt);if(t==null){if(uy(e.keyType))return this.getCounter(e);if(fR(e.keyType))return this.getGauge(e);if(dR(e.keyType))return this.getFrequency(e);if(py(e.keyType))return this.getHistogram(e);if(mR(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=VR(e);if(!g(this.map,ja(e)))g(this.map,Va(e,n));t=n}return t}getFrequency(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=BR(e);if(!g(this.map,ja(e)))g(this.map,Va(e,n));t=n}return t}getGauge(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=KR(e,e.keyType.bigint?BigInt(0):0);if(!g(this.map,ja(e)))g(this.map,Va(e,n));t=n}return t}getHistogram(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=zR(e);if(!g(this.map,ja(e)))g(this.map,Va(e,n));t=n}return t}getSummary(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=WR(e);if(!g(this.map,ja(e)))g(this.map,Va(e,n));t=n}return t}}});var WD="effect/Metric",JD,GD,tk,nk=function(e,t,n,r){let o=Object.assign((i)=>up(i,(a)=>ZD(o,a)),{[JD]:GD,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return T(this,arguments)}});return o},Ic=(e,t)=>rk(yR(e,t)),rk=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=tk.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=tk.get(SR(e,o)),n.set(o,i),i};return nk(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},ok=(e,t,n)=>rk(xR(e,t,n)),ik,YD,ZD;var ak=x(()=>{Be();j();we();rt();_R();DO();ek();JD=Symbol.for(WD),GD={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},tk=V(Symbol.for("effect/Metric/globalMetricRegistry"),()=>QR()),ik=d(3,(e,t,n)=>YD(e,[LO(t,n)])),YD=d(2,(e,t)=>nk(e.keyType,(n,r)=>e.unsafeUpdate(n,lo(t,r)),(n)=>e.unsafeValue(lo(t,n)),(n,r)=>e.unsafeModify(n,lo(t,r)))),ZD=d(2,(e,t)=>vi(yc,(n)=>D(()=>e.unsafeUpdate(t,n))))});var QD="effect/Request",eq,tq,iJ,sk;var ck=x(()=>{j();Gg();rt();Rr();eq=Symbol.for(QD),tq={_E:(e)=>e,_A:(e)=>e},iJ={...Fs,[eq]:tq},sk=d(2,(e,t)=>vi(nd,(n)=>D(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,wp(r.result,t)}})))});var nq="effect/Supervisor",cd,Sy,ld,ud,_y=(e)=>C(e,cd)&&Rs(e,"Zip"),lk,rq=(e)=>new lk(e),Pi;var pd=x(()=>{j();xe();rt();cd=Symbol.for(nq),Sy={_T:(e)=>e};ld=class ld{underlying;value0;[cd]=Sy;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 ld(this,g(this.value,Ke(e)))}zip(e){return new ud(this,e)}};ud=class ud{left;right;_tag="Zip";[cd]=Sy;constructor(e,t){this.left=e,this.right=t}get value(){return dp(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 ld(this,g(this.value,Ke(e)))}zip(e){return new ud(this,e)}};lk=class lk{effect;[cd]=Sy;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 ld(this,g(this.value,Ke(e)))}zip(e){return new ud(this,e)}onRun(e,t){return e()}};Pi=V("effect/Supervisor/none",()=>rq(nt))});var uk;var pk=x(()=>{Gu();uk=wo});var dk="Empty",fk="AddSupervisor",mk="RemoveSupervisor",hk="AndThen",Ba,dd=(e,t)=>({_tag:hk,first:e,second:t}),iq=(e,t)=>aq(t,tt(e)),aq=(e,t)=>{let n=e,r=t;while(Pn(r)){let o=In(r);switch(o._tag){case dk:{r=Mn(r);break}case fk:{n=n.zip(o.supervisor),r=Mn(r);break}case mk:{n=wy(n,o.supervisor),r=Mn(r);break}case hk:{r=kt(o.first)(kt(o.second)(Mn(r)));break}}}return n},wy=(e,t)=>{if(R(e,t))return Pi;else if(_y(e))return wy(e.left,t).zip(wy(e.right,t));else return e},fd=(e)=>{if(R(e,Pi))return er();else if(_y(e))return g(fd(e.left),Lr(fd(e.right)));else return li(e)},sq=(e,t)=>{if(R(e,t))return Ba;let n=fd(e),r=fd(t),o=g(r,jm(n),pi(Ba,(a,s)=>dd(a,{_tag:fk,supervisor:s}))),i=g(n,jm(r),pi(Ba,(a,s)=>dd(a,{_tag:mk,supervisor:s})));return dd(o,i)},gk;var yk=x(()=>{Qn();pk();pe();j();di();pd();Ba={_tag:dk},gk=uk({empty:Ba,patch:iq,combine:dd,diff:sq})});var yq,xk,xq,Sq,_q,Mc="Continue",bq="Done",Sk="Yield",wq,md=(e)=>{throw Error(`BUG: FiberRuntime - ${Er(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Kr,zr,Nc,vq,Tq=(e)=>bi(Vv(e),(t)=>Ii(Kv(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(Uq(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),nd,o)},!1,!1)),Eq,hd,Oq,Rq=(e)=>ad((t)=>{let n=FE(t.context,Ec);Ws(n,Fp).unsafe.log(e.log(t))}),kq,Cq,Aq,wk,vk=(e,t,n)=>Ce(()=>{let r=ke(e),o=Array(r.length);return Ro(Ii(r,(a,s)=>B(t(a,s),(c)=>D(()=>o[s]=c)),n,!1),fe(o))}),Ii=(e,t,n,r,o)=>Oo((i)=>ig((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=[],v=()=>h.forEach((L)=>{L.currentScheduler.scheduleTask(()=>{L.unsafeInterruptAsFork(s.id())},0,L)}),S=[],y=[],E=[],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=pp(a(L)),ee=Iq(ce,s,s.currentRuntimeFlags,kc);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,v()},U=n?og:Eo,te=z(To((L)=>{let se=(ee,Ae)=>{if(ee._op==="Blocked")E.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(mc(),()=>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(Ri(P(),{parallel:!0}),()=>xn)));else if(E.length+m.length===l){let Et=P(),Zi=E.map((to)=>to.effect_instruction_i0).reduce(zh);L(fe(ip(Zi,Ii([Oe(Ri(Et,{parallel:!0}),()=>xn),...E.map((to)=>to.effect_instruction_i1)],(to)=>to,n,!0,o))))}else ce()})}};for(let ee=0;ee<f;ee++)ce()}));return Vr(Pa(pc(i(id(te))),_p({onFailure:(L)=>{X();let se=E.length+1,ce=Math.min(typeof o==="number"?o:E.length,E.length),ee=Array.from(E);return To((Ae)=>{let vt=[],Ft=0,Lt=0,De=(Tt,Et)=>(Zi)=>{if(vt[Tt]=Zi,Ft++,Ft===se)Ae(Ie(Te(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)})))}))),vy=(e,t,n,r)=>Ce(()=>{let o=ke(e),i=Array(o.length);return Ro(Ii(o,(s,c)=>Ke(n(s,c),(l)=>i[c]=l),r,!1,t),fe(i))}),Oy=(e)=>Mq(e,kc),Pq=(e,t,n,r=null)=>{let o=Tk(e,t,n,r);return o.resume(e),o},Iq=(e,t,n,r=null)=>Tk(e,t,n,r),Tk=(e,t,n,r=null)=>{let o=$u(),i=t.getFiberRefs(),a=Ng(i,o),s=new hd(o,a,n),c=Ao(a,Ei),l=s.currentSupervisor;return l.onStart(c,e,F(t),s),s.addObserver((p)=>l.onEnd(p,s)),(r!==null?r:g(t.getFiberRef(op),Oe(()=>t.scope()))).add(n,s),s},Mq=(e,t)=>xt((n,r)=>fe(Pq(e,n,r.runtimeFlags,t))),Ty=(e)=>ki((t)=>Je(_o(t,Fc),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return B(Ma(n,Hp),(r)=>Ry(e,r))}}})),_k=(e)=>(t)=>ki((n)=>Je(_o(n,Fc),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return B(Ma(r,$p(e)),(o)=>Ry(t,o))}})),Ka=(e,t)=>(n)=>ki((r)=>Je(_o(r,Fc),{onNone:()=>n(ue),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?Ty:e._tag==="Sequential"?Ey:_k(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(Ty));case"Sequential":return i(n(Ey));case"ParallelN":return i(n(_k(o.strategy.parallelism)))}}else return n(ue)}})),Ey=(e)=>ki((t)=>Je(_o(t,Fc),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return B(Ma(n,Up),(r)=>Ry(e,r))}}})),Fc,Nq=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},Fq,Lq=(e=Da)=>{let t=Object.create(Fq);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},Ry,Dq=(e)=>Ti(e,{differ:gk,fork:Ba}),bk,qq,Ek,Uq=(e,t,n)=>uc((r)=>Ek(B(Oy(cp(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"&&Na(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&ku(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(dT(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 bi(o,(i)=>sk(i.request,hg(r)))})));var ky=x(()=>{Be();Qn();mn();Rg();AE();Ta();Dg();YE();uO();j();di();Ve();fO();kO();Ge();we();xe();Bh();td();io();zv();ba();wg();Gg();IO();qO();rt();bE();Tg();qp();JO();jp();oy();QO();ak();rR();ck();sc();sc();pd();yk();Dp();yq=Ic("effect_fiber_started",{incremental:!0}),xk=Ic("effect_fiber_active"),xq=Ic("effect_fiber_successes",{incremental:!0}),Sq=Ic("effect_fiber_failures",{incremental:!0}),_q=ik(ok("effect_fiber_lifetimes",nR({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),wq={_E:(e)=>e,_A:(e)=>e},Kr=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),zr=V("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Nc={[ra]:(e,t,n)=>yt(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>Ie(Ie(n)),[oa]:(e,t,n)=>yt(()=>t.effect_instruction_i2(n)),[Ms]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),$r(e.currentRuntimeFlags)&&e.isInterrupted())return Te(e.getInterruptedCause());else return Ie(n)},[ia]:(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},[aa]:(e,t,n)=>{while(!0){let r=yt(()=>t.effect_instruction_i0.next(n));if(r.done)return Ie(r.value);let o=Qf(r.value);if(!Na(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},vq={[ey]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),$r(t)?Te(r.cause):n),[ny]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[ty]:(e,t,n,r)=>(r.onFiber(e,qg(t)),n),[ry]:(e,t,n,r)=>B(mc(),()=>n)},Eq=Ns();hd=class hd extends Og{[iy]=ay;[WO]=wq;_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,Uh(n)){let r=this.getFiberRef(yc);yq.unsafeUpdate(1,r),xk.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return id(this)}id(){return this._fiberId}resume(e){this.tell(Ci(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(lO(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return KO(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(xc)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return Ce(()=>{let t=CT(this._fiberId);return this.tell($a((n,r)=>{wp(t,D(()=>e(n,r)))})),bp(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($a((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),D(()=>this.tell($a((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=Mg(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(bk),c=g(ic(o,s),Vh(Hr),Vh(Xu));return ag(c)})}get poll(){return D(()=>kr(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return D(()=>this.tell(rd(Nn(e))))}unsafeInterruptAsFork(e){this.tell(rd(Nn(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(bk,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=Oc(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=qa(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(Ec),this.currentTracer=this.currentDefaultServices.unsafeMap.get(Tc.key),this.currentSupervisor=this.getFiberRef(qq),this.currentScheduler=this.getFiberRef(ed),this.currentContext=this.getFiberRef(Ei),this.currentSpan=this.currentContext.unsafeMap.get(Lp.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=Mc,n=globalThis[Io];globalThis[Io]=this;try{while(t===Mc)t=this._queue.length===0?bq: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===Sk)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Ia),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=vq[r._tag](this,e,n,r)}return n}isInterrupted(){return!Ru(this.getFiberRef(xc))}addInterruptedCause(e){let t=this.getFiberRef(xc);this.setFiberRef(xc,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(rd(Nn(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return fc({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(Uh(this.currentRuntimeFlags)){let t=this.getFiberRef(yc),n=this.id().startTimeMillis,r=Date.now();switch(_q.unsafeUpdate(r-n,t),xk.unsafeUpdate(-1,t),e._tag){case Vt:{xq.unsafeUpdate(1,t);break}case jt:{Sq.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(ET);if(!_a(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(Aq)}log(e,t,n){let r=Re(n)?n.value:this.getFiberRef(pg),o=this.getFiberRef(Oq);if(pO(o,r))return;let i=this.getFiberRef(bT),a=this.getFiberRef(_T),s=this.getLoggers(),c=this.getFiberRefs();if(Vs(s)>0){let l=Ws(this.getFiberRef(Ec),wc),u=new Date(l.unsafeCurrentTimeMillis());rb(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 ry:return Sk;case ey:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Te(e.cause)),this._asyncInterruptor=null;return Mc}case ny:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),Mc;case ty:return e.onFiber(this,this._exitValue!==null?sO:cO(this.currentRuntimeFlags,this._asyncBlockingOn)),Mc;default:return md(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=$r(this.currentRuntimeFlags)&&this.isInterrupted()?Te(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===sa)if(Uv(this.currentRuntimeFlags))this.tell($O()),this.tell(Ci(xn)),t=null;else t=xn;else if(o._op===ni)t=null}else{this.currentRuntimeFlags=g(this.currentRuntimeFlags,Lh(Xu));let o=this.interruptAllChildren();if(o!==null)t=B(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(Ci(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(Ci(e))}startFork(e){this.tell(Ci(e))}patchRuntimeFlags(e,t){let n=ac(e,t);return globalThis[Io]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(Ci(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!==Is)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==ra&&e._op!==ia&&e._op!==aa)return e;e=this.popStack()}}[ib](e){return D(()=>Js(this.currentContext,e))}["Left"](e){return dt(e.left)}["None"](e){return dt(new Sc)}["Right"](e){return Ie(e.right)}["Some"](e){return Ie(e.value)}["Micro"](e){return cc((t)=>{let n=t,r=RO(TO(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(Ie(o.value));switch(o.cause._tag){case"Interrupt":return n(Te(Nn(hn)));case"Fail":return n(dt(o.cause.error));case"Die":return n(sp(o.cause.defect))}}),cc((o)=>{n=(i)=>{o(nt)},r.unsafeInterrupt()})})}[nu](e){let t=yt(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Nc))md(n);return Nc[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 Nc))md(n);return Nc[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 Is:case oa:if(!($r(this.currentRuntimeFlags)&&this.isInterrupted()))return yt(()=>n.effect_instruction_i1(t));else return Te(Au(t));case"OnStep":if(!($r(this.currentRuntimeFlags)&&this.isInterrupted()))return Ie(Te(t));else return Te(Au(t));case Ms:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),$r(this.currentRuntimeFlags)&&this.isInterrupted())return Te(Ct(t,this.getInterruptedCause()));else return Te(t);default:md(n)}else return zr.currentOp=Te(t),Kr}[ru](e){return yt(()=>e.effect_instruction_i0(this,qg(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=JE(o.refs,t),s=ic(o.flags,n);return Ie(ip(e.effect_instruction_i0,xt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(GE(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=ac(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return Oo((r)=>B(Oy(Yh(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return Tq(e.effect_instruction_i0)}[oi](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=ac(n,t);if($r(r)&&this.isInterrupted())return Te(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=ic(r,n);return this.pushStack(new Zh(o,e)),yt(()=>e.effect_instruction_i1(n))}else return xn}[ra](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[Is](e){return this.pushStack(e),e.effect_instruction_i0}[oa](e){return this.pushStack(e),e.effect_instruction_i0}[ni](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),zr.currentOp=e,Kr}[sa](e){return this._isYielding=!1,zr.currentOp=e,Kr}[ia](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return xn}[aa](e){return Nc[aa](this,e,void 0)}[ri](e){return yt(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&qv)!==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(mc({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(Eq!==t[vo]._V){let n=this.getFiberRef(OT);if(n._tag==="Some"){let r=t[vo]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${Ns()}, 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===sa||n._op===ni)return Kr;return zr.currentOp=null,n._op===Vt||n._op===jt?n:Te(rn(n))}}catch(n){if(t!==Kr&&!C(t,"_op")||!(t._op in this))t=tg(`Not a valid effect: ${Er(t)}`);else if(RT(n))t=Te(Ct(rn(n),Nn(hn)));else t=sp(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};Oq=V("effect/FiberRef/currentMinimumLogLevel",()=>St(dO("Info"))),kq=V(Symbol.for("effect/Logger/defaultLogger"),()=>Rq(ZO)),Cq=V(Symbol.for("effect/Logger/tracerLogger"),()=>ad(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=Qg(_o(Ao(n,Ei),Lp));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=Js(Ao(n,Ec),wc),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=lv(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=Fn(t,{renderErrorCause:!0});a.value.event(Er(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),Aq=V(Symbol.for("effect/FiberRef/currentLoggers"),()=>xT(li(kq,Cq))),wk=d((e)=>Gf(e[0]),(e,t,n)=>xt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(TT);if(n?.discard)return Yg(n.concurrency,()=>Ka(Up,n?.concurrentFinalizers)((i)=>o?Ii(e,(a,s)=>i(t(a,s)),!0,!1,1):bi(e,(a,s)=>i(t(a,s)))),()=>Ka(Hp,n?.concurrentFinalizers)((i)=>Ii(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>Ka($p(i),n?.concurrentFinalizers)((a)=>Ii(e,(s,c)=>a(t(s,c)),o,!1,i)));return Yg(n?.concurrency,()=>Ka(Up,n?.concurrentFinalizers)((i)=>o?vy(e,1,(a,s)=>i(t(a,s)),!0):yn(e,(a,s)=>i(t(a,s)))),()=>Ka(Hp,n?.concurrentFinalizers)((i)=>vk(e,(a,s)=>i(t(a,s)),o)),(i)=>Ka($p(i),n?.concurrentFinalizers)((a)=>vy(e,i,(s,c)=>a(t(s,c)),o)))})),Fc=Kt("effect/Scope"),Fq={[gp]:gp,[yp]:yp,pipe(){return T(this,arguments)},fork(e){return D(()=>{let t=Lq(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),Nq(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 kg(this.strategy)?g(yn(t,(n)=>Eo(n(e))),B((n)=>g(Ri(n),Rn(_c),Oe(()=>xn)))):Cg(this.strategy)?g(vk(t,(n)=>Eo(n(e)),!1),B((n)=>g(Ri(n,{parallel:!0}),Rn(_c),Oe(()=>xn)))):g(vy(t,this.strategy.parallelism,(n)=>Eo(n(e)),!1),B((n)=>g(Ri(n,{parallel:!0}),Rn(_c),Oe(()=>xn))))})},addFinalizer(e){return Ce(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),nt})}},Ry=d(2,(e,t)=>yg(e,Gs(Kw(Fc,t)))),bk=ST(Hv),qq=Dq(Pi),Ek=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 Rk,kk;var Ck=x(()=>{rt();Rk=dg,kk=Ma});class Mk{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return T(this,arguments)}}var Ay=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},Ak,Vq,Pk,Bq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new Pk(e);return Error.stackTraceLimit=t,n},Cy,gd,Ik,Kq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new Ik(e);return Error.stackTraceLimit=t,n},zq=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return bc(t.left);case"Right":return Ie(t.right);case"Some":return Ie(t.value);case"None":return bc(new Sc)}},Wq,Jq=(e)=>new Mk(e.context,e.runtimeFlags,e.fiberRefs),Gq,Nk,Fk,Lk;var Dk=x(()=>{mn();pe();Ta();Dg();Ve();Ge();we();td();Ck();ba();rt();qp();ky();oy();sc();pd();Ak=Ay((e,t,n)=>{let r=$u(),o=[[Ei,[[r,e.context]]]];if(n?.scheduler)o.push([ed,[[r,n.scheduler]]]);let i=LE(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new hd(r,i,e.runtimeFlags),s=t;if(n?.scope)s=B(kk(n.scope,Da),(l)=>Ro(xp(l,uc((u)=>R(u,a.id())?nt:gc(a,u))),Pa(t,(u)=>Rk(l,u))));let c=a.currentSupervisor;if(c!==Pi)c.onStart(e.context,s,A(),a),a.addObserver((l)=>c.onEnd(l,a));if(kc.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),Vq=Ay((e,t)=>{let n=Wq(e)(t);if(n._tag==="Failure")throw Kq(n.effect_instruction_i0);return n.effect_instruction_i0});Pk=class Pk 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}};Cy=Symbol.for("effect/Runtime/FiberFailure"),gd=Symbol.for("effect/Runtime/FiberFailure/Cause");Ik=class Ik extends Error{[Cy];[gd];constructor(e){let t=Bs(e)[0];super(t?.message||"An error has occurred");if(this[Cy]=Cy,this[gd]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[gd].toJSON()}}toString(){return"(FiberFailure) "+Fn(this[gd],{renderErrorCause:!0})}[ne](){return this.toString()}};Wq=Ay((e,t)=>{let n=zq(t);if(n)return n;let r=new Rc,o=Ak(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return mg(ap(Bq(o),vp(o)))});Gq=qh(Hr,Fh,Nh),Nk=Jq({context:So(),runtimeFlags:Gq,fiberRefs:DE()}),Fk=Ak(Nk),Lk=Vq(Nk)});var qk,Lc,Dc,an,Uk,yd,Hk,Mi,Dn,$k,jk;var Vk=x(()=>{rt();ky();Dk();qk=Ca,Lc=wk,Dc=Ce,an=nt,Uk=lc,yd=Ke,Hk=wi,Mi=_i,Dn=B,$k=Fk,jk=Lk});var Py=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return Py(e,t.from)}},qc=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},Iy=(e)=>Array.isArray(e),Kk=(e)=>!Array.isArray(e),Bk=(e)=>`[${Ps(e)}]`,xd=(e)=>Iy(e)?e.map(Bk).join(""):Bk(e);var Uc=x(()=>{Ve()});var No=(e,t,n,r)=>{let o=e;if(n&&ve(n))o+=`
31
+ at path: ${xd(n)}`;if(t!==void 0)o+=`
32
+ details: ${t}`;if(r)o+=`
33
+ schema (${r._tag}): ${r}`;return o},zk=(e)=>No("Invalid Argument",e),Wk=(e)=>No("Unsupported key schema",void 0,void 0,e),Jk=(e)=>No("Unsupported literal",`literal value: ${Zn(e)}`),My=(e)=>No("Duplicate index signature",`${e} index signature`),Gk,Yk,Ny=(e)=>No("Duplicate property signature transformation",`Duplicate key ${Zn(e)}`),Fy=(e)=>No("Duplicate property signature",`Duplicate key ${Zn(e)}`);var Ly=x(()=>{Be();Ve();Uc();Gk=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"),Yk=No("Invalid element","A required element cannot follow an optional element. ts(1257)")});var Xk,Qk,eC,tC,nC,rC,oC;var iC=x(()=>{Xk=Symbol.for("effect/SchemaId/DateFromSelf"),Qk=Symbol.for("effect/SchemaId/GreaterThan"),eC=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),tC=Symbol.for("effect/SchemaId/Int"),nC=Symbol.for("effect/SchemaId/MinLength"),rC=Symbol.for("effect/SchemaId/MaxLength"),oC=Symbol.for("effect/SchemaId/MinItems")});class za{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 Ni{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 Td{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 xC{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class SC{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class _C{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class bC{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class wC{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class TC{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class OC{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class kC{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class AC{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class PC{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class MC{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return qn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class Wa{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 jc{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(Yk)}toString(){return Oe(sr(this),()=>a2(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 Ja{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,FC(e))this.parameter=e;else throw Error(Gk)}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(Fy(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=mx(t[i].parameter);if(Rd(a)){if(o.string)throw Error(My("string"));o.string=!0}else if(IC(a)){if(o.symbol)throw Error(My("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Oe(sr(this),()=>s2(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)=>kd(e)?new Ut(e,t):e.length===1?e[0]:Od;static unify=(e,t)=>Ut.make(u2(LC(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 Cd{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=qc(e)}toString(){return sr(this).pipe(On(()=>kn(Ob(this.f)(),(e)=>sr(e))),Oe(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=Dy.get(e);if(t)return t;return Dy.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:He(this.annotations)},Dy.set(e,t),t}}class Vc{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return Hc(this).pipe(Oe(()=>Je($C(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Bc(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:He(this.annotations)}}}class lx{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 ux{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class px{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(Ny(o));t[o]=!0;let i=r.to;if(n[i])throw Error(Ny(i));n[i]=!0}}}function Sn(e,t){let n=!1,r=ii(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 h2(e){return Je(ex(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Zn(n)}>`).join("")})}var sC,Uy,cC,Hy,_d,bd,zt,wd,Wr,$y,jy,Vy,By,Ky,zy,lC,Wy,Jy,Gy,Yy,Zy,Xy,Qy,Pt,ex,uC,pC,tx,nx,Hc,rx,dC,fC,mC,hC,gC,ox,Qq,ix=(e)=>Cb(Qq(e),(t)=>t===!0),ax,e2,t2=(e)=>On(e2(e),()=>Hc(e)),$c=(e)=>(t)=>t._tag===e,vd,yC,Ed,n2,Od,sx,vC,EC,Rd,RC,CC,r2,o2,IC,i2,Fo,NC=(e)=>e.map((t)=>t.type),a2=(e)=>{let t=e.elements.map(String).join(", ");return Ib(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,FC=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return FC(e.from)}return!1},aC=(e)=>e.map(String).join("; "),s2=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${aC(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${aC(e.indexSignatures)} }`;else return"{}"},c2,l2,LC=(e)=>qs(e,(t)=>cx(t)?LC(t.types):[t]),u2=(e)=>{let t=c2(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[vC];case"UnknownKeyword":return[sx];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=l2[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},DC=(e,t)=>e.map(t),kd=(e)=>e.length>1,cx,Dy,Bc,Ad,Kc=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[bd];let o={...r,...t},i=ox(e);if(Re(i))o[Xy]=Kc(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},p2="[\\s\\S]*?",d2="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",qC=(e,t)=>{switch(e._tag){case"Literal":return La(String(e.literal));case"StringKeyword":return p2;case"NumberKeyword":return d2;case"TemplateLiteral":return UC(e,t,!1);case"Union":return e.types.map((n)=>qC(n,t)).join("|")}},f2=(e,t,n,r)=>{if(cx(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},UC=(e,t,n)=>{let r="";if(e.head!==""){let o=La(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=qC(o.type,t);if(r+=f2(o.type,i,t,n),o.literal!==""){let a=La(o.literal);r+=t&&n?`(${a})`:a}}return r},HC=(e)=>new RegExp(`^${UC(e,!1,!0)}$`),dx=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new Ja(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(Jk(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(Wk(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},fx=(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},m2,at=(e)=>{switch(e._tag){case"Declaration":{let t=Sn(e.typeParameters,at);return t===e.typeParameters?e:new za(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=NC(e.rest),r=Sn(n,at);return t===e.elements&&r===n?e:new jc(t,r.map((o)=>new Wa(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 Ja(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 Cd(()=>at(e.f()),e.annotations);case"Refinement":{let t=at(e.from);return t===e.from?e:new Vc(t,e.filter,e.annotations)}case"Transformation":{let t=m2(e);return at(t!==void 0?Kc(e.to,t):e.to)}}return e},qy=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return qy(e.from);case"Suspend":return qy(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 za(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=NC(e.rest),o=Sn(r,(i)=>ar(i,t));return n===e.elements&&o===r?e:new jc(n,o.map((i)=>new Wa(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 Ja(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=t2(e);if(Re(r)){let o=t?"Bound":"";n={[ax]:`${r.value}Encoded${o}`}}return new Cd(()=>ar(e.f(),t),n)}case"Refinement":{let n=ar(e.from,t);if(t){if(n===e.from)return e;if(qy(e.from)===void 0&&ix(e))return new Vc(n,e.filter,e.annotations);return n}else return n}case"Transformation":return ar(e.from,t)}return e},Pd=(e)=>ar(e,!1),He=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},mx=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return mx(e.from)}},qn=(e)=>Oe(sr(e),()=>e._tag),$C=(e)=>tx(e).pipe(On(()=>rx(e)),On(()=>nx(e)),Rn((t)=>t+h2(e))),sr=(e)=>On(Hc(e),()=>$C(e));var hx=x(()=>{Be();j();Ve();Ly();Uc();vc();Ge();cu();xe();vg();sC=Symbol.for("effect/annotation/TypeConstructor"),Uy=Symbol.for("effect/annotation/Brand"),cC=Symbol.for("effect/annotation/SchemaId"),Hy=Symbol.for("effect/annotation/Message"),_d=Symbol.for("effect/annotation/MissingMessage"),bd=Symbol.for("effect/annotation/Identifier"),zt=Symbol.for("effect/annotation/Title"),wd=Symbol.for("effect/annotation/AutoTitle"),Wr=Symbol.for("effect/annotation/Description"),$y=Symbol.for("effect/annotation/Examples"),jy=Symbol.for("effect/annotation/Default"),Vy=Symbol.for("effect/annotation/JSONSchema"),By=Symbol.for("effect/annotation/Arbitrary"),Ky=Symbol.for("effect/annotation/Pretty"),zy=Symbol.for("effect/annotation/Equivalence"),lC=Symbol.for("effect/annotation/Documentation"),Wy=Symbol.for("effect/annotation/Concurrency"),Jy=Symbol.for("effect/annotation/Batching"),Gy=Symbol.for("effect/annotation/ParseIssueTitle"),Yy=Symbol.for("effect/annotation/ParseOptions"),Zy=Symbol.for("effect/annotation/DecodingFallback"),Xy=Symbol.for("effect/annotation/Surrogate"),Qy=Symbol.for("effect/annotation/StableFilter"),Pt=d(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?F(e.annotations[t]):A()),ex=Pt(Uy),uC=Pt(Hy),pC=Pt(_d),tx=Pt(zt),nx=Pt(wd),Hc=Pt(bd),rx=Pt(Wr),dC=Pt(Wy),fC=Pt(Jy),mC=Pt(Gy),hC=Pt(Yy),gC=Pt(Zy),ox=Pt(Xy),Qq=Pt(Qy),ax=Symbol.for("effect/annotation/JSONIdentifier"),e2=Pt(ax);vd=$c("Literal"),yC=new Ni(null);Ed=new xC({[zt]:"undefined"});n2=new SC({[zt]:"void"});Od=new _C({[zt]:"never"});sx=new bC({[zt]:"unknown"});vC=new wC({[zt]:"any"});EC=new TC({[zt]:"string",[Wr]:"a string"}),Rd=$c("StringKeyword");RC=new OC({[zt]:"number",[Wr]:"a number"});CC=new kC({[zt]:"boolean",[Wr]:"a boolean"});r2=new AC({[zt]:"bigint",[Wr]:"a bigint"});o2=new PC({[zt]:"symbol",[Wr]:"a symbol"}),IC=$c("SymbolKeyword");i2=new MC({[zt]:"object",[Wr]:"an object in the TypeScript meaning, i.e. the `object` type"});Fo=class Fo extends Wa{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)}}};c2=Ar(su(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})),l2={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};cx=$c("Union"),Dy=V(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Bc=$c("Refinement"),Ad={};m2=fx([$y,jy,Vy,By,Ky,zy])});class ct{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class xx{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class Ga{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 Md{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Nd{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 Sx{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function Un(e){return e.sort(_2).map((t)=>t[1])}function O2(e){return rx(e).pipe(On(()=>tx(e)),On(()=>nx(e)),On(()=>Hc(e)),Oe(()=>`{ ${e.from} | filter }`))}function R2(e){if(e.message!==void 0)return e.message;return`Expected ${Bc(e.ast)?O2(e.ast):String(e.ast)}, actual ${Zn(e.actual)}`}var VC,zC,bx=(e)=>new zC({issue:e}),WC,JC,Jt,Jr,Hn,Fd,GC,YC=(e,t)=>{if(t===void 0||Qt(t))return e;if(e===void 0)return t;return{...e,...t}},ZC=(e,t,n)=>{let r=It(e,t);return(o,i)=>r(o,YC(n,i))},g2=(e,t,n)=>{let r=ZC(e,t,n);return(o,i)=>fm(r(o,i),bx)},XC=(e,t)=>ZC(e.ast,!0,t),Ld=(e,t)=>g2(at(e.ast),!0,t),y2,x2,It=(e,t)=>{let n=t?y2:x2,r=n.get(e);if(r)return r;let o=S2(e,t),i=hC(e),a=Re(i)?(l,u)=>o(l,YC(u,i.value)):o,s=gC(e),c=t&&Re(s)?(l,u)=>Wc(GC(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},gx=(e)=>Bt(dC(e)),yx=(e)=>Bt(fC(e)),S2=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=It(e.from,!0);return(r,o)=>{o=o??Ad;let i=o?.errors==="all",a=Jr(GC(n(r,o),(s)=>{let c=new Md(e,r,"From",s);if(i&&ix(e)&&rA(s))return Je(e.filter(r,o,e),{onNone:()=>W(c),onSome:(l)=>W(new $e(e,r,[c,new Md(e,r,"Predicate",l)]))});return W(c)}),(s)=>Je(e.filter(s,o,e),{onNone:()=>Q(s),onSome:(c)=>W(new Md(e,r,"Predicate",c))}));return Wc(a,e,r,o)}}else{let n=It(at(e),!0),r=It(eA(e.from),!1);return(o,i)=>Wc(Jr(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=b2(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)=>Wc(Jr(Fd(r(i,a),(s)=>new Nd(e,i,t?"Encoded":"Type",s)),(s)=>Jr(Fd(n(s,a??Ad,e,i),(c)=>new Nd(e,i,"Transformation",c)),(c)=>Fd(o(c,a),(l)=>new Nd(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)=>Wc(n(r,o??Ad,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,Y_);case"NeverKeyword":return Wt(e,Z_);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,Yo);case"BigIntKeyword":return Wt(e,ro);case"SymbolKeyword":return Wt(e,Zo);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)=>Rd(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=HC(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=gx(e),c=yx(e);return(l,u)=>{if(!_m(l))return W(new _n(e,l));let p=u?.errors==="all",f=[],h=0,m=[],v=l.length;for(let P=v;P<=i-1;P++){let z=new ct(P,l,new Ga(o[P-v]));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<=v-1;P++){let z=new ct(P,l,new xx(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(v<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,Un(m)))}m.push([h++,z.right])}else{let X=h++,U=S;if(!y)y=[];y.push(({es:te,output:L})=>Dn(Mi(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,Un(L)))}return L.push([X,se.right]),an}))}}if(ve(r)){let[P,...z]=r;for(;S<v-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,Un(m)))}else m.push([h++,X.right]);else{let U=h++,te=S;if(!y)y=[];y.push(({es:L,output:se})=>Dn(Mi(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,Un(se)))}else return se.push([U,ce.right]),an}))}}for(let X=0;X<z.length;X++){let U=S+X;if(v<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,Un(m)))}m.push([h++,te.right])}else{let L=h++;if(!y)y=[];y.push(({es:se,output:ce})=>Dn(Mi(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,Un(ce)))}return ce.push([L,ee.right]),an}))}}}}let E=({es:P,output:z})=>co(P)?W(new $e(e,l,Un(P),Un(z))):Q(Un(z));if(y&&y.length>0){let P=y;return Dc(()=>{let z={es:la(f),output:la(m)};return Dn(Lc(P,(X)=>X(z),{concurrency:s,batching:c,discard:!0}),()=>E(z))})}return E({output:m,es:f})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Wt(e,X_);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)=>Zo(u)?new Td(u):new Ni(u)))),s=It(a,t),c=gx(e),l=yx(e);return(u,p)=>{if(!Yf(u))return W(new _n(e,u));let f=p?.errors==="all",h=[],m=0,v=p?.onExcessProperty==="error",S=p?.onExcessProperty==="preserve",y={},E;if(v||S){E=Reflect.ownKeys(u);for(let U of E){let te=s(U,p);if(Jt(te)&&Ee(te))if(v){let L=new ct(U,u,new xx(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 Ga(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 Ga(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})=>Dn(Mi(ee),(De)=>{if(Ee(De)){let je=new ct(vt,u,se?De.left:new Ga(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=Py(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})=>Dn(Mi(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,Un(U),te));if(p?.propertyOrder==="original"){let L=E||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 Dc(()=>{let te={es:la(h),output:Object.assign({},y)};return Dn(Lc(U,(L)=>L(te),{concurrency:c,batching:l,discard:!0}),()=>X(te))})}return X({es:h,output:y})}}case"Union":{let n=QC(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=gx(e)??1,c=yx(e);return(l,u)=>{let p=[],f=0,h=[];if(o>0)if(Os(l))for(let S=0;S<o;S++){let y=r[S],E=n.keys[y].buckets;if(Object.prototype.hasOwnProperty.call(l,y)){let P=String(l[y]);if(Object.prototype.hasOwnProperty.call(E,P))h=h.concat(E[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 Ga(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],E=a.get(y)(l,u);if(Jt(E)&&(!m||m.length===0))if(Ot(E))return E;else p.push([f++,E.left]);else{let P=f++;if(!m)m=[];m.push((z)=>Dc(()=>{if("finalResult"in z)return an;else return Dn(Mi(E),(X)=>{if(Ot(X))z.finalResult=X;else z.es.push([P,X.left]);return an})}))}}let v=(S)=>co(S)?S.length===1&&S[0][1]._tag==="Type"?W(S[0][1]):W(new $e(e,l,Un(S))):W(new _n(e,l));if(m&&m.length>0){let S=m;return Dc(()=>{let y={es:la(p)};return Dn(Lc(S,(E)=>E(y),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in y)return y.finalResult;return v(y.es)})})}return v(p)}}case"Suspend":{let n=qc(()=>It(e.f(),t));return(r,o)=>n()(r,o)}}},Wt=(e,t)=>(n)=>t(n)?Q(n):W(new _n(e,n)),zc=(e,t)=>{switch(e._tag){case"Declaration":{let n=ox(e);if(Re(n))return zc(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?Pd(o.type):at(o.type);if(vd(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?Pd(o.type):at(o.type);if(vd(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return zc(e.from,t);case"Suspend":return zc(e.f(),t);case"Transformation":return zc(t?e.from:e.to,t)}return[]},QC=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=zc(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}},eA=(e)=>Bc(e)?eA(e.from):e,Wc=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(Jt(e))return e;let o=new Rc,i=$k(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(UO(a))return Q(a.value);let s=a.cause;if(PT(s))return W(s.error);return W(new Sx(t,n,IT(s)))}return W(new Sx(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},_2=([e],[t])=>e>t?1:e<t?-1:0,b2=(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=Hn(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}),Jc,w2=(e)=>e.value+tA(`
34
+ `,e.forest),tA=(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+=tA(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},v2=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},T2=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},nA=(e)=>("ast"in e)?F(e.ast):A(),_x,E2=(e)=>nA(e).pipe(kn(uC),Je({onNone:()=>_x,onSome:(t)=>{let n=t(e);if(gt(n))return Q({message:n,override:!1});if(qk(n))return yd(n,(r)=>({message:r,override:!1}));if(gt(n.message))return Q({message:n.message,override:n.override});return yd(n.message,(r)=>({message:r,override:n.override}))}})),wx=(e)=>(t)=>t._tag===e,rA,BC,KC,Gc=(e)=>Jr(E2(e),(t)=>{if(t!==void 0)return!t.override&&(rA(e)||BC(e)&&e.kind==="From"||KC(e)&&e.kind!=="Transformation")?KC(e)||BC(e)?Gc(e.issue):_x:Q(t.message);return _x}),oA=(e)=>nA(e).pipe(kn(mC),Rb((t)=>t(e)),Bt),k2=(e)=>Hn(Gc(e),(t)=>t??oA(e)??R2(e)),Id=(e)=>oA(e)??String(e.ast),C2=(e)=>e.message??"is forbidden",A2=(e)=>e.message??"is unexpected",P2=(e)=>{let t=pC(e.ast);if(Re(t)){let n=t.value();return gt(n)?Q(n):n}return Q(e.message??"is missing")},Ya=(e)=>{switch(e._tag){case"Type":return Hn(k2(e),Ht);case"Forbidden":return Q(Ht(Id(e),[Ht(C2(e))]));case"Unexpected":return Q(Ht(A2(e)));case"Missing":return Hn(P2(e),Ht);case"Transformation":return Jr(Gc(e),(t)=>{if(t!==void 0)return Q(Ht(t));return Hn(Ya(e.issue),(n)=>Ht(Id(e),[Ht(v2(e.kind),[n])]))});case"Refinement":return Jr(Gc(e),(t)=>{if(t!==void 0)return Q(Ht(t));return Hn(Ya(e.issue),(n)=>Ht(Id(e),[Ht(T2(e.kind),[n])]))});case"Pointer":return Hn(Ya(e.issue),(t)=>Ht(xd(e.path),[t]));case"Composite":return Jr(Gc(e),(t)=>{if(t!==void 0)return Q(Ht(t));let n=Id(e);return Iy(e.issues)?Hn(Lc(e.issues,Ya),(r)=>Ht(n,r)):Hn(Ya(e.issues),(r)=>Ht(n,[r]))})}};var iA=x(()=>{Be();MT();vE();Vk();tn();HO();j();Ve();Uc();Ge();xe();td();hx();VC=Symbol.for("effect/Schema/ParseErrorTypeId");zC=class zC extends wE("ParseError"){[VC]=VC;get message(){return this.toString()}toString(){return Jc.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[ne](){return this.toJSON()}};WC=Q,JC=W,Jt=dm,Jr=d(2,(e,t)=>Jt(e)?Ds(e,{onLeft:W,onRight:t}):Dn(e,t)),Hn=d(2,(e,t)=>Jt(e)?_b(e,t):yd(e,t)),Fd=d(2,(e,t)=>Jt(e)?au(e,t):Hk(e,t)),GC=d(2,(e,t)=>Jt(e)?Ds(e,{onLeft:t,onRight:Q}):Uk(e,t)),y2=V(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),x2=V(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);Jc={formatIssue:(e)=>Hn(Ya(e),w2),formatIssueSync:(e)=>{let t=Jc.formatIssue(e);return Jt(t)?wb(t):jk(t)},formatError:(e)=>Jc.formatIssue(e.issue),formatErrorSync:(e)=>Jc.formatIssueSync(e.issue)},_x=Q(void 0),rA=wx("Composite"),BC=wx("Refinement"),KC=wx("Transformation")});var aA,sA;var cA=x(()=>{j();xe();aA=d((e)=>qt(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),sA=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{[Yc]=lA;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[Yc]=lA}}function N2(e){return kd(e)?Ut.make(DC(e,(t)=>new Ni(t))):new Ni(e[0])}function yA(e,t=N2(e)){return class extends _t(t){static annotations(r){return yA(this.literals,lr(this.ast,r))}static literals=[...e]}}function w(...e){return ve(e)?yA(e):Ex}function Tx(e,t){return class extends _t(t){static annotations(r){return Tx(this.typeParameters,lr(this.ast,r))}static typeParameters=[...e]}}function SA(e,t=D2(e)){return class extends _t(t){static annotations(r){return SA(this.members,lr(this.ast,r))}static members=[...e]}}function Se(...e){return kd(e)?SA(e):ve(e)?e[0]:Ex}function Dd(e,t,n=U2(e,t)){return class extends _t(n){static annotations(o){return Dd(this.elements,this.rest,lr(this.ast,o))}static elements=[...e];static rest=[...t]}}function _A(...e){return Array.isArray(e[0])?Dd(e[0],e.slice(1)):Dd(e,[])}function bA(e,t){return class extends Dd([],[e],t){static annotations(r){return bA(this.value,lr(this.ast,r))}static value=e}}class vA{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<${vx(this.to.isOptional)}, ${this.to.type}, ${H2(this.from.fromKey)}, ${vx(this.from.isOptional)}, ${this.from.type}>`}}function Ax(e,t,n=j2(e,t)){return class extends _t(n){static annotations(o){return Ax(this.fields,this.records,lr(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=V2(e,{...o});return Nx(i)?a:Ld(this)(a)};static pick(...o){return _(aA(e,...o))}static omit(...o){return _(sA(e,...o))}}}function _(e,...t){return Ax(e,t)}function RA(e,t,n){return class extends Ax({},[{key:e,value:t}],n){static annotations(o){return RA(e,t,lr(this.ast,o))}static key=e;static value=t}}function kA(e,t){return class extends _t(t){static annotations(r){return kA(this.from,lr(this.ast,r))}static make=(r,o)=>Nx(o)?r:Ld(this)(r);static from=e}}function CA(e,t,n){return class extends _t(n){static annotations(o){return CA(this.from,this.filter,lr(this.ast,o))}static[B2]=e;static from=e;static filter=t;static make=(o,i)=>Nx(i)?o:Ld(this)(o)}}function Ze(e,t){return(n)=>{function r(i,a,s){return K2(e(i,a,s),s,i)}let o=new Vc(n.ast,r,Fi(t));return CA(n,r,o)}}function Nx(e){return Yo(e)?e:e?.disableValidation??!1}var Yc,lA,uA,Fi=(e)=>{if(!e)return{};let t={...e};for(let n in uA)if(n in e){let r=uA[n];t[r]=e[n],delete t[n]}return t},lr=(e,t)=>Kc(e,Fi(t)),gA=(e,t)=>{let n=XC(e,t);return(r,o)=>au(n(r,o),bx)},pA=(e)=>C(e,Yc)&&qt(e[Yc]),F2=(e,t,n)=>Tx(e,new za(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(_t)),(...r)=>t.encode(...r.map(_t)),Fi(n))),L2=(e,t)=>{let n=()=>(o,i,a)=>e(o)?WC(o):JC(new _n(a,o));return Tx([],new za([],n,n,Fi(t)))},H=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return F2(n,r,o)}let e=arguments[0],t=arguments[1];return L2(e,t)},xA,lt,Ex,Ox,k,Gt,J,D2=(e)=>Ut.make(e.map((t)=>t.ast)),q2=(e)=>Se(e,xA),U2=(e,t)=>new jc(e.map((n)=>pA(n)?new Fo(n.ast,!1):n.ast),t.map((n)=>pA(n)?new Wa(n.ast):n.ast),!0),q=(e)=>bA(e),vx=(e)=>e?'"?:"':'":"',Rx,wA,H2=(e)=>{if(e===void 0)return"never";if(gt(e))return JSON.stringify(e);return String(e)},TA=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new Rx(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new vA(e.from,new wA(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},EA,OA=(e)=>C(e,EA),kx,Cx,b=(e)=>{let t=e.ast===Ed||e.ast===Od?Ed:q2(e).ast;return new Cx(new Rx(t,!0,!0,{},void 0),e)},$2,j2=(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(OA(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,$2(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 ux(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(ve(s)){let c=[],l=[];for(let u of t){let{indexSignatures:p,propertySignatures:f}=dx(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 Ja(h.parameter,at(h.type),h.isReadonly))})}return new lx(new cr(i,c,{[wd]:"Struct (Encoded side)"}),new cr(a,l,{[wd]:"Struct (Type side)"}),new px(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=dx(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new cr(r,o)},V2=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&OA(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},qd=(e)=>RA(e.key,e.value),Zc=(e,t)=>(n)=>{let r=Je(ex(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=Kc(n.ast,Fi({[Uy]:r,...t}));return kA(n,o)},B2,dA=(e,t,n)=>{if(Yo(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(ve(e.path)?new ct(e.path,n,r):r)}return A()},K2=(e,t,n)=>{if(Kk(e))return dA(e,t,n);if(ve(e)){let r=uu(e,(o)=>dA(o,t,n));if(ve(r))return F(r.length===1?r[0]:new $e(t,n,r))}return A()},z2,Px=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length<=e,{schemaId:z2,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),W2,Za=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length>=e,{schemaId:W2,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),fA,le=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ze((o)=>(e.lastIndex=0,e.test(o)),{schemaId:fA,[fA]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},J2,mA,G2,Y2,Ix=(e,t)=>(n)=>n.pipe(Ze((r)=>r>e,{schemaId:Y2,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),Z2,AA=(e,t)=>(n)=>n.pipe(Ze((r)=>r>=e,{schemaId:Z2,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),X2,Ud=(e)=>(t)=>t.pipe(Ze((n)=>Number.isSafeInteger(n),{schemaId:X2,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),Mx=(e)=>Ix(0,{title:"positive",...e}),Hd,Q2,Xc=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(zk(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ze((o)=>o.length>=r,{schemaId:Q2,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[Qy]:!0,...t}))},hA,eU;var bt=x(()=>{Be();tn();Ts();Ly();iC();Uc();Ge();iA();we();xe();hx();cA();Yc=Symbol.for("effect/Schema");lA={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},uA={typeConstructor:sC,schemaId:cC,message:Hy,missingMessage:_d,identifier:bd,title:zt,description:Wr,examples:$y,default:jy,documentation:lC,jsonSchema:Vy,arbitrary:By,pretty:Ky,equivalence:zy,concurrency:Wy,batching:Jy,parseIssueTitle:Gy,parseOptions:Yy,decodingFallback:Zy};xA=class xA extends _t(Ed){};lt=class lt extends _t(yC){};Ex=class Ex extends _t(Od){};Ox=class Ox extends _t(sx){};k=class k extends _t(EC){};Gt=class Gt extends _t(RC){};J=class J extends _t(CC){};Rx=class Rx 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=vx(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};wA=class wA extends Fo{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};EA=Symbol.for("effect/PropertySignature");kx=class kx{ast;[Yc];[EA]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return T(this,arguments)}annotations(e){return new kx(TA(this.ast,Fi(e)))}toString(){return String(this.ast)}};Cx=class Cx extends kx{from;constructor(e,t){super(e);this.from=t}annotations(e){return new Cx(TA(this.ast,Fi(e)),this.from)}};$2=fx([_d]);B2=Symbol.for("effect/SchemaId/Refine");z2=rC,W2=nC,fA=Symbol.for("effect/SchemaId/Pattern"),J2=Symbol.for("effect/SchemaId/UUID"),mA=/^[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;G2=class G2 extends k.pipe(le(mA,{schemaId:J2,identifier:"UUID",jsonSchema:{format:"uuid",pattern:mA.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};Y2=Qk,Z2=eC,X2=tC;Hd=class Hd extends Gt.pipe(Ud({identifier:"Int"})){};Q2=oC,hA=Xk;eU=class eU extends H(Yl,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:hA,[hA]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>J_}){}});function bn(e,t){return gA(e,tU)(t)}var tU;var Xa=x(()=>{bt();tU={onExcessProperty:"error"}});function Lx(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(!MA(r)||!IA(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function $n(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);return MA(n)&&IA(r)?`${n}@openai-curated`:void 0}function IA(e){return PA.includes(e)}function MA(e){return $d.includes(e)}function Dx(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 el(e,t=[]){let n=[],r=new Set;for(let o of NA){if(!e[o])continue;for(let i of Qc[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 Fx,nU,rU,oU,PA,$d,Gr,iU,Qc,NA,ur;var qx=x(()=>{bt();Fx=w("computer_use","work","frontend","security"),nU=w("computer_use","work","frontend","security"),rU=w("installed","disabled","missing","uncertain"),oU=w("healthy","missing","disabled","uncertain"),PA=Object.freeze(["openai-curated","openai-curated-remote"]),$d=Object.freeze(["build-web-apps","codex-security"]);Gr=Object.freeze({coding:!0,computer_use:!1,work:!1,frontend:!0,security:!0}),iU={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"}},Qc=Object.freeze(iU),NA=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:w(e),label:k,requiresRootApproval:J})}function FA(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 LA(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var DA,aU,sU,Ux,cU,qA,lU,uU,pU;var UA=x(()=>{bt();DA=w("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"),aU=_({identifier:DA,label:k,requiresRootApproval:J});sU=_({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")}),Ux={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(Ux);cU=w("never","root"),qA=Object.values(Ux);lU=qA.filter((e)=>!e.requiresRootApproval),uU=qA.filter((e)=>e.requiresRootApproval),pU=Object.freeze({noRootApproval:`${LA(FA(lU))} actions do not require Root approval.`,rootApproval:`${LA(FA(uU))} require Root approval.`})});function jd(e){let t=bn(dU,e);if(Ee(t))return Go(xs("sha256 digest",t.left));return Qi(t.right)}var jn,Hx,eY,tY,nY,dU,fU,mU,hU,gU;var Vd=x(()=>{tn();bt();ea();Xa();jn=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Hx=k.pipe(le(/^[0-9a-f]{64}$/u)),eY=jn.pipe(Zc("RunId")),tY=jn.pipe(Zc("ProjectId")),nY=jn.pipe(Zc("TrustId")),dU=Hx.pipe(Zc("Sha256Digest"));fU=_({run_id:jn,objective_lineage:jn,parent_run_id:b(Se(jn,lt))}),mU=_({project_id:jn,trust_id:jn,trust_digest:Hx}),hU=_({project_id:jn,project_digest:Hx}),gU=k.pipe(le(/^state-[0-9]+\.[0-9]+$/u))});function $x(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 jA(e){return typeof e==="string"&&SU.has(e)}function bU(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!jA(t)||typeof n!=="string")return!1;return tl.get(t)?.tasks.some((r)=>r.name===n)===!0}function zd(e,t){return typeof t==="string"&&tl.get(e)?.tasks.some((n)=>n.name===t)===!0}function VA(e){return typeof e==="string"&&_U.has(e)}function Kx(e){let t=`${e.role}.${e.task}`;if(!Vx.has(t))throw Error("Unknown native specialist agent type.");return t}function zx(e){let t=tl.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.instruction}function Wx(e){let t=tl.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function KA(e){let t=tl.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function Jx(e){let n=KA(e.role).tasks.find((o)=>o.name===e.task);if(n===void 0)throw Error("Unknown specialist task policy.");let r=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":n.permissions.network?"current_sources":"disabled";return Object.freeze({network:n.permissions.network,filesystem:n.permissions.filesystem,sourceMutation:n.permissions.sourceMutation,networkScope:r})}var Do,HA,Bd,Li,yU,Kd="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.",Lo="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",xU,wn,tl,SU,jx,_U,$A,Vx,Bx,wU,vU,TU,EU,nl,Di,BA,qo,OU,zA,RU,kU,qi;var rl=x(()=>{bt();Do=w("low","default","high"),HA=w("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),Bd=Se(Do,HA);Li=w("standard","fast","fast-all"),yU=w("low","medium","high","xhigh","max"),xU=w("read-only","workspace-write"),wn=[{role:"Explorer",tasks:[{name:"lookup",description:"Repository fact lookup specialist.",instruction:`Locate the exact requested repository fact. ${Lo}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:`Trace the complete in-scope execution or reference path. ${Lo}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS, lifecycle, and decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:`Locate the exact requested authoritative external fact. ${Lo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:`Synthesize the assigned current sources with citations. ${Lo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS, lifecycle, and decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply only deterministic, already-decided edits.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Implement and verify the bounded behavior seam.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Integrate the decided seams and verify them together.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Observe the assigned post-VCS external gate at the supplied exact ref or SHA. ${Lo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`When independent proof is useful, run the smallest relevant local checks for the delegated seam, classify failures, and report evidence without redesigning the solution or replacing code review. ${Lo}`,permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Establish the failure reproducibly, identify the evidence-backed root cause, make the narrow bounded repair, and prove the regression is gone; return material redesigns to Root.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-assignment",authority:"Concrete task permissions govern observation, proof writes, or source repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",tasks:[{name:"plan",description:"Adversarial implementation-plan review specialist.",instruction:`Review the complete plan to a fixed point. ${Lo}`,permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}},{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. The acceptance contract covers correctness, safety, compatibility, mergeability, clarity, simplicity, cohesion, idiomaticity, appropriate abstraction, accidental complexity, duplication, unnecessary files or file splitting, speculative abstraction, test quality, and generated-artifact hygiene. Prefer simple cohesive code over clever or over-engineered code.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Review and repair the produced artifact to a fixed point.",permissions:{network:!1,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-review",authority:"Concrete task permissions govern observational review or bounded repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!1,filesystem:"read-only",sourceMutation:!1}}];Yn(wn);tl=new Map(wn.map((e)=>[e.role,e])),SU=new Set(wn.map((e)=>e.role)),jx=wn.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),_U=new Set(jx),$A=jx.map((e)=>e.replace(":",".")),Vx=new Set($A);Bx=H(jA),wU=H((e)=>zd("Explorer",e)),vU=H((e)=>zd("Librarian",e)),TU=H((e)=>zd("Worker",e)),EU=H((e)=>zd("Reviewer",e)),nl=H(bU),Di=Object.freeze(jx.filter((e)=>VA(e))),BA=H(VA),qo=Object.freeze($A.filter((e)=>Vx.has(e))),OU=H((e)=>typeof e==="string"&&Vx.has(e));zA=_({profile:Do,service_tier:b(Li)}),RU=w("git_vcs","computer_use"),kU=w("delegated","root_direct","unavailable"),qi=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:Kd,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 Gx(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(Gx(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)}:${Gx(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function dr(e){return Gx(e,"$",new Set)}function Yr(e){return new TextEncoder().encode(dr(e))}function WA(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 AU(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",PU(WA(e,t)));return AU(new Uint8Array(r))}function PU(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var Yx=x(()=>{ea();Vd()});function YA(e){try{return dr(e)!==void 0}catch{return!1}}function Jd(e){let t=bn(rP,e);if(Ee(t))return Go(xs("CLI envelope",t.left));return Qi(t.right)}var JA,GA,ZA,IU,MU,Zx="holycodex-specialist-outcome-2",Yt,ol,NU,FU,LU,DU,qU,UU,Wd,HU,$U,jU,VU,BU,XA,QA,eP,KU,tP,nP,rP;var oP=x(()=>{tn();bt();Yx();qx();ea();Vd();rl();Xa();JA=w("blocked","completed","failed","partial"),GA=Se(w("high","max","xhigh"),lt);ZA=H((e)=>YA(e)),IU=H((e)=>zf(e)&&!Array.isArray(e)&&YA(e)),MU=_({blocked:J,changed_files:q(k),confidence:Gt,context_owner:Se(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:JA,suggested_followup:Se(k,lt),suggested_luna_effort:GA,suggested_specialist:Se(Bx,lt),verification:q(k),verification_passed:J}),Yt=k.pipe(Za(1)),ol={protocol_version:w(Zx),route:nl,evidence:q(Yt)},NU=_(ol),FU=_({...ol,status:w("completed"),summary:Yt}),LU=_({...ol,status:w("blocked"),reason:Yt,needs_root_decision:J}),DU=_({...ol,status:w("partial"),summary:Yt,completed:q(Yt),remaining:q(Yt),needs_root_decision:J}),qU=_({...ol,status:w("failed"),error:Yt}),UU=Se(FU,LU,DU,qU),Wd={protocol_version:w(Zx),capability:Fx,route:Se(nl,lt),evidence:q(Yt),data:ZA},HU=_({...Wd,status:w("completed"),summary:Yt}),$U=_({...Wd,status:w("blocked"),reason:Yt,needs_root_decision:J}),jU=_({...Wd,status:w("partial"),summary:Yt,completed:q(Yt),remaining:q(Yt),needs_root_decision:J}),VU=_({...Wd,status:w("failed"),error:Yt}),BU=Se(HU,$U,jU,VU),XA=q(k),QA=k.pipe(le(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),eP=w(vr),KU=_({code:jn,message:k,details:IU}),tP=_({schema_version:eP,ok:w(!0),command:QA,data:ZA,warnings:XA}),nP=_({schema_version:eP,ok:w(!1),command:QA,error:KU,warnings:XA}),rP=Se(tP,nP)});function zU(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:aP,effort:n}}function GU(e){let t=JU.get(e);if(t===void 0)throw new We("catalog_invalid","A profile has no route effort policy.",{profile:e});return wn.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 zU(n.role,r.name,i)}))}function Xx(e){return{name:e.name,root:{model:"gpt-6-astra",effort:e.effort},specialistModel:"gpt-5.6-luna",defaultServiceTier:"standard",routes:GU(e.name)}}function YU(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!==Di.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)||!WU.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!==Di.length)throw new We("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<Di.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||iP[i.effort]<r)throw new We("catalog_invalid","Profile route effort is not monotonic.",{route:Di[n]??"unknown"});r=iP[i.effort]}}}function fr(e){let t=bn(Do,e);if(Ee(t))return Go(new We("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=cP.get(t.right);if(!n)return Go(new We("invalid_profile","Unknown profile selection.",{profile:t.right}));return Qi(n)}var aP="gpt-5.6-luna",WU,iP,Qx,JU,eS,sP,cP,ZU;var lP=x(()=>{tn();ea();rl();Xa();WU=new Set(Di),iP={low:0,medium:1,high:2,xhigh:3,max:4},Qx=[{profile:"low",rationale:"The low profile keeps bounded specialist work economical.",efforts:{"Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"high","Worker:implementation":"high","Worker:integration":"max","Worker:operations":"high","Worker:validation":"medium","Worker:debugging":"high","Reviewer:plan":"high","Reviewer:code":"max","Reviewer:artifact":"high"}},{profile:"default",rationale:"The default profile is the recommended balanced route.",efforts:{"Explorer:lookup":"medium","Explorer:trace":"xhigh","Librarian:lookup":"medium","Librarian:research":"xhigh","Worker:mechanical":"high","Worker:implementation":"xhigh","Worker:integration":"max","Worker:operations":"high","Worker:validation":"high","Worker:debugging":"xhigh","Reviewer:plan":"xhigh","Reviewer:code":"max","Reviewer:artifact":"xhigh"}},{profile:"high",rationale:"The high profile maximizes specialist reasoning where specified.",efforts:{"Explorer:lookup":"medium","Explorer:trace":"max","Librarian:lookup":"medium","Librarian:research":"max","Worker:mechanical":"xhigh","Worker:implementation":"max","Worker:integration":"max","Worker:operations":"xhigh","Worker:validation":"xhigh","Worker:debugging":"max","Reviewer:plan":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];Yn(Qx);JU=new Map(Qx.map((e)=>[e.profile,e]));eS=[Xx({name:"low",effort:"low"}),Xx({name:"default",effort:"medium"}),Xx({name:"high",effort:"high"})];YU(eS);Yn(eS);sP=eS,cP=new Map,ZU=new Map;for(let e of sP){cP.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);ZU.set(e.name,t)}});import{execFile as XU}from"child_process";import{promisify as QU}from"util";var pP="holycodex-intent-1",dP="holycodex-plan-1",fP="holycodex-assignment-1",Gd="toon-4",Z,Uo,tS,mP,il,Vn,Xe,OY,nS,Ui,rS,oS,eH,uP,tH,nH,iS,hP,gP,rH,RY,oH,iH,aH,sH,cH,lH,uH,kY;var yP=x(()=>{bt();rl();Xa();Z=k.pipe(Ze((e)=>e.trim().length>0)),Uo=k.pipe(le(/^[a-z0-9][a-z0-9-]{0,95}$/u)),tS=k.pipe(le(/^[a-f0-9]{64}$/u)),mP=k.pipe(le(/^[a-f0-9]{40}$/u)),il=Hd.pipe(AA(1)),Vn=k.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),Xe=q(Z),OY=_({pid:Hd.pipe(Ix(0)),token:Z}),nS=_({role:w("Explorer","Librarian","Worker","Reviewer"),task:Z}).pipe(Ze((e)=>wn.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),Ui=_({kind:w("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:Z,result:b(w("passed","failed","observed","unknown"))}),rS=_({root:Z,git_common_dir:Z,initial_head:Z,expected_head:Z,expected_changes:Xe,expected_status_digest:tS,integrated_commit:b(mP),updated_at:Vn}),oS=w("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),eH=w("scoping","ready","executing","verifying","reviewing"),uP=_({required:J,status:w("not_required","missing","passed","failed","accepted","rejected"),evidence:q(Ui)}),tH=_({schema_version:w(pP),toon_compatibility:w(Gd),id:Uo,slug:Uo,title:Z,goal:Z,acceptance_criteria:Xe,state:oS,revision:il,plan_required:J,active_plan_revision:b(il),active_plan_digest:b(tS),blockers:Xe,resume_state:b(eH),verification:uP,review:uP,acceptance_met:J,root_readiness:J,evidence:q(Ui),baseline:rS,created_at:Vn,updated_at:Vn}),nH=_({schema_version:w(dP),toon_compatibility:w(Gd),intent_id:Uo,revision:il,predecessor_digest:b(tS),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}),iS=w("completed","blocked","needs_root_input","failed"),hP=w("pending","executing","completed","blocked","needs_root_input","failed"),gP=_({id:Uo,outcome:iS,started_at:Vn,finished_at:Vn,summary:Z,evidence:q(Ui),blocker:b(Z),remaining_risk:Xe}),rH=_({schema_version:w(fP),toon_compatibility:w(Gd),intent_id:Uo,id:Uo,objective:Z,owner:nS,scope:Xe,constraints:Xe,exclusions:Xe,dependencies:Xe,acceptance_criteria:Xe,status:hP,revision:il,invocations:q(gP),active_invocation_id:b(Z),active_started_at:b(Vn),evidence:q(Ui),blocker:b(Z),remaining_risk:Xe,created_at:Vn,updated_at:Vn}),RY=_({schema_version:w("holycodex-intent-0"),id:Uo,slug:Uo,title:Z,goal:Z,acceptance_criteria:Xe,state:oS,revision:il,baseline:rS,created_at:Vn,updated_at:Vn}),oH=_({title:Z,goal:Z,acceptanceCriteria:q(Z).pipe(Xc(1)),planRequired:b(J),verificationRequired:b(J),reviewRequired:b(J)}),iH=_({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))}),aH=_({id:b(Z),objective:Z,owner:nS,scope:q(Z).pipe(Xc(1)),constraints:b(q(Z)),exclusions:b(q(Z)),dependencies:b(q(Z)),acceptanceCriteria:q(Z).pipe(Xc(1))}),sH=_({scope:q(Z).pipe(Xc(1))}),cH=_({commit:mP}),lH=_({invocationId:b(Z),outcome:iS,startedAt:b(Z),summary:Z,evidence:b(q(Ui)),blocker:b(Z),remainingRisk:b(q(Z))}),uH=_({evidence:b(q(Ui)),verification:b(w("passed","failed")),review:b(w("accepted","rejected")),acceptanceMet:b(J),rootReadiness:b(J),clearBlockers:b(J)}),kY=QU(XU)});var ut=x(()=>{W_();ea();Xa();qx();UA();Vd();rl();oP();lP();Yx();yP()});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 vH(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 _P(e){return{ok:!1,error:e}}function bP(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 Hi(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)=>Hi(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]=Hi(o,t+1)}return n}return"[redacted]"}function wP(e){let t=Hi(e);return re(t)?t:{value:t}}function Le(e,t,n){return new K("invalid_external_data",`Invalid ${e}.`,{field:e,received:Hi(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 vP(e,t){try{return Pe(e,t,"value"),!0}catch{return!1}}var cS,ll=1048576,lS=65536,cn,Ho,T5,Xr,wH,K;var mr=x(()=>{ut();tn();bt();cS=vr;cn=H((e)=>Fe(e)),Ho=H((e)=>re(e)&&Fe(e)),T5=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)),wH=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=vH(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var uS,ul,pl,pS,dS,fS,mS="turn/completed";var Qd=x(()=>{uS=["initialize","thread/start","thread/resume","thread/read","thread/list","thread/fork","thread/unsubscribe","turn/start","turn/steer","turn/interrupt","model/list","modelProvider/capabilities/read","config/read","permissionProfile/list"],ul=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],pl=["item/permissions/requestApproval"],pS=["mcpServer/elicitation/request"],dS=["item/tool/call"],fS={method:"initialized"}});function Qa(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)=>Qa(n,t));return re(e)&&Object.values(e).every((n)=>Qa(n,t))}finally{t.delete(e)}}function hr(e){return re(e)&&Qa(e)}function hS(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('"')?EH(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!qo.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 EH(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Le("TOML quoted key",e)}function ye(e,t){if(!hr(e))throw Le("TOML document",e);let n=e;for(let r of hS(t)){if(!hr(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function ef(e){if(Array.isArray(e))return e.map(ef);if(re(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ef(n)]));return e}function tf(e){return ef(e)}function fl(e,t,n){if(!hr(e)||!Qa(n))throw Le("TOML write",{keyPath:t});let r=hS(t),o={...tf(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)]=ef(n),o}function ml(e,t){if(!hr(e))throw Le("TOML document",e);let n=hS(t),r={...tf(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 hl(e){if(typeof e!=="string")return!1;if(EP.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return qo.some((t)=>e===`agents."${t}".config_file`)}function nf(e){return hl(e)}function $o(e){return typeof e==="string"&&RH.test(e)}function gS(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 kH(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function yS(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function xS(e){if(!re(e)||!yS(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return gS(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&af(e.value);case"digest":return kH(e.value);default:return!1}}function TP(e,t){switch(_S(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 CP(e){return re(e)&&e.kind==="absent"?Object.keys(e).length===1:xS(e)}function AP(e){return re(e)&&yS(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&$o(e.schema)&&$o(e.installId)&&nf(e.keyPath)&&CP(e.originalValue)&&xS(e.lastManagedValue)&&TP(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||TP(e.keyPath,e.originalValue))}function es(e){if(!re(e)||!yS(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!$o(e.schema)||!$o(e.installId)||!re(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>nf(t)&&AP(n)&&n.keyPath===t)}function of(e){if(!$o(e.schema)||!$o(e.installId))throw Le("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function af(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 SS(e){if(!af(e))throw Le("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function gl(e,t){let n=SS(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 _S(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 CH(e,t){let n=_S(e);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&af(t);if(n==="digest")return typeof t==="string";return typeof t==="string"&&gS(t)}async function gr(e,t){if(!nf(e)||!Qa(t))throw Le("managed config value",{keyPath:e});let n=_S(e);if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&af(t))return{kind:n,value:SS(t)};if(n==="enum"&&typeof t==="string"&&gS(t))return{kind:n,value:t};return{kind:"digest",value:await Zr("holycodex-managed-config-value",[Yr({keyPath:e,value:t})])}}function AH(e){if(e.kind==="enum"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function yl(e,t,n,r){if(!hr(e)||!es(t)||!$o(r.schema)||!$o(r.installId))throw Le("managed runtime config",{});let o={...t.managed},i=tf(e),a=[];for(let[c,l]of Object.entries(n)){if(!hl(c)||typeof l!=="string"&&typeof l!=="boolean")throw Le("managed config key",c);let u=c,p=t.managed[u],f=ye(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(!CH(u,l))throw Le("managed config value",{keyPath:u});i=fl(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(!es(s))throw Le("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function $i(e,t,n){if(!hr(e)||!es(t))throw Le("managed runtime config",{});let r=tf(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!nf(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=ye(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=ml(r,u),i.push(u),delete o[u];else{let h=AH(l.originalValue);if(h===void 0){s.push(u),a.push(u);continue}r=fl(r,u,h),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function ts(e,t,n){if(!hl(n)||!es(t))throw Le("managed config key",n);let r=t.managed[n],o=ye(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 TH,dl,EP,OH,OP,RP,kP,rf,RH;var sf=x(()=>{ut();ut();bt();mr();TH=H((e)=>Qa(e)),dl=H((e)=>hr(e));EP=["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"],OH=H((e)=>hl(e));OP=H((e)=>xS(e)),RP=H((e)=>CP(e)),kP=H((e)=>AP(e)),rf=H((e)=>es(e)),RH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function IH(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function PP(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)=>IH(e[i]))}function NP(e){if(!re(e)||!Fe(e))return!1;return PP(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||PP(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function cf(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 FP(e){return re(e)&&Fe(e)&&cf(e.thread)}function FH(e){return re(e)&&Fe(e)&&typeof e.id==="string"}function jo(e){return re(e)&&Fe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function LP(e){return re(e)&&Fe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||NP(e.usage))}function LH(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 DP(e){if(pl.some((t)=>t===e))return"permissions";if(ul.some((t)=>t===e))return"approval";if(pS.some((t)=>t===e))return"elicitation";if(dS.some((t)=>t===e))return"dynamic_tool";return"other"}var IP,xl,MP,Sl,PH,bS,_l,MH,lf,wS,vS,NH,bl,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,GS,YS,ZS,N5,DH,F5;var XS=x(()=>{bt();mr();Qd();sf();IP=k.pipe(le(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),xl=Se(k.pipe(Za(1)),Gt.pipe(Ze((e)=>Number.isSafeInteger(e)))),MP=_({code:Gt.pipe(Ze((e)=>Number.isSafeInteger(e))),message:k,data:b(cn)}),Sl=Se(_({id:xl,result:cn}),_({id:xl,error:MP})),PH=_({id:xl,error:MP}),bS=_({method:IP,params:b(cn)}),_l=_({id:xl,method:IP,params:b(cn),trace:b(cn)});MH=H(NP),lf=_({clientInfo:_({name:Xr,version:Xr,title:Se(Xr,lt)}),capabilities:Se(_({experimentalApi:J,requestAttestation:J,mcpServerOpenaiFormElicitation:b(J),optOutNotificationMethods:b(Se(q(k),lt)),extensions:b(Ho)}),lt)}),wS=H((e)=>re(e)&&Fe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),vS=_({method:w("initialized")});NH=H(cf);bl=H((e)=>FP(e)||FH(e)),TS=bl,ES=bl,OS=H(jo),RS=H((e)=>re(e)&&Fe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),kS=H((e)=>FP(e)),CS=H((e)=>{if(!re(e)||!Fe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>cf(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>cf(r));return t&&e.threads===void 0||n&&e.data===void 0}),AS=H((e)=>re(e)&&Fe(e));PS=H(jo),IS=H(jo),MS=H(jo),NS=H((e)=>re(e)&&Fe(e));FS=H((e)=>jo(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Fe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),LS=H((e)=>jo(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Fe(t))),DS=H((e)=>re(e)&&Fe(e)&&(e.turn!==void 0&&LP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),qS=H((e)=>re(e)&&Fe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),US=H((e)=>jo(e)&&typeof e.turnId==="string"&&e.turnId.length>0),HS=H((e)=>re(e)&&Fe(e)),$S=H((e)=>jo(e)&&(e.turn!==void 0&&LP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),jS=H((e)=>re(e)&&Fe(e));VS=H((e)=>re(e)&&Fe(e)&&Array.isArray(e.data)&&e.data.every((t)=>LH(t))),BS=Ho,KS=Ho,zS=_({includeLayers:b(J),cwd:b(Se(k,lt))}),WS=_({config:dl,origins:Ho,layers:Se(q(Ho),lt)}),JS=Ho,GS=Ho,YS=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")),ZS=cn,N5=H((e)=>re(e)&&Fe(e)&&typeof e.kind==="string"&&typeof e.method==="string");DH=Se(w("stable","experimental","disabled"),J),F5=qd({key:k,value:DH})});class uf{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??ll,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=qH){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(lf,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",AS,e,bl)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",PS,t,TS)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",IS,t,kS)}async listThreads(e={}){return this.action("thread/list",NS,e,CS)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",MS,t,ES)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",OS,t,RS)}async startTurn(e){return this.action("turn/start",FS,e,DS)}async steerTurn(e){return this.action("turn/steer",LS,e,qS)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",US,n,HS)}async listModels(e={}){return this.action("model/list",jS,e,VS)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",BS,e,KS)}async readConfig(e={}){return this.action("config/read",zS,e,WS)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",JS,e,GS)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Pe(lf,t,"initialize parameters"));return Pe(cn,r,"initialize result")}let n=Pe(_l,{id:1,method:e,params:t},"App Server method");if(!UH.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(wS,t,"initialize result"),r=Pe(vS,fS,"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(_l,{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(Sl,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(_l,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(bS,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=$H(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:Hi(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Pe(YS,{...e,params:t,category:DP(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(ZS,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(Sl,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Pe(Sl,{id:e,error:{code:t,message:HH(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===mS){let n=Pe($S,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:wP({params:Hi(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 HH(e){let t=sn(e);return t.length>0?t:"server request failed"}function $H(e){if(pl.some((t)=>t===e))return"permission_denied";if(ul.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var qH,UH;var QS=x(()=>{mr();Qd();XS();qH={clientInfo:{name:"holycodex",title:null,version:cS},capabilities:null},UH=new Set(uS)});import{isAbsolute as jH}from"path";function Vo(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 e_(e=process.env){return Object.freeze(Vo(e))}async function pf(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 df(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 ns(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 ff{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!jH(e.executablePath))throw new K("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??ll,this.maxDiagnosticBytes=e.maxDiagnosticBytes??lS,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:Vo(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 pf(this.stderrStream,this.maxDiagnosticBytes),t=df(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=ns(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var mf=x(()=>{mr()});import{lstat as K5,mkdir as z5,readFile as VH,readdir as W5,realpath as BH,stat as KH}from"fs/promises";import{delimiter as zH,isAbsolute as G5,join as Y5,relative as Z5,resolve as qP}from"path";async function JH(e){let t=[];if(e.executablePath!==void 0)t.push(qP(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(zH).filter((i)=>i.length>0))for(let i of r)t.push(qP(o,i))}for(let n of t)try{let r=await KH(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await BH(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 GH(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 ZH(Promise.all([pf(n.stdout,16384),pf(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=sn(df(r,"Codex version output"));if(i!==0||a.length===0){let s=ns(df(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 YH(e){let t=await VH(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=jd(r);if(!o.ok)throw new K("discovery_failed","The Codex executable digest was invalid.");return o.value}async function t_(e={}){let t=await JH(e),n=Vo(e.environment),r=e.versionRunner?sn(await e.versionRunner(t,n)):await GH(t,n);if(r.length===0)throw new K("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await YH(t)}}async function ZH(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))},WH)})])}finally{if(r!==void 0)clearTimeout(r)}}var WH=30000,t4;var UP=x(()=>{ut();bt();mr();mf();t4=_({exitCode:Gt.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:k.pipe(Px(1048576)),stderr:k.pipe(Px(1048576))})});var XH="packages/codex/generated",QH,e$,n_,i4,a4;var HP=x(()=>{ut();bt();mr();QH=/^codex-cli \d+\.\d+\.\d+$/u,e$=/^codex-app-server-\d+\.\d+\.\d+$/u,n_=k.pipe(le(/^[a-f0-9]{64}$/u)),i4=_({schema_version:w("holycodex-generated-v2"),artifact_root:w(XH),codex_cli_version:k.pipe(le(QH)),codex_cli_digest:n_,protocol_epoch:k.pipe(le(e$)),generator:_({command:_A(w("app-server"),w("generate-ts")),supported_surface:w("codex app-server generators")}),typescript_root:w("typescript"),files:_({count:Gt.pipe(Ud(),Mx()),digest:n_})}),a4=_({path:k.pipe(Za(1)),size:Gt.pipe(Ud(),Mx()),sha256:n_})});var t$;var $P=x(()=>{bt();sf();t$=_({owner:w("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 n$}from"child_process";import{lstat as Ko,mkdir as r$,mkdtemp as o$,readFile as i$,readdir as a$,realpath as r_,rename as s$,rm as c$,stat as d4}from"fs/promises";import{dirname as VP,isAbsolute as c_,join as Bo,relative as BP,resolve as gf,sep as KP}from"path";async function WP(e){let t=d_(e.selectedPluginIds);if(t.length===0)return;if(ZP(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new _e("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>p_(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&xf(r,t))return r;let o=e.initializeRuntime??(()=>S$(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??u_,c=e.pollIntervalMs??l$,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new _e("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&xf(u,t))return u;let p=s-(Date.now()-l);if(p<=0)break;await(e.sleep??b$)(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 _e&&s.code==="cancelled")throw s;a=s instanceof _e?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 JP({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 _e)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 JP(e){let t=d_(e.selectedPluginIds);if(t.length===0)throw Y("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(ZP(e.timeoutMs,void 0),!c_(e.codexHome))throw Y("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new _e("cancelled","Official Codex marketplace fallback was cancelled.");let n=Vo(e.environment),r=e.gitRunner??eI("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??u_,i;try{i=await d$(r,o,e.signal)}catch(u){if(u instanceof _e)throw u;throw Y("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Bo(e.codexHome,"plugins"),s=Bo(a,l_[1]);if(await m$(a,e.codexHome),await Ko(s).catch((u)=>{if(El(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 o$(Bo(a,".openai-plugins-stage-"));try{if(await i_(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(ji,l)}catch(m){if(_$(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",ji,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 yf(l);let u=await GP(l,e.codexHome,t);if(u===void 0||!xf(u,t))throw Y("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await f$(r,l,o,e.signal)!==i)throw Y("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Ko(s).catch((m)=>{if(El(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 s$(l,s);let h=await p_(e.codexHome,e.selectedPluginIds);if(h===void 0||!xf(h,t))throw Y("marketplace_invalid","The published official marketplace failed validation.");return h}catch(u){if(u instanceof _e)throw u;throw Y("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await c$(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function d$(e,t,n){let r=await e.run(["ls-remote",ji,"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 f$(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 m$(e,t){await o_(t,e),await r$(e,{recursive:!0}),await o_(t,e)}async function o_(e,t){let n=gf(e),r=gf(t);while(!0){if((await Ko(r).catch((a)=>{if(El(a))return;throw a}))?.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=VP(r);if(i===r||i!==n&&!h$(n,i))throw Y("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function h$(e,t){let n=BP(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${KP}`)&&!c_(n)}async function yf(e){let t=await Ko(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 a$(e,{withFileTypes:!0});for(let r of n){let o=Bo(e,r.name),i=await Ko(o);if(i.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await yf(o)}}async function p_(e,t=[]){return await GP(Bo(e,...l_),e,d_(t))}async function GP(e,t,n=[]){if(t!==void 0)await o_(t,e);let r=await Ko(e).catch((l)=>{if(El(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 i_(t,e);else await yf(e);if(t!==void 0)await yf(e);let o=await r_(e),i=[Bo(o,".agents","plugins","marketplace.json"),Bo(o,".codex-plugin","marketplace.json"),Bo(o,"marketplace.json")],a,s;for(let l of i){let u=await Ko(l).catch((p)=>{if(El(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 i_(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 i$(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 YP(c,o,a,n)}function YP(e,t=`${l_.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!re(e)||e.name!==Tl)throw Y("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");g$(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=y$(s);if(!x$(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:Tl,source:ji,rootPath:t,manifestPath:n,plugins:i}}function g$(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)!==ji)throw Y("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function y$(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 x$(e){if(e===void 0||e.length===0||c_(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 d_(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!==Tl&&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(!XP(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function xf(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 S$(e){let t=Vo(e.environment),n;try{n=new ff({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new uf(n,{requestTimeoutMs:Math.min(e.timeoutMs??u_,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 ZP(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 i_(e,t){let n=await r_(e),r=await r_(t),o=BP(n,r);if(o===""||o===".."||o.startsWith(`..${KP}`))throw Y("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=gf(e),a=gf(t);while(!0){if((await Ko(a)).isSymbolicLink())throw Y("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=VP(a);if(c===a)throw Y("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function El(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function _$(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function b$(e){await new Promise((t)=>setTimeout(t,e))}function Y(e,t,n){return new _e(e,t,n instanceof Error?{cause:ns(n.message)}:{})}function yr(e,t){let n=$n(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=Lx(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 XP(e){return $d.includes(e)}function QP(e){if(!vP(s_,e))return _P(Le("live official plugin list",e));return bP(Pe(s_,e,"live official plugin list"))}function Sf(e){let t=e.runner??eI(e.executable,{environment:e.environment??Vo(),...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 hf("list",r);let o;try{o=JSON.parse(r.stdout)}catch{throw new _e("command_failed","Codex returned invalid plugin data.")}let i=QP(o);if(!i.ok)throw new _e("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 _e("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await WP({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(vl,r,"plugin marketplace source");if(i===Tl||i===ji)throw new _e("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 hf("marketplace add",a,i)},add:async(r,o)=>{let i=Pe(vl,r,"official plugin id"),a=await t.run(["plugin","add",i,"--json"],o===void 0?void 0:{signal:o});if(a.exitCode!==0)throw hf("add",a,i);let s=await n(),c=yr(s,i),l=$n(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 _e("readback_mismatch",`Codex did not report ${i} after installation.`,{plugin_id:i});if(!p.installed)throw new _e("plugin_missing",`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!p.enabled)throw new _e("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(vl,r,"official plugin id"),a=i;if($n(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 hf("remove",s,a);let c=await n(),l=[...c.installed,...c.available].find((u)=>u.pluginId===a);if(l?.installed)throw new _e("readback_mismatch",`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:l.pluginId})}}}function hf(e,t,n){let r=ns(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new _e("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function eI(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>v$(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 v$(e,t,n){if(n.signal?.aborted)throw new _e("cancelled","The Codex plugin command was cancelled.");let r=n$(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=jP(r.stdout,n.stdoutLimit),i=jP(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 _e("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 _e("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 _e)throw p;throw new _e("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function jP(e,t){if(e===null)return Promise.reject(new _e("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 _e("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new _e("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 Tl="openai-curated",ji="https://github.com/openai/plugins.git",l_,u_=30000,l$=100,zP,u$,wl,vl,p$,w$,a_,s_,_e;var f_=x(()=>{ut();bt();QS();mr();mf();l_=["plugins","openai-plugins"],zP=k.pipe(le(/^[a-z][a-z0-9._-]{1,63}$/u)),u$=k.pipe(le(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),wl=q(k),vl=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),p$=_({name:zP,version:u$,description:Xr,author:b(cn),license:b(Xr),homepage:b(Xr),repository:b(Xr),keywords:b(wl),skills:b(wl),commands:b(wl),hooks:b(wl),assets:b(wl),official:b(J)});w$=_({id:zP,selected:w(!0)}),a_=_({pluginId:vl,installed:J,enabled:J,name:b(Se(k,lt)),marketplaceName:b(Se(k,lt)),version:b(Se(k,lt))},qd({key:k,value:Ox})),s_=_({installed:q(a_),available:q(a_)});_e=class _e extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});var Ol=x(()=>{mr();mr();Qd();XS();QS();mf();UP();HP();$P();sf();f_();f_()});function Zt(e){if(!rs(e))throw Error("The value is not JSON serializable.");return dr(e),e}function rs(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object"||t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>rs(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>rs(n,t))}finally{t.delete(e)}}var Rl=x(()=>{ut()});function mt(e,t){let n=bn(e,t);return Ot(n)?n.right:void 0}function oI(e){return mt(bf,e)!==void 0}var bf,r8,m_,wf,T$,is,E$,O$,R$,nI,kl,vf,os,h_,_f,k$,tI,C$,g_,as,A$,rI,P$,I$,ln;var ss=x(()=>{Ol();ut();tn();bt();Rl();bf=H((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&rs(e)),r8=H(rs),m_=k.pipe(le(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)),wf=k.pipe(le(/^[0-9a-f]{64}$/u)),T$=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),is=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),E$=k.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),O$=_({path:k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:wf}),R$=_({computer_use:J,work:J,frontend:J,security:J,coding:w(!0)}),nI=_({computer_use:b(J),work:b(J),frontend:b(J),security:b(J)}),kl=_({profile:b(Do),tier:b(Li),optional:b(nI),officialPlugins:b(q(is))}),vf=kl,os=_({selected:J,status:w("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:q(is),reason:b(k)}),h_=_({computer_use:os,work:os,frontend:os,security:os}),_f=_({presence:w("absent","present"),digest:wf,safe_value:b(Se(_({kind:w("boolean"),value:J}),_({kind:w("marketplace"),source_type:w("git"),source:w("https://github.com/davidbasilefilho/holycodex.git")})))}),k$=_({plugin_id:w("holycodex@holycodex"),before:_({preference:_f,marketplace:_f}),after:_({preference:_f,marketplace:_f})}),tI=_({presence:w("absent","present"),digest:wf,safe_value:b(_({kind:w("boolean"),value:J}))}),C$=_({plugin_id:is,before:tI,after:tI}),g_={owner:w("holycodex"),schema_epoch:w(En),install_id:T$,version:m_,digest:wf,profile:Do,tier:Li,optional_selections:R$,explicit_optional_selections:nI,official_plugins:b(q(is)),capability_state:b(h_),managed_artifacts:q(O$),installed_at:E$,status:b(w("active")),step:b(w("active")),managed_config:b(rf),plugin_snapshot:b(q(_({plugin_id:is,status:w("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:b(k$),provider_config:b(q(C$)),owned_plugins:b(q(is))},as=_(g_),A$=(({profile:e,...t})=>t)(g_),rI=Se(_({...g_,profile:Bd}),_({...A$,plan:Bd})),P$=w("preparing","conflicted"),I$=w("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),ln=_({...as.fields,status:P$,step:I$})});import{lstat as M$,mkdir as N$}from"fs/promises";import{homedir as F$}from"os";import{dirname as L$,join as Vi,posix as iI,resolve as D$,sep as aI,win32 as sI}from"path";function Bi(e={},t=process.env){let n=F$(),r=e.paths?.codexHome??t.CODEX_HOME??Vi(n,".codex"),o=x_(r,"CODEX_HOME"),i=Vi(o,q$);return{codexHome:o,stateRoot:i,activeRecord:Vi(i,U$),preparingRecord:Vi(i,H$),conflictedRecord:Vi(i,$$),roleRoot:Vi(i,"agents"),configFile:Vi(o,"config.toml")}}function x_(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||V$(e))throw new vn("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?sI:iI,o=y_(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new vn("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":aI).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new vn("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new vn("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function V$(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function Cl(e){x_(e,"owned path"),await xr(e),await N$(e,{recursive:!0}),await xr(e)}async function xr(e){let n=D$(e);while(!0){try{if((await M$(n)).isSymbolicLink())throw new vn("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof vn)throw o;if(!ht(o,"ENOENT"))throw o}let r=L$(n);if(r===n)break;n=r}}async function Al(e){await xr(e)}function cs(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?sI:iI,o=r.resolve(y_(e,n)),i=r.resolve(y_(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":aI}`)&&a!==".."&&!r.isAbsolute(a)}function y_(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 q$="holycodex",U$="active.json",H$="preparing.json",$$="conflicted.json",j$,vn;var Ki=x(()=>{ut();j$=En;vn=class vn extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as cI,open as B$,readFile as lI,rename as K$,unlink as z$,writeFile as W$}from"fs/promises";import{dirname as J$}from"path";async function uI(e){let t;try{t=await B$(e,"r"),await t.sync()}catch(n){if(!pI(n))throw n}finally{await t?.close().catch(()=>{return})}}async function Y$(e){await uI(e).catch((t)=>{if(!pI(t))throw t})}async function zo(e,t){await Qr(e,`${dr(t)}
36
+ `)}async function Qr(e,t){let n=J$(e);await Cl(n),await xr(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await W$(r,t,{encoding:"utf8",mode:384}),await uI(r),await K$(r,e),await Y$(n)}catch(o){throw await z$(r).catch(()=>{return}),o}}async function Z$(e,t){let n=await cI(e);if(!n.isFile()||n.isSymbolicLink())throw new zi("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await lI(e,"utf8"))}catch(i){throw new zi("state_corrupt","A persisted file is not valid JSON.",i)}let o=mt(t,r);if(o===void 0)throw new zi("state_corrupt","A persisted file failed schema validation.");return o}async function Xt(e){try{let t=await cI(e);if(!t.isFile()||t.isSymbolicLink())throw new zi("state_corrupt","A persisted file is not a regular file.");return await lI(e,"utf8")}catch(t){if(ht(t,"ENOENT"))return;throw t}}async function Bn(e,t){try{return await Z$(e,t)}catch(n){if(ht(n,"ENOENT"))return;throw n}}function pI(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return G$.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var G$,zi;var ls=x(()=>{ut();Ki();ss();G$=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);zi=class zi extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as X$}from"fs/promises";import{dirname as Q$,resolve as ej}from"path";import{fileURLToPath as tj}from"url";async function dI(e=Pl){let t=JSON.parse(await X$(e,"utf8")),n=mt(rj,t);if(n===void 0)throw new Il("manifest_invalid","The public package manifest is invalid.");return n}async function Tf(e=Pl){return(await dI(e)).version}async function us(e=Pl){return(await Tf(e)).split("-",1)[0]??""}async function S_(e,t,n=Pl){let r=await dI(n),o=await us(n),i=oj(e,o);if(!t)await zo(n,{...r,version:i});return{previous:o,next:i}}function oj(e,t){if(e!=="patch"&&e!=="minor"){if(mt(m_,e)===void 0)throw new Il("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 nj,rj,Pl,Il;var Ml=x(()=>{bt();ss();ls();nj=k.pipe(le(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*\.[1-9]\d*)?$/u)),rj=H((e)=>oI(e)&&e.name==="holycodex"&&mt(nj,e.version)!==void 0),Pl=ej(Q$(tj(import.meta.url)),"../package.json");Il=class Il extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{lstat as Ef,readFile as Of,rm as Rf}from"fs/promises";import{join as un,relative as fI}from"path";function Wi(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:Kx(o),rolePolicy:wn.find((i)=>i.role===r.role),description:Wx(o),taskInstruction:zx(o),permissions:Jx(o),model:"gpt-5.6-luna",effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function b_(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 w_(e=!1){if(!qi.requiresDelegation||!qi.trivialWorkRequiresDelegation||!qi.codeReviewRequiredForImplementation||!qi.codeReviewRequiredBeforeVcs||!qi.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 repository discovery, source inspection, fact finding, and trivial work, with one active bounded Assignment. For repository implementation, research, testing, review, CI observation, or inspecting source/tests/docs/generated artifacts, Root's first action is to create and start that Assignment and dispatch the native Explorer, Librarian, Worker, or Reviewer route before inspecting anything itself. Root may inspect only returned evidence for integration acceptance. Small work may use one Assignment. Git/VCS, GUI, and browser execution are Root-only. Do the underlying repository 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.","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("Computer Use is selected and is directly executable by Root/session only; it must not be delegated.");else t.push("Computer Use is unavailable for this installation and cannot be delegated. GUI and browser execution remain Root/session-only.");return t.join(`
37
+ `)}async function v_(e,t,n=[],r="standard"){let o=un(e,"holycodex","agents"),i=[],a=[],s=Wi(t,r).map((p)=>({path:un(o,`${p.name}.toml`),contents:Af(p)})),c=new Map(n.map((p)=>[un(e,p.path),p])),l=new Map;for(let p of s){let f=await __(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 v=l.get(m.path),S=c.get(m.path);if(v!==void 0&&S!==void 0){if(await ps(v)!==S.digest&&v!==m.contents){i.push(m.path),u.push({path:fI(e,m.path).replaceAll("\\","/"),digest:S.digest});continue}}if(v===void 0||v!==m.contents)await Qr(m.path,m.contents),a.push({path:m.path,previous:v,installedDigest:await ps(m.contents)});u.push({path:fI(e,m.path).replaceAll("\\","/"),digest:await ps(m.contents)})}let p=un(e,"agents","root.toml"),f=await __(p),h=await mI(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 v=un(e,m.path);if(!s.some((S)=>S.path===v)){if(!cj(e,v,m.path)){i.push(v);continue}let S=await lj(v,m.digest);if(S.status==="preserved")i.push(v);else if(S.previous!==void 0)a.push({path:v,previous:S.previous,installedDigest:void 0})}}for(let m of n){let v=un(e,m.path);if(i.includes(v)&&!u.some((S)=>un(e,S.path)===v))u.push(m)}return{managed_artifacts:u,preserved:i,rollback:a}}catch(p){throw await kf(a).catch(()=>{return}),p}}async function kf(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await __(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await ps(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await Rf(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 Cf(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(!cs(e,l)||!cs(o,l)&&!cs(i,l)&&l!==un(e,"config.toml")){r.push(l);continue}try{await xr(l);let u=await Ef(l);if(u.isSymbolicLink()||!u.isFile()){r.push(l);continue}let p=await Of(l);if(await ps(p)!==c.digest){r.push(l);continue}await Rf(l,{force:!1}),n.push(l)}catch(u){if(!ht(u,"ENOENT"))r.push(l)}}let a=un(e,"agents","root.toml"),s=await mI(a);if(s==="removed")n.push(a);if(s==="preserved")r.push(a);return{removed:n,preserved:r}}function Af(e){let t=[ij,e.taskInstruction,...e.permissions.sourceMutation?[`Surgical mutation rule: ${Kd}`]:[]].join(`
38
+ `),n=Nl(e);return[`name = ${JSON.stringify(e.name)}`,`description = ${JSON.stringify(e.description)}`,`model = ${JSON.stringify(e.model)}`,`model_reasoning_effort = ${JSON.stringify(e.effort)}`,`service_tier = ${JSON.stringify(e.serviceTier)}`,'model_reasoning_summary = "none"','model_verbosity = "low"',`sandbox_mode = ${JSON.stringify(n)}`,'approval_policy = "never"',`web_search = ${JSON.stringify(e.permissions.network?"live":"disabled")}`,`developer_instructions = ${JSON.stringify(t)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","context_management = true","multi_agent_v2 = false","multi_agent = false","computer_use = false","browser_use = false","in_app_browser = false",""].join(`
39
+ `)}function Nl(e){return e.permissions.filesystem==="workspace-write"?"workspace-write":"read-only"}function aj(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 ds(e){return sj.has(e)}function cj(e,t,n){if(n==="agents/root.toml")return!0;if(wn.some((r)=>n===`holycodex/agents/${r.role.toLowerCase()}.toml`))return!0;if(!cs(un(e,"agents"),t))return!1;return qo.some((r)=>{let[o,i]=r.split("."),a=`${o[0].toUpperCase()}${o.slice(1)}.${i}.toml`;return n===`agents/${a}`})}async function mI(e){try{await xr(e);let t=await Ef(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await Of(e,"utf8");if(!ds(n))return"preserved";return await Rf(e,{force:!1}),"removed"}catch(t){if(ht(t,"ENOENT"))return"absent";throw t}}async function __(e){try{await xr(e);let t=await Ef(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await Of(e))}catch(t){if(ht(t,"ENOENT"))return;throw t}}async function lj(e,t){try{await xr(e);let n=await Ef(e);if(n.isSymbolicLink()||!n.isFile())return{status:"preserved"};let r=new TextDecoder("utf-8",{fatal:!0}).decode(await Of(e));if(await ps(r)===t)return await Rf(e,{force:!1}),{status:"removed",previous:r};return{status:"preserved"}}catch(n){if(ht(n,"ENOENT"))return{status:"removed"};throw n}}async function ps(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 ij="You are a HolyCodex GPT-5.6 Luna specialist executing one active bounded Assignment. Follow its exact boundary, exclusions, acceptance criteria, and evidence requirements. Preserve unrelated work and perform no redundant operations. Do not delegate, message peers, mutate global Intent lifecycle, make material decisions, or perform Git/VCS. Repository source mutation is governed only by the concrete task contract; workspace writes for caches, generated test state, and proof outputs do not grant source-mutation authority. Return exactly one compact outcome (`completed`, `blocked`, `needs_root_input`, or `failed`) with changed paths, checks, observable evidence, blockers, and remaining risk.",sj;var Pf=x(()=>{ut();Ki();ls();sj=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)=>aj(e,t,n))))});class Wo{adapter;observedIdentities={};constructor(e){if("run"in e){let t=Sf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await t_({environment:e}),n=Sf({executable:t.path,environment:e_(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new Wo(n)}async list(){try{return await this.adapter.list()}catch(e){throw Fl("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw Fl("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw Fl("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw Fl("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw Fl("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=$n(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 Fl(e,t,n){if(t instanceof Sr)return t;let o=(t instanceof _e?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 Ll=x(()=>{Ol();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 gI(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=pj(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=T_(o.slice(1,-1).trim()),uj(t,n);continue}let i=_I(o);if(i<1)throw Error("TOML assignment is invalid.");let a=T_(o.slice(0,i).trim()),s=If(o.slice(i+1).trim());SI(t,[...n,...a],s)}return t}function yI(e){let t=[];return xI(e,[],t),t.join(`
41
+ `)}function xI(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(O_(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(hI).join(".")}]`)}for(let[i,a]of r)n.push(`${hI(i)} = ${bI(a)}`);for(let[i,a]of o)xI(a,[...t,i],n)}function If(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?[]:E_(t,",").map(If)}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 E_(t,",")){let o=_I(r);if(o<1)throw Error("TOML inline table entry is invalid.");SI(n,T_(r.slice(0,o).trim()),If(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 T_(e){let t=E_(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("'")?If(n):n)}function SI(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(O_(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 uj(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(O_(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function E_(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 _I(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 pj(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 O_(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function hI(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function bI(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(bI).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{rm as k_,rmdir as wI}from"fs/promises";async function P_(e={},t=process.env){let n=Bi(e,t),r={};try{await Al(n.codexHome),await Al(n.stateRoot),r.paths=Dl({state_root:n.stateRoot})}catch(l){r.paths=wt(["path_symlink"],{error:_r(l)})}let[o,i,a]=await Promise.all([hs(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 Ul(o))r.configuration=Dl({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 fj(n,o),r.native_roles=await mj(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&&ds(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 Wo.discover({...t,CODEX_HOME:n.codexHome}).catch(()=>{return});if(o&&s?.status){let l=[...new Set([br,...el({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?Dl({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 ql(e={},t=process.env){let n=Bi(e,t);await Al(n.codexHome),await Al(n.stateRoot);let r=await hs(n),[o,i]=await Promise.all([Bn(n.preparingRecord,ln),Bn(n.conflictedRecord,ln)]),a=i??o??r;R_(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(hj(a)),c=[],l=[],u=[];if(r&&!await Ul(r))return l.push(n.activeRecord),u.push("configuration_changed"),{removed:c,preserved:l,reasons:u};if(a===void 0)return R_(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 $i(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??fs()),{removed:c,preserved:l,reasons:u}}if(a?.plugin_config){if((await C_(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 A_(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 Wo.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 v=await Cf(n.codexHome,a?.managed_artifacts??[]);if(c.push(...v.removed),l.push(...v.preserved),v.preserved.length>0)u.push("managed_artifact_changed");for(let y of s)try{let E=await m.list(),P=gj(E,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(E){throw u.push("native_plugin_remove_failed"),await Kn(n,a??fs()),new N("capability_denied",`Codex native plugin removal did not converge for ${y}: ${_r(E)}`,E)}if(v.preserved.length>0)return await Kn(n,a??fs()),{removed:c,preserved:l,reasons:u};let S;try{let y=f,E=h;if(E){let P=await $i(y,E,{schema:E.schema,installId:E.installId});if(P.preservedKeys.length>0||P.unresolvedKeys.length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Kn(n,a??fs()),{removed:c,preserved:l,reasons:u};y=P.document,E=P.state}if(a?.plugin_config){let P=await C_(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 A_(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=E===void 0?{document:y}:{document:y,state:E};if(S!==void 0)if(Object.keys(S.document).length===0&&p===void 0)await k_(n.configFile,{force:!1});else await Qr(n.configFile,M_(S.document))}catch(y){if(y instanceof N)throw await Kn(n,a??fs()),y;return l.push(n.configFile),u.push("managed_config_write_failed"),await Kn(n,a??fs()),{removed:c,preserved:l,reasons:u}}if(r)try{await k_(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,E]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0]]){if(!E)continue;try{await yj(y),c.push(y)}catch{l.push(y),u.push("state_remove_failed")}}if(l.length===0)try{await wI(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 wI(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 R_(e,{stage:"removal",status:"completed",message:"HolyCodex removal complete"}),{removed:c,preserved:l,reasons:u}}async function I_(e={},t=process.env,n={}){let r=Bi(e,t),[o,i,a]=await Promise.all([hs(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 Ul(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 us()}catch(f){throw new N("upgrade_failed","The running HolyCodex version is unavailable.",f)}let l=dj(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 ms({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 dj(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 fj(e,t){if(!t.managed_config)return wt(["incomplete_install_state"]);try{let n=eo(await Xt(e.configFile)),r=Nf(t.profile,t.tier,t.optional_selections.computer_use),o=[];for(let[i,a]of Object.entries(r))if((await ts(n,t.managed_config,i)).status!=="unchanged"||i!=="developer_instructions"&&ye(n,i)!==a)o.push(i);return o.length===0?Dl({managed_keys:Object.keys(r).length}):wt(["changed_holycodex_config"],{keys:o})}catch(n){return wt(["config_unreadable"],{error:_r(n)})}}async function mj(e,t,n){try{let r=eo(await Xt(e.configFile)),o=[];for(let a of Wi(t,n)){let s=ye(r,`agents."${a.name}".config_file`),c=`${e.roleRoot}/${a.name}.toml`.replaceAll("\\","/");if(typeof s!=="string"||gl(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!==Af(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!==Nl(a)||u.approval_policy!=="never"||u.web_search!==(a.permissions.network?"live":"disabled")||ye(u,"agents.enabled")!==!1||ye(u,"features.multi_agent_v2")!==!1||ye(u,"features.multi_agent")!==!1||ye(u,"features.context_management")!==!0||ye(u,"features.computer_use")!==!1||ye(u,"features.browser_use")!==!1||ye(u,"features.in_app_browser")!==!1)o.push(`${a.name}:malformed`)}let i=await Xt(`${e.codexHome}/agents/root.toml`);if(i!==void 0&&ds(i))o.push("root:stale");return o.length===0?Dl({role_root:e.roleRoot,agent_types:Wi(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 zo(e.conflictedRecord,Zt(n))}function fs(){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 hj(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 gj(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 Dl(e){return{status:"healthy",reasons:[],details:e}}function wt(e,t={}){return{status:"failed",reasons:e,details:t}}async function yj(e){await k_(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 R_(e,t){try{e.onProgress?.(t)}catch{}}var Mf=x(()=>{Ol();ut();Hl();Rl();Ml();Pf();Ll();Ki();ss();ls()});import{rm as II}from"fs/promises";import{join as xj}from"path";function wr(e){let t=mt(vf,e);if(t===void 0)throw new N("install_failed","The installation options are invalid.");return t}async function ms(e={},t={},n=process.env){if(mt(kl,e)===void 0)throw new N("install_failed","The installation options are invalid.");let r=Bi(t,n);zn(t,{stage:"validation",status:"started",message:"Validating Codex target"}),await Cl(r.stateRoot);let o=await Bn(r.preparingRecord,ln),a=await Bn(r.conflictedRecord,ln)??o;if(a!==void 0){await Promise.resolve().then(() => Mf());let qe=await ql(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 ms({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??kI(a)},t,n)}let s=await hs(r);if(s!==void 0&&!await Ul(s))throw new N("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:r.activeRecord});let c=Ij(e.profile,s?.profile),l=Mj(e.tier,s?.tier),u=Nj(e.optional,s?.optional_selections),p=Cj(s?.explicit_optional_selections,e.optional),f=e.officialPlugins??kI(s),h=[...new Set(el(FI(u),f).map((ae)=>$n(ae)??ae))],m;try{m=t.officialPluginManager??await Wo.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 v;try{v=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($n(ae)!==ae)return!1;let qe=Vl(v,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: ${PI(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("-",""),E=await us(),P=(t.now?.()??new Date).toISOString(),z=await Xt(r.configFile),X=eo(z),U=s?.plugin_config?.before??await TI(X),te=[...new Set([...h,...(s?.provider_config??[]).map((ae)=>ae.plugin_id),...s?.owned_plugins??[]])].filter((ae)=>ae!==br),se=(await EI(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??of({schema:En,installId:y}),ee=await OI(X,ce,s),Ae=await RI(ee.document,ee.state),{document:vt,state:Ft}=Ae;Tj(vt,Ft);let Lt=Nf(c,l,u.computer_use),De;try{De=await yl(vt,Ft,Lt,{schema:En,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 Ej({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:En,install_id:y,version:E,digest:s?.digest??"0".repeat(64),profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:AI(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 $l(r.preparingRecord,Tt);let Et,Zi=!1,to=new Set,Xi=new Set(s?.owned_plugins??[]),Hf=new Set,Dt=Tt,$_=!1,j_=!1,$f=z,ys=De.state;try{zn(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await Cl(r.roleRoot),Et=await v_(r.codexHome,c,s?.managed_artifacts,l),Dt={...Tt,step:"roles_prepared",managed_artifacts:Et.managed_artifacts},await $l(r.preparingRecord,Dt),zn(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),zn(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),$_=!0,await m.addMarketplace(Sj),await Pj({list:()=>m.list(),add:(Tn)=>m.add(Tn)},[br,...h],(Tn,Kf)=>{if(Kf==="new")to.add(Tn),Xi.add(Tn),Dt={...Dt,owned_plugins:[...Xi]};else Hf.add(Tn),Xi.add(Tn),Dt={...Dt,owned_plugins:[...Xi]}}),Dt={...Dt,step:"plugins_installed"},await $l(r.preparingRecord,Dt),zn(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let qe=await Xt(r.configFile);$f=qe;let Gn=eo(qe),V_=await OI(Gn,ce,s),B_=await RI(V_.document,V_.state),{document:zl,state:K_}=B_,jf=await TI(zl),Vf=(await EI(zl,te)).map((Tn)=>({plugin_id:Tn.plugin_id,before:se.find((Kf)=>Kf.plugin_id===Tn.plugin_id)?.before??Tn.before,after:Tn.before}));await vj(zl,vt,K_,Lt);let Wl=await yl(zl,K_,Lt,{schema:En,installId:y});if(Wl.driftedKeys.length>0)throw new N("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Wl.driftedKeys.join(",")});j_=!0,zn(t,{stage:"config",status:"started",message:"Configuring Root"}),ys=Wl.state,Dt={...Dt,managed_config:ys,plugin_config:{plugin_id:br,before:U,after:jf},provider_config:Vf},await Qr(r.configFile,M_(Wl.document)),Zi=!0,Dt={...Dt,step:"config_published"},await $l(r.preparingRecord,Dt),zn(t,{stage:"config",status:"completed",message:"Root configuration published"}),zn(t,{stage:"verification",status:"started",message:"Verifying installation"}),await Rj(r,c,l,u.computer_use,ys,Et.preserved),zn(t,{stage:"verification",status:"completed",message:"Installation verified"});let z_=AI(u),QI=await Ff({owner:"holycodex",install_id:y,version:E,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:z_,managed_artifacts:Et.managed_artifacts,managed_config:ys,plugin_config:{plugin_id:br,before:U,after:jf},provider_config:Vf,plugin_snapshot:je,owned_plugins:[...Xi]}),Bf={owner:"holycodex",schema_epoch:En,install_id:y,version:E,digest:QI,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:z_,managed_artifacts:Et.managed_artifacts,installed_at:P,status:"active",step:"active",managed_config:ys,plugin_snapshot:je,plugin_config:{plugin_id:br,before:U,after:jf},provider_config:Vf,owned_plugins:[...Xi]};if(mt(as,Bf)===void 0)throw new N("state_corrupt","The HolyCodex configuration is invalid.");return await zo(r.activeRecord,Zt(Bf)),await N_(r.preparingRecord),await N_(r.conflictedRecord),zn(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Bf,optional_plugins:h,preserved:Et.preserved,warnings:Et.preserved.length===0?[]:["modified managed files were preserved"]}}catch(ae){let qe=[];if(Zi)try{await Oj(r.configFile,$f)}catch{qe.push("config")}if($_&&!j_){if(await Xt(r.configFile).catch(()=>{return})!==$f)qe.push("config")}if(Et!==void 0)try{if((await kf(Et.rollback)).preserved.length>0)qe.push("roles")}catch{qe.push("roles")}if(Hf.size>0)qe.push(...[...Hf].map((Gn)=>`plugin:${Gn}`));for(let Gn of to)try{await m.remove?.(Gn)}catch{qe.push(`plugin:${Gn}`)}if(qe.length>0)await $l(r.conflictedRecord,{...Dt,step:"conflicted",status:"conflicted"}).catch(()=>{return});else await N_(r.preparingRecord).catch(()=>{return});if(ae instanceof vn)throw ae;if(ae instanceof N)throw ae;throw new N(ae instanceof Sr||ae instanceof jl?"capability_denied":"install_failed",PI(ae),ae,qe.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function hs(e){let t=await Bn(e.activeRecord,bf);if(t===void 0)return;let n=mt(as,t);if(n!==void 0)return n;let r=mt(rI,t);if(r===void 0)throw new N("state_corrupt","The HolyCodex configuration is invalid.");if(!await qI(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=$x(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 Ff({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 zo(e.activeRecord,Zt(s)),s}function FI(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):gI(e),r=mt(dl,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 M_(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):yI(e)).trimEnd()}
42
+ `}catch(t){throw new N("install_failed","The merged Codex configuration is not writable.",t)}}async function TI(e){return{preference:await Bl(e,"plugins",MI),marketplace:await Bl(e,"marketplaces",NI)}}async function EI(e,t){return await Promise.all(t.map(async(n)=>{let r=await Bl(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 C_(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",MI],["marketplace","marketplaces",NI]]){let u=t.before[s],p=t.after[s],f=await Bl(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=DI(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=LI(r,c,l,wj(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function A_(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 Bl(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=DI(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=LI(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 Bl(e,t,n){let r=_j(e,t,n),o=await Zr("holycodex-plugin-config",[Yr(Zt({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=bj(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function _j(e,t,n){let r=e[t];if(!gs(r))return;return r[n]}function bj(e,t){if(!gs(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!==vI)return;return{kind:"marketplace",source_type:"git",source:vI}}function wj(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function LI(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!gs(i))throw new N("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function DI(e,t,n){let r=e[t];if(!gs(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 gs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Nf(e,t,n=!1){let r=b_(e,t),o={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,model_verbosity:"low",developer_instructions:w_(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 qo)o[`agents."${i}".config_file`]=`holycodex/agents/${i}.toml`;return o}async function vj(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await ts(e,n,a)).status==="drifted")o.push(a);continue}let c=ye(t,a),l=ye(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 OI(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 $i(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=ye(i,u);if(typeof p!=="string")continue;let f=p.replaceAll("\\","/").replace(/^\.\//u,"");if(f===`agents/${c}.toml`||f===`holycodex/agents/${c}.toml`)i=ml(i,u)}return{document:i,state:a}}async function RI(e,t){let o=t.managed["features.context_management.experimental_mode"];if(o===void 0)return{document:e,state:t};let i=ye(e,"features.context_management.experimental_mode"),a=ye(e,"features.context_management"),s=gs(a)?void 0:a;if(gs(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=ml(c,"features.context_management.experimental_mode"),s===void 0)c=fl(c,"features.context_management",i)}let l=ye(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 Tj(e,t){if(ye(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 Ej(e,t){let n=await e.list();return t.map((r)=>{let o=Vl(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function $l(e,t){if(mt(ln,t)===void 0)throw new N("state_corrupt","The HolyCodex transaction state is invalid.");await zo(e,Zt(t))}async function N_(e){await II(e,{force:!1}).catch((t)=>{if(!ht(t,"ENOENT"))throw t})}async function Oj(e,t){if(t===void 0){await II(e,{force:!1}).catch((n)=>{if(!ht(n,"ENOENT"))throw n});return}await Qr(e,t)}async function Rj(e,t,n,r,o,i=[]){let a=await Xt(e.configFile),s=eo(a),c=Nf(t,n,r);for(let[p,f]of Object.entries(c)){let h=ye(s,p);if(p==="developer_instructions"){if(typeof h!=="string"||await kj(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=Wi(t,n);for(let p of l){let f=`agents."${p.name}".config_file`,h=ye(s,f);if(typeof h!=="string")throw new N("install_failed",`The ${p.name} registration is missing.`);let m=xj(e.roleRoot,`${p.name}.toml`),v=m.replaceAll("\\","/");if(gl(e.configFile,h).replaceAll("\\","/")!==v)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 E=eo(y);if(E.name!==p.name||typeof E.description!=="string"||typeof E.model!=="string"||typeof E.model_reasoning_effort!=="string"||typeof E.service_tier!=="string"||typeof E.developer_instructions!=="string"||E.sandbox_mode!==Nl(p)||E.approval_policy!=="never"||E.web_search!==(p.permissions.network?"live":"disabled")||E.tool_output_token_limit!==void 0||ye(E,"agents.enabled")!==!1||ye(E,"features.multi_agent_v2")!==!1||ye(E,"features.multi_agent")!==!1||ye(E,"features.context_management")!==!0||ye(E,"features.computer_use")!==!1||ye(E,"features.browser_use")!==!1||ye(E,"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&&ds(u))throw new N("install_failed","A stale HolyCodex Root role remains installed.")}async function kj(e,t){return await Zr("holycodex-managed-config-value",[Yr({keyPath:e,value:t})])}function Cj(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 Aj(e){return["computer_use","work","frontend","security"].find((t)=>Qc[t].pluginIds.includes(e))}function kI(e){return(e?.official_plugins??[]).filter((t)=>{let n=Aj(t);return n===void 0||e?.optional_selections[n]!==!0})}async function Pj(e,t,n){for(let r of t){let o;try{o=Vl(await e.list(),r)}catch(s){throw F_("list",s,r)}if(o?.installed&&!o.enabled)throw new jl("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=Vl(await e.list(),r);if(!CI(o,c))n?.(r,"uncertain")}catch{n?.(r,"uncertain")}throw F_("add",s,r)}let a;try{a=Vl(await e.list(),r)}catch(s){if(i)n?.(r,"uncertain");throw F_("list",s,r)}if(!a?.installed){if(i&&!CI(o,a))n?.(r,"uncertain");throw new jl("missing",`${r} is not installed after add`)}if(i&&a.enabled)n?.(r,"new");if(!a.enabled){if(i)n?.(r,"new");throw new jl("uncertain",`${r} is disabled after add`)}}}function CI(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function F_(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 Vl(e,t){let n=yr(e,t);if(n!==void 0)return n.entry;let r=$n(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function Ij(e,t){let n=e??t??"default";if(!fr(n).ok)throw new N("install_failed","Unknown profile.");return n}function Mj(e,t){let n=e??t??"standard";if(mt(Li,n)===void 0)throw new N("install_failed","The tier is not supported.");return n}function Nj(e,t){let n=t?FI(t):ur,r=Dx(e,n);return{computer_use:r.computer_use,work:r.work,frontend:r.frontend,security:r.security,coding:!0}}function AI(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:[...Qc[r].pluginIds]};return[r,i]}))}async function Ff(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 Ul(e){return await qI(e)}async function qI(e){return await Ff({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 PI(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function zn(e,t){try{e.onProgress?.(t)}catch{}}var Sj="davidbasilefilho/holycodex",br="holycodex@holycodex",vI="https://github.com/davidbasilefilho/holycodex.git",MI="holycodex@holycodex",NI="holycodex",jl,N;var Hl=x(()=>{Ol();ut();Rl();Ml();Pf();Ll();Ki();ss();ls();ss();jl=class jl 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 p1}from"readline/promises";ut();ut();ut();var aS=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."}]),xP=new Set(["codex-home","profile","tier","add-plugin"]),pH=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 Yd(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 Yd(["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(!xP.has(u)&&!pH.has(u))throw new ze("invalid_argument","Unknown option.",{option:`--${c}`});if(xP.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 dH(t,n,r),{command:t,positionals:n,options:r}}function dH(e,t,n){let r=mH(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=fH[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 fH={"plus-low":"low",plus:"default","plus-high":"high"};function mH(e){switch(e){case"install":return new Set([...aS.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 hH=`HolyCodex
43
43
 
44
44
  Usage:
45
45
  holycodex install [options]
46
46
  holycodex remove [options]
47
+ holycodex upgrade [options]
47
48
  holycodex doctor [options]
48
49
  holycodex version [<0.x.y|patch|minor>] [options]
49
50
 
@@ -53,7 +54,7 @@ Options:
53
54
  --json Emit one validated JSON envelope.
54
55
 
55
56
  Use --json for scripts. Install and remove use native Codex plugin management.
56
- `,XU=`Install HolyCodex through Codex native plugin management.
57
+ `,gH=`Install HolyCodex through Codex native plugin management.
57
58
 
58
59
  Usage:
59
60
  holycodex install [options]
@@ -70,7 +71,7 @@ Tier is independent service handling (CLI values are lowercase only):
70
71
  fast-all Fast service handling for Root and leaves.
71
72
 
72
73
  Options:
73
- ${Xx.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
74
+ ${aS.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
74
75
  `)}
75
76
  --no-work / --no-frontend / --no-security /
76
77
  --no-computer-use Disable the corresponding plugin.
@@ -80,43 +81,58 @@ Capability defaults: Work false, Frontend true (mapped to build-web-apps),
80
81
  Security true, and Computer Use false. --add-plugin may be repeated.
81
82
  On an interactive TTY, install opens one wizard and final review with Install,
82
83
  Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
83
- `,QU=`Remove HolyCodex-owned state through Codex native plugin management.
84
+ Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
85
+ remains repeatable on the command line.
86
+ `,yH=`Remove HolyCodex-owned state through Codex native plugin management.
84
87
 
85
88
  Usage:
86
89
  holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
87
90
 
88
91
  Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
89
92
  configuration are preserved; changed owned files are preserved for review.
90
- `,eH=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
93
+ `,xH=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
91
94
 
92
95
  Usage:
93
96
  holycodex doctor [--json] [--codex-home <absolute-path>]
94
- `,tH=`Read or update the canonical public package version.
97
+ `,SH=`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
+ `,_H=`Read or update the canonical public package version.
95
106
 
96
107
  Usage:
97
108
  holycodex version [<0.x.y|patch|minor>] [--dry-run] [--json]
98
109
  holycodex --version
99
110
  holycodex -v
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(`
111
+ `;function al(e){switch(e){case"install":return gH;case"remove":return yH;case"doctor":return xH;case"upgrade":return SH;case"version":return _H;default:return hH}}function sS(e,t={}){let n=Xd({...t,stream:"stdout"});return al(e).split(`
112
+ `).map((r)=>{if(r==="HolyCodex")return Zd(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return Zd(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>Zd(o,"option",n)).replace(/<[^>]+>/gu,(o)=>Zd(o,"argument",n))}).join(`
113
+ `)}function sl(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function cl(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 Xd(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 Zd(e,t,n){if(!n)return e;return`\x1B[${{heading:"1",option:"36",argument:"2"}[t]}m${e}\x1B[0m`}ut();Hl();var Fj=["low","default","high"],Lj=["standard","fast","fast-all"],Wn=["work","frontend","security","computer_use"];async function L_(e={}){let t=wr(e),n=await import("@opentui/core"),r=VI(t),o=await n.createCliRenderer({exitOnCtrlC:!0,clearOnShutdown:!0}),i=new n.TextRenderable(o,{content:$I(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",v),o.destroy(),a(S)},h=(S)=>{if(p)return;p=!0,o.keyInput.off("keypress",v),o.destroy(),s(S)},m=()=>{i.content=l?zI(r,u):$I(r,c),o.requestRender()},v=(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:jI(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=KI(r.pluginInput),l=!0,u=0;else if(!S.ctrl&&!S.meta&&S.name.length===1&&!Hj(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)BI(r,c-2);else if(y==="left"||y==="h")UI(r,c,-1);else if(y==="right"||y==="l")UI(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",v);try{o.start()}catch(S){h(S)}})}function jI(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 Dj(e,t="install"){let n=VI(wr(e));return zI(n,t==="install"?0:t==="change"?1:2)}function VI(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 UI(e,t,n){if(t===0)e.profile=HI(Fj,e.profile,n);else if(t===1)e.tier=HI(Lj,e.tier,n);else if(t>=2&&t<Wn.length+2)BI(e,t-2)}function BI(e,t){let n=Wn[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function HI(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function KI(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 $I(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?qj(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":" "} ${JI(o).padEnd(14)} ${e.optional[o]?"[x] enabled":"[ ] disabled"}`),"","ADDITIONAL PLUGINS",...WI(`${t===Wn.length+2?"\u276F":" "} ${e.pluginInput||"(none)"}`),"",n].join(`
103
114
  `)}
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(`
115
+ `}function zI(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)=>` ${JI(o)}: ${Uj(e.optional[o])}`),...WI(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...n.map((o,i)=>`${i===t?"\u203A":" "} ${o}`)].join(`
105
116
  `)}
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}
117
+ `}function qj(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 WI(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 JI(e){return e==="computer_use"?"Computer Use":`${e[0].toUpperCase()}${e.slice(1)}`}function Uj(e){return e?"enabled":"disabled"}function Hj(e){let t=e.codePointAt(0)??0;return t<=31||t===127}Hl();Rl();Mf();Ml();Ll();Ki();ls();async function q_(e,t={}){if(sl(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:cl(e);return{envelope:GI(r===void 0?"help":`${r} help`,{help:al(r)}),exitCode:0}}let n;try{n=Yd(e);let r=await YI(n,t);return{envelope:GI(n.command,r),exitCode:Qj(n.command,r)}}catch(r){return Xj(n?.command??t1(e),r)}}async function YI(e,t){switch(e.command){case"install":return Zt(await $j(e,t));case"doctor":return Zt(await P_(Lf(e,t),t.env));case"remove":return Zt(await Bj(e,t));case"upgrade":return Zt(await Kj(e,t));case"version":return Zt(await zj(e,t));case"help":return{help:al(e.positionals[0])};default:throw new Yi("invalid_argument","Unknown command.")}}async function $j(e,t){let n=Vj(e),r=await jj(e,t,n);if("cancelled"in r)return r;return await ms(r,Lf(e,t),t.env)}async function jj(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??L_)(n);if(i.action==="cancel")return{cancelled:!0};return wr(i.request)}let o=await U_(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new Yi("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return wr(n)}function Vj(e){let t=Gj(e),n=Yj(e),r=Jj(e),o=Zj(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 Bj(e,t){let n=await U_(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable")throw new Yi("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.");return await ql(Lf(e,t),t.env)}async function Kj(e,t){let n=e.options["dry-run"]===!0;if(!n){let r=await U_(e,t,"Upgrade the existing HolyCodex installation in place?");if(r==="cancelled")return{cancelled:!0,status:"cancelled",changes:[]};if(r==="unavailable")throw new Yi("non_tty_confirmation_required","Upgrade requires --yes in non-interactive mode.")}return await I_(Lf(e,t),t.env,{dryRun:n})}async function zj(e,t){let n=e.positionals[0];if(!n)return{version:await Tf()};return await S_(n,e.options["dry-run"]===!0)}async function U_(e,t,n){if(e.options.yes===!0)return"confirmed";if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return"unavailable";return await Wj(t,n)}async function Wj(e,t){if(e.io?.confirm===void 0)return"unavailable";let n=await e.io.confirm(t);if(n==="confirmed"||n==="cancelled"||n==="unavailable")return n;return n?"confirmed":"cancelled"}function Jj(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 Gj(e){let t=e.options.profile;if(typeof t!=="string")return;let n=fr(t);return n.ok?n.value.name:void 0}function Yj(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function Zj(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Lf(e,t){let n=t.installer??{},r=e.options.json===!0,o=(a)=>{n.onProgress?.(a),t.onProgress?.(a),n1(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 GI(e,t){let n=Jd({schema_version:vr,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new Yi("internal_error","The success envelope failed validation.");return n.value}function Xj(e,t){let n=e1(t),r=Jd({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 Qj(e,t){return e==="doctor"&&Jn(t)&&t.healthy===!1?4:0}function e1(e){if(e instanceof ze)return{code:e.code,message:Ji(e.message),details:e.details,exitCode:1};if(e instanceof Yi)return{code:e.code,message:Ji(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof vn)return{code:"trust_boundary_failed",message:Ji(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:Ji(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:Ji(e.message),details:e.details,exitCode:t?4:n?2:3}}if(e instanceof zi)return{code:e.code,message:Ji(e.message),details:{},exitCode:4};if(e instanceof Il)return{code:e.code,message:Ji(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 t1(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function Ji(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 n1(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${ZI(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
118
+ `)}function Df(e,t={}){let n=Xd(t);if(e.envelope.ok){if(e.envelope.command==="version")return r1(e.envelope.data);if(e.envelope.command==="install")return o1(e.envelope.data,n);if(e.envelope.command==="remove")return i1(e.envelope.data,n);if(e.envelope.command==="upgrade")return a1(e.envelope.data,n);if(e.envelope.command==="doctor")return s1(e.envelope.data,n);return`${oe("\u2714","green",n)} ${oe(e.envelope.command,"heading",n)}
119
+ ${c1(e.envelope.data,n)}`}let r=e.envelope.error,o=u1(r.code,e.envelope.command);return[`${oe("\u2716","red",n)} ${oe(e.envelope.command,"heading",n)}`,` ${oe(r.code,"red",n)}: ${r.message}`,...l1(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
120
+ `)}function ZI(e,t={}){return`${oe("\u2022","cyan",Xd({...t,stream:"stderr"}))} ${e}`}function r1(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}
111
122
  `}return`holycodex version completed
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(`
123
+ `}function o1(e,t){if(qf(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("install","heading",t)} cancelled
124
+ `;let n=Kl(e,"record"),r=Jo(n,"version")??"unknown",o=Jo(n,"profile")??"unknown",i=Jo(n,"tier")??"unknown",a=Kl(n,"optional_selections"),s=Kl(n,"capability_state"),c=["frontend","security","work","computer_use"].filter((m)=>a?.[m]===!0).map((m)=>{let v=Jo(Kl(s,m),"status");return v===void 0||v==="healthy"?m:`${m} (${v})`}),l=Gi(e,"preserved"),u=Gi(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)}: ${Uf(m)}`)].join(`
125
+ `)}
126
+ `}function i1(e,t){if(qf(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("remove","heading",t)} cancelled
127
+ `;let n=Gi(e,"removed"),r=Gi(e,"preserved"),o=Gi(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)}: ${Uf(s)}`)].join(`
113
128
  `)}
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(`
129
+ `}function a1(e,t){if(qf(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("upgrade","heading",t)} cancelled
130
+ `;let n=Jo(Jn(e)?e:void 0,"status")??"completed",r=Jo(Jn(e)?e:void 0,"from_version"),o=Jo(Jn(e)?e:void 0,"to_version"),i=Gi(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(Uf).join(", ")}`].join(`
115
131
  `)}
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(`
132
+ `}function s1(e,t){let n=qf(e,"healthy")===!0,r=Kl(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=Jn(l)?l:void 0,p=Jo(u,"status");if(p===void 0||p==="healthy")return[];let f=Gi(u,"reasons");return[` ${oe(c,"option",t)}: ${f.length===0?p:f.map(Uf).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(`
117
133
  `)}
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(`
134
+ `}function Kl(e,t){if(!Jn(e))return;return Jn(e[t])?e[t]:void 0}function qf(e,t){return Jn(e)?e[t]:void 0}function Jo(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function Gi(e,t){if(!Jn(e)||!Array.isArray(e[t]))return[];return e[t]}function Uf(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function c1(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${oe(D_(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)}: ${D_(i)}`).join(`
120
136
  `)}
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};
137
+ `}function l1(e,t){return Object.entries(e).map(([n,r])=>` ${oe(n,"option",t)}: ${oe(D_(r),"dim",t)}`)}function D_(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function u1(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 Yi extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function H_(e=Bun.argv.slice(2),t=d1()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??f1(),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 q_(e,n);if((sl(e)||e[0]==="help")&&!XI(e))n.io?.writeStdout?.(sS(cl(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(XI(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
138
+ `);else if(r.envelope.ok)n.io?.writeStdout?.(Df(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(Df(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function d1(){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=p1({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 XI(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*f1(){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}Hl();Mf();Ml();Ki();Ll();Pf();var EZ="holycodex";if(import.meta.main)process.exitCode=await H_();export{ze as ArgumentError,os as CapabilityInstallStateSchema,h_ as CapabilityStateRecordSchema,Wo as CodexOfficialPluginManager,vf as InstallOptionsSchema,as as InstallRecordSchema,kl as InstallRequestSchema,N as InstallerError,Sr as OfficialPluginManagerError,vn as PathBoundaryError,j$ as STATE_SCHEMA,x_ as assertRootText,P_ as doctorHolyCodex,YI as executeCommand,sl as helpRequested,al as helpText,cl as helpTopic,ms as installHolyCodex,v_ as installNativeAgents,Ff as installRecordDigest,EZ as packageName,Yd as parseArgv,KI as parsePluginInput,cs as pathWithin,Wi as projectNativeAgents,b_ as projectRootAgent,Pl as publicManifestPath,hs as readActiveInstallRecord,us as readCanonicalBaseVersion,Tf as readCanonicalVersion,ql as removeHolyCodex,Cf as removeManagedNativeAgents,sS as renderHelp,Df as renderHuman,Dj as renderInstallWizardReview,Af as renderNativeAgent,ZI as renderProgress,Bi as resolveInstallerPaths,kf as rollbackNativeAgentInstall,w_ as rootDeveloperInstructions,H_ as runBinary,q_ as runCli,L_ as runOpenTuiInstallWizard,jI as toInstallOptions,S_ as updateCanonicalVersion,I_ as upgradeHolyCodex,wr as validateInstallOptions};